import { GoogleGenAI, type GoogleGenAIOptions } from '@google/genai'; import { AIProviderConfig } from '../config/schema'; import { AIClient, GeminiSessionOptions, GenerateContentOptions, ModernAIClient, StreamChunk, StructuredOutputOptions, ThinkingConfig, } from './types'; import { GeminiSession, normalizeTools, parseGeminiChunk } from './gemini-session'; export { normalizeTools }; const OPTION_KEYS = ['schema', 'validator', 'model', 'temperature', 'systemInstruction'] as const; function resolveApiKey(config: AIProviderConfig): string | undefined { return ( config.password || process.env.GEMINI_API_KEY || process.env.GOOGLE_GENAI_API_KEY || process.env.GOOGLE_API_KEY ); } function buildClientOptions( apiKey: string, baseUrl?: string, customHeaders?: Record ): GoogleGenAIOptions { const options: GoogleGenAIOptions = { apiKey }; if (baseUrl || customHeaders) { options.httpOptions = { baseUrl, headers: customHeaders }; } return options; } function readCandidateParts(response: any): any[] { const candidates = response.candidates; if (!Array.isArray(candidates) || !candidates.length) return []; const content = candidates[0].content; return Array.isArray(content?.parts) ? content.parts : []; } function collectResponseText(response: any): string { return readCandidateParts(response) .filter((part: any) => !part.thought && Boolean(part.text)) .map((part: any) => part.text) .join(''); } function extractText(response: any): string { if (response.text !== undefined && response.text !== null) { return response.text; } return collectResponseText(response); } function isStructuredOptions(input: unknown): input is StructuredOutputOptions { if (input === null || typeof input !== 'object') return false; return OPTION_KEYS.some((key) => Object.hasOwn(input, key)); } function parseJsonPayload(rawText: string): unknown { if (!rawText.trim()) { throw new Error('Google GenAI returned empty response for structured output request'); } try { return JSON.parse(rawText); } catch (err: any) { throw new Error(`Failed to parse structured JSON output from Gemini: ${err.message}. Response was: ${rawText}`); } } function validateParsedOutput(parsed: unknown, validator: StructuredOutputOptions['validator']): T { if (!validator) return parsed as T; if (typeof (validator as any).parse === 'function') { return (validator as any).parse(parsed); } return (validator as (data: unknown) => T)(parsed); } function emitChunkCallbacks( delta: ReturnType, options: GenerateContentOptions ): void { const { onText, onThought, onFunctionCall } = options; if (onText) delta.textParts.forEach((text) => onText(text)); if (onThought) delta.thoughts.forEach((thought) => onThought(thought)); if (onFunctionCall) delta.calls.forEach((call) => onFunctionCall(call)); } export class GoogleGenAIClient implements ModernAIClient, AIClient { readonly name = 'google-genai'; private client?: any; private apiKey = ''; private model = 'gemini-2.0-flash'; private temperature = 0.7; private topP?: number; private topK?: number; private maxOutputTokens?: number; private baseUrl?: string; private customHeaders?: Record; private thinkingConfig?: ThinkingConfig; constructor(clientInstance?: any) { if (clientInstance) { this.client = clientInstance; } } setClient(client: any): void { this.client = client; } private requireClient(): any { if (!this.client) { throw new Error('GoogleGenAIClient is not configured. Call configure() before use.'); } return this.client; } async configure(config: AIProviderConfig): Promise { const key = resolveApiKey(config); if (!key && !this.client) { throw new Error('API key is required for Google GenAI provider (password field in AIProviderConfig)'); } this.apiKey = key ?? ''; this.model = config.model || 'gemini-2.0-flash'; this.temperature = config.temperature ?? 0.7; this.topP = config.topP; this.topK = config.topK; this.maxOutputTokens = config.maxTokens; this.baseUrl = config.baseUrl ? config.baseUrl.replace(/\/+$/, '') : undefined; this.customHeaders = config.customHeaders; if (!this.client) { this.client = new GoogleGenAI(buildClientOptions(this.apiKey, this.baseUrl, this.customHeaders)); } } async getCompletion(prompt: string): Promise { const client = this.requireClient(); const response = await client.models.generateContent({ model: this.model, contents: prompt, config: { temperature: this.temperature, topP: this.topP, topK: this.topK, maxOutputTokens: this.maxOutputTokens, }, }); return extractText(response); } private buildStreamRequest(promptOrParts: string | any[], options: GenerateContentOptions) { const contents = typeof promptOrParts === 'string' ? [{ role: 'user', parts: [{ text: promptOrParts }] }] : promptOrParts; return { model: options.model ?? this.model, contents, config: { temperature: options.temperature ?? this.temperature, topP: options.topP ?? this.topP, topK: options.topK ?? this.topK, maxOutputTokens: options.maxOutputTokens ?? this.maxOutputTokens, systemInstruction: options.systemInstruction, thinkingConfig: options.thinkingConfig ?? this.thinkingConfig, tools: normalizeTools(options.tools), responseMimeType: options.responseMimeType, responseSchema: options.responseSchema, abortSignal: options.abortSignal, }, }; } async *generateContentStream( promptOrParts: string | any[], options?: GenerateContentOptions ): AsyncIterable { const client = this.requireClient(); const opts = options ?? {}; const stream = await client.models.generateContentStream(this.buildStreamRequest(promptOrParts, opts)); for await (const chunk of stream) { const delta = parseGeminiChunk(chunk); emitChunkCallbacks(delta, opts); yield delta.event; } } createSession(options?: GeminiSessionOptions): GeminiSession { const client = this.requireClient(); const opts = options ?? {}; return new GeminiSession(client, { model: opts.model ?? this.model, temperature: opts.temperature ?? this.temperature, thinkingConfig: opts.thinkingConfig ?? this.thinkingConfig, ...opts, }); } async getStructuredOutput( prompt: string, schemaOrOptions: unknown | StructuredOutputOptions ): Promise { const client = this.requireClient(); const options: StructuredOutputOptions = isStructuredOptions(schemaOrOptions) ? schemaOrOptions : { schema: schemaOrOptions }; const response = await client.models.generateContent({ model: options.model ?? this.model, contents: prompt, config: { temperature: options.temperature ?? 0.1, systemInstruction: options.systemInstruction, responseMimeType: 'application/json', responseSchema: options.schema, }, }); const parsed = parseJsonPayload(extractText(response)); return validateParsedOutput(parsed, options.validator); } async close(): Promise { this.client = undefined; } }