push
This commit is contained in:
201
dn_ai/controllers/ai.py
Normal file
201
dn_ai/controllers/ai.py
Normal file
@@ -0,0 +1,201 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
|
||||
from odoo import http
|
||||
from odoo.exceptions import AccessError, MissingError, UserError
|
||||
from odoo.http import request
|
||||
|
||||
from ..utils.ai_attachment_tools import format_size, guess_kind
|
||||
from ..utils.ai_utils import get_text_from_parts, markdown_format
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Refused before a single byte reaches the filestore. Generous enough for a
|
||||
# scanned PDF or a photo, small enough that the request cannot be used to fill
|
||||
# the disk.
|
||||
MAX_UPLOAD_BYTES = 32 * 1024 * 1024
|
||||
|
||||
|
||||
class AIController(http.Controller):
|
||||
|
||||
def _get_channel(self, channel_id):
|
||||
channel = request.env['discuss.channel'].sudo().browse(channel_id).exists()
|
||||
if not channel or channel.channel_type != 'ai_chat':
|
||||
raise MissingError(request.env._("This AI conversation does not exist."))
|
||||
channel.check_access('read')
|
||||
return channel
|
||||
|
||||
def _get_session(self, channel):
|
||||
session = request.env['ai.session'].sudo()._get_channel_session(channel)
|
||||
if not session:
|
||||
raise MissingError(request.env._("This AI conversation has no session."))
|
||||
return session
|
||||
|
||||
@http.route('/dn_ai/start_session', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def start_session(self, channel_id, body, current_view_info=None):
|
||||
"""Post a user message and run the agent until it needs input."""
|
||||
channel = self._get_channel(channel_id)
|
||||
session = self._get_session(channel)
|
||||
if not session.agent_id._is_user_access_allowed():
|
||||
raise AccessError(request.env._("You are not allowed to use this agent."))
|
||||
|
||||
# The user message lives in the chatter, like any other message.
|
||||
message = channel.sudo().message_post(
|
||||
body=body or '',
|
||||
author_id=request.env.user.partner_id.id,
|
||||
message_type='comment',
|
||||
subtype_xmlid='mail.mt_comment',
|
||||
)
|
||||
parts = [{'type': 'text', 'text': body or ''}]
|
||||
context = dict(request.env.context)
|
||||
state = session.submit_message(parts, context=context)
|
||||
return self._session_payload(session, message.id)
|
||||
|
||||
@http.route('/dn_ai/start_session_advance', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def start_session_advance(self, channel_id, mail_message_id, current_view_info=None):
|
||||
"""Run the agent on a message the native mail composer already posted.
|
||||
|
||||
The native chat window (``mail.ChatWindow``) posts through
|
||||
``message_post`` itself, so unlike ``/dn_ai/start_session`` the message
|
||||
is already stored and rendered when this route is called. All that is
|
||||
left to do is handing it to the agent loop.
|
||||
"""
|
||||
channel = self._get_channel(channel_id)
|
||||
if not channel.sudo().ai_agent_id:
|
||||
raise MissingError(request.env._("This AI chat has no agent attached."))
|
||||
payload = request.env['ai.session'].dn_ai_submit_message(
|
||||
channel.id, mail_message_id, context=dict(request.env.context))
|
||||
return payload
|
||||
|
||||
@http.route('/dn_ai/resume', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def resume(self, session_id, response):
|
||||
session = request.env['ai.session'].sudo().browse(session_id).exists()
|
||||
if not session:
|
||||
raise MissingError(request.env._("This AI conversation does not exist."))
|
||||
session._root_session().channel_id.check_access('read')
|
||||
state = session.resume_interaction(response)
|
||||
return self._session_payload(session)
|
||||
|
||||
@http.route('/dn_ai/poll', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def poll(self, session_id):
|
||||
"""Drain the browser actions queued by the tools of the current turn."""
|
||||
session = request.env['ai.session'].sudo().browse(session_id).exists()
|
||||
if not session:
|
||||
raise MissingError(request.env._("This AI conversation does not exist."))
|
||||
session._root_session().channel_id.check_access('read')
|
||||
return session.dn_ai_poll()
|
||||
|
||||
@http.route('/dn_ai/direct_response', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def direct_response(self, prompt, interface_key='chatter_ai_button',
|
||||
res_model=None, res_id=None, as_html=True):
|
||||
"""One-shot answer used by composer buttons (no chat session)."""
|
||||
agent = request.env['ai.composer']._get_agent(res_model, interface_key)
|
||||
if not agent:
|
||||
raise MissingError(request.env._("No AI agent is configured."))
|
||||
parts = [{'type': 'text', 'text': prompt}]
|
||||
response = agent._generate_single_response(parts)
|
||||
text = get_text_from_parts(response)
|
||||
return markdown_format(text) if as_html else text
|
||||
|
||||
def _session_payload(self, session, message_id=None):
|
||||
return {
|
||||
'session_id': session.id,
|
||||
'loop_state': session.loop_state,
|
||||
'resume_token': session.resume_token if session.loop_state != 'ready' else False,
|
||||
'pending': (session.pending_tool_call or {}).get('request') or {},
|
||||
'client_tools': session.client_tool_queue or [],
|
||||
'message_id': message_id,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# attachments
|
||||
# ------------------------------------------------------------------
|
||||
@http.route('/dn_ai/upload_attachment', type='http', auth='user', methods=['POST'],
|
||||
csrf=True)
|
||||
def upload_attachment(self, ufile=None, channel_id=None):
|
||||
"""Store one file for an AI conversation.
|
||||
|
||||
Kept as a plain HTTP route rather than a JSON-RPC one because the
|
||||
browser has to post ``multipart/form-data``; JSON-RPC bodies cannot
|
||||
carry binary. The response mirrors ``/web/binary/upload_attachment``
|
||||
so the client-side code looks familiar.
|
||||
|
||||
The attachment is *not* bound to a message yet: it is created as a
|
||||
pending upload (``res_model='mail.compose.message'``) and only promoted
|
||||
to a real message attachment when the user actually sends, which is why
|
||||
abandoned drafts leave nothing behind in the conversation.
|
||||
"""
|
||||
if not ufile:
|
||||
return request.make_json_response({'error': request.env._("No file was uploaded.")})
|
||||
channel = request.env['discuss.channel'].sudo().browse(
|
||||
int(channel_id or 0)).exists()
|
||||
if not channel or channel.channel_type != 'ai_chat':
|
||||
return request.make_json_response(
|
||||
{'error': request.env._("This AI conversation does not exist.")})
|
||||
try:
|
||||
channel.check_access('read')
|
||||
except AccessError:
|
||||
return request.make_json_response(
|
||||
{'error': request.env._("You are not allowed to use this conversation.")})
|
||||
|
||||
data = ufile.read()
|
||||
filename = ufile.filename or 'file'
|
||||
if not data:
|
||||
return request.make_json_response({'error': request.env._("The file is empty.")})
|
||||
if len(data) > MAX_UPLOAD_BYTES:
|
||||
return request.make_json_response({
|
||||
'error': request.env._(
|
||||
"The file is too large (%(size)s). The limit is %(limit)s.",
|
||||
size=format_size(len(data)), limit=format_size(MAX_UPLOAD_BYTES)),
|
||||
})
|
||||
|
||||
attachment = request.env['ir.attachment'].sudo().create({
|
||||
'name': filename,
|
||||
'raw': data,
|
||||
'mimetype': ufile.content_type or None,
|
||||
# Pending-upload convention from mail: linked to a real record only
|
||||
# when `message_post(attachment_ids=...)` runs on send.
|
||||
'res_model': 'mail.compose.message',
|
||||
'res_id': 0,
|
||||
})
|
||||
kind = guess_kind(attachment.mimetype, filename)
|
||||
return request.make_json_response({
|
||||
'id': attachment.id,
|
||||
'name': attachment.name,
|
||||
'mimetype': attachment.mimetype or '',
|
||||
'size': attachment.file_size or 0,
|
||||
# Rendered as a hint under the chip: the model reads text formats
|
||||
# natively, while an image/PDF is only understood when the provider
|
||||
# supports vision — and the user deserves to know which case applies.
|
||||
'kind': kind,
|
||||
'readable': kind != 'unsupported',
|
||||
})
|
||||
|
||||
@http.route('/dn_ai/attachment_preview', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def attachment_preview(self, attachment_id):
|
||||
"""Show what the model will actually receive for a file.
|
||||
|
||||
Useful when a question comes back wrong: the answer is almost always
|
||||
that the extraction found nothing (scanned PDF, legacy .doc, exotic
|
||||
encoding), and this makes that visible instead of mysterious.
|
||||
"""
|
||||
attachment = request.env['ir.attachment'].browse(int(attachment_id)).exists()
|
||||
if not attachment:
|
||||
raise MissingError(request.env._("This attachment does not exist."))
|
||||
if attachment.create_uid != request.env.user and not request.env.is_admin():
|
||||
raise AccessError(request.env._("You are not allowed to read this attachment."))
|
||||
parts = attachment._dn_ai_read()
|
||||
texts = []
|
||||
for part in parts:
|
||||
if part.get('type') == 'text':
|
||||
texts.append(part.get('text') or '')
|
||||
else:
|
||||
texts.append(request.env._(
|
||||
"[binary content, %(mimetype)s]", mimetype=part.get('mimetype')))
|
||||
return {
|
||||
'id': attachment.id,
|
||||
'name': attachment.name,
|
||||
'mimetype': attachment.mimetype or '',
|
||||
'size': attachment.file_size or 0,
|
||||
'content': '\n'.join(texts)[:5000],
|
||||
}
|
||||
Reference in New Issue
Block a user