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

225 lines
8.7 KiB
Python

# -*- 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',
)