1041 lines
44 KiB
Python
1041 lines
44 KiB
Python
# -*- coding: utf-8 -*-
|
|
import logging
|
|
|
|
from markupsafe import Markup
|
|
|
|
from odoo import Command, api, fields, models
|
|
from odoo.exceptions import AccessError, UserError
|
|
from odoo.tools import html2plaintext
|
|
|
|
from ..utils.ai_utils import (
|
|
format_tool_result,
|
|
format_tool_summary,
|
|
get_text_from_parts,
|
|
markdown_format,
|
|
)
|
|
from ..utils.openai_client import ProviderError, chat_completion
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
DEFAULT_SESSION_SCOPED_TOOLS = ['dn_ai.ir_actions_server_ask_user_question']
|
|
|
|
LOOP_STATES = [
|
|
('ready', 'Ready'),
|
|
('waiting_model', 'Waiting for Model'),
|
|
('waiting_confirmation', 'Waiting for Confirmation'),
|
|
('waiting_answer', 'Waiting for Answer'),
|
|
('waiting_client_result', 'Waiting for Client Result'),
|
|
('waiting_child', 'Waiting for Child Session'),
|
|
]
|
|
|
|
|
|
class AISessionEvent(models.Model):
|
|
"""One message exchanged with the model (text, tool calls or results)."""
|
|
_name = 'ai.session.event'
|
|
_description = 'AI Session Event'
|
|
_order = 'id desc'
|
|
|
|
ai_session_id = fields.Many2one('ai.session', ondelete='cascade', index='btree_not_null')
|
|
metadata = fields.Json('JSON representation of the event', required=True)
|
|
|
|
def get_tool_params(self, call_id):
|
|
self.ensure_one()
|
|
event = self.sudo()
|
|
event.ai_session_id.channel_id.sudo(False).check_access('read')
|
|
tool_call = next(
|
|
(part for part in event.metadata.get('content', [])
|
|
if part.get('type') == 'tool_call' and part.get('call_id') == call_id),
|
|
None,
|
|
)
|
|
if not tool_call:
|
|
return None
|
|
return {
|
|
key: value for key, value in (tool_call.get('args') or {}).items()
|
|
if key not in {'tool_status', '__final_message', 'explanation'}
|
|
}
|
|
|
|
|
|
class AISession(models.Model):
|
|
_name = 'ai.session'
|
|
_description = "AI Session"
|
|
_order = 'id desc'
|
|
|
|
active = fields.Boolean(default=True)
|
|
agent_id = fields.Many2one('ai.agent', ondelete='cascade', index='btree_not_null')
|
|
ai_composer_id = fields.Many2one('ai.composer')
|
|
channel_id = fields.Many2one('discuss.channel', ondelete='cascade', index='btree_not_null')
|
|
parent_session_id = fields.Many2one('ai.session', ondelete='cascade', index='btree_not_null')
|
|
event_ids = fields.One2many('ai.session.event', 'ai_session_id')
|
|
state = fields.Json(
|
|
string="State", help="Data persisted between tool calls.",
|
|
)
|
|
res_model = fields.Char("Model")
|
|
res_id = fields.Many2oneReference(model_field='res_model')
|
|
pending_tool_call = fields.Json("Tool call waiting on the client")
|
|
client_tool_queue = fields.Json(
|
|
"Client tools to run in the browser",
|
|
help="Ordered list of browser-side actions produced by the current "
|
|
"turn; the client drains it, then acknowledges with a resume call.",
|
|
)
|
|
auto_confirm = fields.Boolean(
|
|
"Automatically confirm tool calls for the session", default=False,
|
|
)
|
|
show_agent_steps = fields.Boolean("Show agent steps", default=True)
|
|
loop_state = fields.Selection(LOOP_STATES, required=True, default='ready', index=True)
|
|
resume_token = fields.Char()
|
|
request_round = fields.Integer()
|
|
request_round_limit = fields.Integer()
|
|
request_user_id = fields.Many2one("res.users", ondelete="restrict")
|
|
request_context = fields.Json()
|
|
|
|
# ------------------------------------------------------------------
|
|
# channel / session plumbing
|
|
# ------------------------------------------------------------------
|
|
@api.model
|
|
def _get_or_create_chat_channel(self, agent):
|
|
"""Return the current user's AI chat channel for ``agent``."""
|
|
channel = self.env['discuss.channel'].sudo().search([
|
|
('channel_type', '=', 'ai_chat'),
|
|
('ai_agent_id', '=', agent.id),
|
|
('channel_partner_ids', 'in', self.env.user.partner_id.ids),
|
|
], limit=1)
|
|
if channel:
|
|
return channel
|
|
# `name` is NOT NULL in Odoo 20, so the agent name is stored and the
|
|
# display name is re-derived from it (see discuss_channel.py).
|
|
return self.env['discuss.channel'].sudo().create({
|
|
'ai_agent_id': agent.id,
|
|
'channel_type': 'ai_chat',
|
|
'name': agent.name,
|
|
'channel_member_ids': [
|
|
Command.create({'partner_id': self.env.user.partner_id.id}),
|
|
Command.create({'partner_id': agent.partner_id.id}),
|
|
],
|
|
})
|
|
|
|
@api.model
|
|
def dn_ai_get_record_channel(self, res_model, res_id):
|
|
"""Get or create an AI conversation scoped to one record.
|
|
|
|
Backs the "Ask AI" button in a form view's chatter. The record is
|
|
checked with the current user's rights and stored on the session so
|
|
the agent knows what the user is looking at.
|
|
"""
|
|
if res_model not in self.env or not res_id:
|
|
raise UserError(self.env._("This AI conversation does not exist."))
|
|
record = self.env[res_model].browse(int(res_id)).exists()
|
|
if not record:
|
|
raise UserError(self.env._("This AI conversation does not exist."))
|
|
record.check_access('read')
|
|
|
|
agent = self.env['ai.agent'].sudo().search([('is_system_agent', '=', True)], limit=1)
|
|
if not agent:
|
|
agent = self.env['ai.agent'].sudo().search([], limit=1)
|
|
if not agent or not agent._is_user_access_allowed():
|
|
raise UserError(self.env._("No AI agent is configured. Create one in the AI application first."))
|
|
|
|
# One channel per (user, agent, record) so chatter conversations do
|
|
# not mix with the global assistant thread.
|
|
name = f"{agent.name} · {record.display_name}"
|
|
channel = self.env['discuss.channel'].sudo().search([
|
|
('channel_type', '=', 'ai_chat'),
|
|
('ai_agent_id', '=', agent.id),
|
|
('name', '=', name),
|
|
('channel_partner_ids', 'in', self.env.user.partner_id.ids),
|
|
], limit=1)
|
|
if not channel:
|
|
channel = self.env['discuss.channel'].sudo().create({
|
|
'ai_agent_id': agent.id,
|
|
'channel_type': 'ai_chat',
|
|
'name': name,
|
|
'channel_member_ids': [
|
|
Command.create({'partner_id': self.env.user.partner_id.id}),
|
|
Command.create({'partner_id': agent.partner_id.id}),
|
|
],
|
|
})
|
|
session = self.sudo()._get_channel_session(channel)
|
|
if not session:
|
|
session = self.sudo().create({
|
|
'agent_id': agent.id,
|
|
'channel_id': channel.id,
|
|
'request_user_id': self.env.user.id,
|
|
'res_model': res_model,
|
|
'res_id': int(res_id),
|
|
})
|
|
else:
|
|
session.write({'res_model': res_model, 'res_id': int(res_id)})
|
|
return {
|
|
'channel_id': channel.id,
|
|
'agent_id': agent.id,
|
|
'agent_name': agent.name,
|
|
'session_id': session.id,
|
|
'record_name': record.display_name,
|
|
}
|
|
|
|
@api.model
|
|
def _get_channel_session(self, channel):
|
|
return self.sudo().search([
|
|
('channel_id', '=', channel.id),
|
|
('parent_session_id', '=', False),
|
|
], limit=1)
|
|
|
|
def _root_session(self):
|
|
self.ensure_one()
|
|
session = self
|
|
while session.parent_session_id:
|
|
session = session.parent_session_id
|
|
return session
|
|
|
|
def _get_related_record(self):
|
|
self.ensure_one()
|
|
if self.res_model and self.res_id and self.res_model in self.env:
|
|
return self.env[self.res_model].browse(self.res_id).exists()
|
|
return None
|
|
|
|
# ------------------------------------------------------------------
|
|
# public API used by the controllers
|
|
# ------------------------------------------------------------------
|
|
@api.model
|
|
def dn_ai_send_message(self, channel_id, body, context=None, attachment_ids=None):
|
|
"""Entry point for the standalone chat panel.
|
|
|
|
Resolves the root session of an AI channel, appends the user message
|
|
and runs the loop synchronously (the request blocks until the agent
|
|
either answers or needs input).
|
|
|
|
``attachment_ids`` are files previously uploaded through
|
|
``/dn_ai/upload_attachment``: they are both linked to the posted chat
|
|
message and turned into content parts for the model.
|
|
"""
|
|
channel = self.env['discuss.channel'].browse(channel_id).exists()
|
|
if not channel or channel.channel_type != 'ai_chat':
|
|
raise UserError(self.env._("This conversation is not an AI chat."))
|
|
channel.check_access('read')
|
|
session = self.sudo()._get_channel_session(channel)
|
|
if not session:
|
|
agent = channel.sudo().ai_agent_id
|
|
if not agent:
|
|
raise UserError(self.env._("This AI chat has no agent attached."))
|
|
session = self.sudo().create({
|
|
'agent_id': agent.id,
|
|
'channel_id': channel.id,
|
|
'request_user_id': self.env.user.id,
|
|
})
|
|
body = (body or '').strip()
|
|
attachments = self._dn_ai_authorized_attachments(attachment_ids)
|
|
if not body and not attachments:
|
|
raise UserError(self.env._("The message is empty."))
|
|
session.submit_message(
|
|
[{'type': 'text', 'text': body}], context=context, attachments=attachments)
|
|
return session._dn_ai_payload()
|
|
|
|
@api.model
|
|
def dn_ai_submit_message(self, channel_id, mail_message_id, context=None):
|
|
"""Run the agent on a message the native mail composer already posted.
|
|
|
|
This is the counterpart of ``dn_ai_send_message`` for the native chat
|
|
window. There the user's text is posted by ``mail`` itself (``Thread.post``
|
|
→ ``message_post``), so by the time we get here the message already
|
|
exists and is visible to every recipient. Re-posting it would duplicate
|
|
every question, hence ``mirror=False``.
|
|
|
|
Text comes from the stored body rather than from the request body: the
|
|
composer may have sent HTML (bold, lists, pasted tables) and the model
|
|
should read the same content the transcript shows. Attachments are read
|
|
from the message, which is where the composer's uploads end up.
|
|
"""
|
|
channel = self.env['discuss.channel'].browse(channel_id).exists()
|
|
if not channel or channel.channel_type != 'ai_chat':
|
|
raise UserError(self.env._("This conversation is not an AI chat."))
|
|
channel.check_access('read')
|
|
message = self.env['mail.message'].sudo().browse(mail_message_id).exists()
|
|
if not message or message.channel_id != channel:
|
|
raise UserError(self.env._("The AI prompt message was not found."))
|
|
session = self.sudo()._get_channel_session(channel)
|
|
if not session:
|
|
agent = channel.sudo().ai_agent_id
|
|
if not agent:
|
|
raise UserError(self.env._("This AI chat has no agent attached."))
|
|
session = self.sudo().create({
|
|
'agent_id': agent.id,
|
|
'channel_id': channel.id,
|
|
'request_user_id': self.env.user.id,
|
|
})
|
|
body = html2plaintext(message.body or '').strip()
|
|
attachments = message.attachment_ids.sudo()
|
|
if not body and not attachments:
|
|
raise UserError(self.env._("The message is empty."))
|
|
session.submit_message(
|
|
[{'type': 'text', 'text': body}],
|
|
context=context,
|
|
attachments=attachments,
|
|
mirror=False,
|
|
)
|
|
return session._dn_ai_payload()
|
|
|
|
@api.model
|
|
def _dn_ai_authorized_attachments(self, attachment_ids):
|
|
"""Resolve upload ids to a recordset the current user may send.
|
|
|
|
Only internal users may chat, and the upload route already refrained
|
|
from creating files they cannot read; the check here is about *this*
|
|
conversation not being able to reference someone else's upload by
|
|
guessing an id.
|
|
"""
|
|
if not attachment_ids:
|
|
return self.env['ir.attachment']
|
|
ids = [int(attachment_id) for attachment_id in attachment_ids if str(attachment_id).isdigit()]
|
|
if not ids:
|
|
return self.env['ir.attachment']
|
|
attachments = self.env['ir.attachment'].sudo().browse(ids).exists()
|
|
# `create_uid` is the uploader; anything else was not handed over by
|
|
# this user and must not be read on their behalf.
|
|
return attachments.filtered(lambda a: a.create_uid == self.env.user)
|
|
|
|
def dn_ai_resume(self, response):
|
|
"""Feed a confirmation / answer coming from the chat panel."""
|
|
self.ensure_one()
|
|
self.check_access('write')
|
|
self.resume_interaction(response or {})
|
|
return self._dn_ai_payload()
|
|
|
|
def dn_ai_poll(self, after_event_id=0):
|
|
"""Hand over pending browser actions, draining them.
|
|
|
|
The panel calls this right after a turn and again whenever it needs to
|
|
catch up. Draining (instead of plain reading) keeps the call
|
|
idempotent: polling twice never navigates twice.
|
|
"""
|
|
self.ensure_one()
|
|
self.check_access('read')
|
|
client_tools = self.client_tool_queue or []
|
|
if client_tools:
|
|
self.write({'client_tool_queue': False})
|
|
return {
|
|
'session_id': self.id,
|
|
'loop_state': self.loop_state,
|
|
'resume_token': self.resume_token,
|
|
'client_tools': client_tools,
|
|
}
|
|
|
|
def _dn_ai_payload(self):
|
|
"""Small JSON-able summary consumed by the chat panel.
|
|
|
|
``client_tools`` is drained here: the payload is returned exactly once
|
|
per turn, so the browser runs each navigation once.
|
|
"""
|
|
self.ensure_one()
|
|
request = (self.pending_tool_call or {}).get('request') or {}
|
|
pending = False
|
|
if request and self.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 [],
|
|
}
|
|
client_tools = self.client_tool_queue or []
|
|
if client_tools:
|
|
self.write({'client_tool_queue': False})
|
|
return {
|
|
'session_id': self.id,
|
|
'loop_state': self.loop_state,
|
|
'pending': pending,
|
|
'client_tools': client_tools,
|
|
}
|
|
|
|
def submit_message(self, message_parts, context=None, attachments=None, mirror=True):
|
|
"""Start (or continue) a turn with a new user message.
|
|
|
|
``attachments`` is an ``ir.attachment`` recordset uploaded by the user.
|
|
Their content parts are appended to the user turn so the model reads
|
|
the files in the same round as the question — exactly how the
|
|
Enterprise assistant treats an attached file.
|
|
|
|
``mirror`` decides whether this method posts the user's text itself. It
|
|
is ``False`` when the message was already posted by the native mail
|
|
composer (see ``dn_ai_submit_message``): posting it again would show
|
|
every question twice, once from the composer and once from here.
|
|
"""
|
|
self.ensure_one()
|
|
if not message_parts:
|
|
raise UserError(self.env._("The message is empty."))
|
|
if self.loop_state != 'ready':
|
|
# An in-flight confirmation/question is superseded by the new message.
|
|
self._abort_pending_tools()
|
|
attachments = attachments or self.env['ir.attachment']
|
|
content_parts = list(message_parts)
|
|
if attachments:
|
|
content_parts += attachments._dn_ai_read()
|
|
self.write({
|
|
'request_context': context or {},
|
|
'loop_state': 'waiting_model',
|
|
'request_round': 1,
|
|
'request_round_limit': self.env['dn.ai.provider'].get_max_rounds(),
|
|
'resume_token': False,
|
|
})
|
|
self._append_event({'role': 'user', 'content': content_parts})
|
|
if mirror:
|
|
# Only the typed text is mirrored in the chat: the extracted content
|
|
# of a 40 000-character PDF has no business being pasted into the
|
|
# bubble. The files themselves are listed as attachment cards.
|
|
self._post_user_message(message_parts, attachments=attachments)
|
|
self._run_loop()
|
|
return self.loop_state
|
|
|
|
def resume_interaction(self, response):
|
|
"""Resume after the user confirmed, answered or the client replied."""
|
|
self.ensure_one()
|
|
if self.loop_state not in (
|
|
'waiting_confirmation', 'waiting_answer', 'waiting_client_result', 'waiting_child',
|
|
):
|
|
raise UserError(self.env._("Nothing is waiting for your input."))
|
|
pending = self.pending_tool_call or {}
|
|
tool_calls = pending.get('tool_calls') or []
|
|
results = list(pending.get('results') or [])
|
|
confirmed_call_id = False
|
|
self._post_user_choice(response, pending)
|
|
|
|
if self.loop_state == 'waiting_child':
|
|
results.extend(self._collect_child_results())
|
|
elif tool_calls and results and 'child_session_id' in results[-1]:
|
|
# The child session finished; drop its marker and re-run from there.
|
|
results.pop()
|
|
elif tool_calls:
|
|
kind = response.get('kind')
|
|
call = tool_calls[len(results)]
|
|
if kind == 'confirmation':
|
|
if response.get('value') == 'decline':
|
|
results.append(format_tool_result(
|
|
call, error="The user chose not to proceed with this action."))
|
|
else:
|
|
if response.get('value') == 'auto_confirm':
|
|
self.auto_confirm = True
|
|
# do not append: the very same call is re-executed, this time
|
|
# flagged as approved
|
|
confirmed_call_id = call.get('call_id')
|
|
elif kind == 'question':
|
|
answer = response.get('value') or []
|
|
if isinstance(answer, str):
|
|
answer = [answer]
|
|
results.append(format_tool_result(
|
|
call, result=f"USER ANSWER: {', '.join(answer)}"))
|
|
elif kind == 'client_result':
|
|
results.append(format_tool_result(call, result=response.get('value')))
|
|
elif kind == 'client_error':
|
|
results.append(format_tool_result(call, error=response.get('value')))
|
|
|
|
# `results` is exactly as long as the calls already resolved, so the
|
|
# next call to execute sits at that index.
|
|
self.write({'loop_state': 'waiting_model', 'resume_token': False})
|
|
if self._run_tool_batch(tool_calls, results, len(results),
|
|
confirmed_call_id=confirmed_call_id) == 'done':
|
|
self._run_loop()
|
|
return self.loop_state
|
|
|
|
# ------------------------------------------------------------------
|
|
# agent loop
|
|
# ------------------------------------------------------------------
|
|
def _run_loop(self):
|
|
"""Ask the model; execute tools; repeat until a final answer."""
|
|
self.ensure_one()
|
|
provider = self.env['dn.ai.provider']
|
|
agent = self.agent_id
|
|
if not agent:
|
|
raise UserError(self.env._("This session has no agent."))
|
|
cfg = provider.get_config()
|
|
|
|
while True:
|
|
if (self.request_round or 0) > (self.request_round_limit or 20):
|
|
self._finish_exchange(
|
|
self.env._("The AI used too many successive tool rounds. "
|
|
"Please try a more precise request."), failed=True)
|
|
return
|
|
|
|
# Rebuild each round: `load_skills` widens the tool set mid-flight.
|
|
tools_context = self._build_tools_context()
|
|
tools = self._resolve_tools(tools_context)
|
|
tools_by_name = {tool.sudo().ai_tool_name: tool for tool in tools}
|
|
formatted_tools = self._format_tools(tools_by_name)
|
|
|
|
messages = self._get_history()
|
|
try:
|
|
reply = chat_completion(
|
|
cfg, messages,
|
|
instructions=agent._get_instructions(self._get_context_instructions()),
|
|
tools=formatted_tools or None,
|
|
timeout=cfg['timeout'],
|
|
)
|
|
except ProviderError as exc:
|
|
_logger.warning("dn_ai: completion failed: %s", exc)
|
|
self._finish_exchange(
|
|
self.env._("I could not reach the AI service: %(error)s",
|
|
error=str(exc)[:300]),
|
|
failed=True)
|
|
return
|
|
|
|
self._append_event(reply)
|
|
tool_calls = [part for part in reply.get('content', [])
|
|
if part.get('type') == 'tool_call']
|
|
if not tool_calls:
|
|
parts = [part for part in reply.get('content', [])
|
|
if part.get('type') in ('text', 'inline_data')]
|
|
self._finish_exchange_parts(parts)
|
|
return
|
|
|
|
if text := get_text_from_parts(
|
|
[part for part in reply['content'] if part.get('type') == 'text']):
|
|
self._post_agent_step(markdown_format(text))
|
|
|
|
self.write({
|
|
'loop_state': 'waiting_model',
|
|
'request_round': (self.request_round or 1) + 1,
|
|
})
|
|
if self._run_tool_batch(tool_calls, [], 0) == 'paused':
|
|
return
|
|
# tools are done: loop again and let the model react to the results
|
|
|
|
def _run_tool_batch(self, tool_calls, results, start_index, confirmed_call_id=False):
|
|
"""Execute tool calls from ``start_index``.
|
|
|
|
Returns ``'paused'`` when the batch stopped waiting on the user or on a
|
|
client action, ``'done'`` when every call completed and the loop should
|
|
continue.
|
|
|
|
``confirmed_call_id`` marks a single call the user just approved, so it
|
|
runs even when ``auto_confirm`` is off.
|
|
"""
|
|
self.ensure_one()
|
|
tools_context = self._build_tools_context()
|
|
max_tools = self.env['dn.ai.provider'].get_max_tools_per_call()
|
|
tools = self._resolve_tools(tools_context)
|
|
tools_by_name = {tool.sudo().ai_tool_name: tool for tool in tools}
|
|
record = self._get_related_record()
|
|
results = list(results)
|
|
|
|
for index in range(start_index, len(tool_calls)):
|
|
call = tool_calls[index]
|
|
if index >= max_tools:
|
|
results.append(format_tool_result(call, error="Not executed (tool call limit reached)"))
|
|
continue
|
|
|
|
tool = tools_by_name.get(call.get('name'))
|
|
if not tool:
|
|
results.append(format_tool_result(
|
|
call, error=f"Unknown tool '{call.get('name')}'"))
|
|
continue
|
|
|
|
tools_context['tool_request_confirmed'] = bool(
|
|
self.auto_confirm or (confirmed_call_id
|
|
and call.get('call_id') == confirmed_call_id))
|
|
tools_context['result'] = None
|
|
tools_context['user_input_request'] = None
|
|
tools_context['final_message'] = None
|
|
tools_context['tool_call_id'] = call.get('call_id')
|
|
|
|
args = dict(call.get('args') or {})
|
|
args.pop('tool_status', None)
|
|
snapshot = {k: (list(v) if isinstance(v, list) else v)
|
|
for k, v in tools_context.items() if k != 'state'}
|
|
state_snapshot = self._copy_state(tools_context.get('state') or {})
|
|
|
|
context_vals = {}
|
|
if record:
|
|
context_vals = {
|
|
'active_model': record._name,
|
|
'active_id': record.id,
|
|
'active_ids': record.ids,
|
|
}
|
|
try:
|
|
outcome = tool.sudo().with_context(**context_vals)._ai_tool_run(
|
|
record, args, tools_context)
|
|
except Exception as exc: # noqa: BLE001 - surfaced to the model
|
|
_logger.warning("dn_ai: tool %s failed: %s", call.get('name'), exc,
|
|
exc_info=_logger.isEnabledFor(logging.DEBUG))
|
|
tools_context.clear()
|
|
tools_context.update(snapshot)
|
|
tools_context['state'] = state_snapshot
|
|
results.append(format_tool_result(call, error=f"Tool call failed: {exc}"))
|
|
self._post_agent_step(format_tool_summary(
|
|
{'icon': 'warning', 'text': tool.name}, call))
|
|
continue
|
|
|
|
if isinstance(outcome, dict):
|
|
self._post_agent_step(format_tool_summary(
|
|
outcome.get('summary', {'text': tool.name}), call))
|
|
if child_id := outcome.get('child_session_id'):
|
|
results.append({
|
|
'tool_name': call.get('name'),
|
|
'tool_call_id': call.get('call_id'),
|
|
'child_session_id': child_id,
|
|
})
|
|
self._pause('waiting_child', tool_calls, results,
|
|
state=self._copy_state(tools_context.get('state') or {}))
|
|
return 'paused'
|
|
if client_tool := outcome.get('client_tool'):
|
|
self._queue_client_tool(client_tool)
|
|
if not client_tool.get('oneway'):
|
|
self._pause('waiting_client_result', tool_calls, results,
|
|
state=self._copy_state(tools_context.get('state') or {}),
|
|
client_tool=client_tool)
|
|
return 'paused'
|
|
if 'response' in outcome:
|
|
outcome = outcome['response']
|
|
else:
|
|
self._post_agent_step(format_tool_summary({'text': tool.name}, call))
|
|
|
|
if request := tools_context.get('user_input_request'):
|
|
# Do NOT append a placeholder result: `pending['results']` must
|
|
# stay aligned with the calls already resolved so that
|
|
# `resume_interaction` can find the paused call by index.
|
|
self._pause(
|
|
'waiting_confirmation' if request.get('type') == 'confirmation' else 'waiting_answer',
|
|
tool_calls, results, request=request,
|
|
state=self._copy_state(tools_context.get('state') or {}),
|
|
)
|
|
return 'paused'
|
|
|
|
results.append(format_tool_result(call, result=outcome))
|
|
|
|
# every call finished: persist results and let the caller continue
|
|
self._persist_state(tools_context.get('state') or {})
|
|
self._append_event({'role': 'user', 'content': list(results)})
|
|
self.write({'pending_tool_call': False})
|
|
return 'done'
|
|
|
|
def _pause(self, loop_state, tool_calls, results, request=None, state=None,
|
|
client_tool=None):
|
|
import secrets
|
|
resume_token = secrets.token_urlsafe(24)
|
|
vals = {
|
|
'loop_state': loop_state,
|
|
'resume_token': resume_token,
|
|
'pending_tool_call': {
|
|
'tool_calls': tool_calls,
|
|
'results': results,
|
|
'request': request or {},
|
|
},
|
|
}
|
|
if state is not None:
|
|
# `load_skills` widens the tool set mid-turn. Without persisting it
|
|
# the resumed batch rebuilds the context from the old state and
|
|
# cannot resolve the very call awaiting confirmation.
|
|
vals['state'] = state
|
|
if client_tool is not None:
|
|
# Stamp the *new* token on the queued actions so the client echoes
|
|
# back something the server still recognises.
|
|
vals['client_tool_queue'] = [
|
|
{**entry, 'resume_token': resume_token}
|
|
for entry in self.client_tool_queue or []
|
|
]
|
|
self.write(vals)
|
|
if request:
|
|
self._post_user_input_request(request)
|
|
|
|
# ------------------------------------------------------------------
|
|
# browser-side tools
|
|
# ------------------------------------------------------------------
|
|
def _queue_client_tool(self, client_tool):
|
|
"""Append a browser action to the drain queue.
|
|
|
|
``oneway`` tools (opening a view) are fire-and-forget: the batch keeps
|
|
running server-side and the client picks the action up on its next
|
|
poll. Two-way tools additionally pause the session, so their result has
|
|
to reach ``resume_interaction`` before the loop continues.
|
|
|
|
An ``exclusive`` entry is the *outcome* of the turn — the view that
|
|
shows what was just written. Creating a contact, two products and a
|
|
sales order queues four such navigations; running all of them would
|
|
flicker through every form before settling on the last. Keeping only
|
|
the latest means the user lands on the record the answer talks about.
|
|
|
|
The ``resume_token`` is deliberately *not* stamped here: ``_pause``
|
|
mints a fresh one afterwards and rewrites the whole queue, so stamping
|
|
early would hand the client a token the server has already replaced.
|
|
"""
|
|
self.ensure_one()
|
|
queue = list(self.client_tool_queue or [])
|
|
if client_tool.get('exclusive'):
|
|
queue = [entry for entry in queue if not entry.get('exclusive')]
|
|
queue.append(dict(client_tool))
|
|
self.write({'client_tool_queue': queue})
|
|
|
|
def _pending_client_tools(self):
|
|
self.ensure_one()
|
|
return self.client_tool_queue or []
|
|
|
|
def _abort_pending_tools(self):
|
|
"""Close an unfinished tool batch before a new user message.
|
|
|
|
The assistant ``tool_calls`` event is already persisted, so simply
|
|
dropping ``pending_tool_call`` would leave those calls without results
|
|
and every later request would be rejected by the provider. Persist one
|
|
"aborted" result per unresolved call to keep the history valid.
|
|
"""
|
|
pending = self.pending_tool_call or {}
|
|
tool_calls = pending.get('tool_calls') or []
|
|
resolved = pending.get('results') or []
|
|
if tool_calls and len(resolved) < len(tool_calls):
|
|
aborted = [
|
|
format_tool_result(
|
|
call,
|
|
error="The user interrupted this action with a new message.",
|
|
)
|
|
for call in tool_calls[len(resolved):]
|
|
]
|
|
self._append_event({'role': 'user', 'content': aborted})
|
|
self.write({
|
|
'loop_state': 'ready',
|
|
'pending_tool_call': False,
|
|
'resume_token': False,
|
|
})
|
|
|
|
# ------------------------------------------------------------------
|
|
# tools context / state
|
|
# ------------------------------------------------------------------
|
|
def _build_tools_context(self):
|
|
self.ensure_one()
|
|
state = self.state or {}
|
|
return {
|
|
'session_id': self.id,
|
|
'channel_id': self.channel_id.id,
|
|
'agent_id': self.agent_id.id,
|
|
'auto_confirm': self.auto_confirm,
|
|
'state': {
|
|
'available_tools': state.get('available_tools') or self._initial_tool_ids(),
|
|
'loaded_skills': state.get('loaded_skills') or [],
|
|
'message_body_suffix': '',
|
|
},
|
|
'message_body_suffix': Markup(''),
|
|
'result': None,
|
|
'final_message': None,
|
|
'user_input_request': None,
|
|
'preview_links': None,
|
|
}
|
|
|
|
def _initial_tool_ids(self):
|
|
self.ensure_one()
|
|
tools = self.agent_id._get_default_tools()
|
|
return tools.ids
|
|
|
|
def _persist_state(self, state):
|
|
self.ensure_one()
|
|
self.state = state
|
|
|
|
@staticmethod
|
|
def _copy_state(state):
|
|
return {
|
|
'available_tools': list(state.get('available_tools') or []),
|
|
'loaded_skills': list(state.get('loaded_skills') or []),
|
|
'message_body_suffix': state.get('message_body_suffix') or '',
|
|
}
|
|
|
|
def _resolve_tools(self, tools_context):
|
|
ids = tools_context['state'].get('available_tools') or []
|
|
return self.env['ir.actions.server'].sudo().browse(ids).exists().filtered('use_in_ai')
|
|
|
|
def _format_tools(self, tools_by_name):
|
|
formatted = []
|
|
for name, tool in tools_by_name.items():
|
|
schema = None
|
|
if tool.ai_tool_schema:
|
|
import json
|
|
try:
|
|
schema = json.loads(tool.ai_tool_schema)
|
|
except ValueError:
|
|
schema = None
|
|
formatted.append({
|
|
'name': name,
|
|
'instructions': tool.ai_tool_description or tool.name,
|
|
'schema': schema,
|
|
})
|
|
return formatted
|
|
|
|
def _get_context_instructions(self):
|
|
"""Extra instructions describing the current UI surface."""
|
|
self.ensure_one()
|
|
record = self._get_related_record()
|
|
if not record:
|
|
return ''
|
|
return (
|
|
f"The user is currently looking at a {record._description} record: "
|
|
f'"{record.display_name}".'
|
|
)
|
|
|
|
# ------------------------------------------------------------------
|
|
# history / events
|
|
# ------------------------------------------------------------------
|
|
def _append_event(self, metadata):
|
|
self.ensure_one()
|
|
self.env['ai.session.event'].create({
|
|
'ai_session_id': self.id,
|
|
'metadata': metadata,
|
|
})
|
|
|
|
def _get_history(self, limit=40):
|
|
"""Rebuild the model conversation from persisted events.
|
|
|
|
The window must not start in the middle of a tool exchange: an
|
|
assistant ``tool_calls`` event and the ``tool_result`` events answering
|
|
it are one indivisible unit. Cutting between them makes providers
|
|
reject the request outright ("an assistant message with tool_calls must
|
|
be followed by tool messages responding to each tool_call_id"). So we
|
|
take the last ``limit`` events and then walk the start forward until it
|
|
sits on a plain user text message.
|
|
"""
|
|
self.ensure_one()
|
|
events = self.sudo().event_ids.sorted('id')
|
|
if limit and len(events) > limit:
|
|
events = events[-limit:]
|
|
events = self._align_history_start(events)
|
|
return [event.metadata for event in events]
|
|
|
|
@staticmethod
|
|
def _align_history_start(events):
|
|
"""Move the window start forward to the next self-contained turn."""
|
|
def is_clean_start(event):
|
|
metadata = event.metadata or {}
|
|
if metadata.get('role') != 'user':
|
|
return False
|
|
content = metadata.get('content') or []
|
|
# A turn made only of tool results depends on the assistant call
|
|
# that produced them, so it cannot open the window.
|
|
return any(part.get('type') == 'text' for part in content
|
|
if isinstance(part, dict))
|
|
|
|
events = events.filtered(lambda ev: ev) # keep recordset semantics
|
|
for index in range(len(events)):
|
|
if is_clean_start(events[index]):
|
|
return events[index:]
|
|
# No clean boundary found: better an empty window than a broken pair.
|
|
return events[:0]
|
|
|
|
# ------------------------------------------------------------------
|
|
# posting into the chat
|
|
# ------------------------------------------------------------------
|
|
def _post_agent_step(self, body):
|
|
self.ensure_one()
|
|
if not self.channel_id:
|
|
return
|
|
if not self.show_agent_steps:
|
|
return
|
|
self.channel_id.sudo().message_post(
|
|
body=body,
|
|
author_id=self.agent_id.partner_id.id,
|
|
message_type='comment',
|
|
subtype_xmlid='mail.mt_comment',
|
|
)
|
|
|
|
def _post_user_input_request(self, request):
|
|
"""Post the confirmation / question card as a message in the chat."""
|
|
self.ensure_one()
|
|
if not self.channel_id:
|
|
return
|
|
# NB: `request` is a reserved QWeb name (the HTTP request), so the card
|
|
# payload is passed as `ai_request`.
|
|
body = self.env['ir.qweb']._render('dn_ai.ai_user_input_request', {
|
|
'ai_request': request,
|
|
'ai_session': self,
|
|
})
|
|
self.channel_id.sudo().message_post(
|
|
body=body,
|
|
author_id=self.agent_id.partner_id.id,
|
|
message_type='comment',
|
|
subtype_xmlid='mail.mt_comment',
|
|
)
|
|
|
|
def _post_user_choice(self, response, pending):
|
|
"""Echo the user's confirmation / answer back into the thread.
|
|
|
|
Without this the card silently disappears and the transcript looks like
|
|
the agent acted on its own.
|
|
"""
|
|
self.ensure_one()
|
|
if not self.channel_id:
|
|
return
|
|
kind = response.get('kind')
|
|
value = response.get('value')
|
|
if kind == 'confirmation':
|
|
# Values come from the confirmation card built in ir_actions_server.
|
|
labels = {
|
|
'confirm_once': self.env._("Yes, do it"),
|
|
'auto_confirm': self.env._("Yes, always approve in this chat"),
|
|
'decline': self.env._("No, I want something else"),
|
|
}
|
|
text = labels.get(value) or str(value)
|
|
elif kind == 'question':
|
|
if isinstance(value, (list, tuple)):
|
|
values = [str(item) for item in value]
|
|
else:
|
|
values = [str(value)]
|
|
# Choices carry a machine `value` plus a human `label`; echo the
|
|
# label so the transcript reads naturally.
|
|
request = pending.get('request') or {}
|
|
labels_by_value = {
|
|
str(choice.get('value')): choice.get('label') or choice.get('value')
|
|
for choice in request.get('choices') or []
|
|
if isinstance(choice, dict)
|
|
}
|
|
text = ', '.join(labels_by_value.get(item, item) for item in values)
|
|
else:
|
|
return
|
|
if not text:
|
|
return
|
|
self.channel_id.sudo().message_post(
|
|
body=markdown_format(text),
|
|
author_id=self.request_user_id.partner_id.id or self.env.user.partner_id.id,
|
|
message_type='comment',
|
|
subtype_xmlid='mail.mt_comment',
|
|
)
|
|
|
|
def _post_user_message(self, parts, attachments=None):
|
|
"""Mirror the user's own message into the chat so the thread reads
|
|
like a normal conversation instead of only showing the agent side."""
|
|
self.ensure_one()
|
|
if not self.channel_id:
|
|
return
|
|
texts = [part.get('text') for part in parts if part.get('type') == 'text']
|
|
body = markdown_format('\n'.join(text for text in texts if text))
|
|
attachments = attachments or self.env['ir.attachment']
|
|
if not body and not attachments:
|
|
return
|
|
self.channel_id.sudo().message_post(
|
|
body=body,
|
|
# Linking (not re-creating) the uploads is what makes them show up
|
|
# as a file card under the message instead of a broken link.
|
|
attachment_ids=attachments.ids or None,
|
|
author_id=self.request_user_id.partner_id.id or self.env.user.partner_id.id,
|
|
message_type='comment',
|
|
subtype_xmlid='mail.mt_comment',
|
|
)
|
|
|
|
def _finish_exchange_parts(self, parts):
|
|
self.ensure_one()
|
|
body = self._parts_to_html(parts)
|
|
self.channel_id.sudo().message_post(
|
|
body=body,
|
|
author_id=self.agent_id.partner_id.id,
|
|
message_type='comment',
|
|
subtype_xmlid='mail.mt_comment',
|
|
)
|
|
self._finish_exchange()
|
|
|
|
def _finish_exchange(self, error_message=None, failed=False):
|
|
self.ensure_one()
|
|
if error_message:
|
|
self.channel_id.sudo().message_post(
|
|
body=Markup('<p>%s</p>') % error_message,
|
|
author_id=self.agent_id.partner_id.id,
|
|
message_type='comment',
|
|
subtype_xmlid='mail.mt_comment',
|
|
)
|
|
self.write({
|
|
'loop_state': 'ready',
|
|
'pending_tool_call': False,
|
|
'resume_token': False,
|
|
'request_round': 0,
|
|
})
|
|
|
|
def _parts_to_html(self, parts):
|
|
texts = [part['text'] for part in parts if part.get('type') == 'text']
|
|
if not texts:
|
|
return Markup('')
|
|
return markdown_format('\n'.join(texts))
|
|
|
|
# ------------------------------------------------------------------
|
|
# one-shot helpers (no session persistence)
|
|
# ------------------------------------------------------------------
|
|
@api.model
|
|
def _get_direct_response(self, instructions, message, tools=None, agent_id=None,
|
|
schema=None, record=None):
|
|
"""Run a bounded tool loop without persisting a session."""
|
|
provider = self.env['dn.ai.provider']
|
|
cfg = provider.get_config()
|
|
messages = [{'role': 'user', 'content': message}]
|
|
tools = tools or self.env['ir.actions.server']
|
|
tools_by_name = {tool.sudo().ai_tool_name: tool for tool in tools}
|
|
formatted = []
|
|
for name, tool in tools_by_name.items():
|
|
import json
|
|
schema_val = None
|
|
if tool.ai_tool_schema:
|
|
try:
|
|
schema_val = json.loads(tool.ai_tool_schema)
|
|
except ValueError:
|
|
schema_val = None
|
|
formatted.append({
|
|
'name': name,
|
|
'instructions': tool.ai_tool_description or tool.name,
|
|
'schema': schema_val,
|
|
})
|
|
|
|
dummy = self.sudo().new({'agent_id': agent_id, 'loop_state': 'ready'})
|
|
tools_context = {
|
|
'session_id': False,
|
|
'agent_id': agent_id,
|
|
'auto_confirm': True,
|
|
'state': {'available_tools': list(tools_by_name.values()) and tools.ids,
|
|
'loaded_skills': [], 'message_body_suffix': ''},
|
|
'message_body_suffix': Markup(''),
|
|
'user_input_request': None,
|
|
'result': None,
|
|
}
|
|
tools_context['state']['available_tools'] = tools.ids
|
|
|
|
for _round in range(provider.get_max_rounds()):
|
|
try:
|
|
reply = chat_completion(
|
|
cfg, messages, instructions=instructions,
|
|
tools=formatted or None, schema=schema, timeout=cfg['timeout'])
|
|
except ProviderError as exc:
|
|
_logger.warning("dn_ai: direct response failed: %s", exc)
|
|
return [{'type': 'text', 'text': str(exc)}]
|
|
messages.append(reply)
|
|
tool_calls = [part for part in reply.get('content', [])
|
|
if part.get('type') == 'tool_call']
|
|
if not tool_calls:
|
|
return [part for part in reply.get('content', [])
|
|
if part.get('type') in ('text', 'inline_data')]
|
|
|
|
results = []
|
|
for call in tool_calls:
|
|
tool = tools_by_name.get(call.get('name'))
|
|
if not tool:
|
|
results.append(format_tool_result(call, error="Unknown tool"))
|
|
continue
|
|
try:
|
|
outcome = tool.sudo()._ai_tool_run(record, dict(call.get('args') or {}), tools_context)
|
|
except Exception as exc: # noqa: BLE001
|
|
results.append(format_tool_result(call, error=str(exc)))
|
|
continue
|
|
if isinstance(outcome, dict) and 'response' in outcome:
|
|
outcome = outcome['response']
|
|
results.append(format_tool_result(call, result=outcome))
|
|
messages.append({'role': 'user', 'content': results})
|
|
|
|
return [{'type': 'text', 'text': self.env._("Too many tool rounds.")}]
|
|
|
|
def _collect_child_results(self):
|
|
"""Gather the answers of delegated child sessions."""
|
|
self.ensure_one()
|
|
pending = self.pending_tool_call or {}
|
|
results = []
|
|
for call in pending.get('tool_calls') or []:
|
|
child = self.sudo().search([
|
|
('parent_session_id', '=', self.id),
|
|
('loop_state', '=', 'ready'),
|
|
], order='id desc', limit=1)
|
|
if child:
|
|
text = child._last_agent_text()
|
|
results.append(format_tool_result(call, result=text or 'done'))
|
|
return results
|
|
|
|
def _last_agent_text(self):
|
|
self.ensure_one()
|
|
for event in self.sudo().event_ids.sorted('id', reverse=True):
|
|
content = event.metadata.get('content') or []
|
|
if event.metadata.get('role') == 'assistant':
|
|
text = get_text_from_parts(content)
|
|
if text:
|
|
return text
|
|
return ''
|