universal-llm-client 4.3.0 → 4.5.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.
Files changed (151) hide show
  1. package/CHANGELOG.md +27 -24
  2. package/README.md +60 -11
  3. package/dist/ai-model.d.ts +12 -1
  4. package/dist/ai-model.d.ts.map +1 -1
  5. package/dist/ai-model.js +36 -1
  6. package/dist/ai-model.js.map +1 -1
  7. package/dist/auditor.js.map +1 -1
  8. package/dist/client.js.map +1 -1
  9. package/dist/gemma-channel.d.ts +14 -0
  10. package/dist/gemma-channel.d.ts.map +1 -0
  11. package/dist/gemma-channel.js +38 -0
  12. package/dist/gemma-channel.js.map +1 -0
  13. package/dist/gemma-diffusion.d.ts +49 -0
  14. package/dist/gemma-diffusion.d.ts.map +1 -0
  15. package/dist/gemma-diffusion.js +147 -0
  16. package/dist/gemma-diffusion.js.map +1 -0
  17. package/dist/http.d.ts +4 -0
  18. package/dist/http.d.ts.map +1 -1
  19. package/dist/http.js +14 -1
  20. package/dist/http.js.map +1 -1
  21. package/dist/index.d.ts +2 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +4 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/interfaces.d.ts +163 -7
  26. package/dist/interfaces.d.ts.map +1 -1
  27. package/dist/interfaces.js.map +1 -1
  28. package/dist/mcp.js.map +1 -1
  29. package/dist/providers/anthropic.d.ts.map +1 -1
  30. package/dist/providers/anthropic.js +28 -3
  31. package/dist/providers/anthropic.js.map +1 -1
  32. package/dist/providers/google.d.ts +22 -1
  33. package/dist/providers/google.d.ts.map +1 -1
  34. package/dist/providers/google.js +223 -13
  35. package/dist/providers/google.js.map +1 -1
  36. package/dist/providers/index.js.map +1 -1
  37. package/dist/providers/ollama.d.ts +2 -0
  38. package/dist/providers/ollama.d.ts.map +1 -1
  39. package/dist/providers/ollama.js +59 -30
  40. package/dist/providers/ollama.js.map +1 -1
  41. package/dist/providers/openai.d.ts +14 -0
  42. package/dist/providers/openai.d.ts.map +1 -1
  43. package/dist/providers/openai.js +200 -22
  44. package/dist/providers/openai.js.map +1 -1
  45. package/dist/router.d.ts +2 -0
  46. package/dist/router.d.ts.map +1 -1
  47. package/dist/router.js +4 -0
  48. package/dist/router.js.map +1 -1
  49. package/dist/stream-decoder.d.ts +12 -0
  50. package/dist/stream-decoder.d.ts.map +1 -1
  51. package/dist/stream-decoder.js +182 -5
  52. package/dist/stream-decoder.js.map +1 -1
  53. package/dist/structured-output.js.map +1 -1
  54. package/dist/thinking.d.ts +36 -0
  55. package/dist/thinking.d.ts.map +1 -0
  56. package/dist/thinking.js +52 -0
  57. package/dist/thinking.js.map +1 -0
  58. package/dist/tools.js.map +1 -1
  59. package/dist/zod-adapter.js.map +1 -1
  60. package/package.json +4 -1
  61. package/src/ai-model.ts +400 -0
  62. package/src/auditor.ts +213 -0
  63. package/src/client.ts +402 -0
  64. package/src/debug/debug-google-streaming.ts +97 -0
  65. package/src/debug/debug-tool-execution.ts +86 -0
  66. package/src/debug/test-lmstudio-tools.ts +155 -0
  67. package/src/demos/README.md +47 -0
  68. package/src/demos/basic/universal-llm-examples.ts +161 -0
  69. package/src/demos/diffusion-gemma/.env +29 -0
  70. package/src/demos/diffusion-gemma/.env.example +27 -0
  71. package/src/demos/diffusion-gemma/CLAUDE.md +95 -0
  72. package/src/demos/diffusion-gemma/README.md +59 -0
  73. package/src/demos/diffusion-gemma/canvas.ts +1606 -0
  74. package/src/demos/diffusion-gemma/docker-compose.yml +29 -0
  75. package/src/demos/diffusion-gemma/probe-stream.ts +51 -0
  76. package/src/demos/diffusion-gemma/probe-tools.ts +55 -0
  77. package/src/demos/diffusion-gemma/server.ts +1205 -0
  78. package/src/demos/diffusion-gemma/start-vllm.sh +98 -0
  79. package/src/demos/mcp/astrid-memory-demo.ts +295 -0
  80. package/src/demos/mcp/astrid-persona-memory.ts +357 -0
  81. package/src/demos/mcp/mcp-mongodb-demo.ts +275 -0
  82. package/src/demos/mcp/simple-astrid-memory.ts +148 -0
  83. package/src/demos/mcp/simple-mcp-demo.ts +68 -0
  84. package/src/demos/mcp/working-mcp-demo.ts +62 -0
  85. package/src/demos/model-alias-demo.ts +0 -0
  86. package/src/demos/tools/RAG_MEMORY_INTEGRATION.md +267 -0
  87. package/src/demos/tools/astrid-memory-demo.ts +270 -0
  88. package/src/demos/tools/astrid-production-memory-clean.ts +785 -0
  89. package/src/demos/tools/astrid-production-memory.ts +558 -0
  90. package/src/demos/tools/basic-translation-test.ts +66 -0
  91. package/src/demos/tools/chromadb-similarity-tuning.ts +390 -0
  92. package/src/demos/tools/clean-multilingual-conversation.ts +209 -0
  93. package/src/demos/tools/clean-translation-test.ts +119 -0
  94. package/src/demos/tools/clean-universal-multilingual-test.ts +131 -0
  95. package/src/demos/tools/complete-rag-demo.ts +369 -0
  96. package/src/demos/tools/complete-tool-demo.ts +132 -0
  97. package/src/demos/tools/demo-tool-calling.ts +124 -0
  98. package/src/demos/tools/dynamic-language-switching-test.ts +251 -0
  99. package/src/demos/tools/hybrid-thinking-test.ts +154 -0
  100. package/src/demos/tools/memory-integration-test.ts +420 -0
  101. package/src/demos/tools/multilingual-memory-system.ts +802 -0
  102. package/src/demos/tools/ondemand-translation-demo.ts +655 -0
  103. package/src/demos/tools/production-tool-demo.ts +245 -0
  104. package/src/demos/tools/revolutionary-multilingual-test.ts +151 -0
  105. package/src/demos/tools/rigorous-language-analysis.ts +218 -0
  106. package/src/demos/tools/test-universal-memory-system.ts +126 -0
  107. package/src/demos/tools/translation-integration-guide.ts +346 -0
  108. package/src/demos/tools/universal-memory-system.ts +560 -0
  109. package/src/gemma-channel.ts +47 -0
  110. package/src/gemma-diffusion.ts +167 -0
  111. package/src/http.ts +261 -0
  112. package/src/index.ts +180 -0
  113. package/src/interfaces.ts +843 -0
  114. package/src/mcp.ts +345 -0
  115. package/src/providers/anthropic.ts +796 -0
  116. package/src/providers/google.ts +840 -0
  117. package/src/providers/index.ts +8 -0
  118. package/src/providers/ollama.ts +503 -0
  119. package/src/providers/openai.ts +587 -0
  120. package/src/router.ts +785 -0
  121. package/src/stream-decoder.ts +535 -0
  122. package/src/structured-output.ts +759 -0
  123. package/src/test-scripts/test-advanced-tools.ts +310 -0
  124. package/src/test-scripts/test-google-deep-research.ts +33 -0
  125. package/src/test-scripts/test-google-streaming-enhanced.ts +147 -0
  126. package/src/test-scripts/test-google-streaming.ts +63 -0
  127. package/src/test-scripts/test-google-system-prompt-comprehensive.ts +189 -0
  128. package/src/test-scripts/test-google-thinking.ts +46 -0
  129. package/src/test-scripts/test-mcp-config.ts +28 -0
  130. package/src/test-scripts/test-mcp-connection.ts +29 -0
  131. package/src/test-scripts/test-system-message-positions.ts +163 -0
  132. package/src/test-scripts/test-system-prompt-improvement-demo.ts +83 -0
  133. package/src/test-scripts/test-tool-calling.ts +231 -0
  134. package/src/test-scripts/test-vllm-qwen36.ts +256 -0
  135. package/src/tests/ai-model.test.ts +1614 -0
  136. package/src/tests/auditor.test.ts +224 -0
  137. package/src/tests/gemma-diffusion.test.ts +115 -0
  138. package/src/tests/http.test.ts +200 -0
  139. package/src/tests/interfaces.test.ts +117 -0
  140. package/src/tests/providers/anthropic.test.ts +118 -0
  141. package/src/tests/providers/google.test.ts +841 -0
  142. package/src/tests/providers/ollama.test.ts +1034 -0
  143. package/src/tests/providers/openai.test.ts +1511 -0
  144. package/src/tests/router.test.ts +254 -0
  145. package/src/tests/stream-decoder.test.ts +263 -0
  146. package/src/tests/structured-output.test.ts +1450 -0
  147. package/src/tests/thinking.test.ts +65 -0
  148. package/src/tests/tools.test.ts +175 -0
  149. package/src/thinking.ts +73 -0
  150. package/src/tools.ts +246 -0
  151. package/src/zod-adapter.ts +72 -0
@@ -0,0 +1,840 @@
1
+ /**
2
+ * Universal LLM Client v3 — Google Provider
3
+ *
4
+ * Implements BaseLLMClient for Google AI Studio and Vertex AI.
5
+ * Supports Gemini and Gemma models with full tool calling,
6
+ * streaming, embeddings, and system prompt handling.
7
+ */
8
+
9
+ import { BaseLLMClient } from '../client.js';
10
+ import { resolveThinking, geminiThinkingBudget } from '../thinking.js';
11
+ import { httpRequest, httpStream, parseSSE, type HttpRequestOptions } from '../http.js';
12
+ import { StandardChatDecoder } from '../stream-decoder.js';
13
+ import {
14
+ normalizeJsonSchema,
15
+ stripUnsupportedFeatures,
16
+ getJsonSchemaFromConfig,
17
+ type JSONSchema,
18
+ } from '../structured-output.js';
19
+ import type {
20
+ LLMClientOptions,
21
+ LLMChatMessage,
22
+ LLMChatResponse,
23
+ ChatOptions,
24
+ LLMToolDefinition,
25
+ LLMToolCall,
26
+ LLMContentPart,
27
+ LLMTextContent,
28
+ GooglePart,
29
+ GoogleContent,
30
+ GoogleRequest,
31
+ GoogleResponse,
32
+ GoogleFunctionDeclaration,
33
+ TokenUsageInfo,
34
+ AIModelApiType,
35
+ DeepResearchOptions,
36
+ DeepResearchResult,
37
+ DeepResearchStep,
38
+ DeepResearchEvent,
39
+ } from '../interfaces.js';
40
+ import type { DecodedEvent } from '../stream-decoder.js';
41
+ import type { Auditor } from '../auditor.js';
42
+
43
+ export class GoogleClient extends BaseLLMClient {
44
+ private isVertex: boolean;
45
+ private apiVersion: string;
46
+
47
+ constructor(options: LLMClientOptions, auditor?: Auditor) {
48
+ super(options, auditor);
49
+ this.isVertex = options.apiType === ('vertex' as AIModelApiType);
50
+ this.apiVersion = options.apiVersion ?? 'v1beta';
51
+ }
52
+
53
+ // ========================================================================
54
+ // URL Building
55
+ // ========================================================================
56
+
57
+ private getBaseUrl(): string {
58
+ if (this.isVertex) {
59
+ const region = this.options.region ?? 'us-central1';
60
+ return `https://${region}-aiplatform.googleapis.com/${this.apiVersion}/projects/-/locations/${region}/publishers/google/models/${this.options.model}`;
61
+ }
62
+ if (this.options.url) return this.options.url.replace(/\/+$/, '');
63
+ return `https://generativelanguage.googleapis.com/${this.apiVersion}/models/${this.options.model}`;
64
+ }
65
+
66
+ private getChatUrl(): string {
67
+ const base = this.getBaseUrl();
68
+ if (this.isVertex) {
69
+ return `${base}:generateContent`;
70
+ }
71
+ return `${base}:generateContent?key=${this.options.apiKey}`;
72
+ }
73
+
74
+ private getStreamUrl(): string {
75
+ const base = this.getBaseUrl();
76
+ if (this.isVertex) {
77
+ return `${base}:streamGenerateContent?alt=sse`;
78
+ }
79
+ return `${base}:streamGenerateContent?alt=sse&key=${this.options.apiKey}`;
80
+ }
81
+
82
+ private getEmbedUrl(): string {
83
+ if (this.isVertex) {
84
+ const region = this.options.region ?? 'us-central1';
85
+ return `https://${region}-aiplatform.googleapis.com/${this.apiVersion}/projects/-/locations/${region}/publishers/google/models/${this.options.model}:embedContent`;
86
+ }
87
+ return `https://generativelanguage.googleapis.com/${this.apiVersion}/models/${this.options.model}:embedContent?key=${this.options.apiKey}`;
88
+ }
89
+
90
+ private getHeaders(): Record<string, string> {
91
+ const headers: Record<string, string> = {
92
+ 'Content-Type': 'application/json',
93
+ };
94
+ if (this.isVertex && this.options.apiKey) {
95
+ headers['Authorization'] = `Bearer ${this.options.apiKey}`;
96
+ }
97
+ return headers;
98
+ }
99
+
100
+ // ========================================================================
101
+ // Chat
102
+ // ========================================================================
103
+
104
+ async chat(
105
+ messages: LLMChatMessage[],
106
+ options?: ChatOptions,
107
+ ): Promise<LLMChatResponse> {
108
+ // Structured output and tools can now be used together.\n // The provider sends both responseSchema and tools in the request.\n // The Router handles skipping validation when the response contains tool calls.
109
+
110
+ const url = this.getChatUrl();
111
+ const body = this.buildRequestBody(messages, options);
112
+
113
+ // Flex tier: increase timeout (Google recommends 600s+) and use retry logic
114
+ const tier = options?.serviceTier;
115
+ const effectiveTimeout = tier === 'flex'
116
+ ? Math.max(this.options.timeout ?? 60000, 600_000)
117
+ : (this.options.timeout ?? 60000);
118
+
119
+ const start = Date.now();
120
+ this.auditor.record({
121
+ timestamp: start,
122
+ type: 'request',
123
+ provider: this.isVertex ? 'vertex' : 'google',
124
+ model: this.options.model,
125
+ });
126
+
127
+ const reqOptions = {
128
+ method: 'POST' as const,
129
+ headers: this.getHeaders(),
130
+ body,
131
+ timeout: effectiveTimeout,
132
+ };
133
+
134
+ const response = tier === 'flex'
135
+ ? await this.fetchWithFlexRetry<GoogleResponse>(url, reqOptions)
136
+ : await httpRequest<GoogleResponse>(url, reqOptions);
137
+
138
+ const result = this.parseGoogleResponse(response.data);
139
+
140
+ // Surface the tier that actually served the request
141
+ const resolvedTier = response.headers?.get('x-gemini-service-tier');
142
+ if (resolvedTier) {
143
+ result.serviceTier = resolvedTier.toLowerCase() as 'flex' | 'priority' | 'standard';
144
+ }
145
+
146
+ this.auditor.record({
147
+ timestamp: Date.now(),
148
+ type: 'response',
149
+ provider: this.isVertex ? 'vertex' : 'google',
150
+ model: this.options.model,
151
+ duration: Date.now() - start,
152
+ usage: result.usage,
153
+ });
154
+
155
+ return result;
156
+ }
157
+
158
+ // ========================================================================
159
+ // Streaming
160
+ // ========================================================================
161
+
162
+ async *chatStream(
163
+ messages: LLMChatMessage[],
164
+ options?: ChatOptions,
165
+ ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {
166
+ const url = this.getStreamUrl();
167
+ const body = this.buildRequestBody(messages, options);
168
+
169
+ // Flex tier: increase timeout (Google recommends 600s+)
170
+ const tier = options?.serviceTier;
171
+ const effectiveTimeout = tier === 'flex'
172
+ ? Math.max(this.options.timeout ?? 120000, 600_000)
173
+ : (this.options.timeout ?? 120000);
174
+
175
+ const start = Date.now();
176
+ this.auditor.record({
177
+ timestamp: start,
178
+ type: 'stream_start',
179
+ provider: this.isVertex ? 'vertex' : 'google',
180
+ model: this.options.model,
181
+ });
182
+
183
+ const decoder = new StandardChatDecoder(() => {});
184
+ let usage: TokenUsageInfo | undefined;
185
+ const allToolCalls: LLMToolCall[] = [];
186
+
187
+ const stream = httpStream(url, {
188
+ method: 'POST',
189
+ headers: this.getHeaders(),
190
+ body,
191
+ timeout: effectiveTimeout,
192
+ });
193
+
194
+ // Google streams SSE with JSON payloads
195
+ let buffer = '';
196
+ let reasoningBuffer = '';
197
+ for await (const chunk of stream) {
198
+ buffer += chunk;
199
+
200
+ // Google SSE uses "data: " prefix
201
+ const lines = buffer.split('\n');
202
+ buffer = lines.pop() ?? '';
203
+
204
+ for (const line of lines) {
205
+ if (!line.startsWith('data: ')) continue;
206
+ const jsonStr = line.slice(6).trim();
207
+ if (!jsonStr || jsonStr === '[DONE]') continue;
208
+
209
+ try {
210
+ const data = JSON.parse(jsonStr) as GoogleResponse;
211
+
212
+ if (data.usageMetadata) {
213
+ usage = {
214
+ inputTokens: data.usageMetadata.promptTokenCount ?? 0,
215
+ outputTokens: data.usageMetadata.candidatesTokenCount ?? 0,
216
+ totalTokens: data.usageMetadata.totalTokenCount ?? 0,
217
+ cachedTokens: data.usageMetadata.cachedContentTokenCount,
218
+ reasoningTokens: data.usageMetadata.thoughtsTokenCount,
219
+ };
220
+ }
221
+
222
+ const candidate = data.candidates?.[0];
223
+ if (!candidate?.content?.parts) continue;
224
+
225
+ for (const part of candidate.content.parts) {
226
+ if (part.text) {
227
+ if (part.thought) {
228
+ reasoningBuffer += part.text;
229
+ yield { type: 'thinking', content: part.text };
230
+ } else {
231
+ decoder.push(part.text);
232
+ yield { type: 'text', content: part.text };
233
+ }
234
+ }
235
+ if (part.functionCall) {
236
+ const toolCall = this.convertFunctionCallToToolCall(
237
+ part.functionCall,
238
+ part.thoughtSignature,
239
+ );
240
+ allToolCalls.push(toolCall);
241
+ yield { type: 'tool_call', calls: [toolCall] };
242
+ }
243
+ }
244
+ } catch {
245
+ // Skip unparseable JSON
246
+ }
247
+ }
248
+ }
249
+
250
+ decoder.flush();
251
+
252
+ this.auditor.record({
253
+ timestamp: Date.now(),
254
+ type: 'stream_end',
255
+ provider: this.isVertex ? 'vertex' : 'google',
256
+ model: this.options.model,
257
+ duration: Date.now() - start,
258
+ usage,
259
+ });
260
+
261
+ return {
262
+ message: {
263
+ role: 'assistant',
264
+ content: decoder.getCleanContent(),
265
+ tool_calls: allToolCalls.length > 0 ? allToolCalls : undefined,
266
+ },
267
+ reasoning: reasoningBuffer || decoder.getReasoning(),
268
+ usage,
269
+ provider: this.isVertex ? 'vertex' : 'google',
270
+ };
271
+ }
272
+
273
+ // ========================================================================
274
+ // Deep Research (Gemini interactions API)
275
+ // ========================================================================
276
+
277
+ /** Deep Research is available via Google AI Studio only (not Vertex AI). */
278
+ supportsDeepResearch(): boolean {
279
+ return !this.isVertex;
280
+ }
281
+
282
+ private interactionsBase(): string {
283
+ if (this.isVertex) {
284
+ throw new Error('Deep Research is only available via Google AI Studio, not Vertex AI.');
285
+ }
286
+ return `https://generativelanguage.googleapis.com/${this.apiVersion}/interactions`;
287
+ }
288
+
289
+ private deepResearchHeaders(): Record<string, string> {
290
+ return {
291
+ 'Content-Type': 'application/json',
292
+ 'x-goog-api-key': this.options.apiKey ?? '',
293
+ 'Api-Revision': '2026-05-20',
294
+ };
295
+ }
296
+
297
+ private buildInteractionBody(input: string, opts: DeepResearchOptions, background: boolean): Record<string, unknown> {
298
+ return {
299
+ input,
300
+ agent: opts.agent ?? 'deep-research-preview-04-2026',
301
+ background,
302
+ agent_config: {
303
+ type: 'deep-research',
304
+ thinking_summaries: opts.thinkingSummaries ?? 'auto',
305
+ },
306
+ ...(opts.tools?.length ? { tools: opts.tools.map(t => ({ type: t })) } : {}),
307
+ ...(opts.previousInteractionId ? { previous_interaction_id: opts.previousInteractionId } : {}),
308
+ };
309
+ }
310
+
311
+ private toDeepResearchResult(i: Record<string, unknown> | undefined): DeepResearchResult {
312
+ const obj = i ?? {};
313
+ const steps = obj['steps'] as DeepResearchStep[] | undefined;
314
+ let report = (obj['output_text'] ?? obj['outputText'] ?? obj['output']) as string | undefined;
315
+ // Some responses carry the final report only inside the steps' content
316
+ // blocks (the last step is typically the answer) — concatenate text there.
317
+ if (!report && Array.isArray(steps)) {
318
+ const text = steps
319
+ .flatMap(s => (Array.isArray(s.content) ? s.content : []))
320
+ .map(c => (c && typeof c === 'object' && typeof (c as { text?: unknown }).text === 'string'
321
+ ? (c as { text: string }).text
322
+ : ''))
323
+ .filter(Boolean)
324
+ .join('\n\n');
325
+ report = text || undefined;
326
+ }
327
+ return {
328
+ id: (obj['id'] as string) ?? '',
329
+ status: (obj['status'] as string) ?? 'in_progress',
330
+ report,
331
+ steps,
332
+ error: obj['error'],
333
+ raw: obj,
334
+ };
335
+ }
336
+
337
+ /** httpRequest with small backoff retries — the preview interactions API is flaky (503s). */
338
+ private async drRequest(
339
+ url: string,
340
+ init: HttpRequestOptions,
341
+ retries = 3,
342
+ ): Promise<Record<string, unknown>> {
343
+ let lastErr: unknown;
344
+ for (let attempt = 0; attempt <= retries; attempt++) {
345
+ try {
346
+ const res = await httpRequest<Record<string, unknown>>(url, init);
347
+ return res.data;
348
+ } catch (e) {
349
+ lastErr = e;
350
+ if (attempt < retries) await this.delay(1500 * (attempt + 1), init.signal);
351
+ }
352
+ }
353
+ throw lastErr;
354
+ }
355
+
356
+ /**
357
+ * Run an agentic Deep Research interaction: create it, then poll until it
358
+ * completes/fails or the timeout elapses. Returns the final report + steps.
359
+ */
360
+ async deepResearch(input: string, opts: DeepResearchOptions = {}): Promise<DeepResearchResult> {
361
+ const base = this.interactionsBase();
362
+ const headers = this.deepResearchHeaders();
363
+ const pollInterval = opts.pollIntervalMs ?? 5000;
364
+ const deadline = Date.now() + (opts.timeoutMs ?? 600_000);
365
+
366
+ let interaction = await this.drRequest(base, {
367
+ method: 'POST',
368
+ headers,
369
+ body: this.buildInteractionBody(input, opts, true),
370
+ timeout: this.options.timeout ?? 60_000,
371
+ signal: opts.signal,
372
+ });
373
+ const id = interaction?.['id'] as string;
374
+ if (!id) return this.toDeepResearchResult(interaction);
375
+
376
+ while ((interaction?.['status'] ?? 'in_progress') === 'in_progress') {
377
+ if (Date.now() > deadline) break;
378
+ await this.delay(pollInterval, opts.signal);
379
+ try {
380
+ interaction = await this.drRequest(
381
+ `${base}/${id}`,
382
+ { method: 'GET', headers, timeout: this.options.timeout ?? 60_000, signal: opts.signal },
383
+ 2,
384
+ );
385
+ } catch {
386
+ // Tolerate transient errors during a long poll; keep trying until the deadline.
387
+ }
388
+ }
389
+ return this.toDeepResearchResult(interaction);
390
+ }
391
+
392
+ /**
393
+ * Stream a Deep Research interaction's intermediate updates (`step.delta`
394
+ * thought/text/image events) and return the final result. Best-effort:
395
+ * falls back to the created interaction object if the stream ends early.
396
+ */
397
+ async *deepResearchStream(
398
+ input: string,
399
+ opts: DeepResearchOptions = {},
400
+ ): AsyncGenerator<DeepResearchEvent, DeepResearchResult, unknown> {
401
+ const base = this.interactionsBase();
402
+ const headers = this.deepResearchHeaders();
403
+ // Streaming long-running research requires background:true AND stream:true
404
+ // in the create body (per the Deep Research Interactions API docs).
405
+ const stream = httpStream(base, {
406
+ method: 'POST',
407
+ headers,
408
+ body: { ...this.buildInteractionBody(input, opts, true), stream: true },
409
+ timeout: opts.timeoutMs ?? 600_000,
410
+ signal: opts.signal,
411
+ });
412
+
413
+ let last: Record<string, unknown> | undefined;
414
+ for await (const { data } of parseSSE(stream)) {
415
+ if (!data || data === '[DONE]') continue;
416
+ let parsed: Record<string, unknown>;
417
+ try { parsed = JSON.parse(data) as Record<string, unknown>; } catch { continue; }
418
+ last = parsed;
419
+ const delta = (parsed['delta'] ?? (parsed['step'] as Record<string, unknown> | undefined)?.['delta']) as
420
+ | Record<string, unknown> | undefined;
421
+ if (delta) {
422
+ const dtype = delta['type'] as string | undefined;
423
+ if (dtype === 'thought') yield { type: 'thought', content: String(delta['text'] ?? delta['content'] ?? '') };
424
+ else if (dtype === 'text') yield { type: 'text', content: String(delta['text'] ?? delta['content'] ?? '') };
425
+ else if (dtype === 'image') yield { type: 'image', content: delta['image'] ?? delta['content'] };
426
+ }
427
+ if (typeof parsed['status'] === 'string') yield { type: 'status', status: parsed['status'] as string };
428
+ }
429
+ return this.toDeepResearchResult(last);
430
+ }
431
+
432
+ private delay(ms: number, signal?: AbortSignal): Promise<void> {
433
+ return new Promise((resolve, reject) => {
434
+ if (signal?.aborted) return reject(new Error('aborted'));
435
+ const t = setTimeout(resolve, ms);
436
+ signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('aborted')); }, { once: true });
437
+ });
438
+ }
439
+
440
+ // ========================================================================
441
+ // Embeddings
442
+ // ========================================================================
443
+
444
+ async embed(text: string): Promise<number[]> {
445
+ const url = this.getEmbedUrl();
446
+ const response = await httpRequest<{
447
+ embedding: { values: number[] };
448
+ }>(url, {
449
+ method: 'POST',
450
+ headers: this.getHeaders(),
451
+ body: {
452
+ content: {
453
+ parts: [{ text }],
454
+ },
455
+ },
456
+ timeout: this.options.timeout ?? 30000,
457
+ });
458
+ return response.data.embedding.values;
459
+ }
460
+
461
+ // ========================================================================
462
+ // Model Discovery
463
+ // ========================================================================
464
+
465
+ async getModels(): Promise<string[]> {
466
+ const baseUrl = this.isVertex
467
+ ? `https://${this.options.region ?? 'us-central1'}-aiplatform.googleapis.com/${this.apiVersion}/models`
468
+ : `https://generativelanguage.googleapis.com/${this.apiVersion}/models?key=${this.options.apiKey}`;
469
+
470
+ try {
471
+ const response = await httpRequest<{
472
+ models: Array<{ name: string }>;
473
+ }>(baseUrl, {
474
+ headers: this.getHeaders(),
475
+ timeout: 10000,
476
+ });
477
+ return response.data.models.map(m =>
478
+ m.name.replace(/^models\//, ''),
479
+ );
480
+ } catch {
481
+ return [];
482
+ }
483
+ }
484
+
485
+ // ========================================================================
486
+ // Request Building
487
+ // ========================================================================
488
+
489
+ private buildRequestBody(
490
+ messages: LLMChatMessage[],
491
+ options?: ChatOptions,
492
+ ): GoogleRequest {
493
+ const isGemma = this.options.model.toLowerCase().includes('gemma');
494
+ const { systemInstruction, contents } = this.convertToGoogleMessages(messages, isGemma);
495
+
496
+ const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);
497
+
498
+ const body: GoogleRequest = {
499
+ contents,
500
+ generationConfig: this.buildGenerationConfig(options),
501
+ };
502
+
503
+ // System instruction (Gemini supports it, Gemma doesn't)
504
+ if (systemInstruction && !isGemma) {
505
+ body.systemInstruction = {
506
+ parts: [{ text: systemInstruction }],
507
+ };
508
+ }
509
+
510
+ // Tools
511
+ if (tools?.length) {
512
+ body.tools = [{
513
+ functionDeclarations: tools.map(t => this.convertToGoogleTool(t)),
514
+ }];
515
+ }
516
+
517
+ // Inference tier (Flex / Priority)
518
+ const tier = options?.serviceTier;
519
+ if (tier && tier !== 'standard') {
520
+ body.service_tier = tier.toUpperCase() as 'FLEX' | 'PRIORITY';
521
+ }
522
+
523
+ return body;
524
+ }
525
+
526
+ private buildGenerationConfig(options?: ChatOptions): Record<string, unknown> {
527
+ const config: Record<string, unknown> = {
528
+ ...this.options.defaultParameters,
529
+ ...options?.parameters,
530
+ };
531
+ if (options?.temperature !== undefined) config['temperature'] = options.temperature;
532
+ if (options?.maxTokens !== undefined) config['maxOutputTokens'] = options.maxTokens;
533
+ // Unified thinking flag → Gemini thinkingConfig. Per-call overrides model
534
+ // config. Gemini 3.x uses `thinkingLevel`; 2.5/2.0 use `thinkingBudget`
535
+ // (0 = off, -1 = dynamic). `includeThoughts` surfaces the reasoning text.
536
+ // A user-supplied thinkingConfig (via parameters) is left untouched.
537
+ const thinking = resolveThinking(options?.thinking, this.options.thinking);
538
+ if (thinking && config['thinkingConfig'] === undefined) {
539
+ if (/gemini-3/i.test(this.options.model)) {
540
+ const tc: Record<string, unknown> = {};
541
+ if (!thinking.enabled) {
542
+ tc['thinkingLevel'] = 'MINIMAL';
543
+ } else {
544
+ if (thinking.level) tc['thinkingLevel'] = thinking.level.toUpperCase();
545
+ tc['includeThoughts'] = true;
546
+ }
547
+ config['thinkingConfig'] = tc;
548
+ } else {
549
+ config['thinkingConfig'] = thinking.enabled
550
+ ? { thinkingBudget: geminiThinkingBudget(thinking.level), includeThoughts: true }
551
+ : { thinkingBudget: 0 };
552
+ }
553
+ }
554
+
555
+ // Structured output: add responseMimeType and responseSchema
556
+ const schemaOptions = this.extractSchemaOptions(options);
557
+ if (schemaOptions) {
558
+ config['responseMimeType'] = 'application/json';
559
+
560
+ // Convert schema to Google-compatible format
561
+ let jsonSchema: JSONSchema;
562
+ if (schemaOptions.jsonSchema) {
563
+ jsonSchema = normalizeJsonSchema(schemaOptions.jsonSchema);
564
+ } else if (schemaOptions.schemaConfig) {
565
+ jsonSchema = getJsonSchemaFromConfig(schemaOptions.schemaConfig);
566
+ } else {
567
+ throw new Error('Either schemaConfig or jsonSchema must be provided');
568
+ }
569
+
570
+ // Strip unsupported features for Google
571
+ const googleSchema = stripUnsupportedFeatures(jsonSchema, 'google');
572
+ config['responseSchema'] = googleSchema;
573
+ }
574
+
575
+ return config;
576
+ }
577
+
578
+ // ========================================================================
579
+ // Message Conversion
580
+ // ========================================================================
581
+
582
+ private convertToGoogleMessages(
583
+ messages: LLMChatMessage[],
584
+ isGemma: boolean,
585
+ ): { systemInstruction?: string; contents: GoogleContent[] } {
586
+ let systemInstruction: string | undefined;
587
+ const contents: GoogleContent[] = [];
588
+
589
+ for (const msg of messages) {
590
+ if (msg.role === 'system') {
591
+ if (isGemma) {
592
+ // Gemma: prepend system message to first user message
593
+ systemInstruction = typeof msg.content === 'string'
594
+ ? msg.content
595
+ : msg.content.filter((p): p is LLMTextContent => p.type === 'text').map(p => p.text).join('');
596
+ } else {
597
+ systemInstruction = typeof msg.content === 'string'
598
+ ? msg.content
599
+ : msg.content.filter((p): p is LLMTextContent => p.type === 'text').map(p => p.text).join('');
600
+ }
601
+ continue;
602
+ }
603
+
604
+ if (msg.role === 'tool') {
605
+ // Convert tool result to Google functionResponse
606
+ let responseData: Record<string, unknown>;
607
+ try {
608
+ responseData = typeof msg.content === 'string'
609
+ ? JSON.parse(msg.content)
610
+ : { result: msg.content };
611
+ } catch {
612
+ responseData = { result: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) };
613
+ }
614
+
615
+ contents.push({
616
+ role: 'function',
617
+ parts: [{
618
+ functionResponse: {
619
+ name: msg.tool_call_id ?? 'unknown',
620
+ response: responseData,
621
+ },
622
+ }],
623
+ });
624
+ continue;
625
+ }
626
+
627
+ if (msg.role === 'assistant') {
628
+ const parts: GooglePart[] = [];
629
+ const textContent = typeof msg.content === 'string' ? msg.content : '';
630
+ if (textContent) parts.push({ text: textContent });
631
+
632
+ // Convert tool calls to functionCall parts
633
+ if (msg.tool_calls) {
634
+ for (const tc of msg.tool_calls) {
635
+ const part: GooglePart = {
636
+ functionCall: {
637
+ name: tc.function.name,
638
+ args: this.parseToolArguments(tc.function.arguments),
639
+ },
640
+ };
641
+ // Echo thought signature back (required by Gemini 3.x)
642
+ if (tc.thoughtSignature) {
643
+ part.thoughtSignature = tc.thoughtSignature;
644
+ }
645
+ parts.push(part);
646
+ }
647
+ }
648
+
649
+ contents.push({ role: 'model', parts });
650
+ continue;
651
+ }
652
+
653
+ // User messages
654
+ const parts = this.convertContentToGoogleParts(msg.content);
655
+
656
+ // Gemma: prepend system instruction to first user message
657
+ if (isGemma && systemInstruction && contents.length === 0) {
658
+ const systemParts = [{ text: `[System Instructions]\n${systemInstruction}\n\n[User Message]\n` }];
659
+ contents.push({
660
+ role: 'user',
661
+ parts: [...systemParts, ...parts],
662
+ });
663
+ systemInstruction = undefined; // Consumed
664
+ } else {
665
+ contents.push({ role: 'user', parts });
666
+ }
667
+ }
668
+
669
+ return { systemInstruction, contents };
670
+ }
671
+
672
+ private convertContentToGoogleParts(content: string | LLMContentPart[]): GooglePart[] {
673
+ if (typeof content === 'string') {
674
+ return [{ text: content }];
675
+ }
676
+
677
+ return content.map(part => {
678
+ if (part.type === 'text') {
679
+ return { text: part.text };
680
+ }
681
+ if (part.type === 'audio') {
682
+ return {
683
+ inlineData: {
684
+ mimeType: part.audio.mimeType,
685
+ data: part.audio.data,
686
+ },
687
+ };
688
+ }
689
+ // Image content
690
+ const url = part.image_url.url;
691
+ if (url.startsWith('data:')) {
692
+ const match = url.match(/^data:([^;]+);base64,(.+)$/);
693
+ if (match) {
694
+ return {
695
+ inlineData: {
696
+ mimeType: match[1]!,
697
+ data: match[2]!,
698
+ },
699
+ };
700
+ }
701
+ }
702
+ // For regular URLs, try inline data format
703
+ return { text: `[Image: ${url}]` };
704
+ });
705
+ }
706
+
707
+ // ========================================================================
708
+ // Tool Conversion
709
+ // ========================================================================
710
+
711
+ private convertToGoogleTool(tool: LLMToolDefinition): GoogleFunctionDeclaration {
712
+ return {
713
+ name: tool.function.name,
714
+ description: tool.function.description,
715
+ parameters: {
716
+ type: 'object',
717
+ properties: tool.function.parameters.properties ?? {},
718
+ required: tool.function.parameters.required,
719
+ },
720
+ };
721
+ }
722
+
723
+ private convertFunctionCallToToolCall(
724
+ fc: { name?: string; args?: Record<string, unknown> },
725
+ thoughtSignature?: string,
726
+ ): LLMToolCall {
727
+ const toolCall: LLMToolCall = {
728
+ id: this.generateToolCallId(),
729
+ type: 'function',
730
+ function: {
731
+ name: fc.name || '',
732
+ arguments: JSON.stringify(fc.args ?? {}),
733
+ },
734
+ };
735
+ if (thoughtSignature) {
736
+ toolCall.thoughtSignature = thoughtSignature;
737
+ }
738
+ return toolCall;
739
+ }
740
+
741
+ private parseToolArguments(args: string | Record<string, unknown> | undefined): Record<string, unknown> {
742
+ if (typeof args !== 'string') {
743
+ return args ?? {};
744
+ }
745
+ if (args.length === 0) {
746
+ return {};
747
+ }
748
+ try {
749
+ const parsed = JSON.parse(args) as unknown;
750
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
751
+ ? parsed as Record<string, unknown>
752
+ : {};
753
+ } catch {
754
+ return {};
755
+ }
756
+ }
757
+
758
+ // ========================================================================
759
+ // Response Parsing
760
+ // ========================================================================
761
+
762
+ private parseGoogleResponse(data: GoogleResponse): LLMChatResponse {
763
+ const candidate = data.candidates?.[0];
764
+ if (!candidate?.content?.parts) {
765
+ return {
766
+ message: { role: 'assistant', content: '' },
767
+ provider: this.isVertex ? 'vertex' : 'google',
768
+ };
769
+ }
770
+
771
+ let textContent = '';
772
+ let reasoningText = '';
773
+ const toolCalls: LLMToolCall[] = [];
774
+
775
+ for (const part of candidate.content.parts) {
776
+ if (part.text) {
777
+ // Thought summaries (includeThoughts) carry the reasoning trace;
778
+ // keep them out of `content` and surface them as `reasoning`.
779
+ if (part.thought) reasoningText += part.text;
780
+ else textContent += part.text;
781
+ }
782
+ if (part.functionCall) {
783
+ toolCalls.push(this.convertFunctionCallToToolCall(
784
+ part.functionCall,
785
+ part.thoughtSignature,
786
+ ));
787
+ }
788
+ }
789
+
790
+ const usage: TokenUsageInfo | undefined = data.usageMetadata
791
+ ? {
792
+ inputTokens: data.usageMetadata.promptTokenCount,
793
+ outputTokens: data.usageMetadata.candidatesTokenCount,
794
+ totalTokens: data.usageMetadata.totalTokenCount,
795
+ cachedTokens: data.usageMetadata.cachedContentTokenCount,
796
+ reasoningTokens: data.usageMetadata.thoughtsTokenCount,
797
+ }
798
+ : undefined;
799
+
800
+ return {
801
+ message: {
802
+ role: 'assistant',
803
+ content: textContent,
804
+ tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
805
+ },
806
+ reasoning: reasoningText || undefined,
807
+ usage,
808
+ provider: this.isVertex ? 'vertex' : 'google',
809
+ };
810
+ }
811
+
812
+ // ========================================================================
813
+ // Flex Retry Logic
814
+ // ========================================================================
815
+
816
+ /**
817
+ * Retry HTTP requests for Flex tier when receiving 503/429 errors.
818
+ * Uses exponential backoff (5s → 10s → 20s) as recommended by Google.
819
+ */
820
+ private async fetchWithFlexRetry<T>(
821
+ url: string,
822
+ reqOptions: { method: 'POST'; headers: Record<string, string>; body: unknown; timeout: number },
823
+ maxRetries = 3,
824
+ baseDelay = 5000,
825
+ ): Promise<import('../http.js').HttpResponse<T>> {
826
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
827
+ try {
828
+ return await httpRequest<T>(url, reqOptions);
829
+ } catch (error) {
830
+ const isRetryable = error instanceof Error
831
+ && (error.message.includes('HTTP 503') || error.message.includes('HTTP 429'));
832
+ if (!isRetryable || attempt >= maxRetries - 1) throw error;
833
+ const delay = baseDelay * (2 ** attempt);
834
+ await new Promise(r => setTimeout(r, delay));
835
+ }
836
+ }
837
+ throw new Error('Unreachable');
838
+ }
839
+
840
+ }