fix: 探测 Responses/store 能力并在无状态时用 Completions 带全量历史

This commit is contained in:
2026-09-25 00:23:28 +08:00
parent d20c6a1302
commit 71eca63461
14 changed files with 584 additions and 193 deletions
+109 -20
View File
@@ -1,8 +1,10 @@
"""解析是否走 Responses API(显式开关,避免仅靠模型名推断)。"""
"""协议偏好与错误分类:先验缓存 + 运行时探测回退(不写死主机)。"""
from __future__ import annotations
from urllib.parse import urlparse
from dataclasses import dataclass
from domain.models import LlmProtocolCapability
def normalize_api_style(raw: str | None) -> str:
@@ -12,27 +14,114 @@ def normalize_api_style(raw: str | None) -> str:
return "auto"
def resolve_use_responses_api(api_style: str | None, base_url: str | None) -> bool:
@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]:
"""
auto:仅官方 OpenAI 主机默认 Responses;其余 Completions。
completions / responses:强制对应协议。
同轮探测顺序(未产出 token 前可依次尝试):
- store 已证实:Responses+store,有链则增量续聊
- store 未知:Responses+store + **Mongo 全量**,成功后再语义探测
- store 证伪:走 **Completions + Mongo 全量**
(DeepSeek 等无状态 Responses 会返回 id,但多轮 input 不可靠)
- Responses 不可用:Completions
"""
style = normalize_api_style(api_style)
if style == "responses":
return True
cap = cap or LlmProtocolCapability()
if style == "completions":
return False
host = _host(base_url)
return host == "api.openai.com"
return [ProtocolAttempt(False, False, False)]
attempts: list[ProtocolAttempt] = []
if cap.store is False:
# 无真实 store:一律 Completions + Mongo 全量(DeepSeek Responses 多轮不可靠)
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 _host(base_url: str | None) -> str:
raw = (base_url or "").strip()
if not raw:
return ""
if "://" not in raw:
raw = "https://" + raw
try:
return (urlparse(raw).hostname or "").lower()
except Exception: # noqa: BLE001
return ""
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"
+299 -99
View File
@@ -1,7 +1,7 @@
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。
P0:按 api_style 选择 Completions / Responses。
P1:Responses 同选型可带 previous_response_id 续链;失效则同轮回退 Mongo rebuild。
优先 Responses+store → Responses store=false → Completions;
能力结果写入 Redis,不按主机写死。未产出 token 前可同轮回退。
"""
from __future__ import annotations
@@ -15,18 +15,36 @@ 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, LlmRuntimeConfig, MessageRole, StreamEvent
from domain.ports import ChatStreamer
from infrastructure.llm.api_style import resolve_use_responses_api
from domain.models import (
ChatMessage,
LlmProtocolCapability,
LlmRuntimeConfig,
MessageRole,
StreamEvent,
)
from domain.ports import ChatStreamer, LlmProtocolCapabilityCache
from infrastructure.llm.api_style import (
ProtocolAttempt,
classify_protocol_error,
normalize_api_style,
plan_protocol_attempts,
)
logger = logging.getLogger(__name__)
class ResponseChainInvalidError(Exception):
"""previous_response_id 失效,调用方应清空链并以 Mongo rebuild 重试。"""
_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,
*,
@@ -38,51 +56,239 @@ class OpenAICompatibleStreamer(ChatStreamer):
max_tool_result_chars: int = 8000,
previous_response_id: str | None = None,
) -> AsyncIterator[StreamEvent]:
use_responses = resolve_use_responses_api(llm.api_style, llm.base_url)
chain_id = (previous_response_id or "").strip() or None
if not use_responses:
chain_id = None
logger.debug(
"LLM stream model=%s api_style=%s use_responses=%s chain=%s base_url=%s",
llm.model,
llm.api_style,
use_responses,
bool(chain_id),
llm.base_url,
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)
)
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=use_responses,
previous_response_id=chain_id,
):
yield event
except ResponseChainInvalidError:
if not chain_id:
raise
logger.warning(
"Responses 链失效,回退 Mongo rebuild model=%s provider_id=%s",
llm.model,
llm.provider_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
)
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=use_responses,
previous_response_id=None,
):
yield event
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,
):
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,
@@ -94,6 +300,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
tools: list[Any] | None,
max_tool_result_chars: int,
use_responses: bool,
use_store: bool,
previous_response_id: str | None,
) -> AsyncIterator[StreamEvent]:
kwargs: dict[str, Any] = {
@@ -107,14 +314,15 @@ class OpenAICompatibleStreamer(ChatStreamer):
}
if use_responses:
kwargs["output_version"] = "responses/v1"
# 续链依赖厂商侧 store;Key 属租户,不落我方
kwargs["store"] = True
# 同轮 tool 多跳:从 AIMessage.response_metadata.id 续 previous_response_id
kwargs["use_previous_response_id"] = True
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:
# 仅发本轮增量;历史由厂商侧链承接
if previous_response_id and use_store:
# 已证实 store:只发本轮,靠 previous_response_id 续上下文
messages: list[Any] = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_text),
@@ -123,6 +331,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
"previous_response_id": previous_response_id
}
else:
# 无 store / Completions / 未证实:Mongo 全量历史 + 本轮
messages = [SystemMessage(content=system_prompt)]
for m in history:
if m.role == MessageRole.USER:
@@ -131,21 +340,30 @@ class OpenAICompatibleStreamer(ChatStreamer):
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:
try:
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)
except Exception as e: # noqa: BLE001
if previous_response_id and _is_chain_invalid_error(e):
raise ResponseChainInvalidError(str(e)) from e
raise
if use_responses and last_response_id:
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
@@ -156,27 +374,22 @@ class OpenAICompatibleStreamer(ChatStreamer):
gathered = None
saw_tool = False
call_extra = first_extra if round_idx == 0 else {}
try:
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)
except Exception as e: # noqa: BLE001
if previous_response_id and round_idx == 0 and _is_chain_invalid_error(e):
raise ResponseChainInvalidError(str(e)) from e
raise
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_responses and last_response_id:
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
@@ -184,7 +397,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
messages.append(gathered)
tool_calls = getattr(gathered, "tool_calls", None) or []
if not tool_calls:
if use_responses and last_response_id:
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
@@ -236,7 +449,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
)
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
if use_responses and last_response_id:
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
@@ -252,19 +465,6 @@ def _response_id_of(msg: Any) -> str | None:
return None
def _is_chain_invalid_error(exc: BaseException) -> bool:
"""判断是否为 previous_response_id 不可用(过期/不存在/无权)。"""
text = str(exc).lower()
if "previous_response_id" in text or "previous response" in text:
return True
status = getattr(exc, "status_code", None) or getattr(
getattr(exc, "response", None), "status_code", None
)
if status == 400 and ("response" in text and "not found" in text):
return True
return False
def _chunk_text(content: Any) -> str:
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
if content is None: