Skip to content

工具

工具(Tools)是Chaite为LLM提供的Agent功能的核心组成部分。通过工具,LLM可以获取外部信息、执行特定操作,从而扩展其能力边界,实现更加强大和实用的功能。

Chaite中的工具需要继承CustomTool抽象类并实现相关方法。以下是编写和使用工具的基本步骤:

工具需要定义以下内容:

  • name: 工具名称
  • function: 工具元数据,包含名称、描述和参数
  • run: 实际执行的方法

每个工具需要导出一个工具实例,而非类定义。

import { CustomTool } from 'chaite'
class WeatherTool extends CustomTool {
name = 'getWeather'
function = {
name: 'getWeather',
description: 'Get the current weather in a given location',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: '城市或地区名称'
},
unit: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
description: '温度单位,celsius或fahrenheit'
}
},
required: ['location']
}
}
async run(args) {
const { location, unit = 'celsius' } = args
try {
// 这里是实际获取天气的逻辑
// 示例返回
return `${location}的天气: 晴天, 温度25°${unit === 'celsius' ? 'C' : 'F'}`
} catch (e) {
return `获取天气失败: ${e.message}`
}
}
}
export default new WeatherTool()

在工具中,你可以通过asyncLocalStorage获取当前上下文信息:

import { asyncLocalStorage, CustomTool } from 'chaite'
class MyTool extends CustomTool {
// ...
async run(args) {
// 获取上下文
const context = asyncLocalStorage.getStore()
// 获取事件对象
const e = context.getEvent()
// 现在你可以访问事件信息
// 工具逻辑...
}
}
export default new MyTool()

编写完工具后,需要通过管理面板的工具管理页面添加才能使用。你可以将工具文件放在指定目录下,Chaite会自动加载它们。

  1. 明确的功能边界:每个工具应该有明确的功能
  2. 详细的描述:提供清晰的描述和参数说明,帮助LLM正确调用
  3. 健壮的错误处理:妥善处理可能出现的错误
  4. 合理的参数设计:使用适当的参数类型和必填项设置
  5. 工具组合管理:工具过多可能会影响AI的理解甚至造成冲突,建议通过配置不同的工具组,给不同的预设搭配不同的工具组。例如,为写作助手预设配置文本处理相关工具,为旅游顾问预设配置地图和天气相关工具,这样能更有针对性地增强AI能力,提高AI调用工具的精准度和效率。