mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 03:49:21 +08:00
132 lines
4.7 KiB
Python
132 lines
4.7 KiB
Python
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
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 domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
|
|
from domain.ports import ChatStreamer
|
|
|
|
|
|
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,
|
|
) -> 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,
|
|
)
|
|
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))
|
|
|
|
if not tools:
|
|
async for chunk in model.astream(messages):
|
|
text = _chunk_text(chunk.content)
|
|
if text:
|
|
yield StreamEvent.token(text)
|
|
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):
|
|
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)
|
|
if gathered is None:
|
|
yield StreamEvent.token("(模型未返回内容)")
|
|
return
|
|
messages.append(gathered)
|
|
tool_calls = getattr(gathered, "tool_calls", None) or []
|
|
if not tool_calls:
|
|
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
|
|
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("工具调用轮次过多,请缩小问题范围后重试。")
|
|
|
|
|
|
def _chunk_text(content: Any) -> str:
|
|
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":
|
|
t = part.get("text")
|
|
if t:
|
|
parts.append(str(t))
|
|
elif isinstance(part, str):
|
|
parts.append(part)
|
|
return "".join(parts)
|
|
return ""
|