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

307 lines
12 KiB
Python

# -*- coding: utf-8 -*-
import json
import logging
import re
from odoo import api, fields, models
from odoo.exceptions import UserError, ValidationError
from ..utils.agent_instructions_prompts import AI_ACTIONS_PROMPT
from ..utils.ai_utils import format_tool_result, get_text_from_parts
_logger = logging.getLogger(__name__)
# Server action types that can safely be exposed to the model.
ALLOWED_STATES_FOR_AI = {
'code', 'next_activity', 'object_create', 'object_copy',
'followers', 'remove_followers', 'webhook', 'mail_post',
}
TOOL_NAME_RE = re.compile(r'[a-zA-Z0-9_]{1,64}')
class IrActionsServer(models.Model):
_inherit = "ir.actions.server"
# ---- AI action ---------------------------------------------------
state = fields.Selection(
selection_add=[("ai", "AI")],
ondelete={"ai": "cascade"},
)
ai_action_prompt = fields.Html(
string="AI Action Prompt",
help='Prompt used by the "AI" action type.',
sanitize=True,
sanitize_output_method="xml",
)
ai_tool_ids = fields.Many2many(
"ir.actions.server", "dn_ai_action_tool_rel", "parent_id", "tool_id",
string="Tools",
)
# ---- AI tool -----------------------------------------------------
ai_tool_name = fields.Char("AI Tool Name")
ai_tool_description = fields.Text("AI Tool Description", translate=True)
ai_tool_schema = fields.Text(
"AI Schema",
help="JSON Schema describing the arguments the model must provide.",
store=True,
readonly=False,
compute="_compute_use_in_ai",
)
use_in_ai = fields.Boolean(
"Use in AI", store=True, readonly=False, compute="_compute_use_in_ai",
)
ai_tool_is_candidate = fields.Boolean(compute="_compute_ai_tool_is_candidate")
ai_tool_has_schema = fields.Boolean(compute="_compute_ai_tool_has_schema")
ai_tool_thinking_text = fields.Char(
"AI Tool Thinking Text", translate=True,
help="Progress message shown while the tool runs.",
)
ai_tool_requires_confirmation = fields.Boolean(
"Requires confirmation",
help="Show a confirmation card before executing this tool.",
)
_ai_tool_name_unique = models.UniqueIndex(
"(ai_tool_name) WHERE use_in_ai IS TRUE",
"Two AI tools cannot share the same name.",
)
# ------------------------------------------------------------------
# computes / constraints
# ------------------------------------------------------------------
@api.depends("state")
def _compute_use_in_ai(self):
for action in self:
if not action.ai_tool_is_candidate:
action.use_in_ai = False
action.ai_tool_schema = False
@api.depends("state", "child_ids", "evaluation_type")
def _compute_ai_tool_is_candidate(self):
for action in self:
action.ai_tool_is_candidate = (
action.state in ALLOWED_STATES_FOR_AI
or (action.state == 'object_write' and action.evaluation_type in ('value', 'sequence'))
or (action.state == 'multi' and all(c.ai_tool_is_candidate for c in action.child_ids))
)
@api.depends("state", "child_ids")
def _compute_ai_tool_has_schema(self):
for action in self:
action.ai_tool_has_schema = (
action.state == 'code'
or (action.state == 'multi' and any(c.ai_tool_has_schema for c in action.child_ids))
)
@api.constrains("state", "use_in_ai")
def _check_use_in_ai(self):
for action in self:
if action.use_in_ai and not action.ai_tool_is_candidate:
raise ValidationError(
self.env._("The action '%s' cannot be used as an AI tool.", action.name))
@api.constrains("use_in_ai", "ai_tool_name")
def _check_ai_tool_name(self):
for action in self.filtered('use_in_ai'):
if not action.ai_tool_name:
raise ValidationError(self.env._(
"The action '%s' must have an AI Tool Name.", action.name))
if not TOOL_NAME_RE.fullmatch(action.ai_tool_name):
raise ValidationError(self.env._(
"The tool name may only contain letters, digits and underscores "
"(max 64 characters)."))
@api.constrains("ai_tool_schema")
def _check_ai_tool_schema(self):
for action in self:
if not action.ai_tool_schema:
continue
try:
data = json.loads(action.ai_tool_schema)
except ValueError:
raise ValidationError(self.env._("Invalid JSON schema (malformed JSON).")) from None
if not isinstance(data, dict):
raise ValidationError(self.env._("Invalid JSON schema (must be an object)."))
# ------------------------------------------------------------------
# execution
# ------------------------------------------------------------------
def _ai_tool_run(self, record, arguments, tools_context):
"""Execute this action as a tool call."""
self.ensure_one()
arguments = dict(arguments or {})
if self.ai_tool_schema:
try:
schema = json.loads(self.ai_tool_schema)
except ValueError:
schema = {}
arguments = self._ai_coerce_arguments(arguments, schema)
if self.ai_tool_requires_confirmation and self._ai_needs_confirmation(tools_context):
tools_context['user_input_request'] = {
'type': 'confirmation',
'body': self.ai_tool_thinking_text or self.env._(
'Should I run "%s"?', self.name),
'choices': [
{'label': self.env._("Yes, do it"), 'value': 'confirm_once'},
{'label': self.env._("Yes, always approve in this chat"), 'value': 'auto_confirm'},
{'label': self.env._("No, I want something else"), 'value': 'decline'},
],
'allow_free_text': False,
}
return {'summary': {'icon': 'help', 'text': self.env._("Waiting for your confirmation")},
'response': 'Waiting for the user to confirm.'}
model_name = self.model_id.model
record = record if record and record._name == model_name else self.env[model_name]
eval_context = arguments.copy()
eval_context |= self._get_eval_context(self)
eval_context['ai'] = tools_context or {}
eval_context['record'] = record.sudo(False)
eval_context['records'] = record.sudo(False)
eval_context['model'] = eval_context['model'].sudo(False)
eval_context['env'] = self.env(su=False)
if self.state == 'code':
eval_context = self._ai_fill_missing_names(eval_context)
self._run_action_code_multi(eval_context=eval_context)
if eval_context.get('action'):
raise UserError(self.env._(
'This action is interactive and cannot be executed by the agent.'))
return eval_context['ai'].get('result')
if self.state == 'multi':
result = None
for action in self.child_ids:
result = action._ai_tool_run(record, arguments, tools_context) or result
return result
if self.ai_tool_is_candidate:
self._run(record, eval_context)
return self._ai_get_action_description(record)
raise UserError(self.env._("This action cannot be executed by the AI."))
def _ai_needs_confirmation(self, tools_context):
return not tools_context.get('tool_request_confirmed')
def _ai_is_confirmed(self, tools_context):
return bool(tools_context.get('tool_request_confirmed'))
def _ai_get_action_description(self, record):
self.ensure_one()
if self.state == 'next_activity':
return self.env._('Activity created.')
return self.env._('Action "%(action)s" done.', action=self.name)
@api.model
def _ai_fill_missing_names(self, eval_context):
"""Define any bare name the action code reads but the schema omits.
Server-action code runs ``record._ai_tool_xxx(menu_id, ..., search)``
with the arguments injected as locals. A name the schema never declared
is therefore simply *undefined*, and the whole tool call dies with::
NameError: name 'search' is not defined
which the model then reports to the user as an opaque internal error.
Binding those names to ``None`` turns a hard failure into an argument the
tool can default, so a stale schema degrades instead of breaking.
"""
import ast
import builtins
code = self.code or ''
try:
tree = ast.parse(code.lstrip('\n'), mode='exec')
except SyntaxError:
return eval_context # let the regular runner report the real error
defined = set(eval_context) | set(dir(builtins))
loaded = {
node.id for node in ast.walk(tree)
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)
}
for name in loaded - defined:
eval_context[name] = None
return eval_context
def _ai_coerce_arguments(self, arguments, schema):
"""Coerce LLM strings to the declared types and fill optional args.
Server-action code interpolates arguments as local variables, so every
declared property must exist — otherwise a missing optional argument
would raise ``NameError`` inside the tool body.
"""
properties = schema.get('properties') or {}
for key, spec in properties.items():
if key not in arguments and spec.get('default') is not None:
arguments[key] = spec['default']
if key not in arguments:
arguments[key] = None
for key, value in list(arguments.items()):
spec = properties.get(key) or {}
expected = spec.get('type')
if isinstance(expected, list):
expected = expected[0] if expected else None
if expected == 'integer' and isinstance(value, str):
try:
arguments[key] = int(value)
except ValueError:
pass
elif expected == 'number' and isinstance(value, str):
try:
arguments[key] = float(value)
except ValueError:
pass
elif expected == 'boolean' and isinstance(value, str):
arguments[key] = value.strip().lower() in ('true', '1', 'yes')
elif expected == 'array' and isinstance(value, str):
try:
arguments[key] = json.loads(value)
except ValueError:
pass
return arguments
# ------------------------------------------------------------------
# "AI" action type: run the agent on a record
# ------------------------------------------------------------------
def _run_action_ai_multi(self, eval_context=None):
for record in self._ai_get_records(eval_context):
self._ai_action_run(record)
def _ai_get_records(self, eval_context):
if self.env.context.get('onchange_self'):
return self.env.context['onchange_self']
records = eval_context.get('record') or eval_context['model']
return records | (eval_context.get('records') or eval_context['model'])
def _ai_action_run(self, record):
self.ensure_one()
action_prompt = ''
if self.ai_action_prompt:
action_prompt = get_text_from_parts(
self.env['ir.qweb']._render('dn_ai.ai_action_prompt_text', {
'action': self, 'record': record}))
from datetime import UTC, datetime
now = datetime.now(UTC).astimezone().replace(second=0, microsecond=0).isoformat()
context_text = f"# Context\n## Current date\n{now}"
context_text += f'\n## Current record\n{{"model": "{record._name}", "id": {record.id}}}'
parts = [{'type': 'text', 'text': f"# Action request\n{action_prompt}\n{context_text}"}]
responses, history = self.env['ai.session']._get_direct_response(
instructions=AI_ACTIONS_PROMPT,
message=parts,
tools=self.ai_tool_ids.filtered('use_in_ai'),
record=record,
)
return responses, history
def action_open_ai_action(self):
"""Smart button helper: open the record form (placeholder)."""
self.ensure_one()
return True