This commit is contained in:
2026-10-21 23:23:48 +08:00
commit a9e4f6cd90
2983 changed files with 303453 additions and 0 deletions
+128
View File
@@ -0,0 +1,128 @@
"""协议偏好与错误分类:先验缓存 + 运行时探测回退(不写死主机)。"""
from __future__ import annotations
from dataclasses import dataclass
from domain.models import LlmProtocolCapability
def normalize_api_style(raw: str | None) -> str:
s = (raw or "auto").strip().lower()
if s in ("auto", "completions", "responses"):
return s
return "auto"
@dataclass(frozen=True)
class ProtocolAttempt:
"""单次调用策略。"""
use_responses: bool
use_store: bool
use_chain: bool # 是否只发增量 + previous_response_id(须 store 已证实)
def plan_protocol_attempts(
api_style: str | None,
cap: LlmProtocolCapability | None,
*,
has_chain_id: bool,
) -> list[ProtocolAttempt]:
"""
同轮探测顺序(未产出 token 前可依次尝试):
- store 已证实:Responses+store,有链则增量续聊
- store 未知:Responses+store + **Mongo 全量**,成功后再语义探测
- store 证伪:先 **无状态 Responses + Mongo 全量**,失败再 **Completions**
- Responses 不可用:Completions
"""
style = normalize_api_style(api_style)
cap = cap or LlmProtocolCapability()
if style == "completions":
return [ProtocolAttempt(False, False, False)]
attempts: list[ProtocolAttempt] = []
if cap.store is False:
# 无真实 store:无状态 Responses(全量历史)→ Completions
if cap.responses is not False:
attempts.append(ProtocolAttempt(True, False, False))
attempts.append(ProtocolAttempt(False, False, False))
return _dedupe(attempts)
if cap.responses is not False:
if cap.store is True:
attempts.append(
ProtocolAttempt(True, True, use_chain=bool(has_chain_id))
)
# 有链失败时可降到同协议全量
attempts.append(ProtocolAttempt(True, True, use_chain=False))
else:
# store 未知:Responses+store,必须全量历史,禁止 use_chain
attempts.append(ProtocolAttempt(True, True, use_chain=False))
attempts.append(ProtocolAttempt(True, False, False))
# Completions 兜底
if style == "auto" or cap.responses is False:
attempts.append(ProtocolAttempt(False, False, False))
elif style == "responses" and cap.responses is False:
attempts.append(ProtocolAttempt(False, False, False))
return _dedupe(attempts) or [ProtocolAttempt(False, False, False)]
def _dedupe(attempts: list[ProtocolAttempt]) -> list[ProtocolAttempt]:
seen: set[tuple[bool, bool, bool]] = set()
out: list[ProtocolAttempt] = []
for a in attempts:
key = (a.use_responses, a.use_store, a.use_chain)
if key in seen:
continue
seen.add(key)
out.append(a)
return out
def classify_protocol_error(exc: BaseException) -> str:
"""返回: store | responses | chain | other。"""
text = str(exc).lower()
status = getattr(exc, "status_code", None) or getattr(
getattr(exc, "response", None), "status_code", None
)
if "previous_response_id" in text or "previous response" in text:
return "chain"
if status == 400 and "response" in text and "not found" in text:
return "chain"
if "store" in text and any(
n in text
for n in (
"unsupported",
"unknown",
"unrecognized",
"invalid",
"not support",
"not supported",
)
):
return "store"
if status in (404, 405):
return "responses"
responses_needles = (
"/responses",
"responses api",
"unknown endpoint",
"not implemented",
"invalid pathname",
"no route",
)
if any(n in text for n in responses_needles):
return "responses"
if status == 400 and ("responses" in text or "response.create" in text):
return "responses"
return "other"
+503
View File
@@ -0,0 +1,503 @@
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。
优先 Responses+store → Responses store=false → Completions;
能力结果写入 Redis,不按主机写死。未产出 token 前可同轮回退。
"""
from __future__ import annotations
import json
import logging
from typing import Any, AsyncIterator
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
from langchain_openai import ChatOpenAI
from agent.tools.labels import tool_status_label
from agent.tools.publish_ui import is_client_tool_name
from domain.models import (
ChatMessage,
LlmProtocolCapability,
LlmRuntimeConfig,
MessageRole,
StreamEvent,
)
from domain.ports import ChatStreamer, ClientToolTurn, LlmProtocolCapabilityCache
from infrastructure.llm.api_style import (
ProtocolAttempt,
classify_protocol_error,
normalize_api_style,
plan_protocol_attempts,
)
logger = logging.getLogger(__name__)
_UNSET = object()
class OpenAICompatibleStreamer(ChatStreamer):
def __init__(
self,
capability_cache: LlmProtocolCapabilityCache | None = None,
*,
capability_ttl_seconds: int = 604800,
) -> None:
self._cap_cache = capability_cache
self._cap_ttl = capability_ttl_seconds
async def stream_reply(
self,
*,
llm: LlmRuntimeConfig,
history: list[ChatMessage],
user_text: str,
system_prompt: str,
tools: list[Any] | None = None,
max_tool_result_chars: int = 8000,
previous_response_id: str | None = None,
client_tool_turn: ClientToolTurn | None = None,
) -> AsyncIterator[StreamEvent]:
chain_id = (previous_response_id or "").strip() or None
style = normalize_api_style(llm.api_style)
# 未知 store 时先做语义探测(能否靠 previous_response_id 记住上下文)
cap = await self._ensure_protocol_capability(llm, style)
attempts = plan_protocol_attempts(
llm.api_style, cap, has_chain_id=bool(chain_id)
)
i = 0
while i < len(attempts):
attempt = attempts[i]
# 仅缓存已证实 store=true 时才丢历史、纯续链
use_chain_id = (
chain_id if (attempt.use_chain and cap and cap.store is True) else None
)
logger.warning(
"LLM attempt model=%s responses=%s store=%s chain=%s hist=%s api_style=%s",
llm.model,
attempt.use_responses,
attempt.use_store,
bool(use_chain_id),
len(history),
style,
)
yielded_any = False
got_chain_id: str | None = None
try:
async for event in self._stream_once(
llm=llm,
history=history,
user_text=user_text,
system_prompt=system_prompt,
tools=tools,
max_tool_result_chars=max_tool_result_chars,
use_responses=attempt.use_responses,
use_store=attempt.use_store,
previous_response_id=use_chain_id,
client_tool_turn=client_tool_turn,
):
if event.kind == "token" and event.text:
yielded_any = True
if event.kind == "response_chain" and event.response_id:
got_chain_id = event.response_id
continue
yield event
if attempt.use_responses:
if use_chain_id:
# 已证实 store 且本轮续链成功
await self._update_cap(llm, responses=True, store=True)
if got_chain_id:
yield StreamEvent.response_chain(got_chain_id)
elif attempt.use_store:
# store 未证实或待刷新:本轮是全量历史;语义探测真伪
need_probe = cap is None or cap.store is not True
if need_probe:
store_ok = await self._probe_store_semantic(llm)
await self._update_cap(
llm, responses=True, store=store_ok
)
cap = LlmProtocolCapability(
responses=True, store=store_ok
)
if store_ok and got_chain_id:
yield StreamEvent.response_chain(got_chain_id)
else:
await self._update_cap(llm, responses=True, store=True)
if got_chain_id:
yield StreamEvent.response_chain(got_chain_id)
else:
# Responses 无 store:能通端点但不持久
await self._update_cap(llm, responses=True, store=False)
cap = LlmProtocolCapability(responses=True, store=False)
else:
# Completions:若已知有 Responses 只是无 store,不要把 responses 打成 false
if cap is not None and cap.responses is True and cap.store is False:
await self._update_cap(llm, responses=True, store=False)
elif cap is not None and cap.store is False:
await self._update_cap(llm, responses=cap.responses, store=False)
else:
await self._update_cap(llm, responses=False, store=False)
cap = LlmProtocolCapability(responses=False, store=False)
return
except Exception as e: # noqa: BLE001
if yielded_any:
raise
kind = classify_protocol_error(e)
logger.warning(
"LLM attempt failed kind=%s model=%s err=%s",
kind,
llm.model,
e,
)
if kind == "chain" and use_chain_id:
await self._update_cap(llm, responses=True, store=False)
cap = LlmProtocolCapability(responses=True, store=False)
nxt = ProtocolAttempt(True, False, False)
if nxt not in attempts[i + 1 :]:
attempts.insert(i + 1, nxt)
i += 1
continue
if kind == "store" and attempt.use_responses and attempt.use_store:
await self._update_cap(llm, responses=True, store=False)
cap = LlmProtocolCapability(responses=True, store=False)
nxt = ProtocolAttempt(True, False, False)
if nxt not in attempts[i + 1 :]:
attempts.insert(i + 1, nxt)
i += 1
continue
if kind == "responses" and attempt.use_responses:
await self._update_cap(llm, responses=False, store=False)
cap = LlmProtocolCapability(responses=False, store=False)
nxt = ProtocolAttempt(False, False, False)
if nxt not in attempts[i + 1 :]:
attempts.insert(i + 1, nxt)
i += 1
continue
if i + 1 < len(attempts):
i += 1
continue
if style == "responses" and attempt.use_responses:
attempts.append(ProtocolAttempt(False, False, False))
i += 1
continue
raise
i += 1 # pragma: no cover
async def _ensure_protocol_capability(
self, llm: LlmRuntimeConfig, style: str
) -> LlmProtocolCapability | None:
"""读取能力缓存;completions 强制走 Completions,不探测。"""
if style == "completions":
return LlmProtocolCapability(responses=False, store=False)
return await self._load_cap(llm)
async def _load_cap(self, llm: LlmRuntimeConfig) -> LlmProtocolCapability | None:
if self._cap_cache is None:
return None
try:
return await self._cap_cache.get(
provider_id=llm.provider_id, base_url=llm.base_url
)
except Exception: # noqa: BLE001
logger.exception("读取协议能力缓存失败")
return None
async def _update_cap(
self,
llm: LlmRuntimeConfig,
*,
responses: bool | None | object = _UNSET,
store: bool | None | object = _UNSET,
) -> None:
"""更新能力缓存;参数为 _UNSET 表示不改该字段,显式 None 表示未知。"""
if self._cap_cache is None:
return
try:
prev = await self._cap_cache.get(
provider_id=llm.provider_id, base_url=llm.base_url
) or LlmProtocolCapability()
new_responses = (
prev.responses if responses is _UNSET else responses # type: ignore[arg-type]
)
new_store = prev.store if store is _UNSET else store # type: ignore[arg-type]
await self._cap_cache.set(
provider_id=llm.provider_id,
base_url=llm.base_url,
capability=LlmProtocolCapability(
responses=new_responses, # type: ignore[arg-type]
store=new_store, # type: ignore[arg-type]
),
ttl_seconds=self._cap_ttl,
)
except Exception: # noqa: BLE001
logger.exception("写入协议能力缓存失败")
async def _probe_store_semantic(self, llm: LlmRuntimeConfig) -> bool:
"""
语义探测:先写入密钥,再用 previous_response_id 且不带历史追问。
能答对密钥 → 真支持 store 续链;否则(报错或静默丢上下文)→ false。
"""
secret = "ALPHA7X"
try:
model = ChatOpenAI(
api_key=llm.api_key,
base_url=llm.base_url,
model=llm.model,
temperature=0,
streaming=False,
default_headers=llm.extra_headers or None,
use_responses_api=True,
output_version="responses/v1",
store=True,
use_previous_response_id=True,
)
first = await model.ainvoke(
[
HumanMessage(
content=(
f"这是接口能力测试。请记住密钥:{secret}。"
"只回复一个词:OK"
)
)
]
)
rid = _response_id_of(first)
if not rid:
logger.info("store 语义探测失败:首轮无 response.id model=%s", llm.model)
return False
second = await model.ainvoke(
[
HumanMessage(
content="接口能力测试续问:刚才的密钥是什么?只回复密钥本身。"
)
],
previous_response_id=rid,
)
text = _chunk_text(getattr(second, "content", None)).upper()
ok = secret in text.replace(" ", "").replace("-", "")
if not ok:
logger.info(
"store 语义探测未通过(静默丢上下文)model=%s reply=%s",
llm.model,
text[:80],
)
return ok
except Exception as e: # noqa: BLE001
logger.info(
"store 语义探测异常 model=%s kind=%s err=%s",
llm.model,
classify_protocol_error(e),
e,
)
return False
async def _stream_once(
self,
*,
llm: LlmRuntimeConfig,
history: list[ChatMessage],
user_text: str,
system_prompt: str,
tools: list[Any] | None,
max_tool_result_chars: int,
use_responses: bool,
use_store: bool,
previous_response_id: str | None,
client_tool_turn: ClientToolTurn | None = None,
) -> AsyncIterator[StreamEvent]:
kwargs: dict[str, Any] = {
"api_key": llm.api_key,
"base_url": llm.base_url,
"model": llm.model,
"temperature": 0.3,
"streaming": True,
"default_headers": llm.extra_headers or None,
"use_responses_api": use_responses,
}
if use_responses:
kwargs["output_version"] = "responses/v1"
kwargs["store"] = use_store
# 仅真正续链时打开;否则 LangChain 可能按 AIMessage.id 截断历史
kwargs["use_previous_response_id"] = bool(
previous_response_id and use_store
)
model = ChatOpenAI(**kwargs)
if previous_response_id and use_store:
# 已证实 store:只发本轮,靠 previous_response_id 续上下文
messages: list[Any] = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_text),
]
first_extra: dict[str, Any] = {
"previous_response_id": previous_response_id
}
else:
# 无 store / Completions / 未证实:Mongo 全量历史 + 本轮
messages = [SystemMessage(content=system_prompt)]
for m in history:
if m.role == MessageRole.USER:
messages.append(HumanMessage(content=m.content))
elif m.role == MessageRole.ASSISTANT:
messages.append(AIMessage(content=m.content))
messages.append(HumanMessage(content=user_text))
first_extra = {}
logger.warning(
"LLM pack full history lc_messages=%s hist_rows=%s preview=%s",
len(messages),
len(history),
[
(
m.role.value if hasattr(m, "role") else type(m).__name__,
(getattr(m, "content", None) or "")[:40],
)
for m in (
history[-4:] if len(history) > 4 else history
)
],
)
last_response_id: str | None = None
if not tools:
async for chunk in model.astream(messages, **first_extra):
last_response_id = _response_id_of(chunk) or last_response_id
text = _chunk_text(chunk.content)
if text:
yield StreamEvent.token(text)
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
bound = model.bind_tools(tools)
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
tool_cap = max(500, max_tool_result_chars)
for round_idx in range(5):
gathered = None
saw_tool = False
call_extra = first_extra if round_idx == 0 else {}
async for chunk in bound.astream(messages, **call_extra):
gathered = chunk if gathered is None else gathered + chunk
if getattr(chunk, "tool_call_chunks", None) or getattr(
chunk, "tool_calls", None
):
saw_tool = True
continue
if saw_tool:
continue
text = _chunk_text(getattr(chunk, "content", None))
if text:
yield StreamEvent.token(text)
if gathered is None:
yield StreamEvent.token("(模型未返回内容)")
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
last_response_id = _response_id_of(gathered) or last_response_id
messages.append(gathered)
tool_calls = getattr(gathered, "tool_calls", None) or []
if not tool_calls:
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
seen: set[str] = set()
for tc in tool_calls:
name = tc.get("name") or ""
if name in seen:
continue
seen.add(name)
yield StreamEvent.tool(
phase="start",
name=name,
label=tool_status_label(name),
)
for tc in tool_calls:
name = tc.get("name") or ""
args = tc.get("args") or {}
call_id = tc.get("id") or name
try:
if is_client_tool_name(name):
# 占位函数不代表页面已写入;先登记等待再推事件,回执到达后才进 ToolMessage
tool_args = args if isinstance(args, dict) else {}
if client_tool_turn is None:
result = "写入失败:前端回执通道未配置"
else:
client_tool_turn.arm(str(call_id))
yield StreamEvent.client_tool(
tool_call_id=str(call_id),
name=name,
args=tool_args,
label=tool_status_label(name),
)
result = await client_tool_turn.wait_result(str(call_id))
else:
tool = tool_map.get(name)
if tool is None:
result = f"未知工具: {name}"
else:
raw = await tool.ainvoke(args)
result = (
raw
if isinstance(raw, str)
else json.dumps(raw, ensure_ascii=False, default=str)
)
except Exception as e: # noqa: BLE001
result = f"工具执行失败: {e}"
messages.append(
ToolMessage(content=str(result)[:tool_cap], tool_call_id=call_id)
)
for name in seen:
yield StreamEvent.tool(
phase="end",
name=name,
label=tool_status_label(name),
)
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
def _response_id_of(msg: Any) -> str | None:
meta = getattr(msg, "response_metadata", None) or {}
if isinstance(meta, dict):
rid = meta.get("id")
if isinstance(rid, str) and rid.strip():
return rid.strip()
mid = getattr(msg, "id", None)
if isinstance(mid, str) and mid.startswith("resp_"):
return mid
return None
def _chunk_text(content: Any) -> str:
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for part in content:
if isinstance(part, str):
parts.append(part)
continue
if not isinstance(part, dict):
text = getattr(part, "text", None)
ptype = getattr(part, "type", None)
if text and ptype in (None, "text", "output_text"):
parts.append(str(text))
continue
ptype = part.get("type")
if ptype in (None, "text", "output_text"):
t = part.get("text")
if t:
parts.append(str(t))
return "".join(parts)
return ""
+78
View File
@@ -0,0 +1,78 @@
"""从 Server 内部接口拉取 LLM 运行时配置。"""
from __future__ import annotations
import logging
import httpx
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeGateway
from infrastructure.llm.api_style import normalize_api_style
logger = logging.getLogger(__name__)
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
"""GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=。"""
def __init__(self, settings: Settings) -> None:
self._settings = settings
async def fetch(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
params: dict[str, str | int] = {"companyId": company_id}
if provider_id is not None:
params["providerId"] = provider_id
if model:
params["model"] = model
try:
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.get(url, params=params, headers=headers)
if resp.status_code == 400:
return None
resp.raise_for_status()
body = resp.json()
data = body.get("data") if isinstance(body, dict) else None
if not isinstance(data, dict):
return None
pid = data.get("providerId")
return LlmRuntimeConfig(
base_url=str(data.get("baseUrl") or "").rstrip("/"),
api_key=str(data.get("apiKey") or ""),
model=str(data.get("model") or ""),
provider_id=int(pid) if pid is not None else provider_id,
extra_headers={
str(k): str(v)
for k, v in (data.get("extraHeaders") or {}).items()
},
context_window=_optional_positive_int(data.get("contextWindow")),
api_style=normalize_api_style(
None if data.get("apiStyle") is None else str(data.get("apiStyle"))
),
)
except Exception:
logger.exception(
"拉取 Server LLM runtime 失败 company_id=%s provider_id=%s model=%s",
company_id,
provider_id,
model,
)
return None
def _optional_positive_int(v) -> int | None:
if v is None:
return None
try:
n = int(v)
except (TypeError, ValueError):
return None
return n if n > 0 else None