mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge pull request #441 from Huan-zhaojun/feat/multi-agent-thinking-stream
feat: 多 Agent 思维链完整输出与精简模式切换
This commit is contained in:
9 files changed
+146
-48
No files matched your search
@@ -149,6 +149,20 @@ _GROK_RENDER_RE = re.compile(
|
||||
|
||||
_IMAGE_BASE = "https://assets.grok.com/"
|
||||
|
||||
# 工具使用卡片 → emoji 单行格式化映射(详细模式专用)
|
||||
# 格式: tool_name → (emoji, (可展示的参数 key 列表))
|
||||
_TOOL_FMT: dict[str, tuple[str, tuple[str, ...]]] = {
|
||||
"web_search": ("🔍", ("query", "q")),
|
||||
"x_search": ("🔍", ("query",)),
|
||||
"x_keyword_search": ("🔍", ("query",)),
|
||||
"x_semantic_search": ("🔍", ("query",)),
|
||||
"browse_page": ("🌐", ("url",)),
|
||||
"search_images": ("🖼️", ("image_description", "imageDescription")),
|
||||
"image_search": ("🖼️", ("image_description", "imageDescription")),
|
||||
"chatroom_send": ("📋", ("message",)),
|
||||
"code_execution": ("💻", ()),
|
||||
}
|
||||
|
||||
|
||||
class StreamAdapter:
|
||||
"""Parse upstream SSE frames and emit :class:`FrameEvent` objects.
|
||||
@@ -163,6 +177,9 @@ class StreamAdapter:
|
||||
"_citation_map",
|
||||
"_emitted_reasoning_keys",
|
||||
"_reasoning",
|
||||
"_summary_mode",
|
||||
"_last_rollout",
|
||||
"_content_started",
|
||||
"thinking_buf",
|
||||
"text_buf",
|
||||
"image_urls",
|
||||
@@ -173,7 +190,11 @@ class StreamAdapter:
|
||||
self._citation_order: list[str] = []
|
||||
self._citation_map: dict[str, int] = {}
|
||||
self._emitted_reasoning_keys: set[str] = set()
|
||||
self._reasoning = ReasoningAggregator()
|
||||
# 思维链模式:精简摘要 / 详细原始流
|
||||
self._summary_mode: bool = get_config().get_bool("features.thinking_summary", False)
|
||||
self._last_rollout: str = ""
|
||||
self._content_started: bool = False
|
||||
self._reasoning = ReasoningAggregator() if self._summary_mode else None
|
||||
self.thinking_buf: list[str] = []
|
||||
self.text_buf: list[str] = []
|
||||
self.image_urls: list[tuple[str, str]] = [] # [(url, imageUuid), ...]
|
||||
@@ -217,14 +238,29 @@ class StreamAdapter:
|
||||
step_id = resp.get("messageStepId")
|
||||
|
||||
if tag == "tool_usage_card":
|
||||
for line in self._summarize_tool_usage(resp, rollout=rollout, step_id=step_id):
|
||||
self._append_reasoning(
|
||||
events,
|
||||
line,
|
||||
rollout=rollout,
|
||||
tag=tag,
|
||||
step_id=step_id,
|
||||
)
|
||||
# 正文已开始后的迟到 tool card:静默丢弃
|
||||
if self._content_started:
|
||||
return events
|
||||
if self._summary_mode:
|
||||
# 精简模式:走 ReasoningAggregator 提炼摘要
|
||||
for line in self._summarize_tool_usage_summary(
|
||||
resp, rollout=rollout, step_id=step_id,
|
||||
):
|
||||
self._append_reasoning(
|
||||
events, line,
|
||||
rollout=rollout, tag=tag, step_id=step_id,
|
||||
)
|
||||
else:
|
||||
# 详细模式:格式化为 emoji 单行(含 Agent 身份)
|
||||
line = self._format_tool_card(resp, rollout=rollout)
|
||||
if line:
|
||||
# 同步 Agent 标识,确保后续 Grok summary 能正确插前缀
|
||||
if rollout:
|
||||
self._last_rollout = rollout
|
||||
self._append_reasoning(
|
||||
events, line,
|
||||
rollout=rollout, tag=tag, step_id=step_id,
|
||||
)
|
||||
return events # card events (if any) already added
|
||||
|
||||
# ── raw_function_result ───────────────────────────────────
|
||||
@@ -235,25 +271,51 @@ class StreamAdapter:
|
||||
if resp.get("toolUsageCardId") and not resp.get("webSearchResults") and not resp.get("codeExecutionResult"):
|
||||
return events
|
||||
|
||||
# ── thinking token ────────────────────────────────────────
|
||||
# ── 思维链 token 处理 ──────────────────────────────────────
|
||||
if token is not None and think is True:
|
||||
for line in self._reasoning.on_thinking(
|
||||
str(token),
|
||||
tag=tag,
|
||||
rollout=rollout,
|
||||
step_id=step_id if isinstance(step_id, int) else None,
|
||||
):
|
||||
# 正文已开始后的迟到 thinking:写入 buf(非流式可用)但不发事件(流式不显示)
|
||||
if self._content_started:
|
||||
raw = str(token).strip()
|
||||
if raw:
|
||||
formatted = raw if raw.endswith("\n") else raw + "\n"
|
||||
self.thinking_buf.append(formatted)
|
||||
return events
|
||||
if self._summary_mode:
|
||||
# 精简模式:走 ReasoningAggregator 提炼摘要
|
||||
for line in self._reasoning.on_thinking(
|
||||
str(token), tag=tag, rollout=rollout,
|
||||
step_id=step_id if isinstance(step_id, int) else None,
|
||||
):
|
||||
self._append_reasoning(
|
||||
events, line,
|
||||
rollout=rollout, tag=tag, step_id=step_id,
|
||||
)
|
||||
else:
|
||||
# 详细模式:Agent 切换时插入身份前缀,原始 token 直接透传
|
||||
raw = str(token)
|
||||
# 去掉 Grok summary 自带的 "- " 前缀,避免触发 markdown 列表缩进
|
||||
if raw.startswith("- "):
|
||||
raw = raw[2:]
|
||||
if not raw:
|
||||
return events
|
||||
agent = rollout or ""
|
||||
if agent and agent != self._last_rollout:
|
||||
self._last_rollout = agent
|
||||
# Agent 切换标识:绕过去重,直接写 buf + 发 event(同一 Agent 可多次出现)
|
||||
header = f"\n[{agent}]\n"
|
||||
self.thinking_buf.append(header)
|
||||
events.append(FrameEvent(
|
||||
"thinking", header, rollout_id=agent,
|
||||
))
|
||||
self._append_reasoning(
|
||||
events,
|
||||
line,
|
||||
rollout=rollout,
|
||||
tag=tag,
|
||||
step_id=step_id,
|
||||
events, raw,
|
||||
rollout=rollout, tag=tag, step_id=step_id,
|
||||
)
|
||||
return events
|
||||
|
||||
# ── final text token (needs cleaning) ─────────────────────
|
||||
if token is not None and think is not True and tag == "final":
|
||||
self._content_started = True
|
||||
cleaned = self._clean_token(token)
|
||||
if cleaned:
|
||||
self.text_buf.append(cleaned)
|
||||
@@ -355,15 +417,25 @@ class StreamAdapter:
|
||||
tag: str | None,
|
||||
step_id: Any,
|
||||
) -> None:
|
||||
text = line.strip()
|
||||
if not text:
|
||||
return
|
||||
"""将思维链文本追加到 thinking_buf 和事件列表(双模式去重)"""
|
||||
if self._summary_mode:
|
||||
# 精简模式:激进去重(移除标点/空格后比较)
|
||||
text = line.strip()
|
||||
if not text:
|
||||
return
|
||||
key = self._normalize_key(text)
|
||||
else:
|
||||
# 详细模式:精确去重(rollout + 原文)
|
||||
text = line
|
||||
if not text:
|
||||
return
|
||||
key = f"{rollout or ''}:{text}"
|
||||
|
||||
key = self._normalize_key(text)
|
||||
if key in self._emitted_reasoning_keys:
|
||||
return
|
||||
|
||||
self._emitted_reasoning_keys.add(key)
|
||||
|
||||
# 统一用 \n 换行(去掉 "- " 前缀后不再有列表上下文,普通 \n 即可)
|
||||
formatted = text if text.endswith("\n") else text + "\n"
|
||||
self.thinking_buf.append(formatted)
|
||||
events.append(FrameEvent(
|
||||
@@ -375,40 +447,51 @@ class StreamAdapter:
|
||||
))
|
||||
|
||||
def _flush_pending_reasoning(self, events: list[FrameEvent]) -> None:
|
||||
for line in self._reasoning.finalize():
|
||||
self._append_reasoning(
|
||||
events,
|
||||
line,
|
||||
rollout="",
|
||||
tag="summary",
|
||||
step_id=None,
|
||||
)
|
||||
"""flush ReasoningAggregator 缓冲事件(仅精简模式有效)"""
|
||||
if self._summary_mode and self._reasoning is not None:
|
||||
for line in self._reasoning.finalize():
|
||||
self._append_reasoning(events, line, rollout="", tag="summary", step_id=None)
|
||||
|
||||
def _summarize_tool_usage(self, resp: dict[str, Any], *, rollout: str | None, step_id: int | None) -> list[str]:
|
||||
@staticmethod
|
||||
def _extract_tool_info(resp: dict[str, Any]) -> tuple[str, dict[str, Any]]:
|
||||
"""从 toolUsageCard 提取工具名(snake_case)和参数"""
|
||||
card = resp.get("toolUsageCard")
|
||||
if not isinstance(card, dict):
|
||||
return []
|
||||
|
||||
tool_name = ""
|
||||
args: dict[str, Any] = {}
|
||||
return "", {}
|
||||
for key, value in card.items():
|
||||
if key == "toolUsageCardId" or not isinstance(value, dict):
|
||||
continue
|
||||
# camelCase → snake_case
|
||||
tool_name = re.sub(r"(?<!^)([A-Z])", r"_\1", key).lower()
|
||||
raw_args = value.get("args")
|
||||
if isinstance(raw_args, dict):
|
||||
args = raw_args
|
||||
break
|
||||
return tool_name, (raw_args if isinstance(raw_args, dict) else {})
|
||||
return "", {}
|
||||
|
||||
# 精简模式:走 ReasoningAggregator 提炼摘要
|
||||
def _summarize_tool_usage_summary(self, resp: dict[str, Any], *, rollout: str | None, step_id: int | None) -> list[str]:
|
||||
tool_name, args = self._extract_tool_info(resp)
|
||||
if not tool_name:
|
||||
return []
|
||||
return self._reasoning.on_tool_usage(tool_name, args, rollout=rollout, step_id=step_id)
|
||||
|
||||
return self._reasoning.on_tool_usage(
|
||||
tool_name,
|
||||
args,
|
||||
rollout=rollout,
|
||||
step_id=step_id,
|
||||
)
|
||||
# 详细模式:格式化为 emoji 单行(含 Agent 身份)
|
||||
def _format_tool_card(self, resp: dict[str, Any], *, rollout: str | None) -> str:
|
||||
tool_name, args = self._extract_tool_info(resp)
|
||||
if not tool_name:
|
||||
return ""
|
||||
emoji, arg_keys = _TOOL_FMT.get(tool_name, ("🔧", ()))
|
||||
# 提取要展示的参数值
|
||||
display_arg = ""
|
||||
for ak in arg_keys:
|
||||
val = args.get(ak)
|
||||
if val:
|
||||
display_arg = str(val).strip()
|
||||
break
|
||||
# 构造 Agent 前缀(不加前导 \n,由 _append_reasoning 统一处理换行)
|
||||
prefix = f"[{rollout}] " if rollout else ""
|
||||
if display_arg:
|
||||
return f"{prefix}{emoji} {tool_name}: {display_arg}"
|
||||
return f"{prefix}{emoji} {tool_name}"
|
||||
|
||||
def _normalize_key(self, text: str) -> str:
|
||||
lowered = text.lower()
|
||||
|
||||
@@ -354,6 +354,7 @@ const SCHEMA_DEF = [
|
||||
{ key: 'memory', label: '开启会话记忆', labelKey: 'config.schema.fields.memory.label', type: 'bool', desc: '启用 Grok Memory,允许模型跨会话记忆用户偏好与上下文。', descKey: 'config.schema.fields.memory.desc' },
|
||||
{ key: 'stream', label: '默认流式输出', labelKey: 'config.schema.fields.stream.label', type: 'bool', desc: '请求未显式指定 stream 参数时所采用的默认值。', descKey: 'config.schema.fields.stream.desc' },
|
||||
{ key: 'thinking', label: '默认思考输出', labelKey: 'config.schema.fields.thinking.label', type: 'bool', desc: '请求未显式指定 thinking 参数时所采用的默认值。启用后将在 reasoning_content 字段返回思考过程。', descKey: 'config.schema.fields.thinking.desc' },
|
||||
{ key: 'thinking_summary', label: '思考精简输出', labelKey: 'config.schema.fields.thinkingSummary.label', type: 'bool', desc: '启用后将思考过程提炼为结构化摘要。关闭时输出完整的原始推理过程,支持多 Agent 模型的协作详情与工具调用展示。', descKey: 'config.schema.fields.thinkingSummary.desc' },
|
||||
{ key: 'dynamic_statsig', label: '动态 Statsig', labelKey: 'config.schema.fields.dynamicStatsig.label', type: 'bool', desc: '为每次请求动态生成 Statsig 设备指纹,以降低风控拦截概率。', descKey: 'config.schema.fields.dynamicStatsig.desc' },
|
||||
{ key: 'enable_nsfw', label: '允许 NSFW 生成', labelKey: 'config.schema.fields.enableNsfw.label', type: 'bool', desc: '允许图像生成接口绕过 NSFW 内容过滤。', descKey: 'config.schema.fields.enableNsfw.desc' },
|
||||
{ key: 'custom_instruction', label: '全局附加指令', labelKey: 'config.schema.fields.customInstruction.label', type: 'textarea', desc: '为每次请求注入统一的 system 消息,用于约束模型行为或固定角色设定。', descKey: 'config.schema.fields.customInstruction.desc' },
|
||||
|
||||
@@ -371,6 +371,7 @@
|
||||
"memory": { "label": "Konversationsspeicher" },
|
||||
"stream": { "label": "Standard-Streaming" },
|
||||
"thinking": { "label": "Standard-Ausgabe für Reasoning" },
|
||||
"thinkingSummary": { "label": "Kompakte Reasoning-Ausgabe" },
|
||||
"dynamicStatsig": { "label": "Dynamisches Statsig" },
|
||||
"enableNsfw": { "label": "NSFW-Erzeugung zulassen" },
|
||||
"customInstruction": { "label": "Globale Zusatzanweisung" },
|
||||
|
||||
@@ -398,6 +398,10 @@
|
||||
"label": "Default Reasoning Output",
|
||||
"desc": "Default value applied when the request does not explicitly provide the thinking parameter. When enabled, reasoning steps are returned in reasoning_content."
|
||||
},
|
||||
"thinkingSummary": {
|
||||
"label": "Condensed Reasoning",
|
||||
"desc": "When enabled, reasoning steps are condensed into a structured summary. When disabled, the full raw reasoning stream is output, with multi-agent collaboration details and tool call traces."
|
||||
},
|
||||
"dynamicStatsig": {
|
||||
"label": "Dynamic Statsig",
|
||||
"desc": "Generates a fresh Statsig device fingerprint for each request to reduce the likelihood of risk-control challenges."
|
||||
|
||||
@@ -371,6 +371,7 @@
|
||||
"memory": { "label": "Memoria de conversación" },
|
||||
"stream": { "label": "Streaming predeterminado" },
|
||||
"thinking": { "label": "Salida de razonamiento predeterminada" },
|
||||
"thinkingSummary": { "label": "Razonamiento condensado" },
|
||||
"dynamicStatsig": { "label": "Statsig dinámico" },
|
||||
"enableNsfw": { "label": "Permitir generación NSFW" },
|
||||
"customInstruction": { "label": "Instrucción suplementaria global" },
|
||||
|
||||
@@ -371,6 +371,7 @@
|
||||
"memory": { "label": "Mémoire conversationnelle" },
|
||||
"stream": { "label": "Streaming par défaut" },
|
||||
"thinking": { "label": "Sortie de raisonnement par défaut" },
|
||||
"thinkingSummary": { "label": "Raisonnement condensé" },
|
||||
"dynamicStatsig": { "label": "Statsig dynamique" },
|
||||
"enableNsfw": { "label": "Autoriser la génération NSFW" },
|
||||
"customInstruction": { "label": "Instruction globale supplémentaire" },
|
||||
|
||||
@@ -371,6 +371,7 @@
|
||||
"memory": { "label": "会話メモリ" },
|
||||
"stream": { "label": "デフォルトのストリーミング" },
|
||||
"thinking": { "label": "デフォルトの推論出力" },
|
||||
"thinkingSummary": { "label": "思考要約出力" },
|
||||
"dynamicStatsig": { "label": "動的 Statsig" },
|
||||
"enableNsfw": { "label": "NSFW 生成を許可" },
|
||||
"customInstruction": { "label": "グローバル補助指示" },
|
||||
|
||||
@@ -398,6 +398,10 @@
|
||||
"label": "默认思考输出",
|
||||
"desc": "请求未显式指定 thinking 参数时所采用的默认值。启用后将在 reasoning_content 字段返回思考过程。"
|
||||
},
|
||||
"thinkingSummary": {
|
||||
"label": "思考精简输出",
|
||||
"desc": "启用后将思考过程提炼为结构化摘要。关闭时输出完整的原始推理过程,支持多 Agent 模型的协作详情与工具调用展示。"
|
||||
},
|
||||
"dynamicStatsig": {
|
||||
"label": "动态 Statsig",
|
||||
"desc": "为每次请求动态生成 Statsig 设备指纹,以降低风控拦截概率。"
|
||||
|
||||
@@ -22,6 +22,8 @@ memory = false
|
||||
stream = true
|
||||
# 是否输出思考过程
|
||||
thinking = true
|
||||
# 思考精简输出(false=完整原始推理过程,true=提炼结构化摘要)
|
||||
thinking_summary = false
|
||||
# 是否动态生成 Statsig 指纹
|
||||
dynamic_statsig = true
|
||||
# 是否允许生成 NSFW 图片
|
||||
|
||||
Reference in new issue
Block a user