用户需求 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 会议模式(节点+连线编排)—— 最大的一块,下一轮开始
197 lines
6.7 KiB
JavaScript
197 lines
6.7 KiB
JavaScript
/**
|
||
* Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||
* 支持两种安全模式:
|
||
* open 所有工具都交给模型
|
||
* restricted 只有白名单里的工具可用(连执行都会再拦一道)
|
||
*/
|
||
import { providerInfo } from './config.mjs';
|
||
import { streamChat } from './providers.mjs';
|
||
import { discoverPythonTools, runPythonTool, toOpenAITool } from './python-tools.mjs';
|
||
import { callMcpTool, isMcpTool, mcpToolDefs } from './mcp.mjs';
|
||
|
||
/** 汇总当前可用的全部工具 */
|
||
export async function listAllTools(settings) {
|
||
const out = { python: [], mcp: [], errors: [], pythonInfo: null };
|
||
if (settings.tools?.python !== false) {
|
||
const res = await discoverPythonTools();
|
||
out.python = res.tools;
|
||
out.errors = res.errors;
|
||
out.pythonInfo = res.python;
|
||
}
|
||
if (settings.tools?.mcp !== false) {
|
||
out.mcp = mcpToolDefs();
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** 只读工具的名字特征,用来给"限制模式"生成一份保守的默认白名单 */
|
||
const READONLY_NAME = /^(read|list|get|search|open|find|fetch|show|describe|query|inspect|calc|now|web_fetch)/i;
|
||
|
||
export function suggestAllowlist(toolNames) {
|
||
return toolNames.filter((name) => READONLY_NAME.test(name.split('__').pop() || name));
|
||
}
|
||
|
||
/** 按安全模式过滤工具 */
|
||
export function applySecurity(defs, settings) {
|
||
const mode = settings.security?.mode || 'open';
|
||
if (mode !== 'restricted') return defs;
|
||
const allow = new Set(settings.security?.allow || []);
|
||
return defs.filter((def) => allow.has(def.function.name));
|
||
}
|
||
|
||
export async function buildToolDefs(settings) {
|
||
const all = await listAllTools(settings);
|
||
const defs = [...all.python.map(toOpenAITool), ...all.mcp];
|
||
return applySecurity(defs, settings);
|
||
}
|
||
|
||
/** 执行任意工具(Python 或 MCP),返回可序列化结果 */
|
||
export async function executeTool(name, args, settings) {
|
||
// 限制模式下即使模型硬编出工具名也不能执行
|
||
if ((settings?.security?.mode || 'open') === 'restricted') {
|
||
const allow = settings.security?.allow || [];
|
||
if (!allow.includes(name)) {
|
||
return { ok: false, error: `限制模式:工具 ${name} 未授权` };
|
||
}
|
||
}
|
||
if (isMcpTool(name)) {
|
||
const res = await callMcpTool(name, args);
|
||
const parts = [];
|
||
for (const item of res.content || []) {
|
||
if (item.type === 'text') parts.push(item.text);
|
||
else parts.push(`[${item.type}]`);
|
||
}
|
||
return { ok: !res.isError, result: parts.join('\n') || '(空结果)' };
|
||
}
|
||
return runPythonTool(name, args);
|
||
}
|
||
|
||
function truncate(text, max = 6000) {
|
||
const s = typeof text === 'string' ? text : JSON.stringify(text);
|
||
return s.length > max ? `${s.slice(0, max)}\n…(已截断)` : s;
|
||
}
|
||
|
||
/**
|
||
* 跑一轮完整对话。
|
||
* @param {object} opts
|
||
* @param {object} opts.settings 当前设置
|
||
* @param {Array} opts.messages [{role, content}] 历史(不含 system)
|
||
* @param {object} [opts.agent] 当前智能体(systemPrompt 覆盖全局的)
|
||
* @param {(event:object)=>void} opts.emit 事件回调
|
||
* @param {AbortSignal} [opts.signal]
|
||
*/
|
||
export async function runAgent({ settings, messages, agent, emit, signal }) {
|
||
// ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||
// 留空才继承全局
|
||
const provider = providerInfo(settings, agent);
|
||
const providerKey = provider.provider || settings.provider;
|
||
const toolDefs = await buildToolDefs(settings);
|
||
const maxRounds = Math.max(1, Math.min(12, Number(settings.maxRounds) || 6));
|
||
const mode = settings.security?.mode || 'open';
|
||
const systemPrompt = (agent?.systemPrompt || '').trim() || settings.systemPrompt;
|
||
const thinkingLevel = settings.thinkingLevel || 'auto';
|
||
|
||
emit({
|
||
type: 'start',
|
||
provider: providerKey,
|
||
model: provider.model,
|
||
tools: toolDefs.length,
|
||
mode,
|
||
thinkingLevel,
|
||
agent: agent ? { id: agent.id, name: agent.name } : null,
|
||
});
|
||
|
||
const convo = [];
|
||
if (systemPrompt?.trim()) {
|
||
convo.push({ role: 'system', content: systemPrompt });
|
||
}
|
||
convo.push(...messages);
|
||
|
||
let answer = '';
|
||
let reasoningAll = '';
|
||
let toolCallCount = 0;
|
||
let usage = null;
|
||
|
||
for (let round = 0; round < maxRounds; round += 1) {
|
||
let roundText = '';
|
||
let toolCalls = [];
|
||
|
||
for await (const ev of streamChat({
|
||
// provider 是"提供商名字"(ark/openai),已按"智能体 > 全局"解析过
|
||
provider: providerKey,
|
||
baseUrl: provider.baseUrl,
|
||
apiKey: settings.apiKey,
|
||
model: provider.model,
|
||
messages: convo,
|
||
tools: toolDefs.length ? toolDefs : undefined,
|
||
temperature: settings.temperature,
|
||
thinkingLevel,
|
||
signal,
|
||
})) {
|
||
if (ev.type === 'text') {
|
||
roundText += ev.text;
|
||
// 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||
// 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||
answer += ev.text;
|
||
emit({ type: 'delta', text: ev.text, round });
|
||
} else if (ev.type === 'reasoning') {
|
||
reasoningAll += ev.text;
|
||
emit({ type: 'reasoning', text: ev.text, round });
|
||
} else if (ev.type === 'tool_calls') {
|
||
toolCalls = ev.toolCalls;
|
||
} else if (ev.type === 'usage') {
|
||
usage = ev.usage;
|
||
}
|
||
}
|
||
|
||
if (!toolCalls.length) {
|
||
emit({
|
||
type: 'done',
|
||
content: answer,
|
||
reasoning: reasoningAll,
|
||
rounds: round + 1,
|
||
toolCalls: toolCallCount,
|
||
usage,
|
||
});
|
||
return { content: answer, reasoning: reasoningAll, rounds: round + 1, toolCalls: toolCallCount, usage };
|
||
}
|
||
|
||
convo.push({
|
||
role: 'assistant',
|
||
content: roundText || '',
|
||
tool_calls: toolCalls.map((tc) => ({
|
||
id: tc.id,
|
||
type: 'function',
|
||
function: { name: tc.name, arguments: tc.argsRaw || JSON.stringify(tc.args || {}) },
|
||
})),
|
||
});
|
||
|
||
for (const tc of toolCalls) {
|
||
toolCallCount += 1;
|
||
emit({ type: 'tool_call', id: tc.id, name: tc.name, args: tc.args });
|
||
let result;
|
||
try {
|
||
result = await executeTool(tc.name, tc.args, settings);
|
||
} catch (err) {
|
||
result = { ok: false, error: err?.message || String(err) };
|
||
}
|
||
const payload = result.ok
|
||
? truncate(result.result ?? '(无输出)')
|
||
: `调用失败:${result.error || '未知错误'}`;
|
||
emit({ type: 'tool_result', id: tc.id, name: tc.name, ok: Boolean(result.ok), result: payload });
|
||
convo.push({ role: 'tool', tool_call_id: tc.id, content: payload });
|
||
}
|
||
}
|
||
|
||
emit({
|
||
type: 'done',
|
||
content: answer,
|
||
reasoning: reasoningAll,
|
||
rounds: maxRounds,
|
||
toolCalls: toolCallCount,
|
||
usage,
|
||
truncated: true,
|
||
});
|
||
return { content: answer, reasoning: reasoningAll, rounds: maxRounds, toolCalls: toolCallCount, usage };
|
||
}
|