mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-16 18:31:59 +00:00
把 Copilot 的思考显示出来:模型一直在想,只是被丢掉了
用户问能不能看到"正在理解需求、规划步骤"里面发生了什么。查下来是这样:
模型确实在想,reasoning 花了实打实的 token,但一路上被丢了三次。
1. langchain 的 ChatOpenAI **故意**不保留第三方的 reasoning_content——它的
文档原话是 "Non-standard response fields added by third-party providers
are not extracted or preserved",建议换 ChatDeepSeek 之类的专用包。可
"用哪个供应商"在这个产品里是用户在设置页配的(DeepSeek / Qianfan /
vLLM / OpenRouter 都可能),为每种装一个专用包不现实。在 factory 里
子类化捞回 additional_kwargs,只加字段,不动 langchain 对正文的处理。
2. thinking_text 只认 Anthropic 的 thinking 块。补上兼容端点那一种。
3. 前端把一段思考的标题固定成开头 60 个字。思考是流式的,开头往往是
"用户想要一个……"这类复述,之后几十秒里它一直在推进——固定显示开头
等于把一段活的叙述冻在起点上,看着就像卡住了。改成:还在想的时候显示
最新一句,想完了换回开头那句(那时它是一条历史记录)。
实测一次真实生成,60 秒里侧栏逐句变化:
3s 可用数据源 bi
9s 人工节点 approve 模式,审核
18s 我们可以用 db_query__sales 执行 SELECT COUNT(*) FROM orders 等
36s 更合理:rejected -> query_agent(重新
45s 对于 bi 有 53 个对象,靠
57s (plan 到达,思考收尾,换回开头那句)
顺带运行期的 LLM 节点也跟着有了思考——走的是同一个 thinking_text,之前
同样只有 Anthropic 系才有。已验证流式合并后思考连成完整一段,不是只剩
最后一片。
tests/test_thinking.py 守两种形态、合并、以及"不产思考的模型不硬凑"。
check-decode 补 5 条守"还在想显示最新一句、想完了换开头"。
This commit is contained in:
@@ -88,11 +88,22 @@ def message_text(message: Any) -> str:
|
||||
|
||||
|
||||
def thinking_text(message: Any) -> str:
|
||||
"""抽出思考块的内容。
|
||||
"""抽出思考内容。
|
||||
|
||||
开了 adaptive thinking 的模型(Claude 4.6+)返回的 content 里混着 thinking 块,
|
||||
正文提取必须跳过它们,但它本身对"看清楚模型怎么想的"很有价值,所以单独取出来。
|
||||
两种形态都要认,因为两边的模型都会产出思考,而界面上"它大致在想什么"
|
||||
只有这一个来源:
|
||||
|
||||
- Anthropic 系:content 是块列表,思考混在里面(type == "thinking")。
|
||||
正文提取必须跳过它们,但它本身很有价值,所以单独取出来。
|
||||
- OpenAI 兼容系(DeepSeek / Qianfan / vLLM 等):思考走 delta 里的
|
||||
reasoning_content。langchain 的 ChatOpenAI 明确不保留这个字段,
|
||||
我们在 providers/factory.py 里子类化捞回了 additional_kwargs。
|
||||
"""
|
||||
extra = getattr(message, "additional_kwargs", None) or {}
|
||||
reasoning = extra.get("reasoning_content") or extra.get("reasoning")
|
||||
if isinstance(reasoning, str) and reasoning:
|
||||
return reasoning
|
||||
|
||||
content = getattr(message, "content", message)
|
||||
if not isinstance(content, list):
|
||||
return ""
|
||||
|
||||
@@ -168,8 +168,6 @@ def build_chat_model(provider: Provider, spec: ModelSpec) -> BaseChatModel:
|
||||
return chat
|
||||
|
||||
# openai 与 openai 兼容走同一个类,区别只在 base_url
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
if provider.kind == "openai_compatible" and not base_url:
|
||||
raise ProviderNotConfigured(f"provider {provider.name!r} 需要填 base_url")
|
||||
# 很多本地服务(Ollama、vLLM)不校验 key,但 SDK 要求非空
|
||||
@@ -178,7 +176,56 @@ def build_chat_model(provider: Provider, spec: ModelSpec) -> BaseChatModel:
|
||||
kwargs["base_url"] = base_url
|
||||
if extra.get("headers"):
|
||||
kwargs["default_headers"] = extra["headers"]
|
||||
return ChatOpenAI(**kwargs)
|
||||
return _ReasoningAwareChatOpenAI(**kwargs)
|
||||
|
||||
|
||||
def _reasoning_aware_openai() -> type:
|
||||
"""ChatOpenAI 的子类,保留供应商的思考内容。
|
||||
|
||||
langchain 的 ChatOpenAI 只认官方 OpenAI 规范,第三方加的 reasoning_content
|
||||
是**明确丢弃**的(它的文档原话:"Non-standard response fields added by
|
||||
third-party providers are not extracted or preserved"),建议换用
|
||||
ChatDeepSeek 之类的专用包。
|
||||
|
||||
但"用哪个供应商"在这个产品里是用户在设置页配的,可能是 DeepSeek、
|
||||
Qianfan、vLLM、OpenRouter 里任何一个——为每种装一个专用包不现实。而这
|
||||
段内容正是界面上"它大致在想什么"的唯一真实来源:实测 deepseek-v4-pro
|
||||
一次调用花 160 个 token 在推理上,全被丢掉了,于是编排期那 50 秒里
|
||||
界面上只有一行不动的"正在理解需求"。
|
||||
|
||||
所以在这里把它捞回 additional_kwargs,thinking_text 再统一读出来。
|
||||
只加字段,不改 langchain 对正文的任何处理。
|
||||
"""
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
class ReasoningAwareChatOpenAI(ChatOpenAI): # type: ignore[misc]
|
||||
def _convert_chunk_to_generation_chunk(
|
||||
self, chunk: dict, default_chunk_class: type, base_generation_info: dict | None
|
||||
):
|
||||
gen = super()._convert_chunk_to_generation_chunk(
|
||||
chunk, default_chunk_class, base_generation_info
|
||||
)
|
||||
if gen is None:
|
||||
return gen
|
||||
choices = chunk.get("choices") or chunk.get("chunk", {}).get("choices") or []
|
||||
delta = (choices[0] or {}).get("delta") or {} if choices else {}
|
||||
# 不同网关的叫法不统一,见到哪个用哪个
|
||||
text = delta.get("reasoning_content") or delta.get("reasoning")
|
||||
if isinstance(text, str) and text:
|
||||
gen.message.additional_kwargs["reasoning_content"] = text
|
||||
return gen
|
||||
|
||||
return ReasoningAwareChatOpenAI
|
||||
|
||||
|
||||
class _LazyReasoningChatOpenAI:
|
||||
"""延迟导入 langchain_openai:它加载得慢,而 mock/anthropic 路径用不上。"""
|
||||
|
||||
def __call__(self, **kwargs: Any) -> Any:
|
||||
return _reasoning_aware_openai()(**kwargs)
|
||||
|
||||
|
||||
_ReasoningAwareChatOpenAI = _LazyReasoningChatOpenAI()
|
||||
|
||||
|
||||
async def get_chat_model(session: AsyncSession, spec: ModelSpec) -> tuple[BaseChatModel, str]:
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""思考内容的提取。
|
||||
|
||||
界面上"它大致在想什么"只有这一个来源。两家的形态完全不同,漏掉任何一种,
|
||||
那一侧的模型在编排期就只剩一行不动的"正在理解需求"——而它其实想了 50 秒。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from langchain_core.messages import AIMessage, AIMessageChunk
|
||||
|
||||
from app.engine.state import message_text, thinking_text
|
||||
|
||||
|
||||
def test_anthropic_thinking_blocks() -> None:
|
||||
msg = AIMessage(content=[
|
||||
{"type": "thinking", "thinking": "先看看有哪些表。"},
|
||||
{"type": "text", "text": "查到 3 张表。"},
|
||||
{"type": "thinking", "thinking": "再按月份聚合。"},
|
||||
])
|
||||
assert thinking_text(msg) == "先看看有哪些表。再按月份聚合。"
|
||||
# 正文不能把思考混进来
|
||||
assert thinking_text(msg) not in message_text(msg)
|
||||
assert "查到 3 张表。" in message_text(msg)
|
||||
|
||||
|
||||
def test_openai_compatible_reasoning_content() -> None:
|
||||
"""DeepSeek / Qianfan / vLLM 这类兼容端点把思考放在 reasoning_content。
|
||||
|
||||
langchain 的 ChatOpenAI 明确不保留这个字段("Non-standard response fields
|
||||
added by third-party providers are not extracted or preserved"),
|
||||
providers/factory.py 子类化捞了回来。
|
||||
"""
|
||||
chunk = AIMessageChunk(content="", additional_kwargs={"reasoning_content": "先看看现有的节点。"})
|
||||
assert thinking_text(chunk) == "先看看现有的节点。"
|
||||
|
||||
|
||||
def test_merged_chunks_keep_whole_reasoning() -> None:
|
||||
"""流式合并后思考要连成一整段,不能只剩最后一片。"""
|
||||
parts = ["用户想要", "一个能查销量的流程。", "先看看现有的节点。"]
|
||||
merged = AIMessageChunk(content="", additional_kwargs={"reasoning_content": parts[0]})
|
||||
for p in parts[1:]:
|
||||
merged = merged + AIMessageChunk(content="", additional_kwargs={"reasoning_content": p})
|
||||
assert thinking_text(merged) == "".join(parts)
|
||||
|
||||
|
||||
def test_plain_message_has_no_thinking() -> None:
|
||||
"""不产思考的模型不该被硬凑出一段来。"""
|
||||
assert thinking_text(AIMessage(content="就是 2")) == ""
|
||||
assert thinking_text(AIMessageChunk(content="x", additional_kwargs={})) == ""
|
||||
|
||||
|
||||
def test_empty_reasoning_is_not_reported() -> None:
|
||||
"""空串不算思考,否则界面上会出现一行什么都没有的"思考"。"""
|
||||
assert thinking_text(AIMessageChunk(content="", additional_kwargs={"reasoning_content": ""})) == ""
|
||||
@@ -724,6 +724,28 @@ export interface CopilotOp {
|
||||
[k: string]: any
|
||||
}
|
||||
|
||||
/**
|
||||
* 一段思考在列表里显示哪一句。
|
||||
*
|
||||
* 还在想的时候取**最后一句**:思考是流式的,第一句往往是"用户想要一个……"
|
||||
* 这种复述,之后几十秒里它其实一直在推进("先看看现有的节点"、"这里需要
|
||||
* 一个分支")。固定显示开头,等于把一段活的叙述冻在起点上,看着就像卡住了。
|
||||
*
|
||||
* 想完了取**开头**:这时它是一条历史记录,开头那句最接近"这段在想什么"。
|
||||
*/
|
||||
function thinkingHeadline(text: string, live: boolean): string {
|
||||
const flat = text.replace(/\s+/g, ' ').trim()
|
||||
if (!flat) return '正在思考…'
|
||||
if (!live) return flat.slice(0, 60) + (flat.length > 60 ? '…' : '')
|
||||
// 按中英文句末切;最后一段往往还没说完,取它前面那句更完整
|
||||
const parts = flat.split(/(?<=[。!?;.!?;])\s*/).filter(Boolean)
|
||||
const tail = parts.length > 1 && parts[parts.length - 1].length < 6
|
||||
? parts[parts.length - 2]
|
||||
: parts[parts.length - 1]
|
||||
const line = tail ?? flat
|
||||
return line.length > 60 ? '…' + line.slice(-60) : line
|
||||
}
|
||||
|
||||
const PHASE_LABEL: Record<string, string> = {
|
||||
connecting: '正在连接模型',
|
||||
planning: '正在理解需求、规划步骤',
|
||||
@@ -743,22 +765,33 @@ export function decodeCopilot(ops: CopilotOp[]): Step[] {
|
||||
const out: Step[] = []
|
||||
let i = 0
|
||||
let nodeCount = 0
|
||||
|
||||
/** 一段思考结束了:不再显示"最新一句",换成开头那句,收掉转圈 */
|
||||
const settleThinking = () => {
|
||||
const last = out[out.length - 1]
|
||||
if (last?.kind === 'think' && last.status === 'running') {
|
||||
last.status = 'done'
|
||||
last.title = thinkingHeadline(last.detail ?? '', false)
|
||||
}
|
||||
}
|
||||
|
||||
for (const op of ops) {
|
||||
i += 1
|
||||
// 除了继续思考和心跳,任何一条操作都说明它已经想完、开始动手了
|
||||
if (op.op !== 'thinking' && op.op !== 'heartbeat') settleThinking()
|
||||
switch (op.op) {
|
||||
case 'thinking': {
|
||||
const text = String(op.delta ?? '')
|
||||
if (!text.trim()) break
|
||||
const last = out[out.length - 1]
|
||||
// 思考是连续流,一片 delta 一行会碎成几十条。同一段连续思考并成一条,
|
||||
// 标题取开头、详情是全文——这才是"一次思考是一个节点"。
|
||||
if (last?.kind === 'think') {
|
||||
// 详情是全文——这才是"一次思考是一个节点"。
|
||||
if (last?.kind === 'think' && last.status === 'running') {
|
||||
last.detail = (last.detail ?? '') + text
|
||||
last.title = last.detail.replace(/\s+/g, ' ').slice(0, 60)
|
||||
+ (last.detail.length > 60 ? '…' : '')
|
||||
last.title = thinkingHeadline(last.detail, true)
|
||||
} else {
|
||||
out.push({ id: `ct-${i}`, seq: i, kind: 'think', status: 'done',
|
||||
title: text.replace(/\s+/g, ' ').slice(0, 60), detail: text })
|
||||
out.push({ id: `ct-${i}`, seq: i, kind: 'think', status: 'running',
|
||||
title: thinkingHeadline(text, true), detail: text })
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
@@ -234,6 +234,30 @@ console.log('\n=== Copilot 操作流 ===')
|
||||
check('连续思考并成一条', steps.filter((s) => s.kind === 'think').length === 1,
|
||||
`${steps.filter((s) => s.kind === 'think').length} 条`)
|
||||
check('思考全文保留在详情', steps.find((s) => s.kind === 'think')?.detail?.includes('先看表结构'))
|
||||
|
||||
// 编排期那 50 秒里,界面上只有一行不动的"正在理解需求"。思考是流式的,
|
||||
// 固定显示开头那句等于把一段活的叙述冻在起点上,看着就像卡住了
|
||||
const thinkingNow = mod.decodeCopilot([
|
||||
{ op: 'thinking', delta: '用户想要一个能查销量的流程。' },
|
||||
{ op: 'thinking', delta: '先看看画布上现有的节点有哪些。' },
|
||||
{ op: 'thinking', delta: '这里需要一个分支' },
|
||||
])
|
||||
const live = thinkingNow[thinkingNow.length - 1]
|
||||
check('还在想的时候显示最新一句', live.title.includes('这里需要一个分支'), live.title)
|
||||
check('还在想的时候是进行中状态', live.status === 'running', live.status)
|
||||
check('全文一句不丢', live.detail?.includes('用户想要') && live.detail?.includes('现有的节点'))
|
||||
|
||||
// 想完了它就是条历史记录,开头那句最接近"这段在想什么"
|
||||
const settled = mod.decodeCopilot([
|
||||
...thinkingNow.length ? [
|
||||
{ op: 'thinking', delta: '用户想要一个能查销量的流程。' },
|
||||
{ op: 'thinking', delta: '先看看画布上现有的节点有哪些。' },
|
||||
] : [],
|
||||
{ op: 'plan', summary: '三步走' },
|
||||
])
|
||||
const done = settled.find((s) => s.kind === 'think')
|
||||
check('想完了换成开头那句', done?.title.startsWith('用户想要'), done?.title)
|
||||
check('想完了不再转圈', done?.status === 'done', done?.status)
|
||||
check('连线不单独成行', !steps.some((s) => s.title.includes('edge')))
|
||||
check('节点用标签不用 id', steps.some((s) => s.kind === 'node' && s.title === '取数'))
|
||||
// 生成完了那条"正在理解需求…"还在转圈的话,看上去像卡住了
|
||||
|
||||
Reference in New Issue
Block a user