도구 개발
Gemini CLI의 기능을 확장하는 사용자 정의 도구를 만듭니다. AI 대화와 원활하게 통합되는 도구를 설계, 구현, 테스트 및 배포하는 방법을 배웁니다.
개발 프로세스
사용자 정의 도구 생성을 위한 단계별 가이드
1
도구 인터페이스 정의
매개변수와 설명이 포함된 도구 정의 생성
예제:
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']
}
};2
도구 로직 구현
도구의 작업을 수행하는 실행 함수 작성
예제:
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}`;
}
};3
도구 등록
도구를 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));4
도구 테스트
도구가 올바르게 작동하는지 확인하기 위해 테스트
예제:
// 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();테스트 및 디버깅
도구가 안정적으로 실행되도록 하는 팁
테스트 전략
- 도구 함수를 독립적으로 테스트
- 다양한 입력 매개변수로 테스트
- 오류 조건 및 엣지 케이스 테스트
- AI와의 통합 검증
디버깅 팁
- 상세한 로깅 추가
- 디버깅을 위해 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}`;
}
}
};