工具调用(Function Calling)的前端呈现与确认交互
Agent 会「动手」了,前端就必须把它的动作画出来。本文讲工具调用的状态机、卡片化呈现、以及需要用户确认的危险操作如何设计。
当模型从「会说话」进化到「会动手」,前端突然多了一类全新的 UI 对象:工具调用。它不是消息,不是按钮,而是一段「模型决定要做某事 → 做了 → 拿到结果」的过程。
这篇文章讲怎么把这段过程变成用户看得懂、信得过的界面。
工具调用的三种状态
一次工具调用,本质上是一个小状态机:
pending(准备调用)→ running(执行中)→ success(成功)/ error(失败)
对应到界面,每个状态都有它该有的样子:
function ToolCallCard({ call }: { call: ToolCall }) {
if (call.status === 'pending') {
return <Card icon="⏳">准备调用 {call.name}</Card>;
}
if (call.status === 'running') {
return <Card icon="⚙️">{call.name} 执行中…</Card>;
}
if (call.status === 'error') {
return <Card icon="❌" tone="danger">{call.name} 失败:{call.error}</Card>;
}
return <Card icon="✓" tone="success">{call.name} 完成</Card>;
}
命名与参数的可读性
模型返回的是机器友好的 name 和 JSON arguments,但展示给用户时要翻译成人话:
const TOOL_LABELS: Record<string, string> = {
search_web: '搜索网络',
read_file: '读取文件',
run_code: '执行代码',
query_db: '查询数据库',
};
function summarize(tool: ToolCall): string {
const args = JSON.parse(tool.arguments || '{}');
// search_web → 「搜索:Astro 5 发布」
if (tool.name === 'search_web') return `搜索:${args.query}`;
return TOOL_LABELS[tool.name] || tool.name;
}
这个「翻译层」是 Agent 产品信任感的起点——用户看到的是意图,而不是技术细节。
需要确认的危险操作
有些工具调用不该被静默执行。写入数据库、发邮件、删除文件、真实下单……这些副作用操作需要用户确认:
const DANGEROUS_TOOLS = new Set(['send_email', 'delete_file', 'place_order']);
function needsConfirmation(tool: ToolCall): boolean {
return DANGEROUS_TOOLS.has(tool.name);
}
设计一个「待确认」状态:
- 工具调用卡片变成可交互的按钮:
[确认执行] [取消]。 - 用户确认前,模型停在原地(前端不把工具结果回填给后端)。
- 用户取消后,回填一个
用户已取消该操作的结果,让模型继续走「被拒绝」的分支。
这是 Agent 前端里人机协作的关键一环:把最终决定权留给用户。
工具调用链的可视化
一次 Agent 运行可能连续调用十几个工具,形成一条链。把它们串起来展示,能让用户理解「结论是怎么来的」:
用户提问
↓
🔍 搜索「Astro 5 发布」 ✓ 3 条结果
↓
📖 读取 docs/astro-5.md ✓ 1.2k 字
↓
✍️ 基于资料回答
↓
最终回复
可以折叠成一个「查看 Agent 的思考过程」的展开面板,默认收起,避免信息过载。
一个完整的回填闭环
从数据流看,前端在工具调用里承担的角色是「中转 + 可视化」:
// 1. 收到 assistant 的 tool_calls
for (const call of assistantMsg.toolCalls) {
// 2. 前端渲染卡片,标记 running
renderToolCall(call, 'running');
// 3. 危险操作先确认
if (needsConfirmation(call)) {
const ok = await askUser(call);
if (!ok) {
// 回填「已取消」,让模型继续
push({ role: 'tool', toolCallId: call.id, content: '用户取消了该操作' });
continue;
}
}
// 4. 把工具调用发给后端执行,拿到结果
const result = await executeTool(call);
// 5. 回填结果 + 更新卡片状态
renderToolCall(call, 'success');
push({ role: 'tool', toolCallId: call.id, content: result });
}
// 6. 带着完整上下文再次请求模型,继续生成
await streamAgent(messages);
这个循环就是 Agent 的核心节拍器。下一篇,我们把目光从「单次动作」拉远,看看多轮对话的上下文如何管理。