Files
dn20/ai_deepseek/deepseek_client.py
2026-11-04 19:58:07 +08:00

292 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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