""" 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("值")`,也可以直接放', ' `