工具 API
为 AI 交互创建和管理自定义工具。使用强大的文件操作、shell 命令、网络请求等工具扩展 Gemini CLI。
内置工具
Gemini CLI 中可立即使用的强大工具
文件系统工具
用于读取、写入和管理文件的工具
read_file
从文件读取内容
方法签名:
read_file(path: string): Promise<string>
示例:
const content = await tools.read_file('./package.json');
console.log(content);
write_file
将内容写入文件
方法签名:
write_file(path: string, content: string): Promise<void>
示例:
await tools.write_file('./output.txt', 'Hello, World!');
list_files
列出目录中的文件
方法签名:
list_files(path: string): Promise<string[]>
示例:
const files = await tools.list_files('./src');
console.log(files);
Shell 工具
用于执行 shell 命令的工具
run_shell_command
执行 shell 命令
方法签名:
run_shell_command(command: string, options?: ShellOptions): Promise<ShellResult>
示例:
const result = await tools.run_shell_command('ls -la');
console.log(result.stdout);
run_script
执行脚本文件
方法签名:
run_script(scriptPath: string, args?: string[]): Promise<ShellResult>
示例:
const result = await tools.run_script('./build.sh', ['--production']);
Web 工具
用于网络请求和搜索的工具
web_fetch
从 URL 获取内容
方法签名:
web_fetch(url: string, options?: FetchOptions): Promise<string>
示例:
const content = await tools.web_fetch('https://api.example.com/data');
console.log(content);
web_search
在网络上搜索信息
方法签名:
web_search(query: string, options?: SearchOptions): Promise<SearchResult[]>
示例:
const results = await tools.web_search('Gemini CLI documentation');
console.log(results);
自定义工具开发
创建您自己的工具来扩展 Gemini CLI 功能
创建自定义工具
以下是创建自定义天气工具的完整示例:
import { Tool, ToolDefinition } from '@google/generative-ai-cli';
// 定义自定义工具
const weatherTool: ToolDefinition = {
name: 'get_weather',
description: '获取指定位置的当前天气',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: '城市和州,例如 北京, 中国'
},
unit: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
description: '温度单位'
}
},
required: ['location']
},
execute: async ({ location, unit = 'celsius' }) => {
// 您的天气 API 逻辑
const response = await fetch(`https://api.weather.com/v1/current?location=${location}&unit=${unit}`);
const data = await response.json();
return `${location} 的当前天气: ${data.temperature}°${unit === 'celsius' ? 'C' : 'F'}, ${data.description}`;
}
};
// 注册工具
gemini.registerTool(weatherTool);
// 在对话中使用工具
const response = await gemini.ask("北京的天气怎么样?", {
tools: ['get_weather']
});
工具注册和管理
在您的 Gemini CLI 实例中管理工具
注册工具
// 注册单个工具
gemini.registerTool(myTool);
// 注册多个工具
gemini.registerTools([tool1, tool2, tool3]);
// 从插件加载
gemini.loadPlugin('./my-tools-plugin');
列出和管理工具
// 列出所有可用工具
const tools = gemini.listTools();
// 获取工具信息
const toolInfo = gemini.getTool('tool_name');
// 注销工具
gemini.unregisterTool('tool_name');
最佳实践
创建有效工具的指南
工具设计
- • 保持工具专注于单一职责
- • 提供清晰、描述性的名称和说明
- • 定义全面的参数模式
- • 优雅地处理错误并提供有意义的消息
性能
- • 正确实现异步操作
- • 为长时间操作添加超时处理
- • 在适当时缓存结果
- • 在处理前验证输入