ak-gemini 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/types.d.ts CHANGED
@@ -1,225 +1,339 @@
1
- import type { GoogleGenAI, ThinkingLevel, HarmCategory, HarmBlockThreshold } from '@google/genai';
1
+ import type { ThinkingLevel, HarmCategory, HarmBlockThreshold } from '@google/genai';
2
2
 
3
3
  export { ThinkingLevel, HarmCategory, HarmBlockThreshold };
4
4
 
5
+ // ── Shared Types ─────────────────────────────────────────────────────────────
6
+
5
7
  export interface ThinkingConfig {
6
- /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. */
7
8
  includeThoughts?: boolean;
8
- /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. */
9
+ /** Token budget for thinking. 0 = disabled, -1 = automatic. */
9
10
  thinkingBudget?: number;
10
- /** Optional. The number of thoughts tokens that the model should generate. */
11
11
  thinkingLevel?: ThinkingLevel;
12
12
  }
13
13
 
14
14
  export interface SafetySetting {
15
- category: HarmCategory; // The harm category
16
- threshold: HarmBlockThreshold; // The blocking threshold
15
+ category: HarmCategory;
16
+ threshold: HarmBlockThreshold;
17
17
  }
18
18
 
19
19
  export interface ChatConfig {
20
- responseMimeType?: string; // MIME type for responses
21
- temperature?: number; // Controls randomness (0.0 to 1.0)
22
- topP?: number; // Controls diversity via nucleus sampling
23
- topK?: number; // Controls diversity by limiting top-k tokens
24
- maxOutputTokens?: number; // Maximum number of tokens that can be generated in the response
25
- systemInstruction?: string; // System instruction for the model
26
- safetySettings?: SafetySetting[]; // Safety settings array
27
- responseSchema?: Object; // Schema for validating model responses
28
- thinkingConfig?: ThinkingConfig; // Thinking features configuration
29
- labels?: Record<string, string>; // Labels for billing segmentation
30
- tools?: any[]; // Tools configuration (e.g., grounding)
31
- toolConfig?: any; // Tool configuration (e.g., function calling mode)
32
- [key: string]: any; // Additional properties for flexibility
20
+ responseMimeType?: string;
21
+ temperature?: number;
22
+ topP?: number;
23
+ topK?: number;
24
+ maxOutputTokens?: number;
25
+ systemInstruction?: string;
26
+ safetySettings?: SafetySetting[];
27
+ responseSchema?: Object;
28
+ thinkingConfig?: ThinkingConfig;
29
+ labels?: Record<string, string>;
30
+ tools?: any[];
31
+ toolConfig?: any;
32
+ [key: string]: any;
33
33
  }
34
34
 
35
- /** Metadata from the last API response, useful for debugging and cost tracking */
36
35
  export interface ResponseMetadata {
37
- modelVersion: string | null; // The actual model version that responded
38
- requestedModel: string; // The model that was requested
39
- promptTokens: number; // Number of tokens in the prompt
40
- responseTokens: number; // Number of tokens in the response
41
- totalTokens: number; // Total tokens used
42
- timestamp: number; // Timestamp of when the response was received
36
+ modelVersion: string | null;
37
+ requestedModel: string;
38
+ promptTokens: number;
39
+ responseTokens: number;
40
+ totalTokens: number;
41
+ timestamp: number;
43
42
  }
44
43
 
45
- /** Structured usage data returned by getLastUsage() for billing verification */
46
44
  export interface UsageData {
47
- promptTokens: number; // CUMULATIVE input tokens across all retry attempts
48
- responseTokens: number; // CUMULATIVE output tokens across all retry attempts
49
- totalTokens: number; // CUMULATIVE total tokens across all retry attempts
50
- attempts: number; // Number of attempts (1 = first try success, 2+ = retries needed)
51
- modelVersion: string | null; // Actual model that responded (e.g., 'gemini-2.5-flash-001')
52
- requestedModel: string; // Model you requested (e.g., 'gemini-2.5-flash')
53
- timestamp: number; // When response was received
45
+ /** CUMULATIVE input tokens across all retry attempts */
46
+ promptTokens: number;
47
+ /** CUMULATIVE output tokens across all retry attempts */
48
+ responseTokens: number;
49
+ /** CUMULATIVE total tokens across all retry attempts */
50
+ totalTokens: number;
51
+ /** Number of attempts (1 = first try success, 2+ = retries needed) */
52
+ attempts: number;
53
+ /** Actual model that responded (e.g., 'gemini-2.5-flash-001') */
54
+ modelVersion: string | null;
55
+ /** Model you requested (e.g., 'gemini-2.5-flash') */
56
+ requestedModel: string;
57
+ timestamp: number;
54
58
  }
55
59
 
56
- /** Options for per-message configuration */
57
- export interface MessageOptions {
58
- labels?: Record<string, string>; // Per-message billing labels
59
- stateless?: boolean; // If true, send message without affecting chat history
60
- maxRetries?: number; // Override max retries for this message
61
- retryDelay?: number; // Override retry delay for this message
62
- enableGrounding?: boolean; // Override grounding setting for this message
63
- groundingConfig?: Record<string, any>; // Override grounding config for this message
60
+ export interface TransformationExample {
61
+ CONTEXT?: Record<string, unknown> | string;
62
+ PROMPT?: Record<string, unknown>;
63
+ ANSWER?: Record<string, unknown>;
64
+ INPUT?: Record<string, unknown>;
65
+ OUTPUT?: Record<string, unknown>;
66
+ SYSTEM?: string;
67
+ EXPLANATION?: string;
68
+ [key: string]: any;
64
69
  }
65
70
 
66
- export interface AITransformerContext {
71
+ export interface GoogleAuthOptions {
72
+ keyFilename?: string;
73
+ keyFile?: string;
74
+ credentials?: { client_email?: string; private_key?: string; [key: string]: any };
75
+ scopes?: string | string[];
76
+ projectId?: string;
77
+ universeDomain?: string;
78
+ }
79
+
80
+ export type AsyncValidatorFunction = (payload: Record<string, unknown>) => Promise<unknown>;
81
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'none';
82
+
83
+ // ── Constructor Options ──────────────────────────────────────────────────────
84
+
85
+ export interface BaseGeminiOptions {
86
+ /** Gemini model to use (default: 'gemini-2.5-flash') */
67
87
  modelName?: string;
68
- systemInstructions?: string;
69
- chatConfig?: ChatConfig;
70
- genAI?: any;
71
- chat?: any;
72
- examplesFile?: string | null;
73
- exampleData?: TransformationExample[] | null;
88
+ /** System prompt for the model (null or false to disable) */
89
+ systemPrompt?: string | null | false;
90
+ /** Chat session configuration overrides */
91
+ chatConfig?: Partial<ChatConfig>;
92
+ /** Thinking features configuration */
93
+ thinkingConfig?: ThinkingConfig | null;
94
+ /** Maximum output tokens (default: 50000, null removes limit) */
95
+ maxOutputTokens?: number | null;
96
+ /** Log level (default: based on NODE_ENV) */
97
+ logLevel?: LogLevel;
98
+
99
+ // Authentication
100
+ /** API key for Gemini API */
101
+ apiKey?: string;
102
+ /** Use Vertex AI instead of Gemini API */
103
+ vertexai?: boolean;
104
+ /** Google Cloud project ID (required for Vertex AI) */
105
+ project?: string;
106
+ /** Google Cloud location/region */
107
+ location?: string;
108
+ /** Authentication options for Vertex AI */
109
+ googleAuthOptions?: GoogleAuthOptions;
110
+
111
+ /** Billing labels for cost segmentation (Vertex AI only) */
112
+ labels?: Record<string, string>;
113
+ }
114
+
115
+ export interface TransformerOptions extends BaseGeminiOptions {
116
+ /** Path to JSON file containing transformation examples */
117
+ examplesFile?: string;
118
+ /** Inline examples to seed the transformer */
119
+ exampleData?: TransformationExample[];
120
+ /** Key for source/input data in examples (default: 'PROMPT') */
121
+ sourceKey?: string;
122
+ /** Alias for sourceKey */
74
123
  promptKey?: string;
124
+ /** Key for target/output data in examples (default: 'ANSWER') */
125
+ targetKey?: string;
126
+ /** Alias for targetKey */
75
127
  answerKey?: string;
128
+ /** Key for context data in examples (default: 'CONTEXT') */
76
129
  contextKey?: string;
130
+ /** Key for explanation data in examples (default: 'EXPLANATION') */
77
131
  explanationKey?: string;
78
- systemInstructionsKey?: string;
132
+ /** Key for system prompt overrides in examples (default: 'SYSTEM') */
133
+ systemPromptKey?: string;
134
+ /** Maximum retry attempts for validation failures (default: 3) */
79
135
  maxRetries?: number;
136
+ /** Initial retry delay in milliseconds (default: 1000) */
80
137
  retryDelay?: number;
81
- init?: (force?: boolean) => Promise<void>; // Initialization function
82
- seed?: () => Promise<void>; // Function to seed the transformer with examples
83
- message?: (payload: Record<string, unknown>, opts?: MessageOptions, validatorFn?: AsyncValidatorFunction | null) => Promise<Record<string, unknown>>; // Function to send messages to the model
84
- rebuild?: (lastPayload: Record<string, unknown>, serverError: string) => Promise<Record<string, unknown>>; // Function to rebuild the transformer
85
- rawMessage?: (payload: Record<string, unknown> | string, messageOptions?: { labels?: Record<string, string> }) => Promise<Record<string, unknown>>; // Function to send raw messages to the model
86
- genAIClient?: GoogleGenAI; // Google GenAI client instance
87
- onlyJSON?: boolean; // If true, only JSON responses are allowed
88
- enableGrounding?: boolean; // Enable Google Search grounding (default: false, WARNING: costs $35/1k queries)
89
- groundingConfig?: Record<string, any>; // Additional grounding configuration options
90
- labels?: Record<string, string>; // Custom labels for billing segmentation (keys: 1-63 chars lowercase, values: max 63 chars)
91
- vertexai?: boolean; // Whether using Vertex AI (true) or Gemini API (false)
92
- estimate?: (nextPayload: Record<string, unknown> | string) => Promise<{ inputTokens: number }>;
93
- getLastUsage?: () => UsageData | null;
94
- lastResponseMetadata?: ResponseMetadata | null; // Metadata from the last API response
95
- exampleCount?: number; // Number of example history items from seed()
96
- clearConversation?: () => Promise<void>; // Clears conversation history while preserving examples
97
- _cumulativeUsage?: { promptTokens: number; responseTokens: number; totalTokens: number; attempts: number }; // Internal cumulative tracking
138
+ /** Schema for validating model responses */
139
+ responseSchema?: Object;
140
+ /** If true, only JSON responses are allowed (default: true) */
141
+ onlyJSON?: boolean;
142
+ /** Global async validator function for response validation */
143
+ asyncValidator?: AsyncValidatorFunction;
144
+ /** Enable Google Search grounding (WARNING: costs $35/1k queries) */
145
+ enableGrounding?: boolean;
146
+ /** Additional grounding configuration */
147
+ groundingConfig?: Record<string, any>;
98
148
  }
99
149
 
100
- export interface TransformationExample {
101
- CONTEXT?: Record<string, unknown> | string; // optional context for the transformation
102
- PROMPT?: Record<string, unknown>; // what the user provides as input
103
- ANSWER?: Record<string, unknown>; // what the model should return as output
104
- INPUT?: Record<string, unknown>; // alias for PROMPT
105
- OUTPUT?: Record<string, unknown>; // alias for ANSWER
106
- SYSTEM?: string; // system instructions for this example
107
- EXPLANATION?: string; // explanation for this example
108
- [key: string]: any; // allow additional properties for flexible key mapping
150
+ export interface ChatOptions extends BaseGeminiOptions {
151
+ // Chat uses base options only no additional fields needed
109
152
  }
110
153
 
111
- export interface ExampleFileContent {
112
- examples: TransformationExample[];
154
+ export interface MessageOptions extends BaseGeminiOptions {
155
+ /** Schema for structured output validation */
156
+ responseSchema?: Object;
157
+ /** MIME type for responses (e.g., 'application/json' for structured output) */
158
+ responseMimeType?: string;
113
159
  }
114
160
 
115
- // Google Auth options for Vertex AI authentication
116
- // See: https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts
117
- export interface GoogleAuthOptions {
118
- keyFilename?: string; // Path to a .json, .pem, or .p12 key file
119
- keyFile?: string; // Alias for keyFilename
120
- credentials?: { client_email?: string; private_key?: string; [key: string]: any }; // Object containing client_email and private_key
121
- scopes?: string | string[]; // Required scopes for the API request
122
- projectId?: string; // Your project ID (alias for project)
123
- universeDomain?: string; // The default service domain for a Cloud universe
161
+ /** Tool declaration in @google/genai FunctionDeclaration format */
162
+ export interface ToolDeclaration {
163
+ name: string;
164
+ description: string;
165
+ parametersJsonSchema: {
166
+ type: string;
167
+ properties: Record<string, any>;
168
+ required?: string[];
169
+ [key: string]: any;
170
+ };
124
171
  }
125
172
 
126
- export interface AITransformerOptions {
127
- // ? https://ai.google.dev/gemini-api/docs/models
128
- modelName?: string; // The Gemini model to use
129
- systemInstructions?: string | null | false; // Custom system instructions for the model (null/false = no instructions)
130
- chatConfig?: ChatConfig; // Configuration object for the chat session
131
- thinkingConfig?: ThinkingConfig; // Thinking features configuration (defaults to thinkingBudget: 0, thinkingLevel: "MINIMAL")
132
- maxOutputTokens?: number; // Maximum number of tokens that can be generated in the response (defaults to 50000)
133
- examplesFile?: string; // Path to JSON file containing transformation examples
134
- exampleData?: TransformationExample[]; // Inline examples to seed the transformer
135
- sourceKey?: string; // Key name for source data in examples (alias for promptKey)
136
- targetKey?: string; // Key name for target data in examples (alias for answerKey)
137
- promptKey?: string; // Key for the prompt in examples
138
- answerKey?: string; // Key for the answer in examples
139
- contextKey?: string; // Key name for context data in examples
140
- explanationKey?: string; // Key name for explanation data in examples
141
- systemInstructionsKey?: string; // Key for system instructions in examples
142
- maxRetries?: number; // Maximum retry attempts for auto-retry functionality
143
- retryDelay?: number; // Initial retry delay in milliseconds
144
- // ? https://ai.google.dev/gemini-api/docs/structured-output
145
- responseSchema?: Object; // Schema for validating model responses
146
- apiKey?: string; // API key for Google GenAI (Gemini API)
147
- onlyJSON?: boolean; // If true, only JSON responses are allowed
148
- asyncValidator?: AsyncValidatorFunction; // Optional async validator function for response validation
149
- logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'none'; // Log level for the logger (defaults to 'info', 'none' disables logging)
150
- enableGrounding?: boolean; // Enable Google Search grounding (default: false, WARNING: costs $35/1k queries)
151
- groundingConfig?: Record<string, any>; // Additional grounding configuration options
152
- labels?: Record<string, string>; // Custom labels for billing segmentation
153
-
154
- // Vertex AI Authentication Options
155
- // Use these instead of apiKey for Vertex AI with service account authentication
156
- vertexai?: boolean; // Set to true to use Vertex AI instead of Gemini API
157
- project?: string; // Google Cloud project ID (required for Vertex AI)
158
- location?: string; // Google Cloud location/region (e.g., 'us-central1'). If not set, defaults to 'global' endpoint
159
- googleAuthOptions?: GoogleAuthOptions; // Authentication options for Vertex AI (keyFilename, credentials, etc.)
173
+ export interface ToolAgentOptions extends BaseGeminiOptions {
174
+ /** Tool declarations for the model */
175
+ tools?: ToolDeclaration[];
176
+ /** Function to execute tool calls: (toolName, args) => result */
177
+ toolExecutor?: (toolName: string, args: Record<string, any>) => Promise<any>;
178
+ /** Max tool-use loop iterations (default: 10) */
179
+ maxToolRounds?: number;
180
+ /** Callback fired when a tool is called */
181
+ onToolCall?: (toolName: string, args: Record<string, any>) => void;
182
+ /** Async callback before tool execution; return false to deny */
183
+ onBeforeExecution?: (toolName: string, args: Record<string, any>) => Promise<boolean>;
160
184
  }
161
185
 
162
- // Async validator function type
163
- export type AsyncValidatorFunction = (payload: Record<string, unknown>) => Promise<unknown>;
186
+ export interface CodeAgentOptions extends BaseGeminiOptions {
187
+ /** Working directory for code execution (default: process.cwd()) */
188
+ workingDirectory?: string;
189
+ /** Max code execution loop iterations (default: 10) */
190
+ maxRounds?: number;
191
+ /** Per-execution timeout in milliseconds (default: 30000) */
192
+ timeout?: number;
193
+ /** Async callback before code execution; return false to deny */
194
+ onBeforeExecution?: (code: string) => Promise<boolean>;
195
+ /** Notification callback after code execution */
196
+ onCodeExecution?: (code: string, output: { stdout: string; stderr: string; exitCode: number }) => void;
197
+ }
198
+
199
+ export interface CodeExecution {
200
+ /** The JavaScript code that was executed */
201
+ code: string;
202
+ /** stdout from the execution */
203
+ output: string;
204
+ /** stderr from the execution */
205
+ stderr: string;
206
+ /** Process exit code (0 = success) */
207
+ exitCode: number;
208
+ }
209
+
210
+ export interface CodeAgentResponse {
211
+ /** The agent's final text response */
212
+ text: string;
213
+ /** All code executions during this interaction */
214
+ codeExecutions: CodeExecution[];
215
+ /** Token usage data */
216
+ usage: UsageData | null;
217
+ }
218
+
219
+ export interface CodeAgentStreamEvent {
220
+ type: 'text' | 'code' | 'output' | 'done';
221
+ /** For 'text' events: the text chunk */
222
+ text?: string;
223
+ /** For 'code' events: the code about to be executed */
224
+ code?: string;
225
+ /** For 'output' events: stdout from execution */
226
+ stdout?: string;
227
+ /** For 'output' events: stderr from execution */
228
+ stderr?: string;
229
+ /** For 'output' events: process exit code */
230
+ exitCode?: number;
231
+ /** For 'done' events: complete accumulated text */
232
+ fullText?: string;
233
+ /** For 'done' events: all code executions */
234
+ codeExecutions?: CodeExecution[];
235
+ /** For 'done' events: token usage */
236
+ usage?: UsageData | null;
237
+ /** For 'done' events: e.g. "Max tool rounds reached" or "Agent was stopped" */
238
+ warning?: string;
239
+ }
240
+
241
+ // ── Per-Message Options ──────────────────────────────────────────────────────
242
+
243
+ export interface SendOptions {
244
+ /** Per-message billing labels */
245
+ labels?: Record<string, string>;
246
+ /** Send without affecting chat history (Transformer only) */
247
+ stateless?: boolean;
248
+ /** Override max retries for this message */
249
+ maxRetries?: number;
250
+ /** Override retry delay for this message */
251
+ retryDelay?: number;
252
+ /** Override grounding setting for this message */
253
+ enableGrounding?: boolean;
254
+ /** Override grounding config for this message */
255
+ groundingConfig?: Record<string, any>;
256
+ /** @internal Used to restore grounding state after per-message override */
257
+ _restoreGrounding?: () => Promise<void>;
258
+ [key: string]: any;
259
+ }
260
+
261
+ // ── Response Types ───────────────────────────────────────────────────────────
164
262
 
263
+ export interface ChatResponse {
264
+ /** The model's text response */
265
+ text: string;
266
+ /** Token usage data */
267
+ usage: UsageData | null;
268
+ }
165
269
 
166
- export declare class AITransformer {
167
- // Constructor
168
- constructor(options?: AITransformerOptions);
270
+ export interface MessageResponse {
271
+ /** The model's text response */
272
+ text: string;
273
+ /** Parsed structured data (when responseSchema or responseMimeType is set) */
274
+ data?: any;
275
+ /** Token usage data */
276
+ usage: UsageData | null;
277
+ }
278
+
279
+ export interface AgentResponse {
280
+ /** The agent's final text response */
281
+ text: string;
282
+ /** All tool calls made during this interaction */
283
+ toolCalls: Array<{ name: string; args: Record<string, any>; result: any }>;
284
+ /** Token usage data */
285
+ usage: UsageData | null;
286
+ }
287
+
288
+ export interface AgentStreamEvent {
289
+ type: 'text' | 'tool_call' | 'tool_result' | 'done';
290
+ /** For 'text' events: the text chunk */
291
+ text?: string;
292
+ /** For 'tool_call' and 'tool_result' events */
293
+ toolName?: string;
294
+ /** For 'tool_call' events: the tool arguments */
295
+ args?: Record<string, any>;
296
+ /** For 'tool_result' events: the tool result */
297
+ result?: any;
298
+ /** For 'done' events: the complete accumulated text */
299
+ fullText?: string;
300
+ /** For 'done' events: token usage */
301
+ usage?: UsageData | null;
302
+ /** For 'done' events: e.g. "Max tool rounds reached" */
303
+ warning?: string;
304
+ }
305
+
306
+ // ── Seed Options ─────────────────────────────────────────────────────────────
307
+
308
+ export interface SeedOptions {
309
+ promptKey?: string;
310
+ answerKey?: string;
311
+ contextKey?: string;
312
+ explanationKey?: string;
313
+ systemPromptKey?: string;
314
+ }
315
+
316
+ // ── Class Declarations ───────────────────────────────────────────────────────
317
+
318
+ export declare class BaseGemini {
319
+ constructor(options?: BaseGeminiOptions);
169
320
 
170
- // Properties
171
321
  modelName: string;
172
- promptKey: string;
173
- answerKey: string;
174
- contextKey: string;
175
- explanationKey: string;
176
- systemInstructionKey: string;
177
- maxRetries: number;
178
- retryDelay: number;
179
- systemInstructions: string | null | false;
322
+ systemPrompt: string | null | false;
180
323
  chatConfig: ChatConfig;
181
- apiKey: string;
182
- onlyJSON: boolean;
183
- asyncValidator: AsyncValidatorFunction | null;
184
324
  genAIClient: any;
185
- chat: any;
186
- logLevel: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'none';
187
- enableGrounding: boolean;
188
- groundingConfig: Record<string, any>;
189
- labels: Record<string, string>;
190
- vertexai: boolean;
191
- /** Metadata from the last API response (model version, token counts, etc.) */
325
+ chatSession: any;
192
326
  lastResponseMetadata: ResponseMetadata | null;
193
- /** Number of history items that are seeded examples (used by clearConversation) */
194
327
  exampleCount: number;
328
+ labels: Record<string, string>;
329
+ vertexai: boolean;
195
330
 
196
- // Methods
197
331
  init(force?: boolean): Promise<void>;
198
- seed(examples?: TransformationExample[]): Promise<any>;
199
- /**
200
- * Send a message to the model.
201
- * @param payload - The payload to transform
202
- * @param opts - Options including { stateless: true } to send without affecting history
203
- * @param validatorFn - Optional validator function
204
- */
205
- message(payload: Record<string, unknown>, opts?: MessageOptions, validatorFn?: AsyncValidatorFunction | null): Promise<Record<string, unknown>>;
206
- rawMessage(sourcePayload: Record<string, unknown> | string, messageOptions?: { labels?: Record<string, string> }): Promise<Record<string, unknown> | any>;
207
- transformWithValidation(sourcePayload: Record<string, unknown>, options?: MessageOptions, validatorFn?: AsyncValidatorFunction | null): Promise<Record<string, unknown>>;
208
- messageAndValidate(sourcePayload: Record<string, unknown>, options?: MessageOptions, validatorFn?: AsyncValidatorFunction | null): Promise<Record<string, unknown>>;
209
- rebuild(lastPayload: Record<string, unknown>, serverError: string): Promise<Record<string, unknown>>;
210
- reset(): Promise<void>;
211
- getHistory(): Array<any>;
212
- /**
213
- * Estimate INPUT tokens only for a payload before sending.
214
- * NOTE: Output tokens cannot be predicted before the API call.
215
- * Use getLastUsage() after message() to see actual consumption.
216
- */
332
+ seed(examples?: TransformationExample[], opts?: SeedOptions): Promise<any[]>;
333
+ getHistory(curated?: boolean): any[];
334
+ clearHistory(): Promise<void>;
335
+ getLastUsage(): UsageData | null;
217
336
  estimate(nextPayload: Record<string, unknown> | string): Promise<{ inputTokens: number }>;
218
- updateSystemInstructions(newInstructions: string): Promise<void>;
219
- /**
220
- * Estimates the INPUT cost of sending a payload.
221
- * NOTE: Output cost depends on response length and cannot be predicted.
222
- */
223
337
  estimateCost(nextPayload: Record<string, unknown> | string): Promise<{
224
338
  inputTokens: number;
225
339
  model: string;
@@ -227,76 +341,86 @@ export declare class AITransformer {
227
341
  estimatedInputCost: number;
228
342
  note: string;
229
343
  }>;
230
- /** Clears conversation history while preserving seeded examples */
231
- clearConversation(): Promise<void>;
232
- /**
233
- * Returns structured usage data from the last API response for billing verification.
234
- * Returns null if no API call has been made yet.
235
- */
236
- getLastUsage(): UsageData | null;
237
344
  }
238
345
 
239
- // --- AIAgent Types ---
346
+ export declare class Transformer extends BaseGemini {
347
+ constructor(options?: TransformerOptions);
240
348
 
241
- export interface AIAgentOptions {
242
- // Authentication (same as AITransformer)
243
- apiKey?: string;
244
- vertexai?: boolean;
245
- project?: string;
246
- location?: string;
247
- googleAuthOptions?: GoogleAuthOptions;
349
+ promptKey: string;
350
+ answerKey: string;
351
+ contextKey: string;
352
+ explanationKey: string;
353
+ onlyJSON: boolean;
354
+ asyncValidator: AsyncValidatorFunction | null;
355
+ maxRetries: number;
356
+ retryDelay: number;
357
+ enableGrounding: boolean;
248
358
 
249
- // Agent configuration
250
- systemPrompt?: string; // System prompt for the agent
251
- modelName?: string; // Gemini model to use (default: 'gemini-2.5-flash')
252
- maxToolRounds?: number; // Max tool-use loop iterations (default: 10)
253
- httpTimeout?: number; // Timeout for HTTP tool requests in ms (default: 30000)
254
- maxRetries?: number; // Retries on transient API errors (default: 3)
255
- logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'none';
256
- labels?: Record<string, string>; // Billing labels (Vertex AI)
257
- thinkingConfig?: ThinkingConfig;
258
- chatConfig?: Partial<ChatConfig>;
359
+ seed(examples?: TransformationExample[]): Promise<any[]>;
360
+ send(payload: Record<string, unknown> | string, opts?: SendOptions, validatorFn?: AsyncValidatorFunction | null): Promise<Record<string, unknown>>;
361
+ rawSend(payload: Record<string, unknown> | string, messageOptions?: { labels?: Record<string, string> }): Promise<Record<string, unknown>>;
362
+ rebuild(lastPayload: Record<string, unknown>, serverError: string): Promise<Record<string, unknown>>;
363
+ reset(): Promise<void>;
364
+ updateSystemPrompt(newPrompt: string): Promise<void>;
365
+ }
259
366
 
260
- // Callbacks
261
- onToolCall?: (toolName: string, args: Record<string, any>) => void;
262
- onMarkdown?: (filename: string, content: string) => void;
367
+ export declare class Chat extends BaseGemini {
368
+ constructor(options?: ChatOptions);
369
+
370
+ send(message: string, opts?: { labels?: Record<string, string> }): Promise<ChatResponse>;
263
371
  }
264
372
 
265
- export interface AgentResponse {
266
- text: string; // The agent's final text response
267
- toolCalls: Array<{ name: string; args: Record<string, any>; result: any }>; // All tool calls made
268
- markdownFiles: Array<{ filename: string; content: string }>; // Generated markdown documents
269
- usage: UsageData | null; // Token usage data
373
+ export declare class Message extends BaseGemini {
374
+ constructor(options?: MessageOptions);
375
+
376
+ init(force?: boolean): Promise<void>;
377
+ send(payload: Record<string, unknown> | string, opts?: { labels?: Record<string, string> }): Promise<MessageResponse>;
270
378
  }
271
379
 
272
- export interface AgentStreamEvent {
273
- type: 'text' | 'tool_call' | 'tool_result' | 'markdown' | 'done';
274
- text?: string; // For 'text' events: the text chunk
275
- toolName?: string; // For 'tool_call' and 'tool_result' events
276
- args?: Record<string, any>; // For 'tool_call' events: the tool arguments
277
- result?: any; // For 'tool_result' events: the tool result
278
- filename?: string; // For 'markdown' events: the suggested filename
279
- content?: string; // For 'markdown' events: the markdown content
280
- fullText?: string; // For 'done' events: the complete accumulated text
281
- usage?: UsageData | null; // For 'done' events: token usage
282
- markdownFiles?: Array<{ filename: string; content: string }>; // For 'done' events
283
- warning?: string; // For 'done' events: e.g. "Max tool rounds reached"
380
+ export declare class ToolAgent extends BaseGemini {
381
+ constructor(options?: ToolAgentOptions);
382
+
383
+ tools: ToolDeclaration[];
384
+ toolExecutor: ((toolName: string, args: Record<string, any>) => Promise<any>) | null;
385
+ maxToolRounds: number;
386
+ onToolCall: ((toolName: string, args: Record<string, any>) => void) | null;
387
+ onBeforeExecution: ((toolName: string, args: Record<string, any>) => Promise<boolean>) | null;
388
+
389
+ chat(message: string, opts?: { labels?: Record<string, string> }): Promise<AgentResponse>;
390
+ stream(message: string, opts?: { labels?: Record<string, string> }): AsyncGenerator<AgentStreamEvent, void, unknown>;
391
+ /** Stop the agent before the next tool execution round */
392
+ stop(): void;
284
393
  }
285
394
 
286
- export declare class AIAgent {
287
- constructor(options?: AIAgentOptions);
395
+ export declare class CodeAgent extends BaseGemini {
396
+ constructor(options?: CodeAgentOptions);
288
397
 
289
- modelName: string;
290
- systemPrompt: string;
291
- lastResponseMetadata: ResponseMetadata | null;
398
+ workingDirectory: string;
399
+ maxRounds: number;
400
+ timeout: number;
401
+ onBeforeExecution: ((code: string) => Promise<boolean>) | null;
402
+ onCodeExecution: ((code: string, output: { stdout: string; stderr: string; exitCode: number }) => void) | null;
292
403
 
293
- init(): Promise<void>;
294
- chat(message: string): Promise<AgentResponse>;
295
- stream(message: string): AsyncGenerator<AgentStreamEvent, void, unknown>;
296
- clearHistory(): Promise<void>;
297
- getHistory(curated?: boolean): any[];
298
- getLastUsage(): UsageData | null;
404
+ init(force?: boolean): Promise<void>;
405
+ chat(message: string, opts?: { labels?: Record<string, string> }): Promise<CodeAgentResponse>;
406
+ stream(message: string, opts?: { labels?: Record<string, string> }): AsyncGenerator<CodeAgentStreamEvent, void, unknown>;
407
+ /** Returns all code scripts written across all chat/stream calls. */
408
+ dump(): Array<{ fileName: string; script: string }>;
409
+ /** Stop the agent before the next code execution. Kills any running child process. */
410
+ stop(): void;
299
411
  }
300
412
 
301
- // Default export
302
- export default AITransformer;
413
+ // ── Module Exports ───────────────────────────────────────────────────────────
414
+
415
+ export declare function extractJSON(text: string): any;
416
+ export declare function attemptJSONRecovery(text: string, maxAttempts?: number): any | null;
417
+
418
+ declare const _default: {
419
+ Transformer: typeof Transformer;
420
+ Chat: typeof Chat;
421
+ Message: typeof Message;
422
+ ToolAgent: typeof ToolAgent;
423
+ CodeAgent: typeof CodeAgent;
424
+ };
425
+
426
+ export default _default;