自定义工具
创建 LLM 可以在 opencode 中调用的工具。
自定义工具是你创建的函数,LLM 可以在对话期间调用它们。它们与 opencode 的内置工具(如 read、write 和 bash)一起工作。
# 创建工具#
工具定义为 TypeScript 或 JavaScript 文件。但是,工具定义可以调用用任何语言编写的脚本 — TypeScript 或 JavaScript 仅用于工具定义本身。
## 位置#
工具可以定义在:
- 本地,通过将它们放置在项目的
.opencode/tool/目录中。 - 或全局,通过将它们放置在
~/.config/opencode/tool/中。
## 结构#
创建工具最简单的方法是使用 tool() 辅助函数,它提供类型安全和验证。
typescript1// .opencode/tool/database.ts 2import { tool } from "@opencode-ai/plugin" 3 4export default tool({ 5 description: "查询项目数据库", 6 args: { 7 query: tool.schema.string().describe("要执行的 SQL 查询"), 8 }, 9 async execute(args) { 10 // 你的数据库逻辑 11 return `执行查询: ${args.query}` 12 }, 13})
文件名成为工具名称。上面的代码创建了一个 database 工具。
每个文件多个工具
你也可以从单个文件导出多个工具。每个导出成为一个单独的工具,名称为 <filename>_<exportname>:
typescript1// .opencode/tool/math.ts 2import { tool } from "@opencode-ai/plugin" 3 4export const add = tool({ 5 description: "两个数字相加", 6 args: { 7 a: tool.schema.number().describe("第一个数字"), 8 b: tool.schema.number().describe("第二个数字"), 9 }, 10 async execute(args) { 11 return args.a + args.b 12 }, 13}) 14 15export const multiply = tool({ 16 description: "两个数字相乘", 17 args: { 18 a: tool.schema.number().describe("第一个数字"), 19 b: tool.schema.number().describe("第二个数字"), 20 }, 21 async execute(args) { 22 return args.a * args.b 23 }, 24})
这创建了两个工具:math_add 和 math_multiply。
## 参数#
你可以使用 tool.schema(它就是 Zod↗)来定义参数类型。
typescriptargs: { query: tool.schema.string().describe("要执行的 SQL 查询") }
你也可以直接导入 Zod↗ 并返回一个普通对象:
typescript1import { z } from "zod" 2 3export default { 4 description: "工具描述", 5 args: { 6 param: z.string().describe("参数描述"), 7 }, 8 async execute(args, context) { 9 // 工具实现 10 return "result" 11 }, 12}
## 上下文#
工具接收当前会话的上下文:
typescript1// .opencode/tool/project.ts 2import { tool } from "@opencode-ai/plugin" 3 4export default tool({ 5 description: "获取项目信息", 6 args: {}, 7 async execute(args, context) { 8 // 访问上下文信息 9 const { agent, sessionID, messageID } = context 10 return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}` 11 }, 12})
# 示例#
## 用 Python 编写工具#
你可以用任何你想要的语言编写工具。这是一个使用 Python 将两个数字相加的示例。
首先,创建 Python 脚本形式的工具:
python1# .opencode/tool/add.py 2import sys 3 4a = int(sys.argv[1]) 5b = int(sys.argv[2]) 6print(a + b)
然后创建调用它的工具定义:
typescript1// .opencode/tool/python-add.ts 2import { tool } from "@opencode-ai/plugin" 3 4export default tool({ 5 description: "使用 Python 将两个数字相加", 6 args: { 7 a: tool.schema.number().describe("第一个数字"), 8 b: tool.schema.number().describe("第二个数字"), 9 }, 10 async execute(args) { 11 const result = await Bun.$`python3 .opencode/tool/add.py ${args.a} ${args.b}`.text() 12 return result.trim() 13 }, 14})
这里我们使用 Bun.$↗ 工具来运行 Python 脚本。