From 3c4895960574c627a521a93638687a4db7726984 Mon Sep 17 00:00:00 2001 From: Huan-zhaojun <111294954+Huan-zhaojun@users.noreply.github.com> Date: Fri, 10 Apr 2026 20:06:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A4=9A=20Agent=20=E6=80=9D=E7=BB=B4?= =?UTF-8?q?=E9=93=BE=E5=AE=8C=E6=95=B4=E8=BE=93=E5=87=BA=E4=B8=8E=E7=B2=BE?= =?UTF-8?q?=E7=AE=80=E6=A8=A1=E5=BC=8F=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增详细模式(默认):透传原始多 Agent 思考流,包含 [Grok]/[Agent N] 身份标识、工具调用格式化(emoji + 参数)、chatroom_send 完整报告 - 保留精简模式(可选):通过 thinking_summary 配置项切换回 ReasoningAggregator 结构化摘要 - 正文开始后的迟到 thinking token:流式静默丢弃,非流式写入 buf 保留 - Agent 前缀绕过去重机制,支持同一 Agent 多次出现 - 前端管理面板新增「思考精简输出」开关,含 6 语言 i18n --- app/dataplane/reverse/protocol/xai_chat.py | 179 +++++++++++++++------ app/statics/admin/config.html | 1 + app/statics/i18n/de.json | 1 + app/statics/i18n/en.json | 4 + app/statics/i18n/es.json | 1 + app/statics/i18n/fr.json | 1 + app/statics/i18n/ja.json | 1 + app/statics/i18n/zh.json | 4 + config.defaults.toml | 2 + 9 files changed, 146 insertions(+), 48 deletions(-) diff --git a/app/dataplane/reverse/protocol/xai_chat.py b/app/dataplane/reverse/protocol/xai_chat.py index 0d3003bf..761418d4 100644 --- a/app/dataplane/reverse/protocol/xai_chat.py +++ b/app/dataplane/reverse/protocol/xai_chat.py @@ -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"(? 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() diff --git a/app/statics/admin/config.html b/app/statics/admin/config.html index b5e241e3..098439e4 100644 --- a/app/statics/admin/config.html +++ b/app/statics/admin/config.html @@ -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' }, diff --git a/app/statics/i18n/de.json b/app/statics/i18n/de.json index e06d8703..5786ebf4 100644 --- a/app/statics/i18n/de.json +++ b/app/statics/i18n/de.json @@ -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" }, diff --git a/app/statics/i18n/en.json b/app/statics/i18n/en.json index 8de8aaa0..98c68070 100644 --- a/app/statics/i18n/en.json +++ b/app/statics/i18n/en.json @@ -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." diff --git a/app/statics/i18n/es.json b/app/statics/i18n/es.json index a5067532..274e9bd7 100644 --- a/app/statics/i18n/es.json +++ b/app/statics/i18n/es.json @@ -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" }, diff --git a/app/statics/i18n/fr.json b/app/statics/i18n/fr.json index a7d3e9ac..5f5aa8d7 100644 --- a/app/statics/i18n/fr.json +++ b/app/statics/i18n/fr.json @@ -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" }, diff --git a/app/statics/i18n/ja.json b/app/statics/i18n/ja.json index 9cf463cc..d9872976 100644 --- a/app/statics/i18n/ja.json +++ b/app/statics/i18n/ja.json @@ -371,6 +371,7 @@ "memory": { "label": "会話メモリ" }, "stream": { "label": "デフォルトのストリーミング" }, "thinking": { "label": "デフォルトの推論出力" }, + "thinkingSummary": { "label": "思考要約出力" }, "dynamicStatsig": { "label": "動的 Statsig" }, "enableNsfw": { "label": "NSFW 生成を許可" }, "customInstruction": { "label": "グローバル補助指示" }, diff --git a/app/statics/i18n/zh.json b/app/statics/i18n/zh.json index b50277eb..c928c205 100644 --- a/app/statics/i18n/zh.json +++ b/app/statics/i18n/zh.json @@ -398,6 +398,10 @@ "label": "默认思考输出", "desc": "请求未显式指定 thinking 参数时所采用的默认值。启用后将在 reasoning_content 字段返回思考过程。" }, + "thinkingSummary": { + "label": "思考精简输出", + "desc": "启用后将思考过程提炼为结构化摘要。关闭时输出完整的原始推理过程,支持多 Agent 模型的协作详情与工具调用展示。" + }, "dynamicStatsig": { "label": "动态 Statsig", "desc": "为每次请求动态生成 Statsig 设备指纹,以降低风控拦截概率。" diff --git a/config.defaults.toml b/config.defaults.toml index 2acf2659..71cdbb74 100644 --- a/config.defaults.toml +++ b/config.defaults.toml @@ -22,6 +22,8 @@ memory = false stream = true # 是否输出思考过程 thinking = true +# 思考精简输出(false=完整原始推理过程,true=提炼结构化摘要) +thinking_summary = false # 是否动态生成 Statsig 指纹 dynamic_statsig = true # 是否允许生成 NSFW 图片