This commit is contained in:
2026-11-08 20:08:53 +08:00
parent 7526a5fe4d
commit 9b924747c5
2692 changed files with 394867 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import ir_model_fields
from . import mail_message
from . import models

View File

@@ -0,0 +1,254 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import datetime
import logging
from odoo import api, fields, models
from odoo.exceptions import ValidationError
from odoo.fields import Domain
from odoo.tools import OrderedSet, SQL, frozendict
from .models import MODELS_NO_AI
_logger = logging.getLogger(__name__)
NB_RECORDS_TO_COMPUTE_ON_FIELD_CREATION = 50
class IrModelFields(models.Model):
_inherit = 'ir.model.fields'
_explanation = "AI extensions for model fields, allowing fields to be computed or populated by an AI model based on a system prompt."
ai = fields.Boolean(string="Autofill", help="AI computed field", default=False)
ai_domain = fields.Char(string="AI field domain", compute="_compute_ai_domain", store=True, compute_sudo=True)
# should not be visible by a user
# one should go through "system_prompt"
prompt_custom = fields.Html(
sanitize=True,
sanitize_output_method='xml')
# Computed to allow customization and a value from the registry
system_prompt = fields.Html(
sanitize=True,
sanitize_output_method='xml',
string="Prompt",
compute="_compute_system_prompt",
inverse="_inverse_system_prompt",
compute_sudo=True,
help="Prompt given to the AI model to compute the field value"
)
supports_ai = fields.Boolean(compute="_compute_supports_ai")
def _get_registry_prompt(self):
model = self.env.get(self.model_id.model)
field = model is not None and model._fields.get(self.name)
return field and getattr(field, "ai", False)
@api.depends('model_id')
def _compute_system_prompt(self):
for rec in self:
rec.system_prompt = rec.prompt_custom or rec._get_registry_prompt()
def _inverse_system_prompt(self):
for rec in self:
registry_prompt = rec._get_registry_prompt()
prompt = rec.system_prompt
if prompt and prompt == registry_prompt:
prompt = False
rec.prompt_custom = prompt
@api.constrains('ai', 'model_id')
def _constrains_ai_model_id(self):
for rec in self:
if rec.ai and not rec.supports_ai:
raise ValidationError(self.env._t("The model '%s' doesn't support ai", rec.model_id.name))
@api.depends("model_id")
def _compute_supports_ai(self):
for rec in self:
rec.supports_ai = rec.model_id.model not in MODELS_NO_AI
@api.onchange("model_id")
def _on_change_model_reset_ai(self):
for rec in self:
if not rec.supports_ai:
rec.ai = False
@api.depends('ai', 'model', 'model_id')
def _compute_ai_domain(self):
for model, ir_fields in self.filtered('ai').grouped('model').items():
last_record_id = self.env[model].with_context(active_test=False).search([], order='id desc', limit=1).id
ir_fields.ai_domain = str([('id', '>', max(0, last_record_id - NB_RECORDS_TO_COMPUTE_ON_FIELD_CREATION))])
@api.model
@api.ormcache(cache='stable')
def _get_all_ai_parameters(self):
ai_fields = self.sudo().search_fetch([('ai', '=', True)], ["ai", "system_prompt", "ai_domain", "ttype"])
return frozendict((
(f.model_id.model, f.name),
frozendict({"prompt": f.system_prompt, "ai_domain": f.ai_domain, "ttype": f.ttype, "id": f.id})
) for f in ai_fields)
@api.model
def _get_field_ai_parameters(self, modelname_or_field: str | fields.Field, field_name: str | None = None):
if not isinstance(modelname_or_field, str):
model_name = modelname_or_field.model_name
field_name = modelname_or_field.name
else:
model_name = modelname_or_field
all = self._get_all_ai_parameters()
return all.get((model_name, field_name), {})
@api.model_create_multi
def create(self, vals_list):
"""Trigger the AI field cron when creating a record
"""
ir_model_fields = super().create(vals_list)
if any(f.ai and f.system_prompt for f in ir_model_fields) and (ai_fields_cron := self.env.ref('ai_fields.ir_cron_fill_ai_fields', raise_if_not_found=False)):
ai_fields_cron._trigger()
return ir_model_fields
def write(self, vals):
"""Trigger the AI field cron when making a field ai or when adding/changing its prompt
"""
res = super().write(vals)
if ((vals.get('system_prompt') or vals.get('ai')) and
(ai_fields_cron := self.env.ref('ai_fields.ir_cron_fill_ai_fields', raise_if_not_found=False))
):
ai_fields_cron._trigger()
return res
def _get_writable_properties(self):
return [*super()._get_writable_properties(), "system_prompt", "prompt_custom", "ai", "ai_domain"]
def _instanciate_attrs(self, field_data):
attrs = super()._instanciate_attrs(field_data)
if attrs and field_data.get('ai'):
attrs['ai'] = field_data.get('system_prompt') or ''
return attrs
def _reflect_field_params(self, field, model_id):
field_params = super()._reflect_field_params(field, model_id)
ai = getattr(field, 'ai', None)
field_params['ai'] = isinstance(ai, str) # can be empty string on field creation
return field_params
def _cron_fill_ai_fields(self, batch_size=10):
# currently only openAI is supported (gemini does not support web grounding with structured outputs),
# so make sure the openAI key is set
support_ttypes = ('char', 'text', 'html')
ai_params = self._get_all_ai_parameters()
field_ids = [p["id"] for p in ai_params.values() if p["prompt"] and p["ttype"] in support_ttypes]
property_fields = self.search(
Domain('ttype', '=', 'properties_definition') & Domain('store', '=', True),
order='id'
)
fields = self.browse(field_ids + property_fields.ids)
remaining_fields = len(fields)
total_done = 0 # number of records processed
total_remaining = 0 # number of records remaining for the fields processed
for field in fields:
done, remaining, has_time_left = (
self._ai_fill_records_with_empty_property(field, batch_size, remaining_fields)
if field.ttype == 'properties_definition' else
self._ai_fill_records_with_empty_field(field, batch_size, remaining_fields)
)
total_done += done
total_remaining += remaining
if not remaining:
remaining_fields -= 1
if not has_time_left:
break
if not remaining_fields:
# make sure to not rescheduled the cron
self.env['ir.cron']._commit_progress(remaining=0)
else:
if not total_done:
# all records were locked, reschedule the cron soon hoping they will be unlocked.
# not done when only part of the records were locked because in that case the cron will
# be considered as partially done and rescheduled asap.
self.env['ir.cron']._commit_progress(remaining=0)
_logger.info('AI Fields cron rescheduled soon because all records were locked')
self.env.ref('ai_fields.ir_cron_fill_ai_fields')._trigger(self.env.cr.now() + datetime.timedelta(minutes=1))
elif total_remaining:
_logger.info('AI Fields cron skipped %s records', total_remaining)
def _ai_fill_records_with_empty_field(self, field, batch_size, remaining_fields):
field.ensure_one()
has_time_left = True
model = self.env[field.model]
query = model._search(ast.literal_eval(field.ai_domain) or [], order='id')
query.add_where(SQL("%(field)s IS NULL", field=model._field_to_sql(model._table, field.name, query)))
ids = OrderedSet(query)
total_done = 0
while ids and has_time_left and (records := model.browse(ids).try_lock_for_update(limit=batch_size)):
records._fill_ai_field(model._fields[field.name])
ids -= set(records._ids)
done = len(records)
has_time_left = bool(self.env['ir.cron']._commit_progress(len(records), remaining=remaining_fields))
total_done += done
return total_done, len(ids), has_time_left
def _ai_fill_records_with_empty_property(self, field, batch_size, remaining_fields):
field.ensure_one()
to_process = []
definition_orm_field = self.env[field.model]._fields[field.name]
# Update the properties with a parent
# Need to split definition query from record query because of the domain in the definition
self.env.cr.execute(SQL(
"""
SELECT m.id AS parent_id, definition
FROM %(definition_table)s m, jsonb_array_elements(%(definition_name)s) definition
WHERE definition IS NOT NULL
AND COALESCE(definition->>'name', '') != ''
AND definition->>'ai' = 'true'
AND COALESCE(definition->>'system_prompt', '') != ''
-- because we can add records at the end of the prompt, for security
-- reason, we can not compute their values in the CRON
AND definition->>'type' != 'many2one'
AND definition->>'type' != 'many2many'
ORDER BY m.id
""",
definition_name=SQL.identifier(field.name),
definition_table=SQL.identifier(self.env[field.model]._table),
))
for values in self.env.cr.dictfetchall(): # For all AI definitions.....
definition = values["definition"]
parent_id = values["parent_id"]
# A definition can technically be linked to many properties fields
for properties_orm_field in definition_orm_field.properties_fields:
model = self.env[properties_orm_field.model_name]
ai_domain = Domain.AND([
definition.get("ai_domain") or [],
[[properties_orm_field.definition_record, "=", parent_id]],
])
# Can not use the ORM because we need IS NULL (VS False, empty string, etc...)
query = model._search(ai_domain, order='id DESC')
query.add_where(SQL(
"(%(field)s IS NULL OR %(field)s->%(property_name)s IS NULL)",
field=model._field_to_sql(model._table, properties_orm_field.name, query),
property_name=definition['name'],
))
ids = OrderedSet(query)
if ids:
to_process.append((model, properties_orm_field.name, definition, ids))
has_time_left = True
total_done = 0
for model, fname, definition, ids in to_process:
while has_time_left and (records := model.browse(ids).try_lock_for_update(limit=batch_size)):
records._fill_ai_property(fname, definition)
ids -= set(records._ids)
done = len(records)
has_time_left = bool(self.env['ir.cron']._commit_progress(done, remaining=remaining_fields))
total_done += done
return total_done, sum(len(ids) for *__, ids in to_process), has_time_left

View File

@@ -0,0 +1,21 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailMessage(models.Model):
_inherit = "mail.message"
def _ai_read(self, fnames=None, files_parts=None, files_checksums=None):
"""When messages are inserted in a prompt, one send the subject, body, author_id and date
of mail messages to the LLM.
"""
if fnames:
return super()._ai_read(fnames, files_parts, files_checksums)
# when a message field is inserted in an AI prompt, the subject, body, date and author
# of the mail messages are sent to the LLM
msg_subtype = self.env.ref('mail.mt_comment')
msg_types = ('comment', 'email', 'email_outgoing')
return super(MailMessage, self.filtered(
lambda m: m.message_type in msg_types and m.subtype_id == msg_subtype
))._ai_read(['subject', 'body', 'author_id', 'date'], files_parts, files_checksums)

335
ai_fields/models/models.py Normal file
View File

@@ -0,0 +1,335 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import collections
import logging
from odoo import _, api, Command, models
from odoo.addons.ai.utils.ai_fields_tools import get_ai_value, get_field_prompt_vals, get_property_prompt_vals, parse_ai_prompt_values
from odoo.exceptions import AccessError
from odoo.fields import Domain
from odoo.tools import html_sanitize
_logger = logging.getLogger(__name__)
# It doesn't make sense to have AI fields set anything on those
# models. Moreover, they can trigger stable cache invalidation and
# make requests heavier
MODELS_NO_AI = ["ir.config_parameter", "bus.bus"]
class Base(models.AbstractModel):
_inherit = 'base'
###############
# Overrides #
###############
@api.model_create_multi
def create(self, vals_list):
"""When a record of a model with an ai field or property is created, trigger the cron to
fill the ai fields/properties.
"""
res = super().create(vals_list)
IrModelFields = self.env["ir.model.fields"]
trigger_cron = False
if self._name not in MODELS_NO_AI:
for field in self._fields.values():
if field.type == 'properties':
definitions = [field._get_properties_definition(record) or [] for record in res]
if any(field_def.get("ai") and field_def.get("system_prompt") for d in definitions for field_def in d):
trigger_cron = True
break
elif field.type in ('char', 'text', 'html'):
ai_params = IrModelFields._get_field_ai_parameters(field)
if ai_params.get("prompt"):
trigger_cron = True
break
if trigger_cron and (ai_fields_cron := self.env.ref('ai_fields.ir_cron_fill_ai_fields', raise_if_not_found=False)):
ai_fields_cron._trigger()
return res
@api.model
def fields_get(self, allfields=None, attributes=None):
res = super().fields_get(allfields, attributes)
IrModelFields = self.env["ir.model.fields"]
if attributes is None or 'ai' in attributes:
for fname, val in res.items():
ai_params = IrModelFields._get_field_ai_parameters(self._fields[fname])
val['ai'] = "prompt" in ai_params and (ai_params['prompt'] or '')
return res
def write(self, vals):
"""When a property definition is modified or when the definition record is updated, trigger
the cron to fill the ai properties.
"""
res = super().write(vals)
if not self:
return res
trigger_cron = False
for field in self._fields.values():
if field.type == 'properties':
def_rec_name = self._fields[field.definition_record].name
if vals.get(def_rec_name):
if any(p.get('ai') and p.get('system_prompt') for p in (self[0][def_rec_name][field.definition_record_field] or [])):
trigger_cron = True
break
elif field.type == 'properties_definition':
if any(p.get('ai') and p.get('system_prompt') for p in (vals.get(field.name) or [])):
trigger_cron = True
break
if trigger_cron and (ai_fields_cron := self.env.ref('ai_fields.ir_cron_fill_ai_fields', raise_if_not_found=False)):
ai_fields_cron._trigger()
return res
def _additional_allowed_keys_properties_definition(self):
return super()._additional_allowed_keys_properties_definition() + ('ai', 'system_prompt', 'ai_domain')
def _html_sanitize_prompt_properties_definition(self, properties_definition):
if not properties_definition:
return properties_definition
for property_definition in properties_definition:
if property_definition.get('system_prompt'):
# Equivalent of `sanitize='email_outgoing'` on mail template body
property_definition['system_prompt'] = html_sanitize(
property_definition['system_prompt'],
sanitize_tags=True,
sanitize_attributes=True,
sanitize_style=True,
strip_style=True,
output_method='xml',
)
return properties_definition
@api.model
def _get_view_field_attributes(self):
attrs = super()._get_view_field_attributes()
attrs.append('ai')
return attrs
def _valid_field_parameter(self, field, name):
return name == 'ai' or super()._valid_field_parameter(field, name)
def _validate_properties_definition(self, properties_definition, field):
super()._validate_properties_definition(properties_definition, field)
self._html_sanitize_prompt_properties_definition(properties_definition)
if self.env.su or self.env.user.has_group('mail.group_mail_template_editor'):
return
for property_definition in properties_definition:
if prompt := property_definition.get('system_prompt'):
model_names = [properties_field.model_name for properties_field in field.properties_fields]
__, expressions, record_ids = parse_ai_prompt_values(self.env, prompt, property_definition.get('comodel'), False)
for model_name in model_names:
allowed_expressions = self.env[model_name].mail_allowed_qweb_expressions()
for expression in expressions:
if f"object.{expression}" not in allowed_expressions:
raise AccessError(_("You can not use the field %(field)s in a prompt."))
if (comodel := property_definition.get('comodel')) and record_ids:
self.env[comodel].browse(record_ids).check_access("read")
def _fill_ai_field(self, field, field_prompt=None):
"""Assign a value to the specified field in the given records based on the response of a
LLM. If no prompt is provided and the field is an AI field, it uses the field's prompt.
:param field: the field object for which the values should be obtained
:param field_prompt: the prompt to use for generating the values. If not provided and
the field is an AI field, the field's default prompt is used.
:return None
"""
ai_params = self.env["ir.model.fields"]._get_field_ai_parameters(field)
if field_prompt is None and not ai_params.get('prompt'):
raise ValueError(f"The field {field.name} has no AI prompt")
user_prompt, context_fields, allowed_values = get_field_prompt_vals(self.env, field, field_prompt)
for record in self:
try:
record[field.name] = get_ai_value(
record,
{'type': field.type, 'name': field.name, 'description': field.string},
user_prompt,
context_fields,
allowed_values,
)
except Exception as e: # noqa: BLE001
_logger.info("Could not get a value for an AI Field (%s on %s): %s", field.name, field.model_name, e)
if field.type in ('char', 'text', 'html'):
record[field.name] = "" # prevent query llm again for the field (unresolvable/timeout)
def _fill_ai_property(self, fname, property_definition):
"""Assign values to the specified AI property field for the records in `self` using LLM.
The records must share the same property definition.
:param fname: the name of the properties field
:param property_definition: the definition of the property
:return: None
"""
if not property_definition.get('system_prompt'):
raise ValueError(f"The property {property_definition['string']} has no AI prompt")
user_prompt, context_fields, allowed_values = get_property_prompt_vals(self.env, property_definition)
properties = {v['id']: v[fname] for v in self.read([fname])}
for record in self:
try:
value = get_ai_value(
record,
{'type': property_definition['type'], 'name': property_definition.get('string')},
user_prompt,
context_fields,
allowed_values,
)
except Exception as e: # noqa: BLE001
_logger.info("Could not get a value for an AI property (%s in %s on %s): %s", property_definition['name'], fname, self._name, e)
value = False # prevent query llm again for the property (unresolvable/timeout)
# update the property value (without overriding existing properties)
# we don't write the definition otherwise we will retrigger the cron if there
# is a property that has not been processed yet
record[fname] = {
p['name']: value if p['name'] == property_definition['name'] else p.get('value')
for p in properties.get(record.id, [])
if p['name'] == property_definition['name'] or 'value' in p
}
def get_ai_field_value(self, fname, changes):
"""Get the value of an AI field based on the response of a LLM.
:param fname: name of the field for which the value should be obtained
:param changes: dict of field values containing the changes to apply before querying
the LLM
:return: the value to apply to the field in the format of :meth:`web_read`, except for
many2many fields where the value is a command to apply
"""
self.check_access("read")
self.check_access("write")
record = self.new(changes, origin=self)
field = self._fields.get(fname)
if not field:
raise ValueError(f"The field {fname} is not defined on {self._name}")
ai_params = self.env["ir.model.fields"]._get_field_ai_parameters(field)
if not ai_params.get("prompt"):
raise ValueError(f"The field {fname} has no AI prompt")
user_prompt, context_fields, allowed_values = get_field_prompt_vals(self.env, field)
if field.type in ('many2many', 'many2one') and not allowed_values:
# add most frequent records if no record in prompt
records = self.ai_find_default_records(field.comodel_name, field.domain, fname)
allowed_values = {r.id: r.display_name for r in records}
val = get_ai_value(
record,
{'type': field.type, 'name': field.name, 'description': field.string},
user_prompt,
context_fields,
allowed_values,
) # currency?
if field.type == 'many2one':
return bool(val) and self.env[field.comodel_name].browse(val).read(['id', 'display_name'])[0]
elif field.type == 'many2many':
return [[Command.SET, 0, val or []]]
return val
def get_ai_property_value(self, full_name, changes):
"""Get the value of an AI property based on the response of a LLM.
:param full_name: full name of the property (field.property) for which the value should be
obtained
:param changes: dict of field values containing the changes to apply before querying the
LLM
:return: The value to apply to the property field in the format of :meth:`web_read`
"""
self.check_access("read")
self.check_access("write")
record = self.new(changes, origin=self)
property_definition = None
fname, pname = full_name.split(".")
if changes:
# use the updated property definition if it changed
properties_definition = changes.get(fname)
if properties_definition:
def_field = self[self._fields[fname].definition_record]._fields[self._fields[fname].definition_record_field]
properties_definition = [p for p in properties_definition if not p.get('definition_deleted')]
property_definition = next((p for p in properties_definition if p['name'] == pname), None)
for p in properties_definition:
p.pop('value', None)
p.pop('definition_changed', None)
def_field._validate_properties_definition(properties_definition, self.env)
if property_definition is None:
property_definition = self.get_property_definition(full_name)
if not (property_definition.get('ai') and property_definition.get('system_prompt')):
raise ValueError(f"The property {full_name} has no system prompt")
property_type = property_definition['type']
if property_type in ('many2many', 'many2one'):
if not property_definition.get('comodel'):
return property_type == 'many2many' and []
user_prompt, context_fields, allowed_values = get_property_prompt_vals(self.env, property_definition)
if property_type in ('many2many', 'many2one') and not allowed_values and property_definition.get('comodel'):
# add most frequent records if no record in prompt
records = self.ai_find_default_records(property_definition.get('comodel'), property_definition.get('domain'), fname, pname)
allowed_values = {r.id: r.display_name for r in records}
val = get_ai_value(
record,
{'type': property_definition['type'], 'name': property_definition['name'], 'description': property_definition.get('string')},
user_prompt,
context_fields,
allowed_values,
)
if property_type == 'many2one':
return bool(val) and self.env[property_definition['comodel']].browse(val).read(['id', 'display_name'])[0]
if property_type == 'many2many':
records = self.env[property_definition['comodel']].browse(val)
return [[rec['id'], rec['display_name']] for rec in records.read(['id', 'display_name'])] if records else []
return val
@api.model
def ai_find_default_records(self, comodel, domain, field_name, property_name=None):
"""Heuristic for relational AI fields / properties, find the most used records, and fill if necessary.
Note that `field_name` can be empty, when creating new field in studio.
"""
limit = self.env['ir.config_parameter'].sudo().get_int('ai_field.insert_x_first_records') or 200
domain = ast.literal_eval(domain or "[]") if isinstance(domain, str) else (domain or [])
if field_name and not self._fields[field_name].store:
return []
records_ids = []
if not property_name and field_name:
records_ids = [
record_id
for r in self.search([(field_name, 'any', domain)], limit=limit * 5, order="id DESC")
for record_id in r[field_name].ids
]
elif property_name:
# `any` operator not working on relational properties (because too costly to do)
definition = self.get_property_definition(f"{field_name}.{property_name}")
if definition:
values = self.search_read([(f"{field_name}.{property_name}", '!=', False)], [field_name], limit=limit * 5, order="id DESC")
values = [next(p.get('value') for p in v[field_name] if p.get('name') == property_name) for v in values]
if definition.get('type') == 'many2one':
records_ids = [v[0] for v in values if v]
elif definition.get('type') == 'many2many':
records_ids = [v[0] for rec in values for v in rec if rec and v]
allowed_ids = self.env[comodel].browse(records_ids).filtered_domain(domain).ids
records_ids = [i for i in records_ids if i in allowed_ids]
records_ids = [c[0] for c in collections.Counter(records_ids).most_common(limit)]
records = self.env[comodel].browse(records_ids)
if len(records) < limit: # If we didn't reach the limit, fill with other records
records |= self.env[comodel].search(
Domain.AND([domain, [('id', 'not in', records.ids)]]),
limit=limit - len(records),
order="id DESC",
)
return records