mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 17:09:19 +08:00
feat: 支持 Completions/Responses 双协议,并在同选型下续链加速
This commit is contained in:
@@ -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 ""
|
||||
|
||||
Reference in New Issue
Block a user