feat: 支持 Completions/Responses 双协议,并在同选型下续链加速

This commit is contained in:
2026-09-24 17:10:34 +08:00
parent 9c2c1ed061
commit d20c6a1302
26 changed files with 533 additions and 43 deletions
@@ -0,0 +1,38 @@
"""解析是否走 Responses API(显式开关,避免仅靠模型名推断)。"""
from __future__ import annotations
from urllib.parse import urlparse
def normalize_api_style(raw: str | None) -> str:
s = (raw or "auto").strip().lower()
if s in ("auto", "completions", "responses"):
return s
return "auto"
def resolve_use_responses_api(api_style: str | None, base_url: str | None) -> bool:
"""
auto:仅官方 OpenAI 主机默认 Responses;其余 Completions。
completions / responses:强制对应协议。
"""
style = normalize_api_style(api_style)
if style == "responses":
return True
if style == "completions":
return False
host = _host(base_url)
return host == "api.openai.com"
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 ""
+187 -34
View File
@@ -1,8 +1,13 @@
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。"""
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。
P0:按 api_style 选择 Completions / Responses。
P1:Responses 同选型可带 previous_response_id 续链;失效则同轮回退 Mongo rebuild。
"""
from __future__ import annotations
import json
import logging
from typing import Any, AsyncIterator
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
@@ -12,6 +17,13 @@ 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
logger = logging.getLogger(__name__)
class ResponseChainInvalidError(Exception):
"""previous_response_id 失效,调用方应清空链并以 Mongo rebuild 重试。"""
class OpenAICompatibleStreamer(ChatStreamer):
@@ -24,53 +36,156 @@ class OpenAICompatibleStreamer(ChatStreamer):
system_prompt: str,
tools: list[Any] | None = None,
max_tool_result_chars: int = 8000,
previous_response_id: str | None = None,
) -> AsyncIterator[StreamEvent]:
model = ChatOpenAI(
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 = 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,
)
messages: list[Any] = [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))
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,
)
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
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,
previous_response_id: str | 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"
# 续链依赖厂商侧 store;Key 属租户,不落我方
kwargs["store"] = True
# 同轮 tool 多跳:从 AIMessage.response_metadata.id 续 previous_response_id
kwargs["use_previous_response_id"] = True
model = ChatOpenAI(**kwargs)
if 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:
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 = {}
last_response_id: str | None = None
if not tools:
async for chunk in model.astream(messages):
text = _chunk_text(chunk.content)
if text:
yield StreamEvent.token(text)
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:
yield StreamEvent.response_chain(last_response_id)
return
# 工具轮:每轮用 astream 边生成边推 token;出现 tool_call 再执行工具后继续
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 _ in range(5):
for round_idx in range(5):
gathered = None
saw_tool = False
async for chunk in bound.astream(messages):
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)
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
if gathered is None:
yield StreamEvent.token("(模型未返回内容)")
if use_responses 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_responses and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
seen: set[str] = set()
@@ -121,19 +236,57 @@ class OpenAICompatibleStreamer(ChatStreamer):
)
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
if use_responses 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 _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:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for part in content:
if isinstance(part, dict) and part.get("type") == "text":
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))
elif isinstance(part, str):
parts.append(part)
return "".join(parts)
return ""
+4
View File
@@ -9,6 +9,7 @@ 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__)
@@ -53,6 +54,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
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(