Разработка инструментов
Создавайте пользовательские инструменты для расширения возможностей Gemini CLI. Изучите, как проектировать, реализовывать, тестировать и развертывать инструменты, которые бесшовно интегрируются с ИИ-разговорами.
Процесс разработки
Пошаговое руководство по созданию пользовательских инструментов
Определить интерфейс инструмента
Создать определение инструмента с параметрами и описанием
Пример:
const toolDefinition = {
name: 'calculate_age',
description: 'Calculate age based on birth date',
parameters: {
type: 'object',
properties: {
birthDate: {
type: 'string',
format: 'date',
description: 'Birth date in YYYY-MM-DD format'
},
currentDate: {
type: 'string',
format: 'date',
description: 'Current date (optional, defaults to today)'
}
},
required: ['birthDate']
}
};Реализовать логику инструмента
Написать функцию выполнения, которая выполняет задачу инструмента
Пример:
const executeFunction = async ({ birthDate, currentDate }) => {
try {
const birth = new Date(birthDate);
const current = currentDate ? new Date(currentDate) : new Date();
if (birth > current) {
throw new Error('Birth date cannot be in the future');
}
const ageMs = current.getTime() - birth.getTime();
const ageYears = Math.floor(ageMs / (1000 * 60 * 60 * 24 * 365.25));
return `Age: ${ageYears} years old`;
} catch (error) {
return `Error: ${error.message}`;
}
};Зарегистрировать инструмент
Добавить инструмент в реестр инструментов Gemini CLI
Пример:
import { GeminiCLI } from '@google/generative-ai-cli';
const cli = new GeminiCLI();
// Create complete tool
const ageTool = {
...toolDefinition,
execute: executeFunction
};
// Register the tool
cli.registerTool(ageTool);
// Verify registration
console.log('Registered tools:', cli.listTools().map(t => t.name));Протестировать инструмент
Протестируйте ваш инструмент, чтобы убедиться, что он работает правильно
Пример:
// Test the tool directly
const result = await cli.executeTool('calculate_age', {
birthDate: '1990-05-15'
});
console.log(result); // "Age: 34 years old"
// Test with AI
const response = await cli.ask(
"How old would someone born on May 15, 1990 be today?",
{ tools: ['calculate_age'] }
);Шаблон инструмента
Используйте этот шаблон для быстрого начала разработки пользовательских инструментов
Базовый шаблон инструмента
Скопируйте этот шаблон и измените его в соответствии с вашими потребностями. Убедитесь, что обновили имя, описание, параметры и логику выполнения.
import { Tool, ToolDefinition } from '@google/generative-ai-cli';
export const myCustomTool: ToolDefinition = {
name: 'my_custom_tool',
description: 'Description of what this tool does',
parameters: {
type: 'object',
properties: {
// Define your parameters here
input: {
type: 'string',
description: 'Input parameter description'
}
},
required: ['input']
},
execute: async (params) => {
try {
// Your tool logic here
const { input } = params;
// Process the input
const result = processInput(input);
// Return the result
return result;
} catch (error) {
// Handle errors gracefully
return `Error: ${error.message}`;
}
}
};
function processInput(input: string): string {
// Your processing logic
return `Processed: ${input}`;
}Лучшие практики
Следуйте этим рекомендациям для создания высококачественных, надежных инструментов
Дизайн инструмента
- Держите инструменты сосредоточенными на одной ответственности
- Используйте четкие, описательные имена и описания
- Определите комплексные схемы параметров
- Включите примеры в описания параметров
- Изящно обрабатывайте крайние случаи
Обработка ошибок
- Всегда оборачивайте выполнение в блоки try-catch
- Возвращайте осмысленные сообщения об ошибках
- Проверяйте входные параметры
- Обрабатывайте сетевые таймауты и сбои
- Логируйте ошибки для отладки
Производительность
- Правильно реализовать асинхронные операции
- Добавить обработку таймаутов для длительных операций
- Кэшировать результаты при необходимости
- Минимизировать внешние зависимости
- Использовать потоковую передачу для больших ответов
Безопасность
- Проверять и очищать все входные данные
- Избегать выполнения произвольного кода
- Ограничить доступ к файловой системе
- Использовать безопасные API-эндпоинты
- Осторожно обрабатывать конфиденциальные данные
Тестирование ваших инструментов
Убедитесь, что ваши инструменты работают правильно перед развертыванием
Модульное тестирование
// Test tool execution directly
import { myCustomTool } from './my-tool';
describe('myCustomTool', () => {
test('should process input correctly', async () => {
const result = await myCustomTool.execute({
input: 'test data'
});
expect(result).toBe('Processed: test data');
});
test('should handle errors gracefully', async () => {
const result = await myCustomTool.execute({
input: null
});
expect(result).toMatch(/Error:/);
});
});Интеграционное тестирование
// Test tool with Gemini CLI
import { GeminiCLI } from '@google/generative-ai-cli';
const cli = new GeminiCLI();
cli.registerTool(myCustomTool);
// Test tool registration
const tools = cli.listTools();
expect(tools.find(t => t.name === 'my_custom_tool')).toBeDefined();
// Test tool execution
const result = await cli.executeTool('my_custom_tool', {
input: 'test'
});
expect(result).toBeDefined();Тестирование и отладка
Советы для обеспечения надежной работы ваших инструментов
Стратегии тестирования
- Тестировать функции инструментов изолированно
- Тестировать с различными входными параметрами
- Тестировать условия ошибок и крайние случаи
- Проверить интеграцию с ИИ
Советы по отладке
- Добавить подробное логирование
- Использовать console.log для отладки
- Проверить валидацию параметров
- Мониторить метрики производительности
Общие шаблоны инструментов
Многоразовые шаблоны для различных типов инструментов
Инструмент интеграции API
Шаблон для инструментов, интегрирующихся с внешними API
const apiTool = {
name: 'api_call',
description: 'Make API calls to external services',
parameters: {
type: 'object',
properties: {
endpoint: { type: 'string', description: 'API endpoint URL' },
method: { type: 'string', enum: ['GET', 'POST'], default: 'GET' },
data: { type: 'object', description: 'Request payload' }
},
required: ['endpoint']
},
execute: async ({ endpoint, method = 'GET', data }) => {
try {
const response = await fetch(endpoint, {
method,
headers: { 'Content-Type': 'application/json' },
body: data ? JSON.stringify(data) : undefined
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
return `API Error: ${error.message}`;
}
}
};Инструмент обработки данных
Шаблон для инструментов, обрабатывающих и преобразующих данные
const processingTool = {
name: 'data_processor',
description: 'Process and transform data',
parameters: {
type: 'object',
properties: {
data: { type: 'array', description: 'Data to process' },
operation: {
type: 'string',
enum: ['sort', 'filter', 'map', 'reduce'],
description: 'Operation to perform'
},
criteria: { type: 'string', description: 'Processing criteria' }
},
required: ['data', 'operation']
},
execute: async ({ data, operation, criteria }) => {
try {
switch (operation) {
case 'sort':
return data.sort();
case 'filter':
return data.filter(item => item.includes(criteria));
case 'map':
return data.map(item => `${criteria}: ${item}`);
case 'reduce':
return data.reduce((acc, item) => acc + item, '');
default:
throw new Error(`Unknown operation: ${operation}`);
}
} catch (error) {
return `Processing Error: ${error.message}`;
}
}
};Связанные ресурсы
Углубитесь в разработку инструментов и интеграцию API