Core API

Complete Gemini CLI Core API reference and usage guide

API Reference30 min read

API Modules

Core API modules and methods

GeminiClient

Core Gemini API client class

src/core/gemini.ts

constructor

constructor(config: GeminiConfig)

Create Gemini client instance

Parameters:
configGeminiConfig

Client configuration object

Example:
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>

Send chat message and get response

Parameters:
messagestring

User input message

contextContext

Optional context information

Returns:
Promise<ChatResponse>

Chat response object

Example:
const response = await client.chat('Hello, Gemini!', {
  files: ['src/index.ts'],
  history: previousMessages
})

stream

async stream(message: string, context?: Context): AsyncGenerator<string>

Streaming chat response

Parameters:
messagestring

User input message

contextContext

Optional context information

Returns:
AsyncGenerator<string>

Streaming response generator

Example:
for await (const chunk of client.stream('Explain this code')) {
  process.stdout.write(chunk)
}

SessionManager

Session state manager

src/core/session.ts

createSession

createSession(id?: string): Session

Create new session

Parameters:
idstring

Optional session ID

Returns:
Session

Newly created session object

Example:
const session = sessionManager.createSession('my-session')

getSession

getSession(id: string): Session | null

Get specified session

Parameters:
idstring

Session ID

Returns:
Session | null

Session object or null

Example:
const session = sessionManager.getSession('my-session')

saveSession

async saveSession(session: Session): Promise<void>

Save session to persistent storage

Parameters:
sessionSession

Session object to save

Example:
await sessionManager.saveSession(session)

ContextManager

Context processing manager

src/core/context.ts

addFile

async addFile(filePath: string): Promise<void>

Add file to context

Parameters:
filePathstring

File path

Example:
await contextManager.addFile('src/utils/helper.ts')

addDirectory

async addDirectory(dirPath: string, options?: DirOptions): Promise<void>

Add directory to context

Parameters:
dirPathstring

Directory path

optionsDirOptions

Directory scanning options

Example:
await contextManager.addDirectory('src/', {
  exclude: ['*.test.ts'],
  maxDepth: 3
})

getContext

getContext(): Context

Get current context

Returns:
Context

Current context object

Example:
const context = contextManager.getContext()

Type Definitions

TypeScript type definitions for Core API

GeminiConfig

Gemini client configuration interface

apiKeystring
required

Google AI API key

modelstring

Model name to use, defaults to "gemini-pro"

temperaturenumber

Generation temperature, between 0-1

maxTokensnumber

Maximum number of tokens

timeoutnumber

Request timeout in milliseconds

ChatResponse

Chat response interface

contentstring
required

Response content

usageTokenUsage
required

Token usage information

modelstring
required

Model used

finishReasonstring

Finish reason

Context

Context information interface

filesFileContext[]

File context list

historyMessage[]

Message history

metadataRecord<string, any>

Metadata

Session

Session interface

idstring
required

Unique session identifier

messagesMessage[]
required

Message history

contextContext

Session context

createdAtDate
required

Creation time

updatedAtDate
required

Update time

Usage Examples

Common API usage scenarios and code examples

Basic Chat

Simple chat interaction example

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)
  }
}

File Context

Chat with file context included

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)
}

Session Management

Managing persistent sessions

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)
}

Streaming Response

Real-time streaming output

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!')
}

Error Handling

API error types and handling methods

AuthenticationError

Invalid or expired API key

GEMINI_AUTH_ERROR

Solution:

Check if API key is correctly set, ensure key is valid and not expired

RateLimitError

Request frequency exceeds limits

GEMINI_RATE_LIMIT

Solution:

Implement exponential backoff retry mechanism, or upgrade to higher quota plan

ContextTooLargeError

Context content exceeds model limits

GEMINI_CONTEXT_TOO_LARGE

Solution:

Reduce number of context files or use file summarization feature

NetworkError

Network connection issues

GEMINI_NETWORK_ERROR

Solution:

Check network connection, configure proxy settings, or increase timeout

Next Steps

Continue your development journey with these resources