push
This commit is contained in:
12
dn_ai/models/__init__.py
Normal file
12
dn_ai/models/__init__.py
Normal file
@@ -0,0 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import ai_provider
|
||||
from . import ai_agent
|
||||
from . import ai_skill
|
||||
from . import ai_tool
|
||||
from . import ai_session
|
||||
from . import ai_composer
|
||||
from . import ai_prompt_button
|
||||
from . import ir_actions_server
|
||||
from . import discuss_channel
|
||||
from . import ir_attachment
|
||||
from . import res_config_settings
|
||||
224
dn_ai/models/ai_agent.py
Normal file
224
dn_ai/models/ai_agent.py
Normal file
@@ -0,0 +1,224 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import AccessError, UserError
|
||||
|
||||
from ..utils.agent_instructions_prompts import (
|
||||
DEFAULT_SYSTEM_PROMPT,
|
||||
SKILLS_PROTOCOL,
|
||||
get_global_protocol,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AIAgent(models.Model):
|
||||
_name = 'ai.agent'
|
||||
_description = "AI Agent"
|
||||
_order = 'sequence, name'
|
||||
_inherit = ['mail.thread']
|
||||
|
||||
active = fields.Boolean(default=True)
|
||||
sequence = fields.Integer(
|
||||
default=10,
|
||||
help="Built-in agents ship with a sequence below 10 to be listed first.",
|
||||
)
|
||||
name = fields.Char(string="Agent Name", required=True)
|
||||
subtitle = fields.Char(string="Description")
|
||||
system_prompt = fields.Text(
|
||||
string="System Prompt",
|
||||
help="Customize to control relevance and formatting.",
|
||||
)
|
||||
image_128 = fields.Image("Image", max_width=128, max_height=128)
|
||||
partner_id = fields.Many2one(
|
||||
'res.partner', required=True, ondelete='cascade', index=True,
|
||||
help="Identity used by the agent when it posts messages in Discuss.",
|
||||
)
|
||||
is_system_agent = fields.Boolean('System Agent', default=False)
|
||||
skill_ids = fields.Many2many(
|
||||
'ai.skill', 'ai_agent_skill_rel', 'agent_id', 'skill_id', string="Skills",
|
||||
)
|
||||
restrict_to_sources = fields.Boolean(
|
||||
"Restrict to Sources",
|
||||
help="When enabled the agent only answers from its knowledge sources.",
|
||||
)
|
||||
embedding_model = fields.Char()
|
||||
allowed_agent_ids = fields.Many2many(
|
||||
'ai.agent', 'ai_agent_delegation_rel', 'parent_id', 'child_id',
|
||||
string="Allowed Agents",
|
||||
help="Agents this agent may delegate work to.",
|
||||
)
|
||||
|
||||
_agent_name_uniq = models.Constraint(
|
||||
'UNIQUE(name)', "An agent with this name already exists.",
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for vals in vals_list:
|
||||
if not vals.get('partner_id'):
|
||||
vals['partner_id'] = self.env['res.partner'].create({
|
||||
'name': vals.get('name') or self.env._("AI Assistant"),
|
||||
'is_company': False,
|
||||
}).id
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, vals):
|
||||
# Data files legitimately (re)assert is_system_agent / active during an
|
||||
# install or upgrade; only interactive writes are guarded.
|
||||
if not self.env.context.get('install_mode'):
|
||||
for agent in self:
|
||||
if agent.is_system_agent and set(vals) & {'active', 'is_system_agent'}:
|
||||
raise UserError(self.env._("The built-in agent cannot be archived."))
|
||||
if 'name' in vals:
|
||||
self.mapped('partner_id').sudo().write({'name': vals['name']})
|
||||
return super().write(vals)
|
||||
|
||||
def unlink(self):
|
||||
if not self.env.context.get('install_mode'):
|
||||
if any(agent.is_system_agent for agent in self):
|
||||
raise UserError(self.env._("The built-in agent cannot be deleted."))
|
||||
partners = self.mapped('partner_id')
|
||||
result = super().unlink()
|
||||
partners.sudo().unlink()
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# instructions
|
||||
# ------------------------------------------------------------------
|
||||
def _get_instructions(self, extra_instructions=None):
|
||||
"""Build the layered system prompt, same sectioning as enterprise."""
|
||||
self.ensure_one()
|
||||
|
||||
def section(name, content):
|
||||
content = (content or '').strip()
|
||||
if not content:
|
||||
return ''
|
||||
return f"<{name}>\n{content}\n</{name}>\n\n"
|
||||
|
||||
instructions = "[[START OF INSTRUCTIONS]]\n\n"
|
||||
instructions += section('global_protocol', get_global_protocol(
|
||||
self.env.context.get('debug'), self.env.tz))
|
||||
instructions += section('agent_protocol', self.system_prompt or DEFAULT_SYSTEM_PROMPT)
|
||||
if extra_instructions:
|
||||
instructions += section('usage_context', extra_instructions)
|
||||
|
||||
skills = self.skill_ids
|
||||
if skills:
|
||||
instructions += section('skills_protocol', SKILLS_PROTOCOL)
|
||||
instructions += section(
|
||||
'available_skills',
|
||||
"\n".join(
|
||||
f'<skill id="{skill.id}" name="{skill.name}" type="{skill.type}">{skill.description or ""}</skill>'
|
||||
for skill in skills
|
||||
),
|
||||
)
|
||||
instructions += "[[END OF INSTRUCTIONS]]"
|
||||
return instructions
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# tools & skills
|
||||
# ------------------------------------------------------------------
|
||||
def _get_default_tools(self):
|
||||
"""Tools always available, regardless of the loaded skills."""
|
||||
self.ensure_one()
|
||||
tools = self.env['ir.actions.server']
|
||||
for xmlid in DEFAULT_TOOL_XMLIDS:
|
||||
if tool := self.env.ref(xmlid, raise_if_not_found=False):
|
||||
tools |= tool
|
||||
return tools
|
||||
|
||||
def _get_available_skills(self):
|
||||
self.ensure_one()
|
||||
return self.skill_ids
|
||||
|
||||
def _get_usage_string(self):
|
||||
self.ensure_one()
|
||||
meta = self.get_metadata()[0] if self.get_metadata() else {}
|
||||
return f"agent:{meta.get('xmlid') or 'custom'}"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# discuss store
|
||||
# ------------------------------------------------------------------
|
||||
def _store_agent_fields(self, res):
|
||||
"""Fields exposed to the Discuss store for an AI chat's agent.
|
||||
|
||||
Referenced by name from ``discuss.channel._store_channel_fields``
|
||||
(``res.one("ai_agent_id", "_store_agent_fields", ...)``), so it must be
|
||||
defined on this model.
|
||||
"""
|
||||
res.attr("name")
|
||||
res.attr("subtitle")
|
||||
res.attr("image_128", predicate=lambda agent: bool(agent.image_128))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# chat entry points
|
||||
# ------------------------------------------------------------------
|
||||
def _is_user_access_allowed(self):
|
||||
self.ensure_one()
|
||||
return self.env.user._is_internal()
|
||||
|
||||
def action_launch_ai_chat(self):
|
||||
"""Open (or reuse) the AI chat conversation for this agent."""
|
||||
self.ensure_one()
|
||||
if not self._is_user_access_allowed():
|
||||
raise AccessError(self.env._("You are not allowed to chat with this agent."))
|
||||
channel = self.env['ai.session']._get_or_create_chat_channel(self)
|
||||
return {
|
||||
'type': 'ir.actions.client',
|
||||
'tag': 'dn_ai.chat',
|
||||
'params': {'channel_id': channel.id},
|
||||
'name': self.env._("AI Chat"),
|
||||
}
|
||||
|
||||
@api.model
|
||||
def dn_ai_get_default_channel(self):
|
||||
"""Resolve (creating it on first use) the default agent's chat channel."""
|
||||
# sudo: the built-in agent is a system resource; a plain internal user
|
||||
# may not be allowed to search ai.agent.
|
||||
agent = self.sudo().search([('is_system_agent', '=', True)], limit=1)
|
||||
if not agent:
|
||||
agent = self.sudo().search([], limit=1)
|
||||
if not agent:
|
||||
raise UserError(self.env._(
|
||||
"No AI agent is configured. Create one in the AI application first."
|
||||
))
|
||||
if not agent._is_user_access_allowed():
|
||||
raise AccessError(self.env._("You are not allowed to chat with this agent."))
|
||||
channel = self.env['ai.session']._get_or_create_chat_channel(agent)
|
||||
session = self.env['ai.session'].sudo()._get_channel_session(channel)
|
||||
return {
|
||||
'channel_id': channel.id,
|
||||
'agent_id': agent.id,
|
||||
'agent_name': agent.name,
|
||||
'session_id': session.id if session else False,
|
||||
}
|
||||
|
||||
def _generate_single_response(self, message_parts, extra_instructions=None, schema=None):
|
||||
"""One-shot completion using this agent's configuration."""
|
||||
self.ensure_one()
|
||||
return self.env['ai.session']._get_direct_response(
|
||||
instructions=self._get_instructions(extra_instructions),
|
||||
message=message_parts,
|
||||
tools=self._get_default_tools(),
|
||||
agent_id=self.id,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_TOOL_XMLIDS = (
|
||||
'dn_ai.ir_actions_server_get_models',
|
||||
'dn_ai.ir_actions_server_get_menus',
|
||||
'dn_ai.ir_actions_server_get_menu_details',
|
||||
'dn_ai.ir_actions_server_get_fields',
|
||||
'dn_ai.ir_actions_server_search',
|
||||
'dn_ai.ir_actions_server_read_group',
|
||||
'dn_ai.ir_actions_server_compute_date',
|
||||
'dn_ai.ir_actions_server_load_skills',
|
||||
'dn_ai.ir_actions_server_ask_user_question',
|
||||
'dn_ai.ir_actions_server_preview_records',
|
||||
)
|
||||
65
dn_ai/models/ai_composer.py
Normal file
65
dn_ai/models/ai_composer.py
Normal file
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
|
||||
INTERFACE_KEYS = [
|
||||
('chatter_ai_button', "Chatter AI button"),
|
||||
('systray_ai_button', "Systray AI button"),
|
||||
('html_field_ai', "HTML field assistant"),
|
||||
('email_composer_ai', "Email composer assistant"),
|
||||
('chatter_summarize', "Chatter summarize"),
|
||||
]
|
||||
|
||||
|
||||
class AIComposer(models.Model):
|
||||
_name = 'ai.composer'
|
||||
_description = "AI Composer"
|
||||
_explanation = (
|
||||
"Maps a UI entry point (a button, a field widget) to an agent plus a "
|
||||
"default context prompt."
|
||||
)
|
||||
|
||||
name = fields.Char(required=True, translate=True)
|
||||
active = fields.Boolean(default=True)
|
||||
interface_key = fields.Selection(selection=INTERFACE_KEYS, string="Action", required=True)
|
||||
focused_model_id = fields.Many2one('ir.model', string="Model", ondelete='cascade')
|
||||
ai_agent_id = fields.Many2one('ai.agent', string="Agent", required=True)
|
||||
default_prompt = fields.Text("Context", translate=True)
|
||||
is_system_default = fields.Boolean(
|
||||
'System default', default=False, readonly=True, copy=False)
|
||||
available_prompt_ids = fields.One2many(
|
||||
'ai.prompt.button', 'composer_id', string="Suggested prompts")
|
||||
|
||||
_composer_uniq = models.Constraint(
|
||||
'UNIQUE(interface_key, focused_model_id)',
|
||||
"A composer already exists for this action and model.",
|
||||
)
|
||||
|
||||
@api.model
|
||||
def _get_composer(self, interface_key, res_model=None):
|
||||
"""Find the most specific composer for an entry point."""
|
||||
domain = [('interface_key', '=', interface_key), ('active', '=', True)]
|
||||
if res_model:
|
||||
model = self.env['ir.model']._get(res_model)
|
||||
composer = self.search(domain + [('focused_model_id', '=', model.id)], limit=1)
|
||||
if composer:
|
||||
return composer
|
||||
return self.search(domain + [('focused_model_id', '=', False)], limit=1)
|
||||
|
||||
@api.model
|
||||
def _get_agent(self, res_model=None, interface_key=None):
|
||||
composer = self._get_composer(interface_key or 'chatter_ai_button', res_model)
|
||||
return composer.ai_agent_id or self.env.ref('dn_ai.ai_default_agent', raise_if_not_found=False)
|
||||
|
||||
def _get_initial_context(self, res_model=None, res_id=None):
|
||||
self.ensure_one()
|
||||
parts = []
|
||||
if self.default_prompt:
|
||||
parts.append(self.default_prompt)
|
||||
if res_model and res_id:
|
||||
record = self.env[res_model].browse(res_id).exists()
|
||||
if record:
|
||||
parts.append(self.env['ir.qweb']._render(
|
||||
'dn_ai.ai_record_context',
|
||||
{'record': record},
|
||||
))
|
||||
return '\n'.join(str(part) for part in parts if part)
|
||||
44
dn_ai/models/ai_prompt_button.py
Normal file
44
dn_ai/models/ai_prompt_button.py
Normal file
@@ -0,0 +1,44 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class AIPromptButton(models.Model):
|
||||
_name = "ai.prompt.button"
|
||||
_inherit = ["mail.render.mixin"]
|
||||
_description = "Suggested prompt shown above the chat input"
|
||||
_order = 'sequence, id'
|
||||
|
||||
name = fields.Char(required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
prompt = fields.Html(
|
||||
required=True, translate=True,
|
||||
help="Prompt sent to the agent. QWeb expressions such as "
|
||||
"{{object.name}} are rendered against the record.",
|
||||
)
|
||||
composer_id = fields.Many2one("ai.composer", index='btree_not_null', ondelete='cascade')
|
||||
|
||||
def _compute_render_model(self):
|
||||
for button in self:
|
||||
button.render_model = (button.composer_id.focused_model_id.model
|
||||
or 'res.partner')
|
||||
|
||||
def _render_prompt(self, rendering_record_id=None):
|
||||
"""Return the prompt as an AI message part list."""
|
||||
self.ensure_one()
|
||||
model = self.render_model
|
||||
body = self.prompt or ''
|
||||
if rendering_record_id and model and model in self.env:
|
||||
record = self.env[model].browse(rendering_record_id).exists()
|
||||
if record:
|
||||
body = self.env['ir.qweb']._render(
|
||||
'dn_ai.ai_prompt_button_render',
|
||||
{'button': self, 'record': record},
|
||||
)
|
||||
text = self.env['mail.render.mixin']._render_template(
|
||||
body, model or 'res.partner',
|
||||
[rendering_record_id] if rendering_record_id else [],
|
||||
engine='inline_template',
|
||||
) if rendering_record_id else body
|
||||
if isinstance(text, dict):
|
||||
text = next(iter(text.values()), '')
|
||||
return [{'type': 'text', 'text': str(text)}]
|
||||
128
dn_ai/models/ai_provider.py
Normal file
128
dn_ai/models/ai_provider.py
Normal file
@@ -0,0 +1,128 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Read / write the LLM provider configuration.
|
||||
|
||||
All settings live in ``ir.config_parameter`` so they can be changed without a
|
||||
module upgrade, and so other modules can override them per company later.
|
||||
"""
|
||||
import logging
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
from ..utils.openai_client import PROVIDER_PRESETS
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
PARAM_PROVIDER = 'dn_ai.provider'
|
||||
PARAM_BASE_URL = 'dn_ai.base_url'
|
||||
PARAM_API_KEY = 'dn_ai.api_key'
|
||||
PARAM_MODEL = 'dn_ai.model'
|
||||
PARAM_TEMPERATURE = 'dn_ai.temperature'
|
||||
PARAM_MAX_TOKENS = 'dn_ai.max_tokens'
|
||||
PARAM_EMB_BASE_URL = 'dn_ai.embedding_base_url'
|
||||
PARAM_EMB_API_KEY = 'dn_ai.embedding_api_key'
|
||||
PARAM_EMB_MODEL = 'dn_ai.embedding_model'
|
||||
PARAM_MAX_ROUNDS = 'dn_ai.max_rounds'
|
||||
PARAM_MAX_TOOLS_PER_CALL = 'dn_ai.max_tools_per_call'
|
||||
PARAM_TIMEOUT = 'dn_ai.timeout'
|
||||
PARAM_VISION = 'dn_ai.vision'
|
||||
|
||||
DEFAULT_MAX_ROUNDS = 20
|
||||
DEFAULT_MAX_TOOLS_PER_CALL = 20
|
||||
DEFAULT_TIMEOUT = 120
|
||||
|
||||
|
||||
class DNaiProvider(models.AbstractModel):
|
||||
"""Stateless helper exposing the resolved provider configuration."""
|
||||
_name = 'dn.ai.provider'
|
||||
_description = 'DN AI Provider Configuration'
|
||||
|
||||
@api.model
|
||||
def _params(self):
|
||||
return self.env['ir.config_parameter'].sudo()
|
||||
|
||||
@api.model
|
||||
def get_provider(self):
|
||||
return self._params().get_str(PARAM_PROVIDER) or 'deepseek'
|
||||
|
||||
@api.model
|
||||
def get_preset(self, provider=None):
|
||||
provider = provider or self.get_provider()
|
||||
return PROVIDER_PRESETS.get(provider) or PROVIDER_PRESETS['custom']
|
||||
|
||||
@api.model
|
||||
def get_config(self):
|
||||
"""Resolved chat configuration for the current company."""
|
||||
params = self._params()
|
||||
preset = self.get_preset()
|
||||
base_url = params.get_str(PARAM_BASE_URL) or preset['base_url']
|
||||
model = params.get_str(PARAM_MODEL) or preset['model']
|
||||
# `res.config.settings` stores 0 for a cleared float/integer field, so
|
||||
# treat 0 as "not set" rather than "temperature 0".
|
||||
temperature = params.get_float(PARAM_TEMPERATURE, 0.0) or None
|
||||
max_tokens = params.get_int(PARAM_MAX_TOKENS, 0) or None
|
||||
timeout = params.get_int(PARAM_TIMEOUT, 0) or DEFAULT_TIMEOUT
|
||||
return {
|
||||
'provider': self.get_provider(),
|
||||
'base_url': base_url,
|
||||
'api_key': params.get_str(PARAM_API_KEY),
|
||||
'model': model,
|
||||
'temperature': temperature,
|
||||
'max_tokens': max_tokens,
|
||||
'timeout': timeout,
|
||||
'vision': self.get_vision(),
|
||||
'file_api': bool(preset.get('file_api')),
|
||||
}
|
||||
|
||||
@api.model
|
||||
def get_vision(self):
|
||||
"""Whether uploaded images/PDFs may be sent as multimodal content.
|
||||
|
||||
Tri-state on purpose: an unset parameter falls back to the provider
|
||||
preset, so switching to a text-only provider (DeepSeek, a custom
|
||||
endpoint) stops sending image blocks that would be rejected with an
|
||||
HTTP 400 — while still letting the admin override it per installation.
|
||||
"""
|
||||
raw = self._params().get_str(PARAM_VISION)
|
||||
if raw in ('true', 'false'):
|
||||
return raw == 'true'
|
||||
return bool(self.get_preset().get('vision'))
|
||||
|
||||
@api.model
|
||||
def get_embedding_config(self):
|
||||
params = self._params()
|
||||
preset = self.get_preset()
|
||||
chat = self.get_config()
|
||||
return {
|
||||
'base_url': params.get_str(PARAM_EMB_BASE_URL) or chat['base_url'],
|
||||
'api_key': params.get_str(PARAM_EMB_API_KEY) or chat['api_key'],
|
||||
'embedding_model': params.get_str(PARAM_EMB_MODEL) or preset['embedding_model'],
|
||||
}
|
||||
|
||||
@api.model
|
||||
def is_configured(self):
|
||||
cfg = self.get_config()
|
||||
return bool(cfg['base_url'] and cfg['model'] and cfg['api_key'])
|
||||
|
||||
@api.model
|
||||
def get_max_rounds(self):
|
||||
return self._params().get_int(PARAM_MAX_ROUNDS) or DEFAULT_MAX_ROUNDS
|
||||
|
||||
@api.model
|
||||
def get_max_tools_per_call(self):
|
||||
return self._params().get_int(PARAM_MAX_TOOLS_PER_CALL) or DEFAULT_MAX_TOOLS_PER_CALL
|
||||
|
||||
@api.model
|
||||
def action_test_connection(self):
|
||||
"""Called from the settings page; returns a notification action."""
|
||||
from ..utils.openai_client import probe
|
||||
ok, message = probe(self.get_config())
|
||||
return {
|
||||
'type': 'ir.actions.client',
|
||||
'tag': 'display_notification',
|
||||
'params': {
|
||||
'title': self.env._("Connection successful") if ok else self.env._("Connection failed"),
|
||||
'message': message,
|
||||
'type': 'success' if ok else 'danger',
|
||||
'sticky': not ok,
|
||||
},
|
||||
}
|
||||
1040
dn_ai/models/ai_session.py
Normal file
1040
dn_ai/models/ai_session.py
Normal file
File diff suppressed because it is too large
Load Diff
71
dn_ai/models/ai_skill.py
Normal file
71
dn_ai/models/ai_skill.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class AISkill(models.Model):
|
||||
_name = 'ai.skill'
|
||||
_description = "AI Skill"
|
||||
_explanation = (
|
||||
"A skill bundles instructions and tools so the assistant can handle a "
|
||||
"specific kind of task."
|
||||
)
|
||||
_order = 'sequence, name'
|
||||
|
||||
name = fields.Char(string="Title", required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
description = fields.Text(
|
||||
string="Description", translate=True,
|
||||
help="Shown to the model to decide whether this skill is relevant.",
|
||||
)
|
||||
instructions = fields.Text(
|
||||
string="Instructions", translate=True,
|
||||
help="Injected in full once the skill is loaded.",
|
||||
)
|
||||
tool_ids = fields.Many2many(
|
||||
'ir.actions.server', 'ai_skill_tool_rel', 'skill_id', 'tool_id',
|
||||
string="AI Tools",
|
||||
domain="[('use_in_ai', '=', True)]",
|
||||
groups='base.group_system',
|
||||
)
|
||||
type = fields.Char(string="Type", compute="_compute_type")
|
||||
is_native_skill = fields.Boolean(
|
||||
default=False, readonly=True, copy=False,
|
||||
help="Built-in skill with fixed behavior that cannot be edited.",
|
||||
)
|
||||
|
||||
_skill_name_uniq = models.Constraint(
|
||||
'UNIQUE(name)', "A skill with this title already exists.",
|
||||
)
|
||||
|
||||
@api.depends('tool_ids')
|
||||
def _compute_type(self):
|
||||
for skill in self:
|
||||
skill.type = 'executable' if skill.tool_ids else 'guidance'
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
return super().create(vals_list)
|
||||
|
||||
def _is_install_mode(self):
|
||||
"""Data files are allowed to (re)write built-in skills when installing
|
||||
or upgrading the module; the UI is not."""
|
||||
return bool(self.env.context.get('install_mode'))
|
||||
|
||||
def write(self, vals):
|
||||
if (not self._is_install_mode()
|
||||
and set(vals) & {'name', 'instructions', 'tool_ids'}
|
||||
and any(skill.is_native_skill for skill in self)):
|
||||
raise UserError(self.env._(
|
||||
"Built-in skills cannot be modified. Duplicate the skill to customize it."
|
||||
))
|
||||
return super().write(vals)
|
||||
|
||||
def unlink(self):
|
||||
if not self._is_install_mode() and any(skill.is_native_skill for skill in self):
|
||||
raise UserError(self.env._("Built-in skills cannot be deleted."))
|
||||
return super().unlink()
|
||||
|
||||
def _get_instructions(self):
|
||||
self.ensure_one()
|
||||
return (self.instructions or '').strip()
|
||||
712
dn_ai/models/ai_tool.py
Normal file
712
dn_ai/models/ai_tool.py
Normal file
@@ -0,0 +1,712 @@
|
||||
# -*- 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),
|
||||
}
|
||||
174
dn_ai/models/discuss_channel.py
Normal file
174
dn_ai/models/discuss_channel.py
Normal file
@@ -0,0 +1,174 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from datetime import timedelta
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
from odoo.addons.mail.tools.discuss import Store
|
||||
|
||||
|
||||
class DiscussChannel(models.Model):
|
||||
"""Make Discuss aware of AI conversations."""
|
||||
_inherit = "discuss.channel"
|
||||
|
||||
channel_type = fields.Selection(
|
||||
selection_add=[("ai_chat", "AI chat")],
|
||||
ondelete={"ai_chat": "cascade"},
|
||||
)
|
||||
ai_agent_id = fields.Many2one(
|
||||
"ai.agent", index="btree_not_null", groups=fields.NO_ACCESS,
|
||||
help="Agent driving this conversation. Only written by controlled flows.",
|
||||
)
|
||||
ai_session_ids = fields.One2many('ai.session', inverse_name='channel_id')
|
||||
|
||||
_ai_channel_type_check = models.Constraint(
|
||||
"CHECK(ai_agent_id IS NULL OR channel_type = 'ai_chat')",
|
||||
'An AI agent can only be attached to an AI chat.',
|
||||
)
|
||||
|
||||
def _compute_display_name(self):
|
||||
super()._compute_display_name()
|
||||
for channel in self:
|
||||
# The conversation is named after its agent, so renaming the agent
|
||||
# renames the chat; the stored `name` is only there because the
|
||||
# column is NOT NULL.
|
||||
if channel.channel_type == 'ai_chat':
|
||||
agent = channel.sudo().ai_agent_id
|
||||
if agent:
|
||||
channel.display_name = agent.name
|
||||
|
||||
@api.depends("channel_type", "image_128", "ai_agent_id.partner_id.avatar_128")
|
||||
def _compute_avatar_128(self):
|
||||
base_channels = self.env['discuss.channel']
|
||||
for channel in self:
|
||||
if (channel.channel_type == 'ai_chat' and not channel.image_128
|
||||
and (agent := channel.sudo().ai_agent_id)):
|
||||
channel.avatar_128 = agent.partner_id.avatar_128
|
||||
else:
|
||||
base_channels |= channel
|
||||
super(DiscussChannel, base_channels)._compute_avatar_128()
|
||||
|
||||
@api.autovacuum
|
||||
def _remove_ai_chat_channels(self):
|
||||
self.sudo().search([
|
||||
('channel_type', '=', 'ai_chat'),
|
||||
('has_message', '=', False),
|
||||
('create_date', '<', fields.Datetime.now() - timedelta(days=2)),
|
||||
]).unlink()
|
||||
|
||||
def _store_channel_fields(self, res: Store.FieldList):
|
||||
super()._store_channel_fields(res)
|
||||
res.one("ai_agent_id", "_store_agent_fields", sudo=True,
|
||||
predicate=lambda c: c.channel_type == 'ai_chat')
|
||||
res.attr("create_date", predicate=lambda c: c.channel_type == 'ai_chat')
|
||||
# The confirmation / question card has to be rendered by the chat
|
||||
# window itself: the choices are interactive, and a stored message body
|
||||
# cannot carry working buttons (it is sanitised on the way in).
|
||||
res.attr("dn_ai_pending", predicate=lambda c: c.channel_type == 'ai_chat')
|
||||
|
||||
dn_ai_pending = fields.Json(
|
||||
"Pending AI interaction",
|
||||
compute="_compute_dn_ai_pending",
|
||||
help="Confirmation or question the agent is waiting for, surfaced to "
|
||||
"the chat window so it can render clickable choices.",
|
||||
)
|
||||
|
||||
@api.depends("channel_type", "ai_session_ids.loop_state",
|
||||
"ai_session_ids.pending_tool_call", "ai_session_ids.parent_session_id")
|
||||
def _compute_dn_ai_pending(self):
|
||||
sessions = self.env['ai.session'].sudo().search([
|
||||
('channel_id', 'in', self.ids),
|
||||
('parent_session_id', '=', False),
|
||||
])
|
||||
by_channel = {session.channel_id.id: session for session in sessions}
|
||||
for channel in self:
|
||||
session = by_channel.get(channel.id)
|
||||
if channel.channel_type != 'ai_chat' or not session:
|
||||
channel.dn_ai_pending = False
|
||||
continue
|
||||
request = (session.pending_tool_call or {}).get('request') or {}
|
||||
if not request or session.loop_state not in (
|
||||
'waiting_confirmation', 'waiting_answer',
|
||||
):
|
||||
channel.dn_ai_pending = False
|
||||
continue
|
||||
channel.dn_ai_pending = {
|
||||
'session_id': session.id,
|
||||
'type': 'question' if request.get('type') == 'question' else 'confirmation',
|
||||
'body': request.get('body') or request.get('question') or '',
|
||||
'choices': request.get('choices') or [],
|
||||
'multi_select': bool(request.get('multi_select')),
|
||||
'allow_free_text': request.get('allow_free_text', True),
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# RPC used by the standalone chat panel (static/src/chat.js)
|
||||
# ------------------------------------------------------------------
|
||||
def dn_ai_fetch_messages(self, limit=60):
|
||||
"""Return the transcript plus the pending interaction, if any.
|
||||
|
||||
Kept as a plain server call so the chat panel does not need to know
|
||||
anything about the mail store / websocket protocol.
|
||||
"""
|
||||
self.ensure_one()
|
||||
self.check_access('read')
|
||||
if self.channel_type != 'ai_chat':
|
||||
raise UserError(self.env._("This conversation is not an AI chat."))
|
||||
session = self.env['ai.session'].sudo()._get_channel_session(self)
|
||||
agent = session.agent_id if session else self.sudo().ai_agent_id
|
||||
agent_partner = agent.partner_id
|
||||
|
||||
messages = []
|
||||
for message in self.sudo().message_ids.sorted('id')[-limit:]:
|
||||
author = message.author_id
|
||||
body = message.body or ''
|
||||
messages.append({
|
||||
'id': message.id,
|
||||
'body': body,
|
||||
# A tool summary is one line of progress ("搜索 Contact"),
|
||||
# posted as its own message by the loop. Flagging it lets the
|
||||
# panel fold consecutive steps into a single collapsible
|
||||
# timeline instead of a wall of speech bubbles that buries the
|
||||
# actual answer.
|
||||
'is_step': 'o_ai_tool_summary' in body,
|
||||
'author_name': author.name or self.env._('System'),
|
||||
'is_agent': bool(agent_partner and author == agent_partner),
|
||||
'date': fields.Datetime.to_string(message.date),
|
||||
# The panel renders its own bubble instead of the mail chatter,
|
||||
# so the attachment cards have to travel with the message.
|
||||
'attachments': [
|
||||
{
|
||||
'id': attachment.id,
|
||||
'name': attachment.name,
|
||||
'mimetype': attachment.mimetype or '',
|
||||
'size': attachment.file_size or 0,
|
||||
# Internal users read their own uploads through the
|
||||
# regular ACL, no access token needed.
|
||||
'url': f"/web/content/{attachment.id}?download=true",
|
||||
'is_image': (attachment.mimetype or '').startswith('image/'),
|
||||
}
|
||||
for attachment in message.attachment_ids.sudo()
|
||||
],
|
||||
})
|
||||
|
||||
pending = False
|
||||
if session:
|
||||
request = (session.pending_tool_call or {}).get('request') or {}
|
||||
if request and session.loop_state in (
|
||||
'waiting_confirmation', 'waiting_answer',
|
||||
):
|
||||
pending = {
|
||||
'type': 'question' if request.get('type') == 'question' else 'confirmation',
|
||||
'body': request.get('body') or request.get('question') or '',
|
||||
'choices': request.get('choices') or [],
|
||||
'multi_select': bool(request.get('multi_select')),
|
||||
'allow_free_text': request.get('allow_free_text', True),
|
||||
}
|
||||
|
||||
return {
|
||||
'messages': messages,
|
||||
'agent_name': (agent.name if agent else '') or '',
|
||||
'session_id': session.id if session else False,
|
||||
'pending': pending,
|
||||
'loop_state': session.loop_state if session else False,
|
||||
}
|
||||
|
||||
306
dn_ai/models/ir_actions_server.py
Normal file
306
dn_ai/models/ir_actions_server.py
Normal file
@@ -0,0 +1,306 @@
|
||||
# -*- 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
|
||||
84
dn_ai/models/ir_attachment.py
Normal file
84
dn_ai/models/ir_attachment.py
Normal file
@@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import base64
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
from ..utils.ai_attachment_tools import build_parts, format_size
|
||||
|
||||
DEFAULT_MAX_TEXT_CHARS = 40000
|
||||
|
||||
|
||||
class IrAttachment(models.Model):
|
||||
"""Teach ``ir.attachment`` how to feed a file to the language model.
|
||||
|
||||
Mirrors the Enterprise assistant: an attachment is turned into message
|
||||
parts (``text`` or ``inline_data``) which are then sent as the user turn.
|
||||
The chat panel and the composer share this code path, so any surface that
|
||||
collects attachments behaves the same.
|
||||
"""
|
||||
_inherit = 'ir.attachment'
|
||||
|
||||
@api.model
|
||||
def _dn_ai_max_text_chars(self):
|
||||
char = self.env['ir.config_parameter'].sudo().get_int(
|
||||
'dn_ai.attachment_max_chars', 0)
|
||||
return char or DEFAULT_MAX_TEXT_CHARS
|
||||
|
||||
def _dn_ai_read(self):
|
||||
"""Return a flat list of message parts for ``self``.
|
||||
|
||||
The files are read with ``sudo``: the assistant already runs on behalf
|
||||
of the user and the attachment was access-checked when it was uploaded.
|
||||
Refusing here would only break the very turn the user just started.
|
||||
"""
|
||||
parts = []
|
||||
max_chars = self._dn_ai_max_text_chars()
|
||||
for attachment in self.sudo():
|
||||
name = attachment.name or 'file'
|
||||
try:
|
||||
data = attachment._dn_ai_raw_bytes()
|
||||
except (ValueError, OSError, FileNotFoundError) as exc:
|
||||
parts.append({
|
||||
'type': 'text',
|
||||
'text': f"File '{name}' could not be read: {exc}",
|
||||
})
|
||||
continue
|
||||
parts.extend(build_parts(
|
||||
name, attachment.mimetype or '', data, max_text_chars=max_chars))
|
||||
return parts
|
||||
|
||||
def _dn_ai_raw_bytes(self):
|
||||
"""Return the file content as ``bytes``, whichever Odoo version runs.
|
||||
|
||||
``ir.attachment.raw`` changed shape between versions:
|
||||
|
||||
* 17.0 — a plain ``fields.Binary``, so reading it yields ``bytes``;
|
||||
* 18.0+ — a lazy ``BinaryValue`` wrapper, where the payload is reached
|
||||
through ``.content``.
|
||||
|
||||
Reading ``.content`` unconditionally is what made every PDF upload fail
|
||||
on 17 with ``'bytes' object has no attribute 'content'``; reading
|
||||
``.raw`` unconditionally would return the wrapper object on 18+. The
|
||||
value is coerced here instead of at each call site so both work.
|
||||
"""
|
||||
self.ensure_one()
|
||||
raw = self.raw
|
||||
if not raw:
|
||||
return b''
|
||||
# 18.0+ wrapper: the bytes live behind `.content`.
|
||||
content = getattr(raw, 'content', None)
|
||||
if isinstance(content, (bytes, bytearray)):
|
||||
return bytes(content)
|
||||
if isinstance(raw, (bytes, bytearray)):
|
||||
return bytes(raw)
|
||||
if isinstance(raw, str):
|
||||
# A Binary field can hand back base64 text in some flows.
|
||||
return base64.b64decode(raw)
|
||||
raise ValueError(f"Unexpected attachment payload type: {type(raw).__name__}")
|
||||
|
||||
def _dn_ai_summary(self):
|
||||
"""Short human description used in the chat transcript."""
|
||||
return ', '.join(
|
||||
f"{attachment.name} ({format_size(attachment.file_size or 0)})"
|
||||
for attachment in self
|
||||
)
|
||||
95
dn_ai/models/res_config_settings.py
Normal file
95
dn_ai/models/res_config_settings.py
Normal file
@@ -0,0 +1,95 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
|
||||
from ..utils.openai_client import PROVIDER_PRESETS
|
||||
|
||||
PROVIDER_SELECTION = [(key, preset['label']) for key, preset in PROVIDER_PRESETS.items()]
|
||||
|
||||
|
||||
class ResConfigSettings(models.TransientModel):
|
||||
_inherit = 'res.config.settings'
|
||||
|
||||
dn_ai_provider = fields.Selection(
|
||||
PROVIDER_SELECTION, string="AI Provider", default='deepseek',
|
||||
config_parameter='dn_ai.provider',
|
||||
)
|
||||
dn_ai_base_url = fields.Char(
|
||||
string="API Base URL", config_parameter='dn_ai.base_url',
|
||||
help="Leave empty to use the default endpoint of the selected provider.",
|
||||
)
|
||||
dn_ai_api_key = fields.Char(
|
||||
string="API Key", config_parameter='dn_ai.api_key',
|
||||
help="Stored in a system parameter; never shown to non-admin users.",
|
||||
)
|
||||
dn_ai_model = fields.Char(
|
||||
string="Model", config_parameter='dn_ai.model',
|
||||
help="e.g. deepseek-chat, qwen-plus, gpt-4o-mini.",
|
||||
)
|
||||
dn_ai_temperature = fields.Float(
|
||||
string="Temperature", config_parameter='dn_ai.temperature',
|
||||
help="Leave empty for the provider default.",
|
||||
)
|
||||
dn_ai_max_tokens = fields.Integer(
|
||||
string="Max Tokens", config_parameter='dn_ai.max_tokens',
|
||||
)
|
||||
dn_ai_embedding_model = fields.Char(
|
||||
string="Embedding Model", config_parameter='dn_ai.embedding_model',
|
||||
help="Required for knowledge sources (RAG).",
|
||||
)
|
||||
dn_ai_max_rounds = fields.Integer(
|
||||
string="Max Tool Rounds", config_parameter='dn_ai.max_rounds', default=20,
|
||||
)
|
||||
dn_ai_max_tools_per_call = fields.Integer(
|
||||
string="Max Tools per Round", config_parameter='dn_ai.max_tools_per_call', default=20,
|
||||
)
|
||||
dn_ai_timeout = fields.Integer(
|
||||
string="Request Timeout (s)", config_parameter='dn_ai.timeout', default=120,
|
||||
)
|
||||
dn_ai_vision = fields.Selection(
|
||||
[('true', "Yes"), ('false', "No")],
|
||||
string="Send Images to the Model",
|
||||
config_parameter='dn_ai.vision',
|
||||
help="When enabled, uploaded images and PDFs are sent to the provider "
|
||||
"as multimodal content (or uploaded through its Files API). Turn "
|
||||
"it off for text-only endpoints: PDFs are then read locally and "
|
||||
"sent as text instead. Leave empty to follow the provider default.",
|
||||
)
|
||||
dn_ai_attachment_max_chars = fields.Integer(
|
||||
string="Attachment Text Limit", config_parameter='dn_ai.attachment_max_chars',
|
||||
default=40000,
|
||||
help="Maximum number of characters extracted from one uploaded file. "
|
||||
"Longer documents are truncated.",
|
||||
)
|
||||
|
||||
@api.model
|
||||
def default_get(self, fields_list):
|
||||
values = super().default_get(fields_list)
|
||||
# ``ir.config_parameter`` may hold a value that is not one of the keys
|
||||
# below -- an empty string written by an older build or by hand is the
|
||||
# common case. ``Selection.convert_to_cache`` raises on such a value and
|
||||
# the whole settings page dies with "Wrong value for
|
||||
# res.config.settings.dn_ai_vision". Fall back to "unset" instead, which
|
||||
# makes ``ai.provider.get_vision`` follow the provider preset.
|
||||
#
|
||||
# Note the membership test: ``False`` is the legitimate "unset" value and
|
||||
# an empty string is *not* falsy-insignificant here -- it is exactly the
|
||||
# value that used to crash the form.
|
||||
if 'dn_ai_vision' in values:
|
||||
allowed = self._fields['dn_ai_vision'].get_values(self.env)
|
||||
if values['dn_ai_vision'] not in allowed:
|
||||
values['dn_ai_vision'] = False
|
||||
return values
|
||||
|
||||
@api.onchange('dn_ai_provider')
|
||||
def _onchange_dn_ai_provider(self):
|
||||
preset = PROVIDER_PRESETS.get(self.dn_ai_provider)
|
||||
if preset:
|
||||
self.dn_ai_base_url = preset['base_url']
|
||||
self.dn_ai_model = preset['model']
|
||||
self.dn_ai_embedding_model = preset['embedding_model']
|
||||
# Keep the multimodal switch in sync with the chosen provider:
|
||||
# sending image blocks to a text-only endpoint fails every request.
|
||||
self.dn_ai_vision = 'true' if preset.get('vision') else 'false'
|
||||
|
||||
def action_dn_ai_test_connection(self):
|
||||
return self.env['dn.ai.provider'].action_test_connection()
|
||||
Reference in New Issue
Block a user