初始提交
This commit is contained in:
165
ai_deepseek/README.md
Normal file
165
ai_deepseek/README.md
Normal file
@@ -0,0 +1,165 @@
|
||||
# ai_deepseek —— 让 Odoo 20 AI 模块改走 DeepSeek
|
||||
|
||||
Odoo 20 Enterprise 的 `ai` 模块默认把所有请求发给官方 IAP 服务
|
||||
(`https://ai.api.odoo.com`),需要购买 credits。本模块**在 Odoo 进程内**
|
||||
接管 AI 的传输层,把请求转给 DeepSeek(或任意 OpenAI 兼容端点)。
|
||||
|
||||
**不需要额外运行任何脚本或服务**,安装模块 + 填个 API Key 即可。
|
||||
|
||||
---
|
||||
|
||||
## 一、原理(为什么这样可行)
|
||||
|
||||
Odoo AI 模块的所有对外调用都汇聚到 `ai/utils/ai_utils.py` 的三个函数:
|
||||
|
||||
| 函数 | 作用 |
|
||||
|---|---|
|
||||
| `get_odoo_ai_connection_data(env)` | 有活的 `env`,产出连接信息 |
|
||||
| `call_odoo_ai_transport(connection, route, params)` | **异步**:结果经 webhook 异步回传 |
|
||||
| `call_odoo_ai(env, route, params)` | **同步**:直接取返回值(用于 embedding / 工具内部调用) |
|
||||
|
||||
> Odoo 官方自己的测试 `ai/tests/common.py::mock_iap_results` 就是替换
|
||||
> `ai_session.call_odoo_ai_transport` 来打桩的 —— 这是官方认可的拦截点。
|
||||
|
||||
本模块用 `post_load` 钩子(每次服务器启动都执行)把这些函数换成 DeepSeek 实现。
|
||||
|
||||
### 关键难点与解法
|
||||
|
||||
`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 / 附件 / 工具循环全自动)。
|
||||
|
||||
---
|
||||
|
||||
## 二、安装
|
||||
|
||||
1. `E:\odoo20\odoo20.conf` 的 `addons_path` 追加了 `E:/odoo20/custom-addons`
|
||||
(已自动写入,原文件备份为 `odoo20.conf.bak-ai-deepseek`)。
|
||||
2. 安装模块(先确保 `ai` 已安装):
|
||||
|
||||
```bash
|
||||
E:\odoo20\venv\Scripts\python.exe E:\odoo20\odoo20\odoo-bin ^
|
||||
-c E:\odoo20\odoo20.conf -d odoo20 -i ai_deepseek --stop-after-init
|
||||
```
|
||||
|
||||
3. 重启 Odoo 服务(`post_load` 会在启动时接管传输层)。
|
||||
|
||||
---
|
||||
|
||||
## 三、配置
|
||||
|
||||
**设置 → 技术 → 系统参数**,或直接写库:
|
||||
|
||||
| 参数 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `ai_deepseek.enabled` | `False` | 总开关。关闭则回退官方 IAP |
|
||||
| `ai_deepseek.api_key` | — | **必填**,DeepSeek API Key |
|
||||
| `ai_deepseek.base_url` | `https://api.deepseek.com` | 任意 OpenAI 兼容端点 |
|
||||
| `ai_deepseek.model` | `deepseek-chat` | 可改 `deepseek-reasoner` |
|
||||
| `ai_deepseek.timeout` | `120` | 单次请求超时(秒) |
|
||||
| `ai_deepseek.emb_base_url` | 空 | 嵌入端点;留空复用 base_url |
|
||||
| `ai_deepseek.emb_api_key` | 空 | 留空复用 api_key |
|
||||
| `ai_deepseek.emb_model` | `text-embedding-3-small` | **必须输出 1536 维**(见下) |
|
||||
|
||||
也可在 **设置 → AI DeepSeek** 界面里可视化配置。
|
||||
|
||||
### 关于 Embedding(RAG)
|
||||
|
||||
Odoo 的 `ai.embedding` 向量列固定为 **1536 维**(`Vector(size=1536)`)。
|
||||
DeepSeek **没有** embeddings 接口,所以 RAG 必须另配一个 OpenAI 兼容的
|
||||
嵌入服务(如 OpenAI `text-embedding-3-small`、智谱、硅基流动等)。
|
||||
若不用 RAG,留空即可 —— 只是 Agent 的"知识源"功能不可用。
|
||||
|
||||
---
|
||||
|
||||
## 四、验证
|
||||
|
||||
在任意 AI 会话里发一条消息。正常流程:
|
||||
|
||||
1. 模块拦截 → 后台线程调 DeepSeek
|
||||
2. 结果进程内交付 → 会话显示回复
|
||||
3. 若 AI 调用工具,Odoo 执行后再发下一轮,直到给出最终答复
|
||||
|
||||
日志关键字:
|
||||
|
||||
```
|
||||
ai_deepseek: 传输层已接管
|
||||
ai_deepseek: 交付完成 uuid=...
|
||||
```
|
||||
|
||||
### 已验证结果(2026-10-10)
|
||||
|
||||
| 验证项 | 方式 | 结果 |
|
||||
|---|---|---|
|
||||
| 纯逻辑单测(协议转换 / HMAC) | 离线脚本(验证后已清理) | ✅ 6/6 断言通过 |
|
||||
| Odoo 集成测试(补丁 / 配置注入 / 同步补全 / 工具 / embedding / 回退) | `odoo-bin --test-tags ai_deepseek` | ✅ 6 tests, 0 failed, 0 error |
|
||||
| 异步交付(postcommit → 后台线程 → 新 cursor 交付) | 提交级端到端脚本(验证后已清理) | ✅ 全部通过 |
|
||||
| 工具调用循环(多轮 → 执行工具 → 最终答复) | 提交级端到端脚本(验证后已清理) | ✅ 全部通过 |
|
||||
|
||||
> 一次性验证脚本(`test_deepseek_client.py` / `simulate_*.py`)在验证通过后已删除,
|
||||
> 结论保留于此;模块本身的回归保障由 `tests/test_deepseek_bridge.py` 承担。
|
||||
|
||||
其中工具循环验证的关键结论:**AI 工具多轮循环在 DeepSeek 桥接下自然延续** ——
|
||||
`_finish_tool_batch` → `_submit_agent_request()` 会再次走传输层,无需额外适配。
|
||||
注意:Odoo 的技能需先"加载"(`ai_tool_load_skills`)其 `tool_ids` 才进入
|
||||
`available_tools`;建模时若直接指定技能,需在 `ai.session.state['loaded_skills']`
|
||||
里预置该技能,工具才会被模型看到。
|
||||
|
||||
### 运行集成测试
|
||||
|
||||
```bash
|
||||
E:\\odoo20\\venv\\Scripts\\python.exe E:\\odoo20\\odoo20\\odoo-bin ^
|
||||
--addons-path="E:/odoo20/enterprise20/odoo/addons,E:/odoo20/odoo20/addons,E:/odoo20/odoo20/odoo/addons,E:/odoo20/custom-addons" ^
|
||||
-d odoo20 --db_host=127.0.0.1 --db_port=5433 --db_user=odoo20 --db_password=mark8872 ^
|
||||
--test-tags ai_deepseek --stop-after-init --log-level=test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、切换与回滚
|
||||
|
||||
- **临时关闭**:设 `ai_deepseek.enabled = False` → 立即回退官方 IAP(需重启)。
|
||||
- **彻底卸载**:卸载模块即可。`post_load` 的替换只存在于进程内存中,
|
||||
重启后自然消失;`remove_patch()` 也可在 shell 里手动调用。
|
||||
|
||||
---
|
||||
|
||||
## 六、注意事项
|
||||
|
||||
- 本模块替换的是**私有 API**(`call_odoo_ai*`),Odoo 升级时需重新核对。
|
||||
- 工具执行仍在 Odoo 侧(沙箱化的 `ir.actions.server`),DeepSeek 只负责
|
||||
"调哪个工具、传什么参数"。
|
||||
- 转录(`/ai/transcription`)、实时语音会话等路由暂未代理,会回退官方
|
||||
(因 credits 为 0 而失败)—— 这些不影响文字对话。
|
||||
- DeepSeek 文本模型不支持图片输入,`inline_data` 部件会降级为文字说明。
|
||||
|
||||
## 七、文件说明
|
||||
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `__manifest__.py` | 模块清单,`depends=["ai"]`,`post_load` 钩子 |
|
||||
| `__init__.py` | 加载子模块 + `post_load_hook()` |
|
||||
| `deepseek_client.py` | 纯逻辑:协议转换、HMAC、HTTP 调用(不依赖 odoo,可离线测) |
|
||||
| `transport_patch.py` | 进程内接管传输层、异步交付 |
|
||||
| `models/res_config_settings.py` | 设置界面字段 |
|
||||
| `views/res_config_settings_views.xml` | 设置界面 |
|
||||
| `i18n/zh_CN.po` | 中文翻译 |
|
||||
| `tests/test_deepseek_bridge.py` | Odoo 集成测试(`--test-tags ai_deepseek`) |
|
||||
| `README.md` | 本文档 |
|
||||
21
ai_deepseek/__init__.py
Normal file
21
ai_deepseek/__init__.py
Normal file
@@ -0,0 +1,21 @@
|
||||
# Part of the ai_deepseek module.
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
|
||||
from . import deepseek_client
|
||||
from . import models
|
||||
from . import transport_patch
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def post_load_hook():
|
||||
"""服务器启动、模块导入后立即接管传输层。
|
||||
|
||||
用 post_load 而非 post_init_hook:前者在**每次**服务器启动时都会执行,
|
||||
从而保证重启后拦截持续生效(post_init 只在安装那一次跑)。
|
||||
"""
|
||||
try:
|
||||
transport_patch.apply_patch()
|
||||
except Exception: # noqa: BLE001
|
||||
_logger.exception("ai_deepseek: 传输层接管失败,AI 将回退官方 IAP 服务")
|
||||
33
ai_deepseek/__manifest__.py
Normal file
33
ai_deepseek/__manifest__.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# Part of the ai_deepseek module.
|
||||
# -*- coding: utf-8 -*-
|
||||
{
|
||||
"name": "AI DeepSeek Bridge",
|
||||
"version": "20.0.1.0.0",
|
||||
"category": "Productivity/AI",
|
||||
"summary": "让 Odoo 20 的 AI 模块改走 DeepSeek(或任意 OpenAI 兼容端点),无需 IAP credits",
|
||||
"description": """
|
||||
Odoo 20 Enterprise 的 `ai` 模块默认把所有请求发给官方 IAP 服务
|
||||
(https://ai.api.odoo.com),需要购买 credits。
|
||||
|
||||
本模块在**进程内**接管 `ai/utils/ai_utils.py` 的传输层,把请求
|
||||
转给 DeepSeek 的 OpenAI 兼容 API,于是:
|
||||
|
||||
* 不需要额外运行任何脚本或服务;
|
||||
* 不需要购买 Odoo IAP credits;
|
||||
* 支持 AI 工具调用(function calling)多轮循环;
|
||||
* 支持 RAG / Embedding(用 OpenAI 兼容的 embeddings 端点);
|
||||
* 可在设置界面配置,随时切回官方服务。
|
||||
|
||||
安装:`-i ai_deepseek`(需先安装 `ai` 模块)。
|
||||
""",
|
||||
"author": "Custom",
|
||||
"license": "LGPL-3",
|
||||
"depends": ["ai"],
|
||||
"data": [
|
||||
"views/res_config_settings_views.xml",
|
||||
],
|
||||
"post_load": "post_load_hook",
|
||||
"installable": True,
|
||||
"application": True,
|
||||
"auto_install": False,
|
||||
}
|
||||
291
ai_deepseek/deepseek_client.py
Normal file
291
ai_deepseek/deepseek_client.py
Normal file
@@ -0,0 +1,291 @@
|
||||
# Part of the ai_deepseek module.
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
纯逻辑层:Odoo AI 私有协议 <-> DeepSeek (OpenAI 兼容) 协议的转换。
|
||||
|
||||
本文件刻意不 import odoo,方便离线单测;
|
||||
需要拿 API Key 时由上层把配置以普通 dict 传入。
|
||||
"""
|
||||
import hashlib
|
||||
import hmac as hmac_lib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_BASE_URL = "https://api.deepseek.com"
|
||||
DEFAULT_MODEL = "deepseek-chat"
|
||||
DEFAULT_EMBEDDING_MODEL = "text-embedding-3-small"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Odoo webhook 签名 —— 逐字复刻 odoo.tools.hmac:
|
||||
# message = repr(("odoo_ai-webhook", (request_uuid, llm_result, llm_error)))
|
||||
# signature = HMAC-SHA256(secret, message.encode()).hexdigest()
|
||||
# 注意 dict 的 key 顺序会进入 repr,因此 llm_result 必须用固定 key 顺序构造,
|
||||
# 且 JSON 往返保持顺序,Odoo 侧重算才能匹配。
|
||||
# ---------------------------------------------------------------------------
|
||||
def odoo_hmac(secret, request_uuid, llm_result, llm_error):
|
||||
secret_bytes = secret.encode("utf-8") if isinstance(secret, str) else secret
|
||||
message = repr(("odoo_ai-webhook", (request_uuid, llm_result, llm_error)))
|
||||
return hmac_lib.new(secret_bytes, message.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Odoo 多部件消息 <-> OpenAI 消息
|
||||
# ---------------------------------------------------------------------------
|
||||
def text_from_parts(parts):
|
||||
"""把 Odoo content 部件列表拍平为纯文本(含 tool_result 内嵌文本)。"""
|
||||
if isinstance(parts, str):
|
||||
return parts
|
||||
texts = []
|
||||
for p in parts or []:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
if p.get("type") == "text":
|
||||
texts.append(p.get("text", ""))
|
||||
elif p.get("type") == "tool_result":
|
||||
texts.append(text_from_parts(p.get("result", [])))
|
||||
return "".join(texts)
|
||||
|
||||
|
||||
def _top_level_text(parts):
|
||||
"""只取顶层 text 部件(不包括 tool_result 内嵌文本)。"""
|
||||
return "".join(
|
||||
p.get("text", "") for p in (parts or [])
|
||||
if isinstance(p, dict) and p.get("type") == "text"
|
||||
)
|
||||
|
||||
|
||||
def to_openai_messages(messages):
|
||||
"""Odoo messages -> OpenAI messages。
|
||||
|
||||
Odoo 的 user 消息可能同时含文本与 tool_result 部件,而 OpenAI 要求
|
||||
tool 结果必须是独立的 role='tool' 消息,因此这里做拆分。
|
||||
"""
|
||||
out = []
|
||||
for m in messages or []:
|
||||
role = m.get("role")
|
||||
content = m.get("content", [])
|
||||
if role == "user":
|
||||
top_text = _top_level_text(content)
|
||||
if top_text.strip():
|
||||
out.append({"role": "user", "content": top_text})
|
||||
for p in content or []:
|
||||
if isinstance(p, dict) and p.get("type") == "tool_result":
|
||||
out.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": p.get("tool_call_id"),
|
||||
"content": text_from_parts(p.get("result", [])),
|
||||
})
|
||||
# 图片等 inline_data 部件:DeepSeek 文本模型不支持,降级为文字说明
|
||||
for p in content or []:
|
||||
if isinstance(p, dict) and p.get("type") == "inline_data":
|
||||
out.append({
|
||||
"role": "user",
|
||||
"content": f"[unsupported attachment: {p.get('mimetype', 'binary')}]",
|
||||
})
|
||||
elif role == "assistant":
|
||||
text = _top_level_text(content)
|
||||
tool_calls = []
|
||||
for p in content or []:
|
||||
if isinstance(p, dict) and p.get("type") == "tool_call":
|
||||
args = p.get("args") or {}
|
||||
if not isinstance(args, str):
|
||||
args = json.dumps(args, ensure_ascii=False)
|
||||
tool_calls.append({
|
||||
"id": p.get("call_id"),
|
||||
"type": "function",
|
||||
"function": {"name": p.get("name"), "arguments": args},
|
||||
})
|
||||
msg = {"content": text if text.strip() else None}
|
||||
if tool_calls:
|
||||
msg["tool_calls"] = tool_calls
|
||||
out.append({"role": "assistant", **msg})
|
||||
else:
|
||||
text = text_from_parts(content)
|
||||
if text.strip():
|
||||
out.append({"role": "user", "content": text})
|
||||
return out
|
||||
|
||||
|
||||
def to_openai_tools(tools):
|
||||
"""Odoo tools -> OpenAI functions。"""
|
||||
out = []
|
||||
for t in tools or []:
|
||||
schema = t.get("schema") or {"type": "object", "properties": {}, "required": []}
|
||||
out.append({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": t.get("name"),
|
||||
"description": t.get("instructions", "") or "",
|
||||
"parameters": schema,
|
||||
},
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def build_odoo_assistant(msg):
|
||||
"""DeepSeek 的 assistant message -> Odoo AssistantMessage(key 顺序固定)。"""
|
||||
content = []
|
||||
text = msg.get("content")
|
||||
if text:
|
||||
content.append({"type": "text", "text": text})
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
fn = tc.get("function", {}) or {}
|
||||
raw = fn.get("arguments", "{}")
|
||||
try:
|
||||
args = json.loads(raw) if isinstance(raw, str) else (raw or {})
|
||||
except (ValueError, TypeError):
|
||||
args = {}
|
||||
content.append({
|
||||
"type": "tool_call",
|
||||
"name": fn.get("name"),
|
||||
"args": args,
|
||||
"call_id": tc.get("id"),
|
||||
"provider_data": {},
|
||||
})
|
||||
return {"role": "assistant", "content": content, "provider_metadata": {}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP
|
||||
# ---------------------------------------------------------------------------
|
||||
def _post_json(url, payload, headers, timeout):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
body = resp.read().decode("utf-8")
|
||||
return json.loads(body) if body.strip() else None
|
||||
|
||||
|
||||
_CJK_RE = re.compile(r"[\u4e00-\u9fff\u3400-\u4dbf]")
|
||||
|
||||
|
||||
def _user_message_is_chinese(messages):
|
||||
"""判断用户本轮输入是否为中文。
|
||||
|
||||
Odoo 智能体循环里,工具执行结果会以 role='user' 的 tool_result 消息追加在
|
||||
对话末尾。若只取「最后一条 user 消息」,会取到 tool_result(无文本),从而
|
||||
误判为非中文、漏掉强制中文规则。因此这里跳过纯 tool_result 的消息,定位用户
|
||||
最近一次真正的文本输入再判定。
|
||||
"""
|
||||
for m in reversed(messages or []):
|
||||
if m.get("role") != "user":
|
||||
continue
|
||||
text = _top_level_text(m.get("content", []))
|
||||
if text.strip():
|
||||
return bool(_CJK_RE.search(text))
|
||||
# 该 user 消息只有 tool_result,继续往前找用户的真实文本输入
|
||||
return False
|
||||
|
||||
|
||||
def call_chat(cfg, messages, instructions, tools, schema=None, extra=None):
|
||||
"""调用 DeepSeek chat/completions,返回 assistant message dict。"""
|
||||
api_key = cfg.get("api_key")
|
||||
if not api_key:
|
||||
raise RuntimeError("ai_deepseek.api_key 未配置")
|
||||
base = (cfg.get("base_url") or DEFAULT_BASE_URL).rstrip("/")
|
||||
model = cfg.get("model") or DEFAULT_MODEL
|
||||
timeout = cfg.get("timeout") or 120
|
||||
|
||||
# ---- 语言控制:强制跟随用户语言,消除中英文混排 ----
|
||||
# Odoo 的 agent 系统提示词整段是英文,模型在「澄清反问 / 工具动作描述」这类
|
||||
# 智能体流程里会退回英文;且 ask_user_question 工具描述自带英文示例
|
||||
# ("Which lighting style should the scene use?"),会诱导模型用英文提问。
|
||||
# 因此显式检测用户最新消息语言,并以「强制规则」形式注入到 system prompt 的
|
||||
# 开头与结尾,确保澄清反问、tool 参数(尤其是 ai_tool_ask_user_question 的
|
||||
# question 与 choices/选项标签)、解释说明都用同一语言。
|
||||
user_is_chinese = _user_message_is_chinese(messages)
|
||||
if user_is_chinese:
|
||||
lang_rule = (
|
||||
"[MANDATORY LANGUAGE RULE] The user is writing in Simplified Chinese "
|
||||
"(简体中文). You MUST write EVERYTHING in Simplified Chinese — including "
|
||||
"the `question` AND the `choices` (option labels) arguments of the "
|
||||
"ai_tool_ask_user_question tool: every option label MUST be in "
|
||||
"Simplified Chinese, never in English, even if the tool description's "
|
||||
"examples are in English. This also applies to your free-text reply, "
|
||||
"clarifying questions, explanations, and tool-action descriptions. "
|
||||
"Do NOT use English (including for option labels) unless the user switches to English."
|
||||
)
|
||||
else:
|
||||
lang_rule = (
|
||||
"[MANDATORY LANGUAGE RULE] Reply in the same language as the user's "
|
||||
"latest message. If the user writes in Chinese, answer in Chinese; if "
|
||||
"in English, answer in English. This rule also applies to clarifying "
|
||||
"questions, to the `question` AND `choices` (option labels) arguments "
|
||||
"of the ai_tool_ask_user_question tool, and to tool-action descriptions."
|
||||
)
|
||||
base_instructions = instructions or ""
|
||||
system_text = lang_rule + "\n\n" + base_instructions + "\n\n" + lang_rule
|
||||
if schema:
|
||||
system_text += (
|
||||
"\n\n[OUTPUT FORMAT] Reply with a single JSON object that strictly "
|
||||
"conforms to this JSON schema:\n" + json.dumps(schema, ensure_ascii=False)
|
||||
)
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": ([{"role": "system", "content": system_text}] if system_text else [])
|
||||
+ to_openai_messages(messages),
|
||||
}
|
||||
openai_tools = to_openai_tools(tools)
|
||||
if openai_tools:
|
||||
payload["tools"] = openai_tools
|
||||
payload["tool_choice"] = "auto"
|
||||
if schema:
|
||||
payload["response_format"] = {"type": "json_object"}
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
|
||||
parsed = _post_json(
|
||||
base + "/v1/chat/completions",
|
||||
payload,
|
||||
{"Content-Type": "application/json", "Authorization": "Bearer " + api_key},
|
||||
timeout,
|
||||
)
|
||||
return parsed["choices"][0]["message"]
|
||||
|
||||
|
||||
def call_embeddings(cfg, inputs, model=None):
|
||||
"""调用 OpenAI 兼容 embeddings 端点,返回 [[float, ...], ...]。"""
|
||||
api_key = cfg.get("emb_api_key") or cfg.get("api_key")
|
||||
base = (cfg.get("emb_base_url") or cfg.get("base_url") or DEFAULT_BASE_URL).rstrip("/")
|
||||
model = model or cfg.get("emb_model") or DEFAULT_EMBEDDING_MODEL
|
||||
timeout = cfg.get("timeout") or 120
|
||||
if not api_key:
|
||||
raise RuntimeError("ai_deepseek.emb_api_key / api_key 未配置")
|
||||
|
||||
parsed = _post_json(
|
||||
base + "/v1/embeddings",
|
||||
{"model": model, "input": inputs},
|
||||
{"Content-Type": "application/json", "Authorization": "Bearer " + api_key},
|
||||
timeout,
|
||||
)
|
||||
# 按 index 排序,确保与输入顺序一致
|
||||
data = sorted(parsed["data"], key=lambda d: d.get("index", 0))
|
||||
return [d["embedding"] for d in data]
|
||||
|
||||
|
||||
def post_webhook(webhook_url, request_uuid, webhook_secret, llm_result, llm_error, timeout=30,
|
||||
retries=2):
|
||||
"""把结果回传给 Odoo 的 /ai/completion_result_ready(带 HMAC 签名)。"""
|
||||
signature = odoo_hmac(webhook_secret, request_uuid, llm_result, llm_error)
|
||||
body = {
|
||||
"request_uuid": request_uuid,
|
||||
"llm_result": llm_result,
|
||||
"llm_error": llm_error,
|
||||
"signature": signature,
|
||||
}
|
||||
last_exc = None
|
||||
for attempt in range(retries + 1):
|
||||
try:
|
||||
_post_json(webhook_url, body, {"Content-Type": "application/json"}, timeout)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
last_exc = exc
|
||||
_logger.warning("ai_deepseek: webhook 回传失败(第 %d 次): %s", attempt + 1, exc)
|
||||
_logger.error("ai_deepseek: webhook 最终失败: %s", last_exc)
|
||||
return False
|
||||
102
ai_deepseek/i18n/zh_CN.po
Normal file
102
ai_deepseek/i18n/zh_CN.po
Normal file
@@ -0,0 +1,102 @@
|
||||
# Translation of ai_deepseek in Simplified Chinese.
|
||||
# 本文件由模块自带,仅供 Odoo 设置界面显示。
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: ai_deepseek 20.0\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Language: zh_CN\n"
|
||||
"Plural-Forms: nplurals=1; plural=0;\n"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "AI DeepSeek"
|
||||
msgstr "AI DeepSeek"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "DeepSeek Bridge"
|
||||
msgstr "DeepSeek 桥接"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Use DeepSeek instead of Odoo IAP"
|
||||
msgstr "使用 DeepSeek 替代 Odoo IAP"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Route all Odoo AI requests to DeepSeek. No Odoo credits required."
|
||||
msgstr "将 Odoo 的所有 AI 请求转发到 DeepSeek,无需购买 Odoo credits。"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "API Key"
|
||||
msgstr "API 密钥"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Your DeepSeek API key (kept in a system parameter)."
|
||||
msgstr "你的 DeepSeek API 密钥(保存在系统参数中)。"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Base URL"
|
||||
msgstr "接口地址"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Any OpenAI-compatible endpoint."
|
||||
msgstr "任意 OpenAI 兼容端点。"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Chat Model"
|
||||
msgstr "对话模型"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Timeout (s)"
|
||||
msgstr "超时(秒)"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "HTTP timeout for a single DeepSeek request."
|
||||
msgstr "单次 DeepSeek 请求的 HTTP 超时时间。"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Embeddings (RAG)"
|
||||
msgstr "向量嵌入(RAG)"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Embedding Base URL"
|
||||
msgstr "嵌入接口地址"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Embedding API Key"
|
||||
msgstr "嵌入 API 密钥"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Embedding Model"
|
||||
msgstr "嵌入模型"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Use DeepSeek for Odoo AI"
|
||||
msgstr "让 Odoo AI 使用 DeepSeek"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Leave empty to reuse the chat API key."
|
||||
msgstr "留空则复用对话模型的 API 密钥。"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Must produce 1536-dimension vectors."
|
||||
msgstr "必须输出 1536 维向量。"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Chat base URL"
|
||||
msgstr "对话接口地址"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "e.g. deepseek-chat or deepseek-reasoner"
|
||||
msgstr "例如 deepseek-chat 或 deepseek-reasoner"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "e.g. deepseek-chat, deepseek-reasoner"
|
||||
msgstr "例如 deepseek-chat、deepseek-reasoner"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "Must produce 1536-dimension vectors (Odoo ai.embedding vector size)."
|
||||
msgstr "必须输出 1536 维向量(对应 Odoo ai.embedding 的向量维度)。"
|
||||
|
||||
#. module: ai_deepseek
|
||||
msgid "OpenAI-compatible /v1/embeddings endpoint. Must return 1536-dimension vectors to match Odoo's ai.embedding vector size. Leave empty to reuse the chat base URL."
|
||||
msgstr "OpenAI 兼容的 /v1/embeddings 端点。必须返回 1536 维向量以匹配 Odoo ai.embedding 的向量维度。留空则复用对话接口地址。"
|
||||
3
ai_deepseek/models/__init__.py
Normal file
3
ai_deepseek/models/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
# Part of the ai_deepseek module.
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import res_config_settings
|
||||
52
ai_deepseek/models/res_config_settings.py
Normal file
52
ai_deepseek/models/res_config_settings.py
Normal file
@@ -0,0 +1,52 @@
|
||||
# Part of the ai_deepseek module.
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import fields, models
|
||||
|
||||
|
||||
class ResConfigSettings(models.TransientModel):
|
||||
_inherit = "res.config.settings"
|
||||
|
||||
ai_deepseek_enabled = fields.Boolean(
|
||||
string="Use DeepSeek for Odoo AI",
|
||||
config_parameter="ai_deepseek.enabled",
|
||||
help="When enabled, all Odoo AI requests are routed to DeepSeek instead "
|
||||
"of the official Odoo IAP service (no credits required).",
|
||||
)
|
||||
ai_deepseek_api_key = fields.Char(
|
||||
string="DeepSeek API Key",
|
||||
config_parameter="ai_deepseek.api_key",
|
||||
)
|
||||
ai_deepseek_base_url = fields.Char(
|
||||
string="DeepSeek Base URL",
|
||||
config_parameter="ai_deepseek.base_url",
|
||||
default="https://api.deepseek.com",
|
||||
help="Any OpenAI-compatible endpoint. E.g. https://api.deepseek.com",
|
||||
)
|
||||
ai_deepseek_model = fields.Char(
|
||||
string="Chat Model",
|
||||
config_parameter="ai_deepseek.model",
|
||||
default="deepseek-chat",
|
||||
help="e.g. deepseek-chat or deepseek-reasoner",
|
||||
)
|
||||
ai_deepseek_timeout = fields.Integer(
|
||||
string="Request Timeout (s)",
|
||||
config_parameter="ai_deepseek.timeout",
|
||||
default=120,
|
||||
)
|
||||
ai_deepseek_emb_base_url = fields.Char(
|
||||
string="Embedding Base URL",
|
||||
config_parameter="ai_deepseek.emb_base_url",
|
||||
help="Leave empty to reuse the chat base URL. Must be OpenAI-compatible "
|
||||
"(/v1/embeddings) and return 1536-dimension vectors for RAG to work.",
|
||||
)
|
||||
ai_deepseek_emb_api_key = fields.Char(
|
||||
string="Embedding API Key",
|
||||
config_parameter="ai_deepseek.emb_api_key",
|
||||
help="Leave empty to reuse the chat API key.",
|
||||
)
|
||||
ai_deepseek_emb_model = fields.Char(
|
||||
string="Embedding Model",
|
||||
config_parameter="ai_deepseek.emb_model",
|
||||
default="text-embedding-3-small",
|
||||
help="Must produce 1536-dimension vectors (Odoo ai.embedding vector size).",
|
||||
)
|
||||
3
ai_deepseek/tests/__init__.py
Normal file
3
ai_deepseek/tests/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
# Part of the ai_deepseek module.
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import test_deepseek_bridge
|
||||
121
ai_deepseek/tests/test_deepseek_bridge.py
Normal file
121
ai_deepseek/tests/test_deepseek_bridge.py
Normal file
@@ -0,0 +1,121 @@
|
||||
# Part of the ai_deepseek module.
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
集成测试:验证 ai_deepseek 传输层接管能驱动完整的 AI 会话。
|
||||
|
||||
运行:
|
||||
E:\\odoo20\\venv\\Scripts\\python.exe E:\\odoo20\\odoo20\\odoo-bin ^
|
||||
-c E:\\odoo20\\odoo20.conf -d odoo20 --test-tags ai_deepseek --stop-after-init
|
||||
|
||||
说明:只保留在 TransactionCase 中可靠的断言(补丁生效、配置注入、
|
||||
同步补全/embedding 返回值)。异步交付(postcommit + 后台线程 + 新 cursor)
|
||||
依赖真实提交,用同目录的 simulate_async_delivery.py 脚本做提交级验证。
|
||||
"""
|
||||
import logging
|
||||
from unittest.mock import patch
|
||||
|
||||
from odoo.tests import tagged
|
||||
from odoo.tests.common import TransactionCase
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@tagged("post_install", "-at_install", "ai_deepseek")
|
||||
class TestDeepSeekBridge(TransactionCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
icp = cls.env["ir.config_parameter"].sudo()
|
||||
icp.set_str("ai_deepseek.enabled", "True")
|
||||
icp.set_str("ai_deepseek.api_key", "sk-test-fake")
|
||||
|
||||
def test_patch_installed(self):
|
||||
"""传输层应已被替换(含各模块命名空间的绑定)。"""
|
||||
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_deepseek import transport_patch
|
||||
patched = transport_patch._patched_call_odoo_ai_transport
|
||||
self.assertIs(ai_utils.call_odoo_ai_transport, patched)
|
||||
self.assertIs(ai_session.call_odoo_ai_transport, patched)
|
||||
self.assertIs(ai_session.get_odoo_ai_connection_data,
|
||||
transport_patch._patched_get_connection_data)
|
||||
self.assertIs(ai_embedding.call_odoo_ai,
|
||||
transport_patch._patched_call_odoo_ai)
|
||||
self.assertIs(mail_call_artifact.call_odoo_ai,
|
||||
transport_patch._patched_call_odoo_ai)
|
||||
|
||||
def test_config_injected_into_connection(self):
|
||||
"""get_odoo_ai_connection_data 应把配置塞进 connection。"""
|
||||
from odoo.addons.ai.models import ai_session
|
||||
connection = ai_session.get_odoo_ai_connection_data(self.env)
|
||||
cfg = connection.get("ai_deepseek_cfg")
|
||||
self.assertTrue(cfg, "connection 未注入 ai_deepseek_cfg")
|
||||
self.assertTrue(cfg["enabled"])
|
||||
self.assertEqual(cfg["api_key"], "sk-test-fake")
|
||||
|
||||
def test_sync_completion_uses_deepseek(self):
|
||||
"""同步补全应返回 DeepSeek 的响应(mock HTTP)。"""
|
||||
from odoo.addons.ai.models import ai_session
|
||||
with patch("odoo.addons.ai_deepseek.deepseek_client.call_chat",
|
||||
return_value={"content": "你好,我是 DeepSeek。"}):
|
||||
resp = ai_session.call_odoo_ai(self.env, "1/get_completions_sync", {
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}],
|
||||
"instructions": "你是助手",
|
||||
"tools": [],
|
||||
})
|
||||
self.assertEqual(resp["result"]["role"], "assistant")
|
||||
self.assertEqual(resp["result"]["content"],
|
||||
[{"type": "text", "text": "你好,我是 DeepSeek。"}])
|
||||
|
||||
def test_sync_completion_tool_call(self):
|
||||
"""含工具调用的同步补全应正确转换。"""
|
||||
from odoo.addons.ai.models import ai_session
|
||||
with patch("odoo.addons.ai_deepseek.deepseek_client.call_chat",
|
||||
return_value={
|
||||
"content": None,
|
||||
"tool_calls": [{
|
||||
"id": "call_1", "type": "function",
|
||||
"function": {"name": "ai_tool_search", "arguments": '{"q": "x"}'},
|
||||
}],
|
||||
}):
|
||||
resp = ai_session.call_odoo_ai(self.env, "1/get_completions_sync", {
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": "找"}]}],
|
||||
"instructions": "你是助手",
|
||||
"tools": [],
|
||||
})
|
||||
part = resp["result"]["content"][0]
|
||||
self.assertEqual(part["type"], "tool_call")
|
||||
self.assertEqual(part["name"], "ai_tool_search")
|
||||
self.assertEqual(part["args"], {"q": "x"})
|
||||
self.assertEqual(part["call_id"], "call_1")
|
||||
|
||||
def test_sync_embeddings_uses_deepseek(self):
|
||||
from odoo.addons.ai.models import ai_session
|
||||
with patch("odoo.addons.ai_deepseek.deepseek_client.call_embeddings",
|
||||
return_value=[[0.1] * 1536]):
|
||||
resp = ai_session.call_odoo_ai(self.env, "1/get_embeddings", {
|
||||
"input": [{"content": "hello"}], "model": "m", "mode": "query",
|
||||
})
|
||||
self.assertEqual(len(resp["embeddings"]), 1)
|
||||
self.assertEqual(len(resp["embeddings"][0]), 1536)
|
||||
|
||||
def test_disabled_falls_back(self):
|
||||
"""关闭模块时应回退官方实现(不调用 DeepSeek)。"""
|
||||
from odoo.addons.ai.models import ai_session
|
||||
self.env["ir.config_parameter"].sudo().set_str("ai_deepseek.enabled", "False")
|
||||
from odoo.addons.ai.utils import ai_utils
|
||||
original = ai_utils.call_odoo_ai
|
||||
# 关闭后,call_odoo_ai 会走 _ORIGINALS(即 ai_utils 的原函数),
|
||||
# 这里仅断言不会调用到 deepseek_client(用 mock 探测)。
|
||||
with patch("odoo.addons.ai_deepseek.deepseek_client.call_chat",
|
||||
side_effect=AssertionError("disabled 时不应调用 DeepSeek")):
|
||||
try:
|
||||
# 官方实现会尝试联网,预计抛异常;关键是没走我们的分支。
|
||||
ai_session.call_odoo_ai(self.env, "1/get_default_embedding_model", {},
|
||||
add_iap_token=False)
|
||||
except AssertionError:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
self.env["ir.config_parameter"].sudo().set_str("ai_deepseek.enabled", "True")
|
||||
248
ai_deepseek/transport_patch.py
Normal file
248
ai_deepseek/transport_patch.py
Normal file
@@ -0,0 +1,248 @@
|
||||
# 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: 传输层已还原")
|
||||
69
ai_deepseek/views/res_config_settings_views.xml
Normal file
69
ai_deepseek/views/res_config_settings_views.xml
Normal file
@@ -0,0 +1,69 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<record id="res_config_settings_view_form_ai_deepseek" model="ir.ui.view">
|
||||
<field name="name">res.config.settings.view.form.inherit.ai.deepseek</field>
|
||||
<field name="model">res.config.settings</field>
|
||||
<field name="inherit_id" ref="base.res_config_settings_view_form"/>
|
||||
<field name="arch" type="xml">
|
||||
<xpath expr="//form" position="inside">
|
||||
<app data-string="AI DeepSeek" string="AI DeepSeek" name="ai_deepseek" groups="base.group_system">
|
||||
<block title="DeepSeek Bridge" name="ai_deepseek_bridge">
|
||||
<setting id="ai_deepseek_enabled_setting"
|
||||
string="Use DeepSeek instead of Odoo IAP"
|
||||
help="Route all Odoo AI requests to DeepSeek. No Odoo credits required.">
|
||||
<field name="ai_deepseek_enabled"/>
|
||||
<div class="text-muted mt-2" colspan="2">
|
||||
When disabled, Odoo falls back to the official
|
||||
<code>https://ai.api.odoo.com</code> service (requires credits).
|
||||
</div>
|
||||
</setting>
|
||||
<setting id="ai_deepseek_api_key_setting"
|
||||
string="API Key"
|
||||
help="Your DeepSeek API key (kept in a system parameter)."
|
||||
invisible="not ai_deepseek_enabled">
|
||||
<field name="ai_deepseek_api_key" password="True" placeholder="sk-..."/>
|
||||
</setting>
|
||||
<setting id="ai_deepseek_base_url_setting"
|
||||
string="Base URL"
|
||||
help="Any OpenAI-compatible endpoint."
|
||||
invisible="not ai_deepseek_enabled">
|
||||
<field name="ai_deepseek_base_url" placeholder="https://api.deepseek.com"/>
|
||||
</setting>
|
||||
<setting id="ai_deepseek_model_setting"
|
||||
string="Chat Model"
|
||||
help="e.g. deepseek-chat, deepseek-reasoner"
|
||||
invisible="not ai_deepseek_enabled">
|
||||
<field name="ai_deepseek_model" placeholder="deepseek-chat"/>
|
||||
</setting>
|
||||
<setting id="ai_deepseek_timeout_setting"
|
||||
string="Timeout (s)"
|
||||
help="HTTP timeout for a single DeepSeek request."
|
||||
invisible="not ai_deepseek_enabled">
|
||||
<field name="ai_deepseek_timeout"/>
|
||||
</setting>
|
||||
</block>
|
||||
<block title="Embeddings (RAG)" name="ai_deepseek_embeddings">
|
||||
<setting id="ai_deepseek_emb_base_url_setting"
|
||||
string="Embedding Base URL"
|
||||
help="OpenAI-compatible /v1/embeddings endpoint. Must return 1536-dimension vectors to match Odoo's ai.embedding vector size. Leave empty to reuse the chat base URL."
|
||||
invisible="not ai_deepseek_enabled">
|
||||
<field name="ai_deepseek_emb_base_url"/>
|
||||
</setting>
|
||||
<setting id="ai_deepseek_emb_api_key_setting"
|
||||
string="Embedding API Key"
|
||||
help="Leave empty to reuse the chat API key."
|
||||
invisible="not ai_deepseek_enabled">
|
||||
<field name="ai_deepseek_emb_api_key" password="True"/>
|
||||
</setting>
|
||||
<setting id="ai_deepseek_emb_model_setting"
|
||||
string="Embedding Model"
|
||||
help="Must produce 1536-dimension vectors."
|
||||
invisible="not ai_deepseek_enabled">
|
||||
<field name="ai_deepseek_emb_model" placeholder="text-embedding-3-small"/>
|
||||
</setting>
|
||||
</block>
|
||||
</app>
|
||||
</xpath>
|
||||
</field>
|
||||
</record>
|
||||
</odoo>
|
||||
Reference in New Issue
Block a user