# Part of Odoo. See LICENSE file for full copyright and licensing details.
import inspect
import json
import logging
import re
from urllib.parse import urlsplit
from markupsafe import Markup
from odoo import _, api, models
from odoo.exceptions import ConcurrencyError, MissingError, UserError
from odoo.fields import Domain
from odoo.sql_db import PG_CONCURRENCY_EXCEPTIONS_TO_RETRY
from .ai_website_service_brand_kit import (
_USER_COLOR_PALETTE_URL,
_USER_WEBSITE_VALUES_URL,
)
from odoo.addons.ai.utils.ai_utils import (
UserInputResponse,
get_text_from_parts,
make_confirmation_request_preview,
)
from odoo.addons.ai_website.models.ir_attachment import ALLOWED_IMAGE_SCHEMES
_logger = logging.getLogger(__name__)
_WEBSITE_SCRAPER_TIMEOUT_SECONDS = 600
_MAX_SCRAPE_URLS = 10
_MAX_SCREENSHOT_BYTES = 50 * 1024 * 1024
# Shape check only: cheaper than decoding a multi-megabyte screenshot to throw the result away.
_BASE64_RE = re.compile(r'[A-Za-z0-9+/]*={0,2}')
_MAX_MENU_OPERATIONS = 50
_REVIEW_RESULT_SCHEMA = {
'type': 'object',
'properties': {
'safe': {
'type': 'boolean',
'description': 'True if the content is safe to apply to the website page.',
},
'reason': {
'type': 'string',
'description': 'Empty string when safe. A brief, specific explanation of the safety concern when unsafe.',
},
},
'required': ['safe', 'reason'],
'additionalProperties': False,
}
# External image URLs inside a CSS/SCSS `url()`, e.g. `background-image: url("https://…")`.
_CSS_URL_RE = re.compile(r'url\(\s*[\'"]?(https?://[^\'")\s]+)[\'"]?\s*\)', re.IGNORECASE)
# Routes an AI script must never reach.
_DENIED_ROUTE_PREFIXES = (
'/jsonrpc',
'/xmlrpc',
'/web/dataset',
'/web/session',
'/web/database',
'/web/action',
'/web/webclient',
'/web/binary/upload',
'/web/login',
'/web/signup',
'/web/reset_password',
)
_MAX_ROUTE_SEARCH_RESULTS = 30
def _get_route_doc(endpoint):
"""
Return the documentation of a route, gathered along the whole
controller hierarchy.
"""
method = getattr(endpoint, 'func', endpoint)
controller = getattr(method, '__self__', None)
if controller is None:
return inspect.getdoc(method) or ""
docs = []
for cls in reversed(type(controller).mro()):
submethod = cls.__dict__.get(method.__name__)
doc = getattr(submethod, '__doc__', None)
doc = inspect.cleandoc(doc) if doc else ""
if doc and doc not in docs:
docs.append(doc)
return "\n\n".join(docs)
class AITool(models.AbstractModel):
_inherit = 'ai.tool'
@api.model
def _ai_tool_generate_image(self, tool_context, prompt, images_paths, image_title, feedback, aspect_ratio='1:1'):
"""In a builder session, persist the generated images, return their URLs
and keep the agentic loop alive so the model chains into
apply_html_to_page instead of ending the turn."""
is_builder_session = self.env['ai.session'].sudo().browse(
tool_context.get('session_id'))._is_website_builder_session()
result = super()._ai_tool_generate_image(tool_context, prompt, images_paths, image_title, feedback, aspect_ratio)
if not is_builder_session:
return result
final_message = tool_context.get('final_message') or []
attachments = self.env['ir.attachment'].search([('id', 'in', [
part['metadata']['attachment_id']
for part in final_message
if part.get('type') == 'inline_data' and part.get('metadata', {}).get('attachment_id')
])])
if not attachments:
return result
# The base tool set final_message to the image result; left set it ends
# the turn, so clear it to keep the loop alive for image placement.
tool_context['final_message'] = None
service = self.env['ai.website.service']
urls = "\n".join(f"- ID: {a.id}, URL: {service._create_public_image_url(a)}" for a in attachments)
result['response'] = (
f"Generated {len(attachments)} image(s). Permanent URLs:\n{urls}\n\n"
"You MUST now call `apply_html_to_page` to place these images on the page "
"using appropriate selectors. Do not message the user until placement is done."
)
return result
@api.model
def _ai_tool_get_snippets(self, snippet_keys):
"""
Return the HTML structures of the requested snippets, along with a
description of their purpose and content.
"""
if not snippet_keys:
return "No snippet keys provided. Please specify which snippets you want to retrieve."
service = self.env['ai.website.service']
result = (
"Here are the HTML structures of the snippets you requested.\n\n"
)
for snippet_key in snippet_keys:
result += f"## Snippet: {snippet_key}\n"
hint, html = service._get_snippet_html(snippet_key)
if hint:
result += f"_{hint.label}_ — {hint.intent}\n\n"
if not html:
result += "No snippet found with this key. Try another one.\n\n"
else:
result += f"```html\n{html}\n```\n\n"
return {
'response': result,
'summary': {'icon': 'explore', 'text': self.env._("Looked up snippets")},
}
@api.model
@api.ormcache()
def _ai_get_backend_routes_map__(self): # noqa: PLW3201
"""
Return {path: {path, methods, type, auth, endpoint_name, doc}} for every
route of this database, minus the ones an AI script must never reach.
"""
router = self.env['ir.http'].routing_map()
actions = {}
for rule in router.iter_rules():
if rule.rule in actions or rule.rule.startswith(_DENIED_ROUTE_PREFIXES):
continue
endpoint = rule.endpoint
methods = endpoint.routing.get('methods')
endpoint_func = getattr(endpoint, 'func', endpoint)
actions[rule.rule] = {
'path': rule.rule,
'methods': methods,
'type': endpoint.routing.get('type', 'http'),
'auth': endpoint.routing.get('auth', 'user'),
'endpoint_name': getattr(endpoint_func, '__name__', ''),
'doc': _get_route_doc(endpoint),
}
return actions
@api.model
def _ai_tool_search_backend_routes(self, pattern):
"""
Return the routes whose path, endpoint name or documentation matches
the given regular expression.
"""
try:
route_re = re.compile(pattern, re.IGNORECASE)
except re.error as e:
return f"'{pattern}' is not a valid regular expression ({e}). Search again."
matches = []
for action in self._ai_get_backend_routes_map__().values():
# The path alone is too narrow: "cart" must find a route named
# add_to_cart or one that has "cart" in the doc .
if route_re.search(f"{action['path']} {action['endpoint_name']} {action['doc']}"):
matches.append(action)
if not matches:
return (
f"No route matches '{pattern}'. Try a broader pattern (a single word, or "
"several joined with |). If nothing turns up, tell the user this isn't "
"supported yet rather than calling a path you haven't found here."
)
truncated = len(matches) - _MAX_ROUTE_SEARCH_RESULTS
result = f"# Routes matching '{pattern}'\n\n"
for action in matches[:_MAX_ROUTE_SEARCH_RESULTS]:
result += self._ai_format_route(action)
if truncated > 0:
result += (
f"{truncated} more route(s) matched and are not shown. "
"Search again with a narrower pattern to see them.\n"
)
return {
'response': result,
'summary': {'icon': 'search', 'text': self.env._("Searched backend routes")},
}
@api.model
def _ai_format_route(self, action):
"""
Render one route: what it does, and the `type`/`methods`/`auth` the
skill's own encoding rules key off.
"""
methods = action['methods']
return (
f"## {action['path']}\n"
f"- methods: {', '.join(methods) if methods else 'any'}\n"
f"- type: {action['type']}\n"
f"- auth: {action['auth']}\n"
f"{action['doc'] or 'No documentation available. Do not guess its parameters.'}\n\n"
)
@api.model
def _ai_tool_get_backend_route_docs(self, paths):
"""
Return the full documentation (as written in its own docstring) for
each of the given backend route.
"""
actions = self._ai_get_backend_routes_map__()
result = ""
for path in paths:
action = actions.get(path)
if not action:
result += (
f"## {path}\n"
"No such route on this database, or it is one an AI script is never "
"allowed to call. Do not call it: find the right path with the "
"\"Search Backend Routes\" tool.\n\n"
)
continue
result += self._ai_format_route(action)
return {
'response': result,
'summary': {'icon': 'description', 'text': self.env._("Read backend routes docs")}
}
@api.model
def _ai_tool_search_images(self, query):
"""
Search for images using the Unsplash API.
"""
response = self.env['ir.attachment']._fetch_unsplash_images(
query=query, page=1, per_page=30)
if response.get('error') in ('no_access', 'key_not_found'):
return (
'No stock photo library is configured, so no image can be searched. '
'Do NOT call this tool again this turn. Keep the default placeholder images that '
'come with the snippets exactly as they are: leave their `src` (or `background-image` '
'style) untouched and do NOT remove them. Do NOT generate images instead: only write '
'
if the user explicitly asked for AI generated images.'
)
if 'error' in response:
return f"An unknown error occurred while searching Unsplash: {response['error']}"
if not response.get('results'):
return (
f'No stock photo matches "{query}". Try another query, and if nothing usable comes '
'back, keep the default placeholder images that come with the snippets exactly as '
'they are. Do NOT generate images instead: only write '
'
if the user explicitly asked for AI generated images.'
)
result = (
"Here are some images from Unsplash that match your search query.\n"
)
for image in response['results']:
width = image.get('width') or None
height = image.get('height') or None
result += (
f'- URL: "{image['urls']['regular']}", '
f'Type: "{image.get('asset_type') or 'photo'}", '
f'Description: "{image.get('description') or 'No description'}", '
f'Slug: "{image.get('slug') or 'N/A'}", '
f'Average color: "{image.get('color') or 'N/A'}", '
f'Aspect ratio (W/H): {round(width / height, 2) if width and height else 'N/A'}\n'
)
return {
'response': result,
'summary': {'icon': 'public', 'text': self.env._("Searched images on Unsplash")},
}
@api.model
def _ai_tool_create_image_attachments(self, attachments_ids):
"""
Process the images given in attachments_ids, create permanent
attachments to prevent them from being deleted at the end of the AI
session.
Return the public image URLs.
"""
attachments = self.env['ir.attachment'].search([('id', 'in', attachments_ids)])
if not attachments:
return "No attachments with the given IDs were found."
result = (
"Here are the public URLs of the images you uploaded. "
"Use these URLs to reference the images in your HTML and CSS.\n\n"
)
def is_valid_attachment(attachment):
if attachment.res_model != 'discuss.channel':
return False
channel = self.env['discuss.channel'].browse(attachment.res_id)
return channel.sudo().ai_agent_id and self.env.user.partner_id in channel.channel_member_ids.partner_id
service = self.env['ai.website.service']
error_not_found = "Not found. Please make sure the attachment was provided by the user.\n"
for attachment in attachments:
result += f"- ID: {attachment.id}, "
try:
if is_valid_attachment(attachment):
result += f"URL: {service._create_public_image_url(attachment)}\n"
else:
result += error_not_found
except MissingError:
result += error_not_found
for attachment_id in attachments_ids:
if attachment_id not in attachments.ids:
result += f"- ID: {attachment_id}, {error_not_found}"
return {
'response': result,
'summary': {'icon': 'edit_square', 'text': self.env._("Created Attachments")},
}
@api.model
def _call_ai_reviewer(self, prompt):
"""Call the ai reviewer agent with a pre-formatted prompt.
Returns ``(is_safe, reason)`` where ``is_safe`` is a bool and ``reason``
is an explanation string (empty when safe).
"""
reviewer = self.env.ref('ai_website.ai_agent_reviewer', raise_if_not_found=False)
try:
response = reviewer._generate_single_response(
message=[{'type': 'text', 'text': prompt}],
schema=_REVIEW_RESULT_SCHEMA,
)
except (*PG_CONCURRENCY_EXCEPTIONS_TO_RETRY, ConcurrencyError):
raise
except Exception: # noqa: BLE001
return False, "Safety reviewer call failed"
if not response:
return False, "Safety reviewer returned no response"
try:
result = json.loads(get_text_from_parts(response))
return bool(result.get('safe', False)), result.get('reason', '')
except (json.JSONDecodeError, TypeError, KeyError):
return False, "Safety reviewer returned unparseable response"
@api.model
def _ai_review(self, actions):
"""Ask the safety reviewer to assess AI-generated actions."""
items = []
for i, action in enumerate(actions):
header = (
f"### Action {i + 1}\n"
f"- zone: {action.get('zone', 'n/a')}\n"
f"- mode: {action.get('mode', 'n/a')}\n"
f"- selector: {action.get('selector') or 'none'}\n"
)
items.append(header + f"```html\n{action.get('content', '')}\n```")
prompt = (
"Review the following HTML actions that an AI assistant is about to apply "
"to a public-facing Odoo website page. The HTML of an action may embed its "
"JavaScript in