跳转到内容

Function 注册指南

Function 注册 是让 AI 调用你业务能力的桥梁。注册后的函数会自动生成文档,AI 可以直接阅读并学会使用——无需手写提示词,无需额外的集成代码。

方式适用场景优点
📋 声明式大多数场景(推荐)零配置,设置 agentConfig 即可
🔧 命令式需要精细控制(多 Registry、动态注册)灵活,可手动管理生命周期

最简单的方式——只需设置 agentConfig 属性:

import { z, withMeta } from '@rtc-agent/component';
const agent = document.querySelector('rtc-agent');
agent.agentConfig = {
name: 'OrderApp',
persona: '你是一个订单管理助手,帮助用户创建、查询和处理订单。',
groups: [
{
name: 'order',
description: '订单管理操作',
functions: [
{
name: 'create',
description: '创建一个新订单',
zodSchema: z.object({
productId: withMeta(z.string(), { example: 'PROD-001' }).describe('商品 ID'),
quantity: withMeta(z.number().int().positive(), { example: 2 }).optional().describe('购买数量'),
}),
returns: { zodSchema: z.object({ orderId: z.string() }).describe('订单信息,包含 orderId') },
handler: async (params) => {
const res = await api.createOrder(params.productId, params.quantity);
return { orderId: res.id, status: res.status };
}
}
]
}
]
};

💡 设置 agentConfig 后,系统会自动创建 Registry、注册函数、生成文档——完全零配置。

需要精细控制时,可以使用 defineRegistry 手动注册:

import { defineRegistry } from '@rtc-agent/component';
const registry = defineRegistry({
name: 'OrderApp',
description: '订单管理应用',
persona: '你是一个订单管理助手。'
});
const orderGroup = registry.createGroup({
name: 'order',
description: '订单管理操作'
});
orderGroup.register({
name: 'create',
description: '创建一个新订单',
handler: async (params) => {
return await api.createOrder(params.productId, params.quantity);
}
});

每个函数由以下字段组成:

字段类型必填说明
📛 namestring✅函数名称,与分组名组合成完整路径(如 order.create)
📝 descriptionstring✅函数描述,写入自动生成的文档,AI 据此决定何时调用
🎯 zodSchemaZodType—推荐 Zod Schema,同时提供运行时校验、类型推导和 TypeScript 自动类型推断
📐 parametersParameterDef[]—旧版 OpenAPI 风格参数定义。新代码请使用 zodSchema
🔙 returnsReturnDef—返回值定义 {schema?, zodSchema?, description?},帮助 AI 理解输出。推荐使用 zodSchema。支持所有主要 Zod 类型(ZodObject、ZodArray、ZodUnion 等),自动转换为 OpenAPI schema。嵌套对象会在自动生成的文档中递归展开为属性表格,与 Parameters 行为一致
⚡ handlerfunction✅执行函数,支持 async,接收 params 参数
🪝 hooksobject—UI 钩子(onStart / onSuccess / onError / onProgress)

Zod Schema 提供运行时校验、类型安全和更好的开发体验:

import { z, withMeta } from '@rtc-agent/component';
{
name: 'createOrder',
description: '创建新订单',
zodSchema: z.object({
productId: withMeta(z.string(), { example: 'PROD-001' }).describe('商品 ID'),
quantity: withMeta(z.number().int().positive(), { example: 2 }).describe('购买数量'),
couponCode: withMeta(z.string(), { example: 'SAVE10' }).optional().describe('可选优惠券码')
}),
handler: async (params) => {
// params 具有完整类型:{ productId: string; quantity: number; couponCode?: string }
return await api.createOrder(params.productId, params.quantity, params.couponCode);
}
}

Zod Schema 的优势:

  • ✅ 运行时校验:参数在 handler 执行前自动校验
  • ✅ 类型推导:TypeScript 自动从 schema 推导参数类型
  • ✅ 可组合:易于组合和复用 schema
  • ✅ 可描述:使用 .describe() 添加参数描述,写入自动生成的文档
  • ✅ 示例值:使用 withMeta(schema, { example }) 为自动生成的文档添加示例值
import { z, withMeta } from '@rtc-agent/component';
{
name: 'refund',
description: '对指定订单发起退款,支持全额和部分退款',
zodSchema: z.object({
orderId: withMeta(z.string(), { example: 'ORD-20240101-001' }).describe('订单 ID'),
amount: withMeta(z.number().positive(), { example: 99.99 }).optional().describe('退款金额(留空则全额退款)'),
reason: withMeta(z.string(), { example: '商品损坏' }).describe('退款原因'),
}),
returns: {
zodSchema: z.object({
refundId: z.string(),
status: z.string(),
}).describe('退款结果,包含 refundId 和状态'),
},
handler: async (params, onProgress) => {
onProgress?.(30);
await validateOrder(params.orderId);
onProgress?.(70);
const result = await processRefund(params.orderId, params.amount);
return { refundId: result.id, status: result.status };
},
hooks: {
onStart: () => showToast('正在处理退款...'),
onSuccess: (result) => showToast(`退款成功:${result.refundId}`),
onError: (err) => showToast(`退款失败:${err.message}`)
}
}

旧版 OpenAPI 风格参数(不推荐)

Section titled “旧版 OpenAPI 风格参数(不推荐)”

为保持向后兼容,仍可使用 OpenAPI 风格参数:

{
name: 'refund',
description: '发起退款',
parameters: [
{ name: 'orderId', schema: { type: 'string' }, required: true, description: '订单 ID' },
{ name: 'amount', schema: { type: 'number' }, description: '退款金额' }
],
handler: async (params) => { /* ... */ }
}

⚠️ 迁移提示:建议新函数使用 zodSchema。Zod 提供更好的类型安全、运行时校验和更简洁的语法。

规则推荐避免
📛 分组名业务领域名词(order、user、payment)过于宽泛(utils、misc、do)
🔤 函数名动词或动宾短语(create、getProfile)无意义缩写(fn1、doIt)
📐 粒度每个函数做一件事一个函数做所有事

📌 完整路径:分组名 + 函数名 = 完整调用路径。例如 order.create、payment.refund。

注册完成后,AI 通过 script 工具在沙箱中调用函数:

AI 有两种等价的调用语法:

// 方式一:Proxy 链式调用(自然语法)
await rtcAgent.order.create({ productId: '123', quantity: 2 });
// 方式二:callFunction 方法
await rtcAgent.callFunction('order.create', { productId: '123', quantity: 2 });

💡 Proxy 链式调用让 AI 能像调用普通 API 一样使用注册的函数,语法直观、不易出错。

Hook 让宿主应用能在函数执行的各个阶段介入,实现 UI 反馈、日志记录等:

Hook触发时机说明
🟦 onStart执行前可抛出 CancelledError 取消执行
🟩 onSuccess成功后异步执行,不阻塞主流程
🟥 onError失败后异步执行,不阻塞主流程
🟨 onProgress进度更新handler 调用 onProgress(n) 时触发
// Hook 示例:显示 Toast 通知
{
hooks: {
onStart: () => showToast('操作开始...'),
onSuccess: (result) => showToast(`操作完成:${result.id}`),
onError: (err) => showToastError(`操作失败:${err.message}`)
}
}
生成内容说明
📄 函数文档每个函数一个 Markdown 文件,包含描述、参数表格、返回值(嵌套对象递归展开为属性表格)、调用示例(含 @returns JSDoc 注释)
📑 索引文件INDEX.md 列出所有可用函数,方便 AI 浏览
🧠 Agent 指南AGENT.md 汇总所有函数能力,帮助 AI 理解整体上下文

💡 即注册即用:文档在注册时自动生成,AI 可以直接阅读文档了解函数用法——不需要额外编写提示词。