코어 API

완전한 Gemini CLI Core API 참조 및 사용 가이드

API 참조30분 읽기

API 모듈

핵심 API 모듈 및 메서드

GeminiClient

핵심 Gemini API 클라이언트 클래스

src/core/gemini.ts

constructor

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.ts

createSession

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.ts

addFile

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 클라이언트 구성 인터페이스

apiKeystring
필수

Google 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

해결책:

네트워크 연결을 확인하고, 프록시 설정을 구성하거나 타임아웃을 늘리세요

다음 단계

이러한 리소스로 개발 여정을 계속하세요