Core API
Complete Gemini CLI Core API reference and usage guide
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:
config
GeminiConfigClient 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:
message
stringUser input message
context
ContextOptional 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:
message
stringUser input message
context
ContextOptional 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:
id
stringOptional 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:
id
stringSession 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:
session
SessionSession 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:
filePath
stringFile path
Example:
await contextManager.addFile('src/utils/helper.ts')
addDirectory
async addDirectory(dirPath: string, options?: DirOptions): Promise<void>
Add directory to context
Parameters:
dirPath
stringDirectory path
options
DirOptionsDirectory 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
apiKey
stringGoogle AI API key
model
stringModel name to use, defaults to "gemini-pro"
temperature
numberGeneration temperature, between 0-1
maxTokens
numberMaximum number of tokens
timeout
numberRequest timeout in milliseconds
ChatResponse
Chat response interface
content
stringResponse content
usage
TokenUsageToken usage information
model
stringModel used
finishReason
stringFinish reason
Context
Context information interface
files
FileContext[]File context list
history
Message[]Message history
metadata
Record<string, any>Metadata
Session
Session interface
id
stringUnique session identifier
messages
Message[]Message history
context
ContextSession context
createdAt
DateCreation time
updatedAt
DateUpdate 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