用户需求 A。规则是**智能体 > 全局**:智能体自己配了 provider / model / baseUrl / ttsEngine / ttsVoice / ttsSpeed 就用它的,留空(空串 / null / 0) 就沿用全局设置。 这样"代码搭子走 DeepSeek、文案师换个音色"只改那一个智能体, 而全局设置仍然是没配过的智能体的默认值。 【内核】 - store.provider_info(settings, agent):provider/model/baseUrl 三层解析 (智能体 > 全局 > 预设) - speech.voice_for(settings, agent):音色解析,只有这一份实现 —— 别在别处再抄一遍规则,两处不一致最难查 - agent_loop 用解析后的 provider 发请求(以前永远走全局) - /api/tts 和 /api/tts/stream 接受 agentId;流式的"是不是系统引擎" 判断也要用**智能体覆盖后**的那套 —— 某个智能体单独配了云端音色、 全局是"设备自带"时,不能因为全局是 system 就把它的流式挡掉 【关键设计:多人会议靠它区分谁在说话】 四个智能体一个嗓子的话,会议模式根本没法听。所以音色必须能按智能体覆盖 —— 这是会议模式的前置依赖,先做掉。 【测试抓到的两个真 bug】 1. store.create_agent / update_agent 用的是**硬编码字段白名单**, ttsVoice 这些新字段直接被丢掉 —— 表现就是"界面上填了、保存后又变空"。 两份内核都有这个问题。现在字段表提成常量(AGENT_FIELDS), create / update 共用,加字段不会再漏改一处。 2. Node 的 /api/tts/stream 忘了给 synthesizeStream 传 agent。 这两条都是新加的回归断言抓到的 —— 不是我看代码看出来的。 【顺带】 - store.py 少了 PROVIDER_PRESETS 的 import(一跑内核就 NameError) - 排查时手滑把 VOLC_TTS_URL 的定义删了(node --check 查不出运行时错误, 是导入模块才暴露的) 回归:语音验收 36 → 41 项(新增 5 条智能体音色断言: 带 agentId 用自己的、不传回落全局、智能体没配则继承全局), 两份内核各 41/41;Markdown 对拍 19/19。 【这一轮之后还剩】 - B 的界面部分:可搜索的全量音色选择器(内核数据已就位) - A 的界面部分:智能体编辑页的模型/语音选择 - C 会议模式(节点+连线编排)—— 最大的一块,下一轮开始
183 lines
6.9 KiB
Python
183 lines
6.9 KiB
Python
"""
|
||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||
|
||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||
open 所有工具都交给模型
|
||
restricted 只有白名单里的工具可用(连执行都会再拦一道,见 tools_runtime.execute_tool)
|
||
|
||
同步实现(生成器 + 普通函数),因为上游是 stdlib urllib 的阻塞式读取;
|
||
在 HTTP 服务里每个请求占一个线程,ThreadingHTTPServer 正好够用。
|
||
"""
|
||
|
||
import json
|
||
from typing import Callable, Optional
|
||
|
||
import store
|
||
import tools_runtime
|
||
from providers import stream_chat
|
||
|
||
MAX_TOOL_RESULT_CHARS = 6000
|
||
|
||
|
||
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))
|
||
|
||
|
||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||
should_stop: Optional[Callable[[], bool]] = None) -> dict:
|
||
"""
|
||
跑一轮完整对话。
|
||
|
||
settings 当前设置
|
||
messages [{role, content}] 历史(不含 system)
|
||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||
emit 事件回调,直接往 SSE 里写
|
||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||
"""
|
||
# ★ 传 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 = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||
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})
|
||
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=settings.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 = event.get('usage')
|
||
|
||
if not tool_calls:
|
||
emit({
|
||
'type': 'done',
|
||
'content': answer,
|
||
'reasoning': reasoning_all,
|
||
'rounds': round_index + 1,
|
||
'toolCalls': tool_call_count,
|
||
'usage': usage,
|
||
})
|
||
return {
|
||
'content': answer, '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')})
|
||
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}'}
|
||
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,
|
||
}
|