코어 API
완전한 Gemini CLI Core API 참조 및 사용 가이드
API 모듈
핵심 API 모듈 및 메서드
GeminiClient
핵심 Gemini API 클라이언트 클래스
src/core/gemini.tsconstructor
constructor(config: GeminiConfig)Gemini 클라이언트 인스턴스 생성
매개변수:
configGeminiConfig클라이언트 구성 객체
예제:
const client = new GeminiClient({
apiKey: process.env.GEMINI_API_KEY,
model: 'gemini-pro',
temperature: 0.7
})chat
async chat(message: string, context?: Context): Promise<ChatResponse>채팅 메시지를 보내고 응답 받기
매개변수:
messagestring사용자 입력 메시지
contextContext선택적 컨텍스트 정보
반환:
Promise<ChatResponse>채팅 응답 객체
예제:
const response = await client.chat('Hello, Gemini!', {
files: ['src/index.ts'],
history: previousMessages
})stream
async stream(message: string, context?: Context): AsyncGenerator<string>스트리밍 채팅 응답
매개변수:
messagestring사용자 입력 메시지
contextContext선택적 컨텍스트 정보
반환:
AsyncGenerator<string>스트리밍 응답 생성기
예제:
for await (const chunk of client.stream('Explain this code')) {
process.stdout.write(chunk)
}SessionManager
세션 상태 관리자
src/core/session.tscreateSession
createSession(id?: string): Session새 세션 생성
매개변수:
idstring선택적 세션 ID
반환:
Session새로 생성된 세션 객체
예제:
const session = sessionManager.createSession('my-session')getSession
getSession(id: string): Session | null지정된 세션 가져오기
매개변수:
idstring세션 ID
반환:
Session | null세션 객체 또는 null
예제:
const session = sessionManager.getSession('my-session')saveSession
async saveSession(session: Session): Promise<void>세션을 영구 저장소에 저장
매개변수:
sessionSession저장할 세션 객체
예제:
await sessionManager.saveSession(session)
ContextManager
컨텍스트 처리 관리자
src/core/context.tsaddFile
async addFile(filePath: string): Promise<void>컨텍스트에 파일 추가
매개변수:
filePathstring파일 경로
예제:
await contextManager.addFile('src/utils/helper.ts')addDirectory
async addDirectory(dirPath: string, options?: DirOptions): Promise<void>컨텍스트에 디렉토리 추가
매개변수:
dirPathstring디렉토리 경로
optionsDirOptions디렉토리 스캔 옵션
예제:
await contextManager.addDirectory('src/', {
exclude: ['*.test.ts'],
maxDepth: 3
})getContext
getContext(): Context현재 컨텍스트 가져오기
반환:
Context현재 컨텍스트 객체
예제:
const context = contextManager.getContext()
타입 정의
Core API용 TypeScript 타입 정의
GeminiConfig
Gemini 클라이언트 구성 인터페이스
apiKeystringGoogle AI API 키
modelstring사용할 모델 이름, 기본값은 "gemini-pro"
temperaturenumber생성 온도, 0-1 사이
maxTokensnumber최대 토큰 수
timeoutnumber요청 타임아웃(밀리초)
ChatResponse
채팅 응답 인터페이스
contentstring응답 내용
usageTokenUsage토큰 사용 정보
modelstring사용된 모델
finishReasonstring완료 이유
Context
컨텍스트 정보 인터페이스
filesFileContext[]파일 컨텍스트 목록
historyMessage[]메시지 기록
metadataRecord<string, any>메타데이터
Session
세션 인터페이스
idstring고유 세션 식별자
messagesMessage[]메시지 기록
contextContext세션 컨텍스트
createdAtDate생성 시간
updatedAtDate업데이트 시간
사용 예제
일반적인 API 사용 시나리오 및 코드 예제
기본 채팅
간단한 채팅 상호작용 예제
import { GeminiClient } from '@gemini/core'
const client = new GeminiClient({
apiKey: process.env.GEMINI_API_KEY,
model: 'gemini-pro'
})
async function basicChat() {
try {
const response = await client.chat('Hello, how are you?')
console.log('AI:', response.content)
} catch (error) {
console.error('Chat error:', error.message)
}
}파일 컨텍스트
파일 컨텍스트가 포함된 채팅
import { GeminiClient, ContextManager } from '@gemini/core'
const client = new GeminiClient({ apiKey: process.env.GEMINI_API_KEY })
const contextManager = new ContextManager()
async function chatWithFiles() {
// Add files to context
await contextManager.addFile('src/utils/helper.ts')
await contextManager.addDirectory('src/components/')
const context = contextManager.getContext()
const response = await client.chat(
'Explain the helper functions in this codebase',
context
)
console.log(response.content)
}세션 관리
영구 세션 관리
import { SessionManager } from '@gemini/core'
const sessionManager = new SessionManager()
async function manageSessions() {
// Create new session
const session = sessionManager.createSession('project-review')
// Add messages to session
session.messages.push({
role: 'user',
content: 'Review this code for best practices'
})
// Save session
await sessionManager.saveSession(session)
// Restore session later
const restored = sessionManager.getSession('project-review')
console.log('Session messages:', restored?.messages.length)
}스트리밍 응답
실시간 스트리밍 출력
import { GeminiClient } from '@gemini/core'
const client = new GeminiClient({ apiKey: process.env.GEMINI_API_KEY })
async function streamingChat() {
console.log('AI: ')
for await (const chunk of client.stream('Write a short story')) {
process.stdout.write(chunk)
}
console.log('\n\nStream completed!')
}오류 처리
API 오류 유형 및 처리 방법
AuthenticationError
유효하지 않거나 만료된 API 키
GEMINI_AUTH_ERROR해결책:
API 키가 올바르게 설정되었는지 확인하고, 키가 유효하고 만료되지 않았는지 확인하세요
RateLimitError
요청 빈도가 제한을 초과합니다
GEMINI_RATE_LIMIT해결책:
지수 백오프 재시도 메커니즘을 구현하거나 더 높은 할당량 플랜으로 업그레이드하세요
ContextTooLargeError
컨텍스트 콘텐츠가 모델 제한을 초과합니다
GEMINI_CONTEXT_TOO_LARGE해결책:
컨텍스트 파일 수를 줄이거나 파일 요약 기능을 사용하세요
NetworkError
네트워크 연결 문제
GEMINI_NETWORK_ERROR해결책:
네트워크 연결을 확인하고, 프록시 설정을 구성하거나 타임아웃을 늘리세요