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.tsconstructor
constructor(config: GeminiConfig)Create Gemini client instance
Parameters:
configGeminiConfigClient 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:
messagestringUser input message
contextContextOptional 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:
messagestringUser input message
contextContextOptional 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.tscreateSession
createSession(id?: string): SessionCreate new session
Parameters:
idstringOptional session ID
Returns:
SessionNewly created session object
Example:
const session = sessionManager.createSession('my-session')getSession
getSession(id: string): Session | nullGet specified session
Parameters:
idstringSession ID
Returns:
Session | nullSession object or null
Example:
const session = sessionManager.getSession('my-session')saveSession
async saveSession(session: Session): Promise<void>Save session to persistent storage
Parameters:
sessionSessionSession object to save
Example:
await sessionManager.saveSession(session)
ContextManager
Context processing manager
src/core/context.tsaddFile
async addFile(filePath: string): Promise<void>Add file to context
Parameters:
filePathstringFile path
Example:
await contextManager.addFile('src/utils/helper.ts')addDirectory
async addDirectory(dirPath: string, options?: DirOptions): Promise<void>Add directory to context
Parameters:
dirPathstringDirectory path
optionsDirOptionsDirectory scanning options
Example:
await contextManager.addDirectory('src/', {
exclude: ['*.test.ts'],
maxDepth: 3
})getContext
getContext(): ContextGet current context
Returns:
ContextCurrent context object
Example:
const context = contextManager.getContext()
Type Definitions
TypeScript type definitions for Core API
GeminiConfig
Gemini client configuration interface
apiKeystringGoogle AI API key
modelstringModel name to use, defaults to "gemini-pro"
temperaturenumberGeneration temperature, between 0-1
maxTokensnumberMaximum number of tokens
timeoutnumberRequest timeout in milliseconds
ChatResponse
Chat response interface
contentstringResponse content
usageTokenUsageToken usage information
modelstringModel used
finishReasonstringFinish reason
Context
Context information interface
filesFileContext[]File context list
historyMessage[]Message history
metadataRecord<string, any>Metadata
Session
Session interface
idstringUnique session identifier
messagesMessage[]Message history
contextContextSession context
createdAtDateCreation time
updatedAtDateUpdate 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_ERRORSolution:
Check if API key is correctly set, ensure key is valid and not expired
RateLimitError
Request frequency exceeds limits
GEMINI_RATE_LIMITSolution:
Implement exponential backoff retry mechanism, or upgrade to higher quota plan
ContextTooLargeError
Context content exceeds model limits
GEMINI_CONTEXT_TOO_LARGESolution:
Reduce number of context files or use file summarization feature
NetworkError
Network connection issues
GEMINI_NETWORK_ERRORSolution:
Check network connection, configure proxy settings, or increase timeout
Next Steps
Continue your development journey with these resources