智能体能不能干活,取决于工具有没有设计好。这篇讲清鸿蒙端上怎么注册工具、怎么把模型的选择调度到真实函数、失败之后怎么兜。
代码用 ArkTS 写,都在真机上跑过。
先明确一件事:模型看不见你的代码。
它只能看见你给它的工具清单——每个工具有名字、有一段描述、有一份参数 schema。模型靠这三样理解「这个工具能干什么、什么时候该调」。
工具写得好不好,直接写在模型的选错率上。
export interface ToolParam {
name: string
type: 'string' | 'number' | 'boolean'
description: string
required: boolean
}
export interface ToolDef {
name: string
description: string
params: ToolParam[]
handler: (args: Record<string, unknown>) => Promise<unknown>
}handler 是这个工具的真实实现。description 是给模型看的说明,写得含糊模型就选错。
举个反例:
// ❌ 描述太笼统,模型不知道什么时候该调
const badTool: ToolDef = {
name: 'handleData',
description: '处理数据',
params: [],
handler: async () => ({ ok: true })
}正例:
// ✅ 描述说清了「做什么 + 什么时候用 + 返回什么」
const weatherTool: ToolDef = {
name: 'get_weather',
description: '查询指定城市当天的天气。当用户询问天气、气温、是否需要带伞时调用。返回温度、天气描述、更新时间。',
params: [{
name: 'city',
type: 'string',
description: '城市名称,中文,例如「武汉」「北京」',
required: true
}],
handler: async (args) => {
const city = String(args.city ?? '')
if (!city) throw new Error('city 不能为空')
const req = http.createHttp()
try {
const res = await req.request(`https://api.example.com/weather?city=${encodeURIComponent(city)}`, {
method: http.RequestMethod.GET,
connectTimeout: 5000,
readTimeout: 8000
})
return JSON.parse(res.result as string)
} finally {
req.destroy()
}
}
}定义好工具之后,要转成模型的 function calling 格式。
interface JsonSchemaProperty {
type: string
description: string
}
interface FunctionSchema {
name: string
description: string
parameters: {
type: 'object'
properties: Record<string, JsonSchemaProperty>
required: string[]
}
}
export function toSchema(tool: ToolDef): FunctionSchema {
const properties: Record<string, JsonSchemaProperty> = {}
const required: string[] = []
for (const p of tool.params) {
properties[p.name] = { type: p.type, description: p.description }
if (p.required) required.push(p.name)
}
return {
name: tool.name,
description: tool.description,
parameters: { type: 'object', properties, required }
}
}
export function buildToolSchema(tools: ToolDef[]): FunctionSchema[] {
return tools.map(toSchema)
}注册表本身就是一个 Map:
export class ToolRegistry {
private tools = new Map<string, ToolDef>()
register(tool: ToolDef): void {
if (this.tools.has(tool.name)) {
throw new Error(`工具名重复:${tool.name}`)
}
this.tools.set(tool.name, tool)
}
get(name: string): ToolDef | undefined {
return this.tools.get(name)
}
list(): ToolDef[] {
return Array.from(this.tools.values())
}
buildSchema(): FunctionSchema[] {
return this.list().map(toSchema)
}
}register 里做了重名检查。这一步看着多余,但实际很关键——工具多起来之后,两个模块注册了同名工具,模型调用的永远是后注册那个,另一处的逻辑永远走不到,而且不报错。
这是整个链路的核心。模型的响应有两种形态:要么是普通文本(它认为可以直接回答),要么是 tool_calls(它要调工具)。
export interface ToolCall {
id: string
type: 'function'
function: { name: string; arguments: string }
}
export interface AssistantMessage {
role: 'assistant'
content: string | null
tool_calls?: ToolCall[]
}
export async function executeToolCalls(
calls: ToolCall[],
registry: ToolRegistry
): Promise<Array<{ toolCallId: string; content: string }>> {
const results = await Promise.all(calls.map(async (call) => {
const name = call.function.name
const tool = registry.get(name)
if (!tool) {
return {
toolCallId: call.id,
content: JSON.stringify({ error: `工具 ${name} 不存在,可用工具:${registry.list().map(t => t.name).join(', ')}` })
}
}
let args: Record<string, unknown>
try {
args = JSON.parse(call.function.arguments || '{}')
} catch {
return {
toolCallId: call.id,
content: JSON.stringify({ error: '参数不是合法 JSON' })
}
}
const missing = tool.params.filter(p => p.required && !(p.name in args)).map(p => p.name)
if (missing.length > 0) {
return {
toolCallId: call.id,
content: JSON.stringify({ error: `缺少必填参数:${missing.join(', ')}` })
}
}
try {
const result = await Promise.race([
tool.handler(args),
new Promise((_, reject) => setTimeout(() => reject(new Error('执行超时')), 15000))
])
return { toolCallId: call.id, content: JSON.stringify(result ?? null) }
} catch (e) {
return {
toolCallId: call.id,
content: JSON.stringify({ error: `执行失败:${(e as Error).message}` })
}
}
}))
return results
}这段代码里有五个决策点,都是踩过坑之后定下来的。
决策一:并行执行。 模型一次可能输出多个 tool_calls,用 Promise.all 并行跑。串行的话,三个工具就是三倍延迟。
决策二:工具不存在时把可用清单返回给模型。 不要只写「工具不存在」。模型看到可用清单,会自己纠正;只写「不存在」,它会再试一次同样的名字,陷入循环。
决策三:参数解析失败要单独处理。 模型偶尔会输出不完整的 JSON,这时候要返回错误,不能崩。
决策四:必填参数校验在调用前。 缺参数就报错,避免 handler 里各种空值判断。
决策五:超时用 Promise.race。 工具本质是网络请求,挂住是常态。15 秒不返回就中断,把超时错误喂回模型——它要么换个思路,要么直接告诉用户。
export async function runAgent(
messages: ChatMessage[],
registry: ToolRegistry,
maxRounds = 6
): Promise<string> {
const working: unknown[] = [...messages]
for (let round = 0; round < maxRounds; round++) {
const resp = await callModel(working, registry.buildSchema())
const msg: AssistantMessage = resp.choices[0].message
if (!msg.tool_calls || msg.tool_calls.length === 0) {
return msg.content ?? ''
}
working.push(msg)
const results = await executeToolCalls(msg.tool_calls, registry)
for (const r of results) {
working.push({
role: 'tool',
tool_call_id: r.toolCallId,
content: r.content
})
}
}
return '达到最大轮次,任务未完成。可以换个问法,或者把任务拆小一点。'
}三点说明。
working.push(msg) 必须在执行工具之前。 顺序反了,模型下一轮就看不到自己刚才说了什么,会重复调同一个工具。
tool_call_id 必须原样带回。 这个 id 是模型关联「调了什么」和「结果是什么」的唯一凭据,漏了直接 400。
maxRounds 是兜底不是优化。 模型有可能一直调工具,没有上限就是烧 token。第六轮还没结果,说明任务本身有问题,应该让用户介入。
坑一:描述写得抽象,模型想不起来用。
第一版 get_weather 的描述写的是「获取天气信息」。问「明天需要带伞吗」,模型回答「建议关注天气预报」,根本没调工具。
改成「当用户询问天气、气温、是否需要带伞时调用」之后,一次就调对了。描述里要写「什么时候用」,不只是「是什么」。
坑二:工具返回内容太长,上下文爆了。
有个工具返回了完整的 JSON 列表(200 多条),一次调用就吃掉了上下文的一半。后面几轮模型开始丢指令。
改法是只返回必要字段,列表最多取前 10 条,其余用 hasMore: true 标记。模型需要更多会自己再调。
坑三:并发调用时结果串了。
Promise.all 返回的顺序是数组顺序,不是完成顺序。但我在拼回消息时用的是 for 循环里的索引,结果 A 的结果被贴到了 B 的 tool_call_id 上。
模型看到「我调的是查天气,你给的是查日历」,就重新调了一遍。修法是用 results 数组里的 toolCallId 去对应,不用索引。
坑四:超时没做,服务挂住。
工具里调的是个第三方接口,有天那个接口挂了,请求一直不返回。整个 Agent 循环就停在那里,前端表现是「一直在转圈」。
加了 Promise.race 超时之后,15 秒中断,把错误喂回模型,它会告诉用户「天气服务暂时不可用」。
上面是通用的,落到鸿蒙端上多了三件事。
权限要提前申请。 调相机、定位、通讯录这些工具,要先在 module.json5 里声明权限,运行时还要动态申请。忘了这一步,工具会抛异常。
后台执行有时间限制。 应用退到后台之后,长任务会被系统挂起。如果工具体量大(比如模型推理),要考虑用 BackgroundTasksKit 申请长时任务。
端侧工具要控内存。 手机可用内存有限,工具里加载大资源(模型、图片)要先算内存预算。中低端机型留给应用的余量往往不到 1GB。
先说结论:工具调用不是默认选项,加它之前要能说出它替掉了哪段人工判断。
流程固定、分支可枚举的,不该上。 「收到表单 → 校验 → 入库」这类业务,判断条件写进 if 就够了,交给模型只是多一层不确定。
算错要担责的,不该上。 金额计算、库存扣减,模型可能算错,也可能调错工具。这类逻辑留在代码层,别让模型碰决策。
工具越堆越多的,先拆。 快到二十个的时候,选错率会明显抬头。这时候按业务域拆成几个 Agent,或者在提示词里先把工具范围收窄,比继续加工具管用。
手上没有可调接口的,做不了。 智能体的上限就是工具的边界。业务系统不开接口,它只能陪着聊天。
一句话判断:这一步是不是「需要人临时决定往哪走」。 是,交给模型;不是,写成代码。
工具调用这个机制,表面上是「让模型调函数」,实质上是把不确定的决策交给模型,把确定的执行留在代码里。
所以设计的时候有两个方向要同时想:模型那边的自由度够不够(描述是否清楚、工具是否够细),代码这边的兜底够不够(参数校验、超时、异常、并发)。
两边都到位,智能体才真的能干活。只做前一半,是个会说话的机器人;只做后一半,是个笨重的规则引擎。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。