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
+9 -13
View File
@@ -368,23 +368,19 @@ apps/agent/
原则:**Mongo 仍是对话真相源**;Responses 链(`previous_response_id`)只是同提供商同模型下的加速缓存,切换选型即作废并全量 rebuild。
### Responses-P0(已落地)— 双协议传输,每轮仍 Mongo rebuild
### Responses-P0 / P1(已落地)— 运行时探测,不写死主机
1. 提供商字段 `api_style`:`auto` | `completions` | `responses`(迁移 `V20260924`)
2. Runtime / Redis 带出 `apiStyle`;Agent `ChatOpenAI(use_responses_api=…)` **显式开关**
3. `auto`:仅 `api.openai.com` 默认 Responses,其余 Completions
4. 流式 token 兼容结构化 content 块
5. 管理台提供商表单可选协议;列表展示
原则:优先新协议;能力靠探测 + Redis 缓存(`agent:llm:cap:*`),按错误回退,不按 OpenAI/DeepSeek 主机写死。
### Responses-P1(已落地)— 同链状态缓存 + 切换重建
同轮未产出 token 前的阶梯:
1. 会话 Mongo 字段 `llm_response_chain{provider_id,model,previous_response_id}`
2. Responses 时 `store=true`(Key 属租户);同选型续聊只发本轮增量 + `previous_response_id`
3. 切换 `llmProviderId`/`llmModel`(含聊天内消歧写回)清空链
4. 链失效:同轮回退全量 Mongo rebuild 一次,并写入新链 id
5. Completions 或无 response id:不写/清空链
1. **Responses + `store=true`**(语义证实后;有会话链则只发增量 + `previous_response_id`)
2. store 未知:Responses + `store=true` + **Mongo 全量历史**,成功后再做语义探测
3. **store 证伪**(如 DeepSeek 返回 id 但不持久):**一律 Completions + Mongo 全量历史**
(LangChain 虽可把多轮打进 Responses `input`,但无状态兼容端常不可靠)
4. Responses 端点不可用 → Completions
真相源仍是 Mongo 消息;链只是同提供商同模型下的加速缓存。
成功后写入能力缓存。**`store=true` 认定**:独立语义探测——先让模型记住密钥,再仅用 `previous_response_id`(不带历史)追问;答对才记 true。未证实前禁止只发增量。
---
+1 -1
View File
@@ -16,7 +16,7 @@ uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
健康检查:`GET http://localhost:8200/health`
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
**模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-providers`(凭证 + 协议 `apiStyle` + 多模型);Agent 经 Redis `agent:llm:rt:{companyId}:{providerId}:{model}` 或内部接口拉明文注入。按提供商 `api_style` 走 Chat Completions 或 Responses;Responses 同选型可续 `previous_response_id`(切换模型清链,失效则 Mongo rebuild,见 DESIGN §11)。
**模型 API 配置不在本服务**:浏览器走 Java 提供商 CRUD(含 `apiStyle`);Agent 拉 runtime 后**运行时探测** Responses/store,结果缓存 Redis `agent:llm:cap:*`,失败阶梯为 Responses+store → Responses → Completions(见 DESIGN §11)。
## 分环境配置
+9 -2
View File
@@ -19,7 +19,11 @@ from infrastructure.persistence.mongo.repositories import (
MongoMessageRepository,
MongoSessionRepository,
)
from infrastructure.persistence.redis.cache import RedisLlmRuntimeCache, get_redis
from infrastructure.persistence.redis.cache import (
RedisLlmProtocolCapabilityCache,
RedisLlmRuntimeCache,
get_redis,
)
async def current_actor(
@@ -68,5 +72,8 @@ async def chat_service(
messages=MongoMessageRepository(db),
llm_runtime=llm_svc,
memory=mem_svc,
streamer=OpenAICompatibleStreamer(),
streamer=OpenAICompatibleStreamer(
RedisLlmProtocolCapabilityCache(get_redis(settings)),
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
),
)
+6 -17
View File
@@ -20,7 +20,6 @@ from domain.models import (
StreamEvent,
)
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
from infrastructure.llm.api_style import resolve_use_responses_api
class ChatService:
@@ -70,7 +69,6 @@ class ChatService:
provider_id=session.llm_provider_id,
model=session.llm_model,
)
# 回落默认或消歧后写回会话;选型变化则清链
changed = False
if session.llm_model != llm.model:
session.llm_model = llm.model
@@ -82,10 +80,9 @@ class ChatService:
session.llm_response_chain = None
await self._session_repo.update(session)
use_responses = resolve_use_responses_api(llm.api_style, llm.base_url)
chain_id = _usable_chain_id(session.llm_response_chain, llm, use_responses)
# 链是否可用由 streamer 按 store 能力决定;此处只做选型匹配
chain_id = _usable_chain_id(session.llm_response_chain, llm)
if session.llm_response_chain and not chain_id:
# 链与当前选型不匹配,落库清空避免脏数据
session.llm_response_chain = None
await self._session_repo.update(session)
@@ -157,7 +154,6 @@ class ChatService:
parts: list[str] = []
new_response_id: str | None = None
used_chain = bool(chain_id)
async for event in self._streamer.stream_reply(
llm=llm,
history=history,
@@ -187,26 +183,19 @@ class ChatService:
)
)
session.last_message_at = datetime.utcnow()
if use_responses and new_response_id:
if new_response_id:
session.llm_response_chain = LlmResponseChain(
provider_id=llm.provider_id,
model=llm.model,
previous_response_id=new_response_id,
)
elif used_chain and not new_response_id:
# 续链失败已 rebuild 但仍无 id:清掉以免下次再踩坑
session.llm_response_chain = None
elif not use_responses:
else:
session.llm_response_chain = None
await self._session_repo.update(session)
def _usable_chain_id(
chain: LlmResponseChain | None,
llm,
use_responses: bool,
) -> str | None:
if not use_responses or chain is None:
def _usable_chain_id(chain: LlmResponseChain | None, llm) -> str | None:
if chain is None:
return None
rid = (chain.previous_response_id or "").strip()
if not rid:
+4 -3
View File
@@ -12,9 +12,10 @@ _BASE_SYSTEM = (
"需要经营数据时优先调用可用工具。"
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
"需要称呼、偏好或用户事实时:先 memory_search,必要时再 memory_load;"
"禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
"【本会话上下文】请求里已包含本会话近期的用户与助手原文,你可以直接看见并引用;"
"禁止声称「只收到当前一句」或「前面几轮不会带过来」——那是错误描述。"
"【长期记忆】跨会话的用户级记忆不会自动注入;需要称呼、偏好或用户事实时:"
"先 memory_search,必要时再 memory_load;禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
+2
View File
@@ -77,6 +77,8 @@ class Settings(BaseSettings):
# 为模型输出与本轮 tool 预留的 token
context_reserve_output_tokens: int = 4096
context_reserve_tool_tokens: int = 8192
# Responses/store 能力缓存 TTL(秒)
llm_capability_ttl_seconds: int = 604800
@property
def cors_origin_list(self) -> list[str]:
+8
View File
@@ -133,6 +133,14 @@ class LlmRuntimeConfig:
api_style: str = "auto"
@dataclass(frozen=True)
class LlmProtocolCapability:
"""按提供商缓存的协议能力;None 表示尚未验证。"""
responses: bool | None = None
store: bool | None = None
@dataclass(frozen=True)
class StreamEvent:
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
+27 -1
View File
@@ -5,7 +5,14 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, AsyncIterator
from domain.models import ChatMessage, LlmRuntimeConfig, Session, StreamEvent, UserMemory
from domain.models import (
ChatMessage,
LlmProtocolCapability,
LlmRuntimeConfig,
Session,
StreamEvent,
UserMemory,
)
class SessionRepository(ABC):
@@ -111,6 +118,25 @@ class LlmRuntimeGateway(ABC):
) -> LlmRuntimeConfig | None: ...
class LlmProtocolCapabilityCache(ABC):
"""缓存某提供商(或 base_url)是否支持 Responses / store。"""
@abstractmethod
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None: ...
@abstractmethod
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None: ...
class ChatStreamer(ABC):
"""流式生成助手回复。"""
+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:
@@ -7,8 +7,8 @@ import json
import redis.asyncio as redis
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeCache
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
from infrastructure.llm.api_style import normalize_api_style
@@ -99,6 +99,53 @@ def get_redis(settings: Settings) -> redis.Redis:
return _redis
class RedisLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
"""按 provider_id(优先)或 base_url 缓存 Responses/store 能力。"""
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(*, provider_id: int | None, base_url: str) -> str:
if provider_id is not None and int(provider_id) > 0:
return f"agent:llm:cap:p:{int(provider_id)}"
url = (base_url or "").rstrip("/").lower()
return f"agent:llm:cap:u:{url}"
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None:
raw = await self._r.get(self._key(provider_id=provider_id, base_url=base_url))
if not raw:
return None
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
return LlmProtocolCapability(
responses=data.get("responses"),
store=data.get("store"),
)
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None:
payload = {
"responses": capability.responses,
"store": capability.store,
}
await self._r.set(
self._key(provider_id=provider_id, base_url=base_url),
json.dumps(payload),
ex=max(60, ttl_seconds),
)
async def close_redis() -> None:
global _redis
if _redis is not None:
+55 -9
View File
@@ -1,17 +1,63 @@
"""api_style 解析单测。"""
"""协议探测规划与错误分类。"""
from infrastructure.llm.api_style import normalize_api_style, resolve_use_responses_api
from domain.models import LlmProtocolCapability
from infrastructure.llm.api_style import (
ProtocolAttempt,
classify_protocol_error,
normalize_api_style,
plan_protocol_attempts,
)
def test_normalize_api_style():
assert normalize_api_style(None) == "auto"
assert normalize_api_style("Responses") == "responses"
assert normalize_api_style("weird") == "auto"
def test_resolve_use_responses_api():
assert resolve_use_responses_api("responses", "https://api.deepseek.com/v1") is True
assert resolve_use_responses_api("completions", "https://api.openai.com/v1") is False
assert resolve_use_responses_api("auto", "https://api.openai.com/v1") is True
assert resolve_use_responses_api("auto", "https://api.deepseek.com/v1") is False
assert resolve_use_responses_api("auto", "https://xxx.openai.azure.com/") is False
def test_plan_unknown_auto_tries_store_full_history_then_fallbacks():
attempts = plan_protocol_attempts("auto", None, has_chain_id=True)
assert attempts[0] == ProtocolAttempt(True, True, False)
assert ProtocolAttempt(True, False, False) in attempts
assert ProtocolAttempt(False, False, False) in attempts
assert not any(a.use_chain for a in attempts)
def test_plan_store_true_allows_chain():
cap = LlmProtocolCapability(responses=True, store=True)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
assert attempts[0] == ProtocolAttempt(True, True, True)
assert ProtocolAttempt(True, True, False) in attempts
def test_plan_store_false_uses_completions():
"""DeepSeek 等:Responses 无状态时用 Completions 带 Mongo 历史。"""
cap = LlmProtocolCapability(responses=True, store=False)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
assert attempts == [ProtocolAttempt(False, False, False)]
def test_plan_store_false_forced_responses_still_completions():
cap = LlmProtocolCapability(responses=True, store=False)
attempts = plan_protocol_attempts("responses", cap, has_chain_id=False)
assert attempts == [ProtocolAttempt(False, False, False)]
def test_plan_completions_only():
assert plan_protocol_attempts("completions", None, has_chain_id=True) == [
ProtocolAttempt(False, False, False)
]
def test_plan_responses_known_unsupported_falls_to_completions():
cap = LlmProtocolCapability(responses=False, store=False)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=False)
assert attempts == [ProtocolAttempt(False, False, False)]
def test_classify_protocol_error():
assert classify_protocol_error(Exception("Invalid previous_response_id")) == "chain"
assert (
classify_protocol_error(Exception("Unsupported parameter: store")) == "store"
)
assert classify_protocol_error(Exception("404 /v1/responses not found")) == "responses"
assert classify_protocol_error(Exception("rate limit")) == "other"
+5 -25
View File
@@ -1,8 +1,7 @@
"""Responses 续链匹配与失效判定。"""
"""会话链选型匹配。"""
from domain.models import LlmResponseChain, LlmRuntimeConfig
from application.chat_service import _usable_chain_id
from infrastructure.llm.factory import _is_chain_invalid_error
def test_usable_chain_id_matches():
@@ -11,12 +10,12 @@ def test_usable_chain_id_matches():
api_key="k",
model="gpt-4o-mini",
provider_id=3,
api_style="responses",
api_style="auto",
)
chain = LlmResponseChain(
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
)
assert _usable_chain_id(chain, llm, True) == "resp_abc"
assert _usable_chain_id(chain, llm) == "resp_abc"
def test_usable_chain_id_clears_on_model_switch():
@@ -25,28 +24,9 @@ def test_usable_chain_id_clears_on_model_switch():
api_key="k",
model="gpt-4o",
provider_id=3,
api_style="responses",
api_style="auto",
)
chain = LlmResponseChain(
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
)
assert _usable_chain_id(chain, llm, True) is None
def test_usable_chain_id_requires_responses():
llm = LlmRuntimeConfig(
base_url="https://api.deepseek.com/v1",
api_key="k",
model="deepseek-chat",
provider_id=1,
api_style="completions",
)
chain = LlmResponseChain(
provider_id=1, model="deepseek-chat", previous_response_id="resp_x"
)
assert _usable_chain_id(chain, llm, False) is None
def test_is_chain_invalid_error():
assert _is_chain_invalid_error(Exception("Invalid previous_response_id: resp_x"))
assert not _is_chain_invalid_error(Exception("rate limit exceeded"))
assert _usable_chain_id(chain, llm) is None
@@ -35,7 +35,7 @@ const form = ref({
const apiStyleOptions = [
{
value: 'auto',
label: '自动(官方 OpenAI → Responses,其余 Completions)',
label: '自动(优先 Responses+store,失败再降级)',
},
{ value: 'completions', label: 'Chat Completions' },
{ value: 'responses', label: 'Responses API' },