push
This commit is contained in:
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
|
||||
)
|
||||
Reference in New Issue
Block a user