# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import json
from zoneinfo import ZoneInfo
from lxml import html
from lxml.etree import ParserError, XMLSyntaxError
from markupsafe import Markup
from odoo import api, models
from odoo.api import NewId
from odoo.exceptions import AccessError
from odoo.tools import OrderedSet
from odoo.tools.mail import html_to_inner_content
from odoo.tools.misc import formatLang
AI_SUPPORTED_IMG_TYPES = {'png', 'jpg', 'jpeg', 'webp', 'gif'}
class Model(models.AbstractModel):
_inherit = 'base'
def _ai_truncate(self, value, size=60):
# Limit the size of the field we can, to try to limit prompt injection...
if not isinstance(value, str) or len(value) < size:
return value
return value[:max(0, size - 3)] + "..."
def _ai_field_names_to_truncate(self):
return ('name', 'display_name')
def _ai_serialize_fields_data(self):
if self._name != 'ir.attachment':
try:
self.env['ai.tool']._check_agent_model_access(self._name)
except ValueError:
return f"Data of {self._name} records cannot be used by AI Agents"
fields_info = self.fields_get()
result = {}
for field_name, field_attrs in fields_info.items():
try:
field_type = field_attrs["type"]
field_value = self[field_name]
if field_type == 'char' and field_name in self._ai_field_names_to_truncate():
field_value = self._ai_truncate(field_value)
# Handle relational fields
elif field_type == "many2one":
result[field_name] = (
{'id': field_value.id, field_value._rec_name: self._ai_truncate(field_value.display_name)} if field_value else None
)
elif field_type in ["one2many", "many2many"]:
linked_records = self.env[field_value._name].browse(field_value.ids)
if (
len(linked_records) > 50
): # there have been cases were too many linked records have flooded the context - avoid that by filtering them out
continue
else:
result[field_name] = [
{'id': record.id, field_value._rec_name: self._ai_truncate(record.display_name)} for record in linked_records
]
elif field_type == "binary":
continue # we don't include binary fields in the record info JSON
else:
# Handle basic field types (dates, etc.)
if isinstance(field_value, datetime.datetime):
user_tz = ZoneInfo(self.env.user.tz or 'UTC')
result[field_name] = (
field_value.astimezone(user_tz).strftime(
"%Y-%m-%d %H:%M:%S"
)
if field_value
else None
)
elif isinstance(field_value, models.BaseModel):
# Handle unexpected recordset returns (shouldn't happen for non-relational fields)
result[field_name] = field_value.ids
else:
result[field_name] = field_value
except AccessError: # if the user doesn't have access to a field, don't include it in the AI's context
continue
return json.dumps(result, default=str)
################
# Extensions #
################
def _ai_read(self, fnames=None, files_parts=None, files_checksums=None):
"""Retrieve and format field values for LLM processing.
If no field names are given, return the display name.
This method can be overridden on any model that requires sending more than just the display
name when its records are included in a prompt (such as attachments).
Files are handled separately, as they must be sent independently to LLMs.
:param fnames: list of field names to read and format
:param files_parts: AIMessageParts
:param files_checksums: set of the checksums of files whose data has already been retrieved
:return: (vals_list, files_parts, files_checksums) where vals_list is a list of dicts mapping field names to
their formatted values with one dictionary per record.
files_parts is AIMessageParts of the files (it also includes the files_parts from the input :param: 'files_parts')
files_checksums is a set of the checksums of files whose data
has already been retrieved (it also includes the checksums from the input :param: 'files_checksums')
"""
if not fnames:
fnames = ['display_name'] # by default, send display names
if not files_parts:
files_parts = []
if files_checksums is None:
files_checksums = set()
vals_list = self.read(fnames, load=None)
for fname in fnames:
field = self._fields.get(fname)
if field.type in ('binary', 'image'):
if field.attachment:
attachments = self.env['ir.attachment']._get_field_attachments(self, [fname])
__, files_parts, files_checksums = attachments._ai_read(None, files_parts, files_checksums)
for record, vals in zip(self, vals_list):
raw = record[fname]
if not raw:
continue
checksum = self.env['ir.attachment']._compute_checksum(raw)
if checksum not in files_checksums:
mimetype = raw.mimetype
extension = mimetype.split("/")[-1]
if (is_supported_mimetype := extension in (*AI_SUPPORTED_IMG_TYPES, 'pdf')):
# todo: keep 5 pages max and resize images
content = vals[fname]
if content:
content = content['content']
else:
try:
content = self.env['ir.attachment']._index(raw, mimetype, checksum=checksum)
except TypeError:
content = self.env['ir.attachment']._index(raw, mimetype)
if is_supported_mimetype:
files_checksums.add(checksum)
files_parts.append({
'type': 'inline_data',
'mimetype': mimetype,
'data': content or '',
'metadata': {
'image_path': f'/web/image/{self._name}/{vals["id"]}/{fname}'
}
})
else:
files_checksums.add(checksum)
files_parts.append({
'type': 'text',
'text': content or '',
})
vals[fname] = f"