Files
ecom-dmb/apps/agent/infrastructure/llm/factory.py
T

293 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""按租户构建 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
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
logger = logging.getLogger(__name__)
class ResponseChainInvalidError(Exception):
"""previous_response_id 失效,调用方应清空链并以 Mongo rebuild 重试。"""
class OpenAICompatibleStreamer(ChatStreamer):
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,
) -> 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,
)
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:
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
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 {}
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()
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
if is_client_tool_name(name):
yield StreamEvent.client_tool(
tool_call_id=str(call_id),
name=name,
args=args if isinstance(args, dict) else {},
label=tool_status_label(name),
)
tool = tool_map.get(name)
try:
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_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, 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 ""