249 lines
11 KiB
Python
249 lines
11 KiB
Python
# Part of the ai_deepseek module.
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
进程内接管 Odoo AI 的传输层,改走 DeepSeek。
|
||
|
||
原理
|
||
----
|
||
Odoo 的 AI 模块把所有对外调用汇聚到 `ai/utils/ai_utils.py`:
|
||
- get_odoo_ai_connection_data(env, ...) 有活的 env,产出连接信息
|
||
- call_odoo_ai_transport(connection, route, ...) 异步路径(结果经 webhook 回传)
|
||
- call_odoo_ai(env, route, ...) 同步路径(直接取返回值)
|
||
|
||
Odoo 官方自己的测试 (`ai/tests/common.py::mock_iap_results`) 就是替换
|
||
`ai_session.call_odoo_ai_transport` 来打桩的,说明这是官方认可的拦截点。
|
||
|
||
关键难点
|
||
--------
|
||
`call_odoo_ai_transport` 由核心放在 `@self.env.cr.postcommit.add` 回调里执行,
|
||
此刻事务已提交、`env.transaction is None`、`env.cr` 已关闭,无法再读数据库。
|
||
因此采用"**提前解析配置**"策略:
|
||
|
||
get_odoo_ai_connection_data(env) ← 有活 env,此时把配置一并算好塞进 connection
|
||
└─ connection['ai_deepseek_cfg'] = {...}
|
||
|
||
postcommit → call_odoo_ai_transport(connection, ...) ← 直接读 connection 里的配置
|
||
|
||
异步交付
|
||
--------
|
||
后台线程调完 DeepSeek 后,**进程内**复刻官方 webhook 控制器
|
||
(`ai/controllers/thread.py::completion_result_ready`) 的交付逻辑:
|
||
用 `webhook_dbname` 开新 cursor,重建 env(含 request_context / guest /
|
||
discuss_channel),然后对 pending 的 ai.session 调用 `_continue_agent_loop`
|
||
或 `_continue_channel_name`。
|
||
|
||
这样**完全复用官方交付路径**(discuss / bus / 附件 / 工具循环全自动),
|
||
且无需额外 HTTP 服务、无需自签 HMAC、无需购买 IAP credits。
|
||
"""
|
||
import logging
|
||
import threading
|
||
|
||
from odoo import api
|
||
|
||
from . import deepseek_client as ds
|
||
|
||
_logger = logging.getLogger(__name__)
|
||
|
||
CFG_KEY = "ai_deepseek_cfg"
|
||
_ORIGINALS = {}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 配置读取(只在有活 env 时调用)
|
||
# ---------------------------------------------------------------------------
|
||
def get_config(env):
|
||
icp = env["ir.config_parameter"].sudo()
|
||
return {
|
||
"enabled": icp.get_bool("ai_deepseek.enabled", False),
|
||
"api_key": icp.get_str("ai_deepseek.api_key", ""),
|
||
"base_url": icp.get_str("ai_deepseek.base_url", ds.DEFAULT_BASE_URL),
|
||
"model": icp.get_str("ai_deepseek.model", ds.DEFAULT_MODEL),
|
||
"emb_api_key": icp.get_str("ai_deepseek.emb_api_key", ""),
|
||
"emb_base_url": icp.get_str("ai_deepseek.emb_base_url", ""),
|
||
"emb_model": icp.get_str("ai_deepseek.emb_model", ds.DEFAULT_EMBEDDING_MODEL),
|
||
"timeout": icp.get_int("ai_deepseek.timeout", 120),
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 1) 包装 get_odoo_ai_connection_data:有活 env,顺手解析配置
|
||
# ---------------------------------------------------------------------------
|
||
def _patched_get_connection_data(env, add_iap_token=True):
|
||
connection = _ORIGINALS["get_odoo_ai_connection_data"](env, add_iap_token=add_iap_token)
|
||
try:
|
||
connection[CFG_KEY] = get_config(env)
|
||
except Exception: # noqa: BLE001
|
||
_logger.exception("ai_deepseek: 解析配置失败")
|
||
return connection
|
||
|
||
|
||
def _cfg_of(connection):
|
||
cfg = connection.get(CFG_KEY)
|
||
return cfg if cfg and cfg.get("enabled") else None
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 2) 包装 call_odoo_ai_transport:异步路径
|
||
# ---------------------------------------------------------------------------
|
||
def _patched_call_odoo_ai_transport(connection, route, params, timeout=30, *, raise_user_error=True):
|
||
cfg = _cfg_of(connection)
|
||
if cfg is None or route not in ("1/get_completions", "1/get_completions_sync"):
|
||
return _ORIGINALS["call_odoo_ai_transport"](
|
||
connection, route, params, timeout, raise_user_error=raise_user_error)
|
||
|
||
# Odoo 调用方只等 5 秒(IAP_TRANSPORT_TIMEOUT),必须立即返回;
|
||
# 真正的模型调用 + 结果交付放到后台线程完成。
|
||
threading.Thread(target=_background_complete, args=(cfg, dict(params)), daemon=True).start()
|
||
return {}
|
||
|
||
|
||
def _background_complete(cfg, params):
|
||
request_uuid = params.get("request_uuid")
|
||
dbname = params.get("webhook_dbname")
|
||
try:
|
||
message = ds.call_chat(
|
||
cfg,
|
||
params.get("messages", []),
|
||
params.get("instructions", ""),
|
||
params.get("tools", []),
|
||
schema=params.get("schema"),
|
||
)
|
||
llm_result = {"result": ds.build_odoo_assistant(message)}
|
||
llm_error = False
|
||
except Exception as exc: # noqa: BLE001
|
||
_logger.exception("ai_deepseek: DeepSeek 调用失败 uuid=%s", request_uuid)
|
||
llm_result = False
|
||
llm_error = str(exc)[:500]
|
||
|
||
if not request_uuid or not dbname:
|
||
_logger.error("ai_deepseek: 缺少 uuid/dbname,无法交付结果")
|
||
return
|
||
_deliver(dbname, request_uuid, llm_result, llm_error)
|
||
|
||
|
||
def _deliver(dbname, request_uuid, llm_result, llm_error):
|
||
"""进程内复刻 ai/controllers/thread.py::completion_result_ready 的交付逻辑。"""
|
||
from odoo.modules.registry import Registry
|
||
|
||
try:
|
||
with Registry(dbname).cursor() as cr:
|
||
env = api.Environment(cr, api.SUPERUSER_ID, {})
|
||
session = env["ai.session"].sudo().search([
|
||
("request_uuid", "=", request_uuid),
|
||
("loop_state", "=", "waiting_model"),
|
||
], limit=1)
|
||
if not session:
|
||
_logger.warning("ai_deepseek: 找不到待交付会话 uuid=%s(可能已超时/取消)", request_uuid)
|
||
return
|
||
|
||
# 重建请求环境(与官方控制器一致)
|
||
context = dict(session.request_context or {})
|
||
if session.request_guest_id:
|
||
context["guest"] = session.request_guest_id
|
||
if session.channel_id:
|
||
context["discuss_channel"] = session.channel_id
|
||
user_id = session.request_user_id.id or api.SUPERUSER_ID
|
||
session = session.with_env(api.Environment(cr, user_id, context)).sudo()
|
||
|
||
callback_type = (session.state or {}).get("callback_type")
|
||
|
||
if llm_result is False:
|
||
# 失败:直接展示真实错误(配置错误、限流、超时等),比通用文案更有用。
|
||
error_text = llm_error or "Odoo AI is currently unreachable. Please try again later."
|
||
if callback_type == "channel_name":
|
||
session.unlink()
|
||
else:
|
||
session._finish_exchange("failed", content=error_text)
|
||
_logger.warning("ai_deepseek: 交付失败信息 uuid=%s err=%s", request_uuid, llm_error)
|
||
return
|
||
|
||
completion_result = {"kind": "success", "message": llm_result["result"]}
|
||
if callback_type == "channel_name":
|
||
session._continue_channel_name(completion_result)
|
||
else:
|
||
session._continue_agent_loop(completion_result)
|
||
_logger.info("ai_deepseek: 交付完成 uuid=%s", request_uuid)
|
||
except Exception: # noqa: BLE001
|
||
_logger.exception("ai_deepseek: 交付失败 uuid=%s", request_uuid)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 3) 包装 call_odoo_ai:同步路径(有活 env)
|
||
# ---------------------------------------------------------------------------
|
||
def _patched_call_odoo_ai(env, route, params, add_iap_token=True, timeout=60):
|
||
cfg = get_config(env)
|
||
if not cfg.get("enabled"):
|
||
return _ORIGINALS["call_odoo_ai"](env, route, params, add_iap_token, timeout)
|
||
|
||
if route in ("1/get_completions", "1/get_completions_sync"):
|
||
message = ds.call_chat(
|
||
cfg,
|
||
params.get("messages", []),
|
||
params.get("instructions", ""),
|
||
params.get("tools", []),
|
||
schema=params.get("schema"),
|
||
)
|
||
return {"result": ds.build_odoo_assistant(message)}
|
||
|
||
if route == "1/get_embeddings":
|
||
vectors = ds.call_embeddings(cfg, params.get("input", []), params.get("model"))
|
||
return {"embeddings": vectors}
|
||
|
||
if route in ("1/get_default_embedding_model", "1/get_supported_embedding_models"):
|
||
model = cfg.get("emb_model") or ds.DEFAULT_EMBEDDING_MODEL
|
||
return model if route == "1/get_default_embedding_model" else [model]
|
||
|
||
# 转录 / 实时会话等暂不代理,回退官方(会因 credits 失败,但行为可控)。
|
||
_logger.info("ai_deepseek: 同步路由 %s 未代理,回退官方", route)
|
||
return _ORIGINALS["call_odoo_ai"](env, route, params, add_iap_token, timeout)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 安装 / 卸载
|
||
# ---------------------------------------------------------------------------
|
||
# 这些模块在 import 时把函数绑定进了各自命名空间,替换时必须逐个覆盖。
|
||
def _targets():
|
||
from odoo.addons.ai.utils import ai_utils
|
||
from odoo.addons.ai.models import ai_session, ai_embedding, mail_call_artifact
|
||
from odoo.addons.ai.controllers import ai as ai_controller
|
||
return ai_utils, ai_session, ai_embedding, mail_call_artifact, ai_controller
|
||
|
||
|
||
def apply_patch():
|
||
"""替换传输层函数(幂等)。"""
|
||
if _ORIGINALS:
|
||
return
|
||
ai_utils, ai_session, ai_embedding, mail_call_artifact, ai_controller = _targets()
|
||
_ORIGINALS["get_odoo_ai_connection_data"] = ai_utils.get_odoo_ai_connection_data
|
||
_ORIGINALS["call_odoo_ai_transport"] = ai_utils.call_odoo_ai_transport
|
||
_ORIGINALS["call_odoo_ai"] = ai_utils.call_odoo_ai
|
||
|
||
ai_utils.get_odoo_ai_connection_data = _patched_get_connection_data
|
||
ai_utils.call_odoo_ai_transport = _patched_call_odoo_ai_transport
|
||
ai_utils.call_odoo_ai = _patched_call_odoo_ai
|
||
|
||
ai_session.get_odoo_ai_connection_data = _patched_get_connection_data
|
||
ai_session.call_odoo_ai_transport = _patched_call_odoo_ai_transport
|
||
ai_session.call_odoo_ai = _patched_call_odoo_ai
|
||
ai_embedding.call_odoo_ai = _patched_call_odoo_ai
|
||
mail_call_artifact.call_odoo_ai = _patched_call_odoo_ai
|
||
ai_controller.call_odoo_ai = _patched_call_odoo_ai
|
||
_logger.info("ai_deepseek: 传输层已接管")
|
||
|
||
|
||
def remove_patch():
|
||
if not _ORIGINALS:
|
||
return
|
||
ai_utils, ai_session, ai_embedding, mail_call_artifact, ai_controller = _targets()
|
||
ai_utils.get_odoo_ai_connection_data = _ORIGINALS["get_odoo_ai_connection_data"]
|
||
ai_utils.call_odoo_ai_transport = _ORIGINALS["call_odoo_ai_transport"]
|
||
ai_utils.call_odoo_ai = _ORIGINALS["call_odoo_ai"]
|
||
ai_session.get_odoo_ai_connection_data = _ORIGINALS["get_odoo_ai_connection_data"]
|
||
ai_session.call_odoo_ai_transport = _ORIGINALS["call_odoo_ai_transport"]
|
||
ai_session.call_odoo_ai = _ORIGINALS["call_odoo_ai"]
|
||
ai_embedding.call_odoo_ai = _ORIGINALS["call_odoo_ai"]
|
||
mail_call_artifact.call_odoo_ai = _ORIGINALS["call_odoo_ai"]
|
||
ai_controller.call_odoo_ai = _ORIGINALS["call_odoo_ai"]
|
||
_ORIGINALS.clear()
|
||
_logger.info("ai_deepseek: 传输层已还原")
|