0
# Core AI Functionality
1
2
Core AI functionality for content generation, chat management, and agentic interactions with Google's Gemini models. This module provides the primary interfaces for AI-powered applications.
3
4
## Capabilities
5
6
### GeminiClient
7
8
Main client class that orchestrates AI interactions, tool execution, and conversation management.
9
10
```typescript { .api }
11
/**
12
* Main client for Gemini API interactions with tool integration and conversation management
13
*/
14
class GeminiClient {
15
constructor(config: Config);
16
17
// Initialization and setup
18
initialize(): Promise<void>;
19
isInitialized(): boolean;
20
21
// Chat management
22
startChat(extraHistory?: Content[]): Promise<GeminiChat>;
23
getChat(): GeminiChat;
24
resetChat(): Promise<void>;
25
26
// History management
27
addHistory(content: Content): Promise<void>;
28
getHistory(): Content[];
29
stripThoughtsFromHistory(): void;
30
setHistory(history: Content[]): void;
31
32
// Content generation
33
generateContent(
34
contents: Content[],
35
generationConfig: GenerateContentConfig,
36
abortSignal: AbortSignal,
37
model: string
38
): Promise<GenerateContentResponse>;
39
40
generateJson<T>(
41
contents: Content[],
42
schema: Record<string, unknown>,
43
abortSignal: AbortSignal,
44
model: string,
45
generationConfig?: GenerateContentConfig
46
): Promise<T>;
47
48
sendMessageStream(
49
request: PartListUnion,
50
signal: AbortSignal,
51
prompt_id: string,
52
turns?: number,
53
originalModel?: string
54
): AsyncGenerator<ServerGeminiStreamEvent, Turn>;
55
56
// Tool management
57
setTools(): Promise<void>;
58
59
// Context management
60
addDirectoryContext(): Promise<void>;
61
62
// Advanced features
63
generateEmbedding(texts: string[]): Promise<number[][]>;
64
tryCompressChat(
65
prompt_id: string,
66
force?: boolean
67
): Promise<ChatCompressionInfo>;
68
69
// Services
70
getChatRecordingService(): ChatRecordingService | undefined;
71
}
72
```
73
74
### GeminiChat
75
76
Chat session management with streaming support, tool integration, and conversation history.
77
78
```typescript { .api }
79
/**
80
* Chat session management with streaming support and tool integration
81
*/
82
class GeminiChat {
83
constructor(
84
config: Config,
85
generationConfig?: GenerateContentConfig,
86
history?: Content[]
87
);
88
89
// Message sending
90
sendMessage(
91
params: SendMessageParameters,
92
prompt_id: string
93
): Promise<GenerateContentResponse>;
94
95
sendMessageStream(
96
params: SendMessageParameters,
97
prompt_id: string
98
): Promise<AsyncGenerator<StreamEvent>>;
99
100
// History management
101
getHistory(curated?: boolean): Content[];
102
clearHistory(): void;
103
addHistory(content: Content): void;
104
setHistory(history: Content[]): void;
105
stripThoughtsFromHistory(): void;
106
107
// Configuration
108
setSystemInstruction(sysInstr: string): void;
109
setTools(tools: Tool[]): void;
110
111
// Error handling and context
112
maybeIncludeSchemaDepthContext(error: StructuredError): Promise<void>;
113
114
// Services
115
getChatRecordingService(): ChatRecordingService;
116
recordCompletedToolCalls(toolCalls: CompletedToolCall[]): void;
117
}
118
119
interface SendMessageOptions {
120
systemInstruction?: string;
121
tools?: Tool[];
122
generationConfig?: GenerationConfig;
123
}
124
```
125
126
### Content Generation
127
128
Content generation configuration and factory functions for different authentication types.
129
130
```typescript { .api }
131
/**
132
* Interface for content generation with multiple provider support
133
*/
134
interface ContentGenerator {
135
generateContent(request: GenerateContentRequest): Promise<GenerateContentResponse>;
136
generateContentStream(request: GenerateContentRequest): AsyncGenerator<GenerateContentResponse>;
137
countTokens(request: CountTokensRequest): Promise<CountTokensResponse>;
138
embedContent(request: EmbedContentRequest): Promise<EmbedContentResponse>;
139
}
140
141
/**
142
* Configuration for content generator initialization
143
*/
144
interface ContentGeneratorConfig {
145
authType: AuthType;
146
apiKey?: string;
147
projectId?: string;
148
location?: string;
149
model: string;
150
credentials?: any;
151
}
152
153
/**
154
* Create content generator configuration based on auth type
155
* @param config - Application configuration
156
* @param authType - Authentication method to use
157
* @returns Configuration for content generator
158
*/
159
function createContentGeneratorConfig(
160
config: Config,
161
authType: AuthType
162
): ContentGeneratorConfig;
163
164
/**
165
* Create content generator instance
166
* @param config - Content generator configuration
167
* @param gcConfig - Global configuration
168
* @param sessionId - Optional session identifier
169
* @returns Content generator instance
170
*/
171
function createContentGenerator(
172
config: ContentGeneratorConfig,
173
gcConfig: Config,
174
sessionId?: string
175
): Promise<ContentGenerator>;
176
```
177
178
### Logging Content Generator
179
180
Decorator for logging all content generation API calls for debugging and monitoring.
181
182
```typescript { .api }
183
/**
184
* Decorator for logging content generation API calls
185
*/
186
class LoggingContentGenerator implements ContentGenerator {
187
constructor(wrapped: ContentGenerator, logger?: Logger);
188
189
getWrapped(): ContentGenerator;
190
191
generateContent(request: GenerateContentRequest): Promise<GenerateContentResponse>;
192
generateContentStream(request: GenerateContentRequest): AsyncGenerator<GenerateContentResponse>;
193
countTokens(request: CountTokensRequest): Promise<CountTokensResponse>;
194
embedContent(request: EmbedContentRequest): Promise<EmbedContentResponse>;
195
}
196
```
197
198
### Turn Management
199
200
Agentic loop management for multi-turn conversations with tool execution and event streaming.
201
202
```typescript { .api }
203
/**
204
* Manages agentic loop turns with tool execution and event streaming
205
*/
206
class Turn {
207
constructor(
208
chat: GeminiChat,
209
coreToolScheduler: CoreToolScheduler,
210
config: Config,
211
logger?: Logger
212
);
213
214
// Event streaming
215
sendMessageStream(
216
message: string | Part[],
217
onEvent?: (event: GeminiEvent) => void
218
): AsyncGenerator<GeminiEvent>;
219
220
// Turn execution
221
executeTurn(request: GenerateContentRequest): Promise<GenerateContentResult>;
222
}
223
224
/**
225
* Event types for streaming Gemini interactions
226
*/
227
enum GeminiEventType {
228
Content = 'Content',
229
ToolCallRequest = 'ToolCallRequest',
230
ToolCallResponse = 'ToolCallResponse',
231
ToolCallConfirmation = 'ToolCallConfirmation',
232
UserCancelled = 'UserCancelled',
233
Error = 'Error',
234
ChatCompressed = 'ChatCompressed',
235
Thought = 'Thought',
236
MaxSessionTurns = 'MaxSessionTurns',
237
Finished = 'Finished',
238
LoopDetected = 'LoopDetected',
239
Citation = 'Citation',
240
Retry = 'Retry'
241
}
242
243
/**
244
* Stream event types for real-time communication
245
*/
246
enum StreamEventType {
247
CHUNK = 'CHUNK',
248
RETRY = 'RETRY'
249
}
250
251
type StreamEvent =
252
| { type: StreamEventType.CHUNK; chunk: EnhancedGenerateContentResponse }
253
| { type: StreamEventType.RETRY };
254
```
255
256
### Error Handling
257
258
Specialized error classes for AI operations and error detection utilities.
259
260
```typescript { .api }
261
/**
262
* Error for empty response streams
263
*/
264
class EmptyStreamError extends Error {
265
constructor(message?: string);
266
}
267
268
/**
269
* Structured error with status code information
270
*/
271
interface StructuredError {
272
message: string;
273
status?: number;
274
code?: string;
275
details?: any;
276
}
277
278
/**
279
* Check if error message indicates schema depth issues
280
* @param errorMessage - Error message to check
281
* @returns True if schema depth error
282
*/
283
function isSchemaDepthError(errorMessage: string): boolean;
284
285
/**
286
* Check if error message indicates invalid argument
287
* @param errorMessage - Error message to check
288
* @returns True if invalid argument error
289
*/
290
function isInvalidArgumentError(errorMessage: string): boolean;
291
```
292
293
### Compression and Optimization
294
295
Chat compression functionality for managing conversation length and token usage.
296
297
```typescript { .api }
298
/**
299
* Compression status enumeration
300
*/
301
enum CompressionStatus {
302
COMPRESSED = 'COMPRESSED',
303
COMPRESSION_FAILED_INFLATED_TOKEN_COUNT = 'COMPRESSION_FAILED_INFLATED_TOKEN_COUNT',
304
COMPRESSION_FAILED_TOKEN_COUNT_ERROR = 'COMPRESSION_FAILED_TOKEN_COUNT_ERROR',
305
NOOP = 'NOOP'
306
}
307
308
/**
309
* Chat compression information
310
*/
311
interface ChatCompressionInfo {
312
status: CompressionStatus;
313
originalTokens: number;
314
compressedTokens: number;
315
compressionRatio: number;
316
}
317
318
/**
319
* Find index after specified fraction of conversation history
320
* @param history - Conversation history
321
* @param fraction - Fraction point (0-1)
322
* @returns Index position
323
*/
324
function findIndexAfterFraction(history: Content[], fraction: number): number;
325
```
326
327
### Utility Functions
328
329
Utility functions for model capabilities and content processing.
330
331
```typescript { .api }
332
/**
333
* Check if model supports thinking capability
334
* @param model - Model name to check
335
* @returns True if thinking is supported
336
*/
337
function isThinkingSupported(model: string): boolean;
338
339
/**
340
* Check if thinking is default for model
341
* @param model - Model name to check
342
* @returns True if thinking is default
343
*/
344
function isThinkingDefault(model: string): boolean;
345
346
/**
347
* Convert part list union to string representation
348
* @param value - Part list union value
349
* @returns String representation
350
*/
351
function partListUnionToString(value: PartListUnion): string;
352
353
/**
354
* Gemini code request type alias
355
*/
356
type GeminiCodeRequest = PartListUnion;
357
```
358
359
**Usage Examples:**
360
361
```typescript
362
import {
363
GeminiClient,
364
createContentGeneratorConfig,
365
createContentGenerator,
366
AuthType,
367
Config
368
} from '@google/gemini-cli-core';
369
370
// Basic setup
371
const config = new Config({
372
model: 'gemini-1.5-flash',
373
apiKey: process.env.GEMINI_API_KEY
374
});
375
376
const generatorConfig = createContentGeneratorConfig(config, AuthType.USE_GEMINI);
377
const contentGenerator = await createContentGenerator(generatorConfig, config);
378
379
const client = new GeminiClient(config, contentGenerator);
380
await client.initialize();
381
382
// Simple content generation
383
const response = await client.generateContent({
384
contents: [{
385
role: 'user',
386
parts: [{ text: 'What is quantum computing?' }]
387
}]
388
});
389
390
console.log(response.response.text());
391
392
// Streaming conversation with tools
393
const chat = await client.startChat();
394
395
for await (const event of client.sendMessageStream('List files and analyze the project structure')) {
396
switch (event.type) {
397
case 'Content':
398
process.stdout.write(event.content);
399
break;
400
case 'ToolCallRequest':
401
console.log(`Calling tool: ${event.toolName}`);
402
break;
403
case 'ToolCallResponse':
404
console.log(`Tool result: ${event.result}`);
405
break;
406
}
407
}
408
409
// JSON generation
410
const analysis = await client.generateJson<{summary: string, recommendations: string[]}>(
411
{
412
contents: [{
413
role: 'user',
414
parts: [{ text: 'Analyze this codebase and return a JSON summary with recommendations' }]
415
}]
416
}
417
);
418
419
console.log(analysis.summary);
420
console.log(analysis.recommendations);
421
```