功能全部做完之后做了一次**独立核对**(逐条比对需求与代码)—— 结果**不是"全部实现"**:6 处「内核实现了、界面/调用方没接上」。 ★★ 共同点:**三层各自看都对,只有真的跑一遍才看得见** —— 正是我这几轮一直防的那一类,结果自己犯了 6 次。 ## ★★ 最严重:`pass_turn` 一轮一次**根本不生效** 标记写在 `tools_runtime` 的**工具上下文**里,但工具跑在 **worker 线程**, 而 `_ctx` 是 thread-local —— 标记随线程消失,主线程每次又 `push_context` 重置。 于是 `handoffUsed` **永远是 False**,可以一轮移交无限次。 **更糟:我的探针假通过了。** 探针直接调 `agent_tools.pass_turn`(主线程), 标记留在主线程没被清 → 看着完全正常,真机才露馅。 修法:提到 `tools_runtime` 的**模块级轮次状态**(`begin_round`/`note_handoff`/ `handoff_state`),和线程无关;`agent_loop` 每轮重置。 ★ 并加了一节**走真实路径**(`execute_tool`)的探针 —— **探针的调用路径必须和真实调用路径一致**。直接调函数测的是"逻辑对不对", 不是"它在这个系统里生不生效"。 ## 第二处:移交链路是死的 `app.py` 读的是 **HTTP body** 的 `handoffTo`,而 Kotlin **从不发这个字段** (全仓库只有 2 处:一写一读,读的永远拿空串)→「② AI 移交」是死代码。 修法:改读 `tools_runtime.handoff_state()['to']`。 ## 三处「收了但没用」 · **状态过期事件被丢**:`parseEvent` 没有 `"status"` 分支 → `else -> null` · **状态脚本报错静默**:只 `print` 到 stderr,从不 emit(附录 E 明写"UI 提示") · **仲裁理由算了不显示**:`speakerNote` 赋值了但**没有任何一处读它** ## 一处界面缺入口 **「拉人要先问我」**(§6.1 静默/需确认):内核早就按 `inviteMode` 分流, 界面没入口 → `confirm` 永远打不开。现在加在「能力」组。 ## 还剩 2 处(下一版) · **私聊没有界面入口**(内核完整) · **私聊轮数「可配」界面上改不了** 同一个原因:私聊整个形态还没有界面。 ## 验证 新探针走真实路径确认"第 2 次移交被拒";八个探针全绿;构建通过。
567 lines
27 KiB
Python
567 lines
27 KiB
Python
"""
|
||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||
|
||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||
open 所有工具都交给模型
|
||
restricted 只有白名单里的工具可用(连执行都会再拦一道,见 tools_runtime.execute_tool)
|
||
|
||
同步实现(生成器 + 普通函数),因为上游是 stdlib urllib 的阻塞式读取;
|
||
在 HTTP 服务里每个请求占一个线程,ThreadingHTTPServer 正好够用。
|
||
"""
|
||
|
||
import json
|
||
import re
|
||
import sys
|
||
from typing import Callable, Optional
|
||
|
||
import agent_context
|
||
import store
|
||
import tools_runtime
|
||
from providers import stream_chat
|
||
|
||
MAX_TOOL_RESULT_CHARS = 6000
|
||
|
||
|
||
def add_usage(total, one) -> dict:
|
||
"""
|
||
把一次调用的 usage 累加进总数。
|
||
|
||
★ 各家的字段名不一样(OpenAI 系是 prompt_tokens / completion_tokens,
|
||
兼容网关有时给 input_tokens / output_tokens),**两种都认** ——
|
||
只认一种的话换个提供商统计就静默变成 0,而"统计是 0"极难被发现。
|
||
"""
|
||
if not isinstance(one, dict):
|
||
return total or {}
|
||
out = dict(total or {})
|
||
pairs = (
|
||
('prompt_tokens', 'prompt_tokens'),
|
||
('completion_tokens', 'completion_tokens'),
|
||
('total_tokens', 'total_tokens'),
|
||
('input_tokens', 'prompt_tokens'), # 兼容写法
|
||
('output_tokens', 'completion_tokens'), # 兼容写法
|
||
)
|
||
for src, dst in pairs:
|
||
v = one.get(src)
|
||
if isinstance(v, (int, float)):
|
||
out[dst] = int(out.get(dst) or 0) + int(v)
|
||
# 缓存命中也累加(需求 3.1 的 v1.2 新增)。
|
||
# ★ 累加的是**归一化之后**的两个数,不是原始字段:各家的名字不一样,
|
||
# 直接并进 out 的话,换了模型那个 key 就消失了。
|
||
hit, miss = cache_pair(one)
|
||
if hit or miss:
|
||
out['cache_hit'] = int(out.get('cache_hit') or 0) + hit
|
||
out['cache_miss'] = int(out.get('cache_miss') or 0) + miss
|
||
if 'total_tokens' not in out:
|
||
out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0)
|
||
return out
|
||
|
||
|
||
#: 各家的「缓存命中」字段名。**加新提供商只改这一处**,不要在调用点写 if。
|
||
#:
|
||
#: DeepSeek prompt_cache_hit_tokens / prompt_cache_miss_tokens(两个都给)
|
||
#: Claude cache_read_input_tokens(只给命中)
|
||
#: OpenAI prompt_tokens_details.cached_tokens(嵌套,也只给命中)
|
||
_CACHE_HIT_KEYS = ('prompt_cache_hit_tokens', 'cache_read_input_tokens', 'cached_tokens')
|
||
|
||
|
||
def cache_pair(usage) -> tuple:
|
||
"""
|
||
从 usage 里取出 `(cache_hit, cache_miss)`(需求 3.1 的 v1.2 新增)。
|
||
|
||
★ 为什么必须归一化:三家的字段名完全不同,不归一化的话,
|
||
界面上那个"缓存命中率"会因为换了个模型就**静默变成 0**
|
||
(而不是报错 —— 静默的 0 最难发现,用户会以为"缓存没生效")。
|
||
|
||
★ 两家只给命中、不给未命中(Claude / OpenAI),所以未命中要**自己推**:
|
||
`prompt_tokens - hit`。推不出来时返回 0,界面据此**不显示那一列** ——
|
||
显示一个假的 0% 是误导。
|
||
"""
|
||
u = usage if isinstance(usage, dict) else {}
|
||
hit = 0
|
||
for key in _CACHE_HIT_KEYS:
|
||
v = u.get(key)
|
||
if isinstance(v, (int, float)) and v > 0:
|
||
hit = int(v)
|
||
break
|
||
if not hit:
|
||
# OpenAI 把它塞在嵌套对象里
|
||
details = u.get('prompt_tokens_details')
|
||
if isinstance(details, dict):
|
||
v = details.get('cached_tokens')
|
||
if isinstance(v, (int, float)) and v > 0:
|
||
hit = int(v)
|
||
|
||
miss = 0
|
||
v = u.get('prompt_cache_miss_tokens')
|
||
if isinstance(v, (int, float)) and v > 0:
|
||
miss = int(v)
|
||
if hit and not miss:
|
||
total = u.get('prompt_tokens') or u.get('input_tokens')
|
||
if isinstance(total, (int, float)) and total >= hit:
|
||
miss = int(total) - hit
|
||
return hit, miss
|
||
|
||
|
||
def usage_pair(usage) -> tuple:
|
||
"""从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平"""
|
||
u = usage if isinstance(usage, dict) else {}
|
||
return int(u.get('prompt_tokens') or 0), int(u.get('completion_tokens') or 0)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 幻觉调用检测(需求 3.7)
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 「嘴上说记住了、实际没调工具」是这类有记忆的助手最常见、也最伤信任的毛病:
|
||
# 用户当场看不出来(那句"我记住了"说得很自然),下次对话发现它完全不记得,
|
||
# 从此就不信这个功能了。
|
||
#
|
||
# 而"它打算记"和"它真的记了"在**正文里看不出区别**,只能由程序比对
|
||
# 「说了什么」和「做了什么」。所以这里做一次兜底。
|
||
|
||
#: 「声称记住了」的措辞。
|
||
# ★ 宁可漏判也别误伤:误伤会让用户看到莫名其妙的警告,几次之后他就不看那个警告了
|
||
# (比没有还糟)。所以只收明确说"我记住了"的句式,不收"我会记得的"这种客套。
|
||
_CLAIM_RE = re.compile(
|
||
r'我(已经)?(记住|记下|记好)了|已(经)?(记住|记下)|记到(我的)?记忆|'
|
||
r'存(进|入)(了)?(我的)?记忆|我把它记|已经帮你记|记在小本本'
|
||
)
|
||
|
||
|
||
def detects_memory_claim(content: str) -> bool:
|
||
"""这句话里有没有"我记住了"这类断言"""
|
||
return bool(_CLAIM_RE.search(content or ''))
|
||
|
||
|
||
def check_hallucinated_memory(content: str, tool_call_count: int, tools_available: bool) -> bool:
|
||
"""
|
||
这一轮该不该打「⚠ 声称记忆但未实际调用」的标记(需求 3.7)。
|
||
|
||
★ [tools_available] 是必须的:如果用户把 Python 工具整个关了,
|
||
模型**想调也调不了**,那时警告它"没调用工具"是冤枉它 ——
|
||
而且警告会一直挂着,用户会以为坏了。
|
||
"""
|
||
if not tools_available:
|
||
return False
|
||
if tool_call_count > 0:
|
||
return False
|
||
return detects_memory_claim(content)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 兼容降级:不支持 function calling 的模型(需求 3.3)
|
||
# --------------------------------------------------------------------------- #
|
||
#
|
||
# 有些模型(本地小模型、老网关)根本不支持 tools 参数 —— 传过去轻则被忽略、
|
||
# 重则直接 400。而"记忆/情绪"这些能力**恰恰靠工具**,没有降级的话,
|
||
# 用户换上这类模型之后会发现"记忆功能突然全废了",而且看不出原因。
|
||
#
|
||
# 降级做法:不传 tools,改成**在提示词里约定一种正文内的调用格式**,
|
||
# 回复回来后由内核解析、执行、并从正文里剥掉。用户看到的还是干净的回答。
|
||
#
|
||
# ★ 为什么选"代码块里写 JSON"而不是别的:
|
||
# · 模型对"输出 JSON"这件事训练得很充分,比自创的标记语法可靠得多
|
||
# · 代码块有明确的边界,正则能稳稳地切出来;万一没被剥掉,
|
||
# 用户看到的也是一段像模像样的 JSON,而不是一堆乱码
|
||
|
||
DEGRADED_HINT = '\n'.join([
|
||
'',
|
||
'【工具调用】你**不能直接调用函数**,但需要用到工具时,请在回复里单独写一段:',
|
||
'',
|
||
'```doubao-call',
|
||
'{"tool": "memory_add", "args": {"title": "标题", "content": "内容"}}',
|
||
'```',
|
||
'',
|
||
'可用的工具:memory_add、memory_update、memory_forget、memory_search、'
|
||
'emotion_set、get_token_usage。',
|
||
'这一段会被系统执行并从你的回复里**去掉**,用户看不到它。',
|
||
'★ 需要记住什么的时候,**必须**写这一段 —— 只在正文里说"我记住了"是没用的,'
|
||
'那样你其实什么都没记。',
|
||
])
|
||
|
||
_RE_DEGRADED_CALL = re.compile(r'```doubao-call\s*\n(.*?)\n?```', re.S)
|
||
|
||
|
||
def run_degraded_calls(content: str, settings: dict) -> tuple:
|
||
"""
|
||
执行降级模式写在正文里的结构化调用。
|
||
|
||
返回 `(剥掉调用块之后的正文, 执行记录)`。
|
||
|
||
★ 解析不了的块**原样留在正文里**:与其默默删掉(用户永远不知道它想干什么),
|
||
不如让用户看见"它写了一段系统没认出来的东西" —— 那说明模型该换了。
|
||
"""
|
||
import agent_tools
|
||
|
||
records = []
|
||
|
||
def _one(match):
|
||
raw = (match.group(1) or '').strip()
|
||
try:
|
||
payload = json.loads(raw)
|
||
except Exception: # noqa: BLE001 - 解析不了就留着,见 docstring
|
||
return match.group(0)
|
||
if not isinstance(payload, dict):
|
||
return match.group(0)
|
||
name = str(payload.get('tool') or '').strip()
|
||
args = payload.get('args') if isinstance(payload.get('args'), dict) else {}
|
||
entry = agent_tools.AGENT_TOOLS.get(name)
|
||
rec = {
|
||
'id': f'degraded_{len(records)}',
|
||
'name': name or '(没写工具名)',
|
||
'args': args,
|
||
'ok': False,
|
||
'result': '',
|
||
'error': '',
|
||
}
|
||
if entry is None:
|
||
rec['error'] = f'没有这个工具:{name}'
|
||
else:
|
||
try:
|
||
out = entry['run'](args)
|
||
rec['ok'] = True
|
||
rec['result'] = json.dumps(out, ensure_ascii=False)[:2000]
|
||
except Exception as exc: # noqa: BLE001 - 工具报错不该让整轮回答失败
|
||
rec['error'] = str(exc)
|
||
records.append(rec)
|
||
return ''
|
||
|
||
stripped = _RE_DEGRADED_CALL.sub(_one, content or '')
|
||
# 调用块被剥掉之后往往留下两三行空白,压一压
|
||
stripped = re.sub(r'\n{3,}', '\n\n', stripped).strip()
|
||
return stripped, records
|
||
|
||
|
||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||
if isinstance(text, str):
|
||
out = text
|
||
else:
|
||
try:
|
||
out = json.dumps(text, ensure_ascii=False)
|
||
except (TypeError, ValueError):
|
||
out = str(text)
|
||
return f'{out[:max_len]}\n…(已截断)' if len(out) > max_len else out
|
||
|
||
|
||
def _max_rounds(settings: dict) -> int:
|
||
raw = settings.get('maxRounds')
|
||
try:
|
||
value = int(float(raw))
|
||
except (TypeError, ValueError):
|
||
value = 6
|
||
if not value: # 0 / 空 都按默认 6 处理(对应 JS 的 `Number(x) || 6`)
|
||
value = 6
|
||
return max(1, min(12, value))
|
||
|
||
|
||
# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。
|
||
#
|
||
# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了
|
||
# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。
|
||
# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表
|
||
# 硬塞进 markdown。
|
||
#
|
||
# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。
|
||
# 所以措辞是"确实用文字说不清时才用"。
|
||
UI_TOOLS_HINT = '\n'.join([
|
||
'界面能力(用户已打开):',
|
||
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
|
||
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
|
||
' 界面**支持 JavaScript**(canvas 画图、动态渲染都行)。',
|
||
' ★★ 用户在界面上的选择**会回到你手里**:页面里调',
|
||
' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放',
|
||
' `<button data-doubao-result="值">`。**关掉界面**用 `Doubao.close()`。',
|
||
' ★ show_ui 有个 `wait` 参数,按需要选:',
|
||
' · wait 不传(默认)= 弹出就继续,不等用户。适合图表/报告这类给人看的;',
|
||
' 用户点过什么,等他下次说话时会作为上下文给你。',
|
||
' · wait=true = **等用户点一个回传按钮或关掉界面**(默认不限时,会一直等)。',
|
||
' 用户点的值**立刻**作为返回值给你,你能在同一个回合里接着干。',
|
||
' 适合"弹几个选项让用户挑,然后我继续"。一般别传 timeout。',
|
||
' ★ 放按钮时要做**明显**:亮蓝底 + 白字,别用纯文字当按钮 ——',
|
||
' 深色主题下暗底暗字用户根本看不出那儿能点。',
|
||
' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。',
|
||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||
' 它会**一直等你选完**再继续(默认不限时),所以你不用在正文里再问一遍、',
|
||
' 更不能自己替用户假设一个答案往下写。',
|
||
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
|
||
])
|
||
|
||
|
||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||
should_stop: Optional[Callable[[], bool]] = None,
|
||
conversation_id: str = '', send_depth: int = 0) -> dict:
|
||
"""
|
||
跑一轮完整对话。
|
||
|
||
settings 当前设置
|
||
messages [{role, content}] 历史(不含 system)
|
||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||
emit 事件回调,直接往 SSE 里写
|
||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||
send_depth `send_message` 嵌套了几层。AI 主动发消息会顺手跑一轮回复,
|
||
那一轮就是 depth+1;超过上限时工具会被拒。
|
||
**这是防无限套娃的关键**(见 app.py 的 /api/session-message)。
|
||
"""
|
||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||
provider = store.provider_info(settings, agent)
|
||
provider_key = provider.get('provider') or settings.get('provider')
|
||
tool_defs = tools_runtime.build_tool_defs(settings)
|
||
max_rounds = _max_rounds(settings)
|
||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||
# ★★ system prompt **每轮重新拼**(需求 3.2):人设 → skills → 世界观 →
|
||
# 情绪 → 记忆 → 同伴情绪,顺序固定(附录 C)。
|
||
#
|
||
# 为什么不拼一次缓存住:记忆和情绪**随时会变**,而且 AI 自己就能改它们
|
||
# (memory_add / emotion_set)。缓存住的表现是"我明明让它记住了,
|
||
# 下一句它又忘了"——这种 bug 用户会当成"记忆功能坏了"。
|
||
#
|
||
# 拼法、判空、查库失败的兜底全在 agent_context.py 里。
|
||
system_prompt = agent_context.build_system_prompt(settings, agent or {})
|
||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||
#
|
||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||
# 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里
|
||
# 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。
|
||
# 按开关动态追加,两边永远一致。
|
||
#
|
||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||
# ★ 新一轮开始:清掉上一轮的发言权移交(v1.2 §3.9 的"一轮最多一次")。
|
||
# 放这儿是因为它必须**每轮**重置,而且和线程无关(工具跑在 worker 线程里)
|
||
tools_runtime.begin_round()
|
||
|
||
if tools_runtime.ui_tools_enabled(settings):
|
||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||
|
||
# ★★ 状态脚本要在**重拼 prompt 之前**跑(需求附录 E 的顺序,固定):
|
||
#
|
||
# 状态脚本执行 → 重拼 prompt → 生成
|
||
#
|
||
# 顺序反了的话,脚本这一轮的改动要等下一轮才生效 ——
|
||
# 表现是"中毒了但 AI 这轮还生龙活虎"。
|
||
#
|
||
# ★ 脚本报错**不中断对话**(需求附录 E):错误收集起来给界面提示,
|
||
# 对话照常往下走。规则脚本是用户自己写的,写错了是常态,
|
||
# 一次脚本错误把整轮对话搞崩,用户会以为整个 App 坏了。
|
||
try:
|
||
import rule_engine
|
||
|
||
_turn = rule_engine.run_turn_scripts(agent or {}, agent_context.pack_of(agent or {}))
|
||
if _turn.get('narration'):
|
||
# 脚本返回的旁白"作为系统消息注入下一轮"(需求 §3.10)——
|
||
# 拼在提示词末尾,比单开一条 user 消息干净(不会污染对话记录)
|
||
system_prompt = (system_prompt + '\n\n【当前状况】\n'
|
||
+ '\n'.join(_turn['narration'])).strip()
|
||
for _e in _turn.get('errors') or []:
|
||
# ★ 异常要**让用户看见**(需求附录 E:"异常归零 + UI 提示")。
|
||
# 只 print 到 stderr 的话,用户看到的只是"这轮回复有点怪",
|
||
# 而完全不知道是脚本报错了 —— 而脚本是他自己写的。
|
||
emit({'type': 'rule_error', 'message': _e})
|
||
print(f'[rule] {_e}', file=sys.stderr)
|
||
except Exception as _exc: # noqa: BLE001 - 规则引擎坏了不该让对话发不出去
|
||
print(f'[rule] 状态脚本执行失败:{_exc}', file=sys.stderr)
|
||
|
||
# ★★ 兼容降级(需求 3.3):这个模型不支持 tools 参数时,换成"正文内调用约定"。
|
||
#
|
||
# 为什么要这么绕:记忆/情绪这些能力**全靠工具**,而本地小模型、
|
||
# 老网关很多不支持 function calling(传 tools 过去轻则被忽略、重则 400)。
|
||
# 不降级的话,用户换上这类模型会发现"记忆功能突然全废了",还看不出原因。
|
||
#
|
||
# 判定依据是**模型列表那一项上的开关**(用户在界面上打的标记),
|
||
# 不做自动探测:各家"不支持"的报错方式五花八门,猜错的代价是
|
||
# 把一个本来能用的模型降级掉 —— 那比不降级更糟。
|
||
degraded = bool(provider.get('noTools'))
|
||
if degraded:
|
||
tool_defs = []
|
||
system_prompt = (system_prompt + '\n' + DEGRADED_HINT).strip()
|
||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||
|
||
emit({
|
||
'type': 'start',
|
||
'provider': provider_key,
|
||
'model': provider.get('model'),
|
||
'tools': len(tool_defs),
|
||
'mode': mode,
|
||
'thinkingLevel': thinking_level,
|
||
'agent': {'id': agent.get('id'), 'name': agent.get('name')} if agent else None,
|
||
})
|
||
|
||
convo = []
|
||
if system_prompt.strip():
|
||
convo.append({'role': 'system', 'content': system_prompt})
|
||
|
||
# ★★★ AI 界面的**数据回流**在这里进上下文。
|
||
#
|
||
# AI 用 show_ui 弹的 HTML 里可以调 `Doubao.sendToAi(值)`,
|
||
# 安卓桥把它 POST 到 /api/ui-result 排队;这里取走并作为
|
||
# **一条 system 消息**插在历史前面。
|
||
#
|
||
# ★ 为什么是 system 而不是 user:
|
||
# 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话,
|
||
# 而且用户点"重新生成"时会和真正那条用户消息混在一起。
|
||
# system 的语义就是"背景信息",正合适。
|
||
#
|
||
# ★ 为什么要**取走**:不取走的话这轮用、下轮还用,
|
||
# 模型会反复提同一件事,用户会以为它卡住了。
|
||
#
|
||
# ★ 为什么放在 messages **之前**:它是"用户接下来这句话的前提",
|
||
# 要让模型先看到"用户在界面上选了什么",再读用户那句话。
|
||
ui_results = store.take_pending_ui(conversation_id) if conversation_id else []
|
||
if ui_results:
|
||
lines = '\n'.join(f'- {v}' for v in ui_results)
|
||
convo.append({
|
||
'role': 'system',
|
||
'content': (
|
||
'用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):\n'
|
||
f'{lines}\n'
|
||
'请结合这些信息回答用户接下来的话;如果用户还没说话,就针对这些选择给出回应。'
|
||
),
|
||
})
|
||
# 也让界面知道模型收到了 —— 前端可以据此显示"AI 已收到你的选择"
|
||
emit({'type': 'ui_results', 'count': len(ui_results)})
|
||
|
||
convo.extend(messages)
|
||
|
||
answer = ''
|
||
reasoning_all = ''
|
||
tool_call_count = 0
|
||
usage = None
|
||
|
||
for round_index in range(max_rounds):
|
||
round_text = ''
|
||
tool_calls = []
|
||
|
||
for event in stream_chat(
|
||
# provider 是"提供商名字"(ark/openai),已经按"智能体 > 全局"解析过了
|
||
provider=provider_key,
|
||
base_url=provider.get('baseUrl'),
|
||
api_key=provider.get('apiKey') or '',
|
||
model=provider.get('model'),
|
||
messages=convo,
|
||
tools=tool_defs if tool_defs else None,
|
||
temperature=settings.get('temperature'),
|
||
thinking_level=thinking_level,
|
||
should_stop=should_stop,
|
||
):
|
||
kind = event.get('type')
|
||
if kind == 'text':
|
||
round_text += event['text']
|
||
# 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||
# 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||
answer += event['text']
|
||
emit({'type': 'delta', 'text': event['text'], 'round': round_index})
|
||
elif kind == 'reasoning':
|
||
reasoning_all += event['text']
|
||
emit({'type': 'reasoning', 'text': event['text'], 'round': round_index})
|
||
elif kind == 'tool_calls':
|
||
tool_calls = event.get('toolCalls') or []
|
||
elif kind == 'usage':
|
||
# ★★ **累加**而不是覆盖。
|
||
#
|
||
# 多轮工具调用时每一轮上游都会来一个 usage,以前是直接赋值 ——
|
||
# 只留最后一轮。而消耗的大头恰恰在前面几轮(工具结果很长,
|
||
# 一轮就是几千 input token),丢掉之后统计出来的数字
|
||
# 会少得离谱,用户会以为"怎么才用了这么点"。
|
||
usage = add_usage(usage, event.get('usage'))
|
||
|
||
if not tool_calls:
|
||
# 降级模式(需求 3.3):模型不会 function calling,改成让它把调用
|
||
# **写在正文里**(```doubao-call 代码块),这里执行掉并从正文里剥掉。
|
||
# 执行记录照常发 tool_call / tool_result 事件,所以界面上的工具痕迹、
|
||
# 幻觉检测这些下游逻辑完全不用改。
|
||
final = answer
|
||
if degraded:
|
||
final, records = run_degraded_calls(answer, settings)
|
||
for r in records:
|
||
emit({'type': 'tool_call', 'id': r['id'], 'name': r['name'], 'args': r.get('args')})
|
||
emit({
|
||
'type': 'tool_result', 'id': r['id'], 'name': r['name'],
|
||
'ok': r['ok'], 'result': r['result'], 'error': r['error'],
|
||
})
|
||
if records:
|
||
tool_call_count += len(records)
|
||
emit({
|
||
'type': 'done',
|
||
'content': final,
|
||
'reasoning': reasoning_all,
|
||
'rounds': round_index + 1,
|
||
'toolCalls': tool_call_count,
|
||
'usage': usage,
|
||
})
|
||
return {
|
||
'content': final, 'reasoning': reasoning_all,
|
||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||
}
|
||
|
||
convo.append({
|
||
'role': 'assistant',
|
||
'content': round_text or '',
|
||
'tool_calls': [
|
||
{
|
||
'id': tc.get('id'),
|
||
'type': 'function',
|
||
'function': {
|
||
'name': tc.get('name'),
|
||
# 参数原样回传:模型可能给出坏 JSON,服务端往往还能自己纠正
|
||
'arguments': tc.get('argsRaw') or json.dumps(tc.get('args') or {}, ensure_ascii=False),
|
||
},
|
||
}
|
||
for tc in tool_calls
|
||
],
|
||
})
|
||
|
||
for tc in tool_calls:
|
||
tool_call_count += 1
|
||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||
# ★ 界面工具(show_ui / ask_user / end_conversation)要拿到"当前是哪次对话",
|
||
# 而工具签名只有 run(args)。所以在这里把上下文放进 thread-local,
|
||
# 执行完立刻清掉 —— HTTP 是每请求一线程,thread-local 天然隔离。
|
||
tools_runtime.push_context(
|
||
conversationId=conversation_id,
|
||
agentId=(agent or {}).get('id') or '',
|
||
toolName=tc.get('name') or '',
|
||
# ★★ 防无限套娃:send_message 触发的回复里再发消息,深度 +1。
|
||
# 这个值一路传到(Kotlin 桥 → 内核 /api/session-message),
|
||
# 超过 SESSION_MSG_MAX_DEPTH 就被拒。
|
||
# **不传的话**:模型发一条 → 那轮回复里再发 → 无限套娃,
|
||
# 一个下午能把 API 额度烧光,用户看到满屏没发过的消息。
|
||
sendDepth=send_depth,
|
||
)
|
||
try:
|
||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||
finally:
|
||
tools_runtime.clear_context()
|
||
if result.get('ok'):
|
||
raw = result.get('result')
|
||
payload = truncate('(无输出)' if raw is None else raw)
|
||
else:
|
||
payload = f"调用失败:{result.get('error') or '未知错误'}"
|
||
emit({
|
||
'type': 'tool_result',
|
||
'id': tc.get('id'),
|
||
'name': tc.get('name'),
|
||
'ok': bool(result.get('ok')),
|
||
'result': payload,
|
||
})
|
||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||
|
||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||
emit({
|
||
'type': 'done',
|
||
'content': answer,
|
||
'reasoning': reasoning_all,
|
||
'rounds': max_rounds,
|
||
'toolCalls': tool_call_count,
|
||
'usage': usage,
|
||
'truncated': True,
|
||
})
|
||
return {
|
||
'content': answer, 'reasoning': reasoning_all,
|
||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||
}
|