Files
dn20/dn_ai/models/ai_tool.py
2026-11-25 11:58:57 +08:00

713 lines
32 KiB
Python

# -*- coding: utf-8 -*-
import json
import logging
from odoo import api, fields, models
from odoo.exceptions import AccessError, UserError
from odoo.tools import OrderedSet
from ..utils.ai_utils import coerce_domain, compute_date, get_text_from_parts
_logger = logging.getLogger(__name__)
# Models the agent must never inspect directly.
AI_MODELS_BLOCKLIST = {
'base.automation',
'res.device',
'res.groups',
'res.groups.privilege',
'res.users.settings',
'ir.model',
'ir.model.fields',
'ir.rule',
}
class AITool(models.AbstractModel):
"""Implementation of every tool callable by the model.
Each ``_ai_tool_xxx`` method receives the raw arguments and a mutable
``tools_context`` dict. Returning a dict lets the caller collect a summary
and, for interactive tools, a ``user_input_request``.
"""
_name = 'ai.tool'
_description = 'AI Tool'
# ==================================================================
# access helpers
# ==================================================================
def _check_agent_model_access(self, model_name, operation='read'):
if model_name in AI_MODELS_BLOCKLIST or model_name.startswith('ir.'):
raise ValueError(f"Model '{model_name}' cannot be used by AI agents.")
model = self.env.get(model_name)
if model is None:
raise ValueError(f"Model '{model_name}' does not exist.")
model.check_access(operation)
return model
def _parse_domain(self, model_name, domain, operation='read'):
"""Validate a domain coming from the model, with user-level rights."""
model = self._check_agent_model_access(model_name, operation)
if domain in (None, '', False):
return []
if isinstance(domain, str):
try:
domain = json.loads(domain)
except ValueError:
try:
domain = coerce_domain(domain)
except (ValueError, SyntaxError):
raise ValueError(f"Invalid domain: {domain}") from None
if not isinstance(domain, list):
raise ValueError("A domain must be a list.")
return domain
def _get_model_fields(self, model_name):
model = self._check_agent_model_access(model_name)
return model.fields_get()
@api.model
def _ai_tool_get_models(self):
"""List the models the current user may query."""
rows = []
for index, model_name in enumerate(self.env):
model = self.env[model_name]
if model_name in AI_MODELS_BLOCKLIST or model_name.startswith('ir.'):
continue
if model._abstract or model._transient:
continue
if not model.has_access('read'):
continue
rows.append({'model': model_name, 'description': model._description})
if index > 2000: # guard against a runaway registry
break
rows.sort(key=lambda row: row['model'])
return {
'summary': {'icon': 'view_list', 'text': self.env._("Models")},
'models': rows,
}
@api.model
def _ai_tool_get_fields(self, model_name, include_description=True):
"""Return the technical fields of a model."""
self._check_agent_model_access(model_name)
model = self.env[model_name]
fields_info = model.fields_get()
result = []
for name, info in sorted(fields_info.items()):
row = {
'name': name,
'type': info.get('type'),
'string': info.get('string'),
}
if info.get('relation'):
row['relation'] = info['relation']
if info.get('selection'):
row['selection'] = [v for v, _label in info['selection']][:30]
if info.get('required'):
row['required'] = True
if info.get('readonly'):
row['readonly'] = True
if include_description and info.get('help'):
row['help'] = info['help'][:200]
result.append(row)
return {
'summary': {'icon': 'view_list', 'text': self.env._("Fields of %s", model._description)},
'model': model_name,
'fields': result,
}
# ==================================================================
# menus
# ==================================================================
@api.model
def _get_available_menus(self):
all_menus = self.env['ir.ui.menu'].sudo().load_web_menus(False)
root_ids = set(all_menus['root']['children'])
rows = []
for menu_id, web_menu in all_menus.items():
if menu_id == 'root':
continue
if web_menu.get('actionModel') not in (
'ir.actions.act_window', 'ir.actions.client', 'ir.actions.report',
):
continue
menu = self.env['ir.ui.menu'].sudo().browse(web_menu['id'])
if not menu.exists():
continue
action = self.sudo().env[web_menu['actionModel']].browse(web_menu['actionID'])
if not action.exists():
continue
model = action.res_model if action.type != 'ir.actions.report' else action.model
view_types = ([v[1] for v in action.views] if action.type == 'ir.actions.act_window' and action.views else [])
default_view = view_types[0] if view_types else None
if action.type == 'ir.actions.act_window' and action.view_id:
default_view = action.view_id.type
rows.append({
'menu_id': menu.id,
'action_id': action.id,
'action_type': action.type,
'name': menu.complete_name,
'model': model or '',
'views': view_types,
'default_view': default_view,
})
rows.sort(key=lambda row: row['name'])
return rows
@api.model
def _ai_tool_get_menus(self):
return {
'summary': {'icon': 'apps', 'text': self.env._("Menus")},
'menus': self._get_available_menus(),
}
@api.model
def _ai_tool_get_menu_details(self, menu_ids, include_model_fields=True):
if isinstance(menu_ids, int):
menu_ids = [menu_ids]
menus = self.env['ir.ui.menu'].sudo().browse(menu_ids).exists()
details = []
for menu in menus:
action = menu.action
entry = {
'menu_id': menu.id,
'name': menu.complete_name,
'action_id': action.id if action else None,
'action_type': action.type if action else None,
'model': (action.res_model if action and action.type != 'ir.actions.report'
else getattr(action, 'model', None)),
}
if include_model_fields and entry['model']:
try:
entry['fields'] = list(self._get_model_fields(entry['model']))
except (ValueError, AccessError):
entry['fields'] = []
details.append(entry)
return {
'summary': {'icon': 'apps', 'text': self.env._("Menu details")},
'menus': details,
}
# ==================================================================
# data retrieval
# ==================================================================
def _ai_tool_search(self, model_name, domain="", fields=None, offset=0, limit=None, order=None):
model = self._check_agent_model_access(model_name)
parsed = self._parse_domain(model_name, domain)
limit = min(int(limit or 40), 200)
read_fields = fields or ['display_name']
if isinstance(read_fields, str):
read_fields = [read_fields]
records = model.search(parsed, offset=int(offset or 0), limit=limit, order=order)
vals = records.read(read_fields, load=False)
# Normalise relational values so the model sees ids, not (id, name) tuples.
for row in vals:
for key, value in list(row.items()):
if isinstance(value, tuple):
row[key] = list(value)
return {
'summary': {'icon': 'search', 'text': self.env._("Search %s", model._description)},
'model': model_name,
'count': len(records),
'records': vals,
}
def _ai_tool_read_group(self, model_name, domain, groupby=None, aggregates=None):
model = self._check_agent_model_access(model_name)
parsed = self._parse_domain(model_name, domain)
groupby = groupby or []
aggregates = aggregates or ['__count']
rows = model._read_group(parsed, groupby=groupby, aggregates=aggregates)
result = []
for row in rows:
payload = {}
for index, value in enumerate(groupby):
key = value.split(':')[0]
payload[key] = row[index].display_name if hasattr(row[index], 'display_name') else row[index]
for index, measure in enumerate(aggregates):
payload[measure] = row[len(groupby) + index]
result.append(payload)
return {
'summary': {'icon': 'bar_chart', 'text': self.env._("Group %s", model._description)},
'groups': result,
}
def _ai_tool_read_binary_content(self, model_name, record_ids, field_name=None):
model = self._check_agent_model_access(model_name)
records = model.browse(record_ids if isinstance(record_ids, (list, tuple)) else [record_ids])
payload = []
for record in records.exists():
if field_name:
payload.append({'id': record.id, 'field': field_name,
'content': record._ai_read([field_name])[1]})
else:
payload.append({'id': record.id, 'name': record.display_name})
return {
'summary': {'icon': 'attachment', 'text': self.env._("Attachments")},
'records': payload,
}
# ==================================================================
# dates
# ==================================================================
def _ai_tool_compute_date(self, model_name, field_name, operations=None, pin=None):
model = self._check_agent_model_access(model_name)
field = model._fields.get(field_name)
if not field or field.type not in ('date', 'datetime'):
raise ValueError(f"Field '{field_name}' is not a date/datetime field of {model_name}.")
today = fields.Date.context_today(model)
value = compute_date(field.type, self.env.user.tz or 'UTC', today, operations, pin)
return {
'summary': {'icon': 'calendar', 'text': self.env._("Computed date")},
'field': field_name,
'type': field.type,
'value': value,
}
# ==================================================================
# UI navigation
# ==================================================================
def _resolve_window_action(self, menu_id, model_name=None):
"""Return ``(action, action_dict)`` for a menu, ready to hand to the client.
The browser side runs ``services.action.doAction(action_dict)``, so the
payload must be a **full action dictionary**, not ``{actionId: 12}``.
Passing just an id leaves the client with nothing to load, which is how
the UI ends up "opened" in the transcript but unchanged on screen.
"""
menu = self.env['ir.ui.menu'].sudo().browse(menu_id).exists()
if not menu:
raise ValueError(f"Menu with ID {menu_id} not found.")
action = menu.action
if not action or action.type != 'ir.actions.act_window':
raise ValueError(
f"Menu ID {menu_id} is not bound to a window action "
f"(got {action.type if action else 'no action'}).")
action_dict = action._get_action_dict()
if model_name and action_dict.get('res_model') != model_name:
raise ValueError(
f"The model '{model_name}' does not match the action of menu "
f"ID {menu_id} ('{action_dict.get('res_model')}').")
return action, action_dict
def _model_label(self, model_name):
"""Return the translated, human-readable name of a model.
``model._description`` is a plain Python class attribute — it is never
routed through the translation layer, so a Chinese user would see
"Sales Order" inside an otherwise Chinese sentence. ``ir.model.name``
is the translated variant, which is what the UI itself shows.
"""
ir_model = self.env['ir.model'].sudo().search(
[('model', '=', model_name)], limit=1)
return ir_model.name or self.env[model_name]._description
def _normalize_search_terms(self, model_name, search):
"""Coerce the tool's ``search`` argument into the client's expected shape.
The schema asks for a free-text string, but the browser wants a list of
``{search_field, value}`` objects (that is what "typing in the search
bar" produces). A bare string has no field attached, so anchor it on the
model's ``_rec_name`` — searching "SO001" should look at the display
name, not at every char field.
"""
if not search:
return []
if isinstance(search, (list, tuple)):
return [term for term in search if isinstance(term, dict)]
model = self.env[model_name]
rec_name = model._rec_name
if not rec_name or rec_name not in model._fields:
return []
return [{'search_field': rec_name, 'value': str(search)}]
def _build_view_action(self, menu_id, model_name, domain=None, filters=None,
groupbys=None, search=None, view_type='list', extra=None):
"""Build the ``show_view`` payload for the browser.
``oneway`` matters: opening a view is fire-and-forget. Without it the
server pauses in ``waiting_client_result`` and the conversation hangs
because nothing ever posts a result back.
"""
action, action_dict = self._resolve_window_action(menu_id, model_name)
available = [view[1] for view in action_dict.get('views') or []]
if view_type not in available:
raise ValueError(
f"'{view_type}' view is not available on menu ID {menu_id}; "
f"available: {available}.")
ai_props = {
'selectedFilters': filters or [],
'selectedGroupBys': groupbys or [],
'search': self._normalize_search_terms(model_name, search),
}
if domain:
# The model sends domains as a JSON string; parse (and validate)
# before handing it to the browser.
ai_props['customDomain'] = self._parse_domain(model_name, domain)
if extra:
# Pivot/graph specific keys (``measures``, ``colGroupBys``, ``mode``…)
# belong **inside** ``props.ai``: the view patch only reads
# ``this.componentProps.ai``. Putting them at the top level of
# ``options`` leaves them unread, so the view opens with its default
# measures and grouping.
ai_props.update({key: value for key, value in extra.items()
if value is not None})
options = {'viewType': view_type, 'props': {'ai': ai_props}}
return {
'action': action_dict,
'options': options,
'menuId': menu_id,
}
def _ai_tool_open_menu_list(self, menu_id, model_name, selected_filters=None,
selected_groupbys=None, search=None, custom_domain=None):
params = self._build_view_action(
menu_id, model_name, domain=custom_domain, filters=selected_filters,
groupbys=selected_groupbys, search=search, view_type='list')
return {
'summary': {'icon': 'open_in_browser',
'text': self.env._("Opened the list view for %s",
self._model_label(model_name))},
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
}
def _ai_tool_open_menu_kanban(self, menu_id, model_name, selected_filters=None,
selected_groupbys=None, search=None, custom_domain=None):
params = self._build_view_action(
menu_id, model_name, domain=custom_domain, filters=selected_filters,
groupbys=selected_groupbys, search=search, view_type='kanban')
return {
'summary': {'icon': 'open_in_browser',
'text': self.env._("Opened the kanban view for %s",
self._model_label(model_name))},
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
}
def _ai_tool_open_menu_pivot(self, menu_id, model_name, selected_filters=None,
selected_groupbys=None, row_groupbys=None, col_groupbys=None,
measures=None, search=None, custom_domain=None):
params = self._build_view_action(
menu_id, model_name, domain=custom_domain, filters=selected_filters,
groupbys=row_groupbys or selected_groupbys, search=search, view_type='pivot',
extra={'colGroupBys': col_groupbys, 'measures': measures})
return {
'summary': {'icon': 'open_in_browser',
'text': self.env._("Opened the pivot view for %s",
self._model_label(model_name))},
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
}
def _ai_tool_open_menu_graph(self, menu_id, model_name, selected_filters=None,
selected_groupbys=None, row_groupbys=None, measures=None,
chart_type=None, search=None, custom_domain=None):
grouped_by = row_groupbys or selected_groupbys
params = self._build_view_action(
menu_id, model_name, domain=custom_domain, filters=selected_filters,
groupbys=grouped_by, search=search, view_type='graph',
# Graph reads `measure` (a single field name), `mode` and `groupBys`
# — not `graphMeasures`/`graphType`, which nothing consumes.
extra={'measure': (measures or [None])[0], 'mode': chart_type,
'groupBys': grouped_by})
return {
'summary': {'icon': 'open_in_browser',
'text': self.env._("Opened the graph view for %s",
self._model_label(model_name))},
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
}
def _ai_tool_adjust_search(self, model_name, remove_facets=None, toggle_filters=None,
toggle_groupbys=None, apply_searches=None, measures=None,
mode=None, order=None, stacked=None, cumulated=None,
custom_domain=None, switch_view_type=None):
self._check_agent_model_access(model_name)
params = {
'removeFacets': remove_facets or [],
'toggleFilters': toggle_filters or [],
'toggleGroupBys': toggle_groupbys or [],
'applySearches': self._normalize_search_terms(model_name, apply_searches),
'measures': measures or [],
'mode': mode or None,
'order': order or 'ASC',
'stacked': stacked if stacked is not None else None,
'cumulated': cumulated if cumulated is not None else None,
'switchViewType': switch_view_type or False,
}
if custom_domain:
# `customDomain` is consumed by `SearchModel.splitAndAddDomain`,
# which expects a real domain, not the JSON string the tool gets.
params['customDomain'] = self._parse_domain(model_name, custom_domain)
return {
'summary': {'icon': 'filter_alt',
'text': self.env._("Refined the search on %s",
self._model_label(model_name))},
'client_tool': {'name': 'adjust_view', 'oneway': True, 'params': params},
}
def _ai_tool_run_view_action(self, menu_id, action_type):
params = self._build_view_action(menu_id, None, view_type=action_type)
return {
'summary': {'icon': 'open_in_browser', 'text': self.env._("Opened view")},
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
}
# ------------------------------------------------------------------
# opening one specific record
# ------------------------------------------------------------------
def _find_window_action_for_model(self, model_name):
"""Return ``(menu, action_dict)`` for a form-capable action on a model.
After a write the freshly created record must be shown in the surface
the user knows, with the right menu highlighted, so the menu bound to
the action is preferred. ``menu`` is ``None`` when the model is only
reachable from a child action that no menu points at directly.
"""
actions = self.env['ir.actions.act_window'].sudo().search(
[('res_model', '=', model_name)])
fallback = None
for action in actions:
view_types = [view[1] for view in action.views or []]
if 'form' not in view_types:
continue
action_dict = action._get_action_dict()
menu = self.env['ir.ui.menu'].sudo().search(
[('action', '=', f'ir.actions.act_window,{action.id}')], limit=1)
if menu:
return menu, action_dict
# Keep looking: another action of the same model may be the one a
# menu actually points at. Remember this one in case none is.
if fallback is None:
fallback = action_dict
return None, fallback
def _build_record_action(self, model_name, res_ids, menu_id=None, label=None):
"""Build a ``show_view`` payload that opens the given records.
A single record is opened as a **form view driven by ``res_id``**, not
by putting the id in a domain — a domain lands on a one-row list, which
is the "it says it created the order but nothing opened" symptom. A
batch opens the list filtered on those ids, because a form view cannot
present a set.
"""
res_ids = [int(res_id) for res_id in (res_ids or []) if res_id]
if not res_ids:
raise ValueError("No record to open.")
if menu_id:
menu, action_dict = self._resolve_window_action(menu_id, model_name)
else:
menu, action_dict = self._find_window_action_for_model(model_name)
if action_dict:
action_dict = dict(action_dict)
else:
# No stored action carries the form view (rare, but a model can be
# written to without any menu). A minimal action still opens it.
view_types = ['form'] if len(res_ids) == 1 else ['list', 'form']
action_dict = {
'type': 'ir.actions.act_window',
'res_model': model_name,
'view_mode': ','.join(view_types),
'views': [[False, view] for view in view_types],
'target': 'current',
}
action_dict['name'] = label or action_dict.get('name') or self._model_label(model_name)
options = {}
if len(res_ids) == 1:
# `res_id` on the action is what makes the form controller load the
# record; `viewType: form` forces it even when the action defaults
# to the list (e.g. the "Sales" menu).
action_dict['res_id'] = res_ids[0]
options['viewType'] = 'form'
options['props'] = {'resId': res_ids[0]}
else:
action_dict.pop('res_id', None)
options['viewType'] = 'list'
options['props'] = {
'ai': {'customDomain': [['id', 'in', res_ids]]},
}
if menu:
# Drop the breadcrumb so the back button does not grow a trail of
# AI-opened windows; the menu highlight still points at the app.
options['clearBreadcrumbs'] = True
return {
'action': action_dict,
'options': options,
'menuId': menu.id if menu else None,
}
def _ai_tool_compute_report_measures(self, action_id, model):
model_obj = self._check_agent_model_access(model)
fields_info = model_obj.fields_get()
measures = []
for name, info in fields_info.items():
if info.get('type') in ('integer', 'float', 'monetary') and info.get('aggregator'):
measures.append({
'name': name,
'string': info.get('string'),
'type': info.get('type'),
'aggregator': info.get('aggregator'),
})
return {
'summary': {'icon': 'sum', 'text': self.env._("Measures")},
'measures': measures,
}
# ==================================================================
# write operations (always preview first)
# ==================================================================
def _ai_tool_prepare_record_previews(self, model_name, record_ids, preview_label=None):
model = self._check_agent_model_access(model_name)
records = model.browse(record_ids if isinstance(record_ids, (list, tuple)) else [record_ids])
records.check_access('read')
existing = records.exists()
return {
'summary': {'icon': 'visibility', 'text': preview_label or self.env._("Preview")},
'records': [
{'id': record.id, 'name': record.display_name} for record in existing
],
'preview_links': [
{'label': record.display_name, 'model': model_name, 'id': record.id}
for record in existing
],
}
def _ai_tool_create_records(self, tool_context, explanation, preview_menu_id,
model_name, values):
if not tool_context.get('tool_request_confirmed'):
raise UserError(self.env._("Creating records requires user confirmation."))
if not model_name or not isinstance(model_name, str):
raise ValueError("'model_name' is required (the technical model name, "
"e.g. 'res.partner').")
if not values:
raise ValueError("'values' is required: a dict of field values.")
model = self._check_agent_model_access(model_name, 'create')
created = model.create(values if isinstance(values, list) else [values])
outcome = {
'summary': {'icon': 'add', 'text': self.env._("Created %s", model._description)},
'created': [{'id': record.id, 'name': record.display_name} for record in created],
'response': '\n'.join(
f'Created {model._description}: {record.display_name}' for record in created
),
}
outcome.update(self._open_after_write(
tool_context, model_name, created, preview_menu_id, explanation))
return outcome
def _open_after_write(self, tool_context, model_name, records, menu_id=None,
label=None):
"""Queue the browser action that shows what was just written.
Without this the transcript says "Created Sales Order" and the user is
left to hunt for the record in the menus.
The action is marked ``exclusive``: a turn that creates a contact, two
products and then a sales order queues four navigations, and replaying
them in order would flicker through every form and land on the last one
anyway. An exclusive entry replaces the previous exclusive ones, so the
user lands on the record the answer is about.
"""
if not records:
return {}
try:
params = self._build_record_action(
model_name, records.ids, menu_id=menu_id, label=label)
except (ValueError, AccessError) as exc:
# Opening a view is a convenience: never fail a successful write
# because the model has no action or the user cannot see it.
_logger.info("dn_ai: cannot open %s after write: %s", model_name, exc)
return {}
return {
'client_tool': {
'name': 'show_view', 'oneway': True, 'exclusive': True,
'params': params,
},
}
def _ai_tool_update_records(self, tool_context, explanation, preview_menus, updates):
if not tool_context.get('tool_request_confirmed'):
raise UserError(self.env._("Updating records requires user confirmation."))
if len(updates) > 50:
raise ValueError("At most 50 updates are allowed at once.")
done = []
touched = None
touched_model = None
for update in updates:
model_name = update['model_name']
model = self._check_agent_model_access(model_name, 'write')
domain = self._parse_domain(model_name, update.get('domain'), operation='write')
if not domain:
raise ValueError("You cannot update all records; pass a real domain.")
changes = {}
for item in update.get('changes') or []:
changes[item['field']] = item.get('value')
records = model.search(domain)
records.check_access('write')
records.write(changes)
done.append({'model': model_name, 'count': len(records)})
if records and touched_model is None:
# Remember the first batch: it is the one the explanation is
# about, so it is the one worth showing.
touched, touched_model = records, model_name
outcome = {
'summary': {'icon': 'edit', 'text': self.env._("Updated records")},
'updated': done,
'response': 'Updated: ' + json.dumps(done, ensure_ascii=False),
}
if touched is not None and len(touched) == 1:
# Only a single record has an obvious form to open; a bulk update
# would open an arbitrary member of the set.
outcome.update(self._open_after_write(
tool_context, touched_model, touched,
preview_menus[0] if preview_menus else None))
return outcome
# ==================================================================
# interaction
# ==================================================================
def _ai_tool_ask_user_question(self, tool_context, question, choices=None,
multi_select=False, allow_free_text=True):
normalised = []
for choice in choices or []:
if isinstance(choice, dict):
label = choice.get('label') or choice.get('value') or ''
value = choice.get('value') or label
else:
label = value = str(choice)
normalised.append({'label': label, 'value': value})
tool_context['user_input_request'] = {
'type': 'question',
'question': question,
'choices': normalised,
'multi_select': bool(multi_select),
'allow_free_text': bool(allow_free_text),
}
return {
'summary': {'icon': 'help', 'text': self.env._("Waiting for your answer")},
'response': 'Waiting for the user to answer.',
}
def _ai_tool_load_skills(self, tool_context, skill_ids):
from ..utils.ai_utils import get_text_from_parts # local import avoids cycle
skills = self.env['ai.skill'].browse(skill_ids).exists()
if not skills:
raise ValueError("No valid skill id provided.")
state = tool_context['state']
state['loaded_skills'] = list(dict.fromkeys(
(state.get('loaded_skills') or []) + skills.ids))
new_tools = skills.mapped('tool_ids').filtered('use_in_ai')
state['available_tools'] = list(dict.fromkeys(
(state.get('available_tools') or []) + new_tools.ids))
blocks = []
for skill in skills:
blocks.append(f"## {skill.name}\n{skill.instructions or ''}")
return {
'summary': {'icon': 'lightbulb', 'text': self.env._("Loaded skills")},
'response': "\n\n".join(blocks),
}