universal-llm-client 4.2.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 (108) hide show
  1. package/CHANGELOG.md +142 -103
  2. package/LICENSE +21 -21
  3. package/README.md +640 -591
  4. package/dist/ai-model.d.ts +12 -1
  5. package/dist/ai-model.d.ts.map +1 -1
  6. package/dist/ai-model.js +36 -1
  7. package/dist/ai-model.js.map +1 -1
  8. package/dist/gemma-channel.d.ts +14 -0
  9. package/dist/gemma-channel.d.ts.map +1 -0
  10. package/dist/gemma-channel.js +38 -0
  11. package/dist/gemma-channel.js.map +1 -0
  12. package/dist/gemma-diffusion.d.ts +49 -0
  13. package/dist/gemma-diffusion.d.ts.map +1 -0
  14. package/dist/gemma-diffusion.js +147 -0
  15. package/dist/gemma-diffusion.js.map +1 -0
  16. package/dist/http.d.ts +4 -0
  17. package/dist/http.d.ts.map +1 -1
  18. package/dist/http.js +14 -1
  19. package/dist/http.js.map +1 -1
  20. package/dist/index.d.ts +2 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +4 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/interfaces.d.ts +183 -7
  25. package/dist/interfaces.d.ts.map +1 -1
  26. package/dist/interfaces.js.map +1 -1
  27. package/dist/providers/anthropic.d.ts.map +1 -1
  28. package/dist/providers/anthropic.js +28 -3
  29. package/dist/providers/anthropic.js.map +1 -1
  30. package/dist/providers/google.d.ts +22 -1
  31. package/dist/providers/google.d.ts.map +1 -1
  32. package/dist/providers/google.js +225 -13
  33. package/dist/providers/google.js.map +1 -1
  34. package/dist/providers/ollama.d.ts +2 -0
  35. package/dist/providers/ollama.d.ts.map +1 -1
  36. package/dist/providers/ollama.js +59 -30
  37. package/dist/providers/ollama.js.map +1 -1
  38. package/dist/providers/openai.d.ts +14 -0
  39. package/dist/providers/openai.d.ts.map +1 -1
  40. package/dist/providers/openai.js +200 -22
  41. package/dist/providers/openai.js.map +1 -1
  42. package/dist/router.d.ts +2 -0
  43. package/dist/router.d.ts.map +1 -1
  44. package/dist/router.js +4 -0
  45. package/dist/router.js.map +1 -1
  46. package/dist/stream-decoder.d.ts +12 -0
  47. package/dist/stream-decoder.d.ts.map +1 -1
  48. package/dist/stream-decoder.js +182 -5
  49. package/dist/stream-decoder.js.map +1 -1
  50. package/dist/thinking.d.ts +36 -0
  51. package/dist/thinking.d.ts.map +1 -0
  52. package/dist/thinking.js +52 -0
  53. package/dist/thinking.js.map +1 -0
  54. package/package.json +118 -116
  55. package/src/ai-model.ts +400 -350
  56. package/src/auditor.ts +213 -213
  57. package/src/client.ts +402 -402
  58. package/src/debug/debug-google-streaming.ts +1 -1
  59. package/src/demos/basic/universal-llm-examples.ts +3 -3
  60. package/src/demos/diffusion-gemma/.env +29 -0
  61. package/src/demos/diffusion-gemma/.env.example +27 -0
  62. package/src/demos/diffusion-gemma/CLAUDE.md +95 -0
  63. package/src/demos/diffusion-gemma/README.md +59 -0
  64. package/src/demos/diffusion-gemma/canvas.ts +1606 -0
  65. package/src/demos/diffusion-gemma/docker-compose.yml +29 -0
  66. package/src/demos/diffusion-gemma/probe-stream.ts +51 -0
  67. package/src/demos/diffusion-gemma/probe-tools.ts +55 -0
  68. package/src/demos/diffusion-gemma/server.ts +1205 -0
  69. package/src/demos/diffusion-gemma/start-vllm.sh +98 -0
  70. package/src/gemma-channel.ts +47 -0
  71. package/src/gemma-diffusion.ts +167 -0
  72. package/src/http.ts +261 -247
  73. package/src/index.ts +180 -161
  74. package/src/interfaces.ts +843 -657
  75. package/src/mcp.ts +345 -345
  76. package/src/providers/anthropic.ts +796 -762
  77. package/src/providers/google.ts +840 -620
  78. package/src/providers/index.ts +8 -8
  79. package/src/providers/ollama.ts +503 -469
  80. package/src/providers/openai.ts +587 -392
  81. package/src/router.ts +785 -780
  82. package/src/stream-decoder.ts +535 -361
  83. package/src/structured-output.ts +759 -759
  84. package/src/test-scripts/test-google-deep-research.ts +33 -0
  85. package/src/test-scripts/test-google-streaming-enhanced.ts +147 -147
  86. package/src/test-scripts/test-google-streaming.ts +1 -1
  87. package/src/test-scripts/test-google-system-prompt-comprehensive.ts +189 -189
  88. package/src/test-scripts/test-google-thinking.ts +46 -0
  89. package/src/test-scripts/test-system-message-positions.ts +163 -163
  90. package/src/test-scripts/test-system-prompt-improvement-demo.ts +83 -83
  91. package/src/test-scripts/test-vllm-qwen36.ts +256 -0
  92. package/src/tests/ai-model.test.ts +1614 -1614
  93. package/src/tests/auditor.test.ts +224 -224
  94. package/src/tests/gemma-diffusion.test.ts +115 -0
  95. package/src/tests/http.test.ts +200 -200
  96. package/src/tests/interfaces.test.ts +117 -117
  97. package/src/tests/providers/anthropic.test.ts +118 -0
  98. package/src/tests/providers/google.test.ts +841 -660
  99. package/src/tests/providers/ollama.test.ts +1034 -954
  100. package/src/tests/providers/openai.test.ts +1511 -1122
  101. package/src/tests/router.test.ts +254 -254
  102. package/src/tests/stream-decoder.test.ts +263 -179
  103. package/src/tests/structured-output.test.ts +1450 -1450
  104. package/src/tests/thinking.test.ts +65 -0
  105. package/src/tests/tools.test.ts +175 -175
  106. package/src/thinking.ts +73 -0
  107. package/src/tools.ts +246 -246
  108. package/src/zod-adapter.ts +72 -72
@@ -1,469 +1,503 @@
1
- /**
2
- * Universal LLM Client v3 — Ollama Provider
3
- *
4
- * Implements BaseLLMClient for Ollama's native API.
5
- * Supports chat, streaming (NDJSON), embeddings, model discovery,
6
- * context length detection via /api/show, and structured output.
7
- *
8
- * Structured Output Assertions:
9
- * - VAL-PROVIDER-OLLAMA-001: format parameter with JSON Schema
10
- * - VAL-PROVIDER-OLLAMA-003: Vision with base64 extraction alongside format
11
- * - VAL-PROVIDER-OLLAMA-004: format "json" vs schema modes
12
- */
13
-
14
- import { BaseLLMClient } from '../client.js';
15
- import { httpRequest, httpStream, parseNDJSON, buildHeaders } from '../http.js';
16
- import { StandardChatDecoder } from '../stream-decoder.js';
17
- import {
18
- normalizeJsonSchema,
19
- getJsonSchemaFromConfig,
20
- } from '../structured-output.js';
21
- import type {
22
- LLMClientOptions,
23
- LLMChatMessage,
24
- LLMChatResponse,
25
- ChatOptions,
26
- ModelMetadata,
27
- OllamaResponse,
28
- OllamaModelInfo,
29
- LLMToolDefinition,
30
- TokenUsageInfo,
31
- } from '../interfaces.js';
32
- import type { DecodedEvent } from '../stream-decoder.js';
33
- import type { Auditor } from '../auditor.js';
34
-
35
- export class OllamaClient extends BaseLLMClient {
36
- constructor(options: LLMClientOptions, auditor?: Auditor) {
37
- super({
38
- ...options,
39
- url: (options.url || 'http://localhost:11434').replace(/\/+$/, ''),
40
- }, auditor);
41
- }
42
-
43
- // ========================================================================
44
- // Chat
45
- // ========================================================================
46
-
47
- async chat(
48
- messages: LLMChatMessage[],
49
- options?: ChatOptions,
50
- ): Promise<LLMChatResponse> {
51
- // Structured output and tools can now be used together.\n // The provider sends both format and tools in the request.\n // The Router handles skipping validation when the response contains tool calls.
52
-
53
- const url = `${this.options.url}/api/chat`;
54
- const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);
55
-
56
- const body: Record<string, unknown> = {
57
- model: this.options.model,
58
- messages: this.convertMessages(messages),
59
- stream: false,
60
- options: this.buildOllamaOptions(options),
61
- };
62
-
63
- if (tools?.length) {
64
- body['tools'] = this.convertToolsToOllama(tools);
65
- }
66
-
67
- // Enable native thinking by default — thinking models produce better
68
- // tool selections and reasoning when allowed to think before acting.
69
- body['think'] = this.options.thinking ?? true;
70
-
71
- // Handle structured output via format parameter
72
- const schemaOptions = this.extractSchemaOptions(options);
73
- if (schemaOptions) {
74
- body['format'] = this.buildFormatParameter(schemaOptions);
75
- } else if (options?.responseFormat) {
76
- // Legacy json_object mode - map to Ollama's "json" format
77
- body['format'] = 'json';
78
- }
79
-
80
- const start = Date.now();
81
- this.auditor.record({
82
- timestamp: start,
83
- type: 'request',
84
- provider: 'ollama',
85
- model: this.options.model,
86
- });
87
-
88
- const response = await httpRequest<OllamaResponse>(url, {
89
- method: 'POST',
90
- headers: buildHeaders(this.options),
91
- body,
92
- timeout: this.options.timeout ?? 30000,
93
- });
94
-
95
- const data = response.data;
96
- const usage: TokenUsageInfo | undefined = (data.prompt_eval_count || data.eval_count)
97
- ? {
98
- inputTokens: data.prompt_eval_count ?? 0,
99
- outputTokens: data.eval_count ?? 0,
100
- totalTokens: (data.prompt_eval_count ?? 0) + (data.eval_count ?? 0),
101
- }
102
- : undefined;
103
-
104
- // Normalize tool call IDs (Ollama sometimes omits them)
105
- const toolCalls = data.message.tool_calls?.map(tc => ({
106
- ...tc,
107
- id: tc.id || this.generateToolCallId(),
108
- function: {
109
- ...tc.function,
110
- arguments: typeof tc.function.arguments === 'string'
111
- ? tc.function.arguments
112
- : JSON.stringify(tc.function.arguments),
113
- },
114
- }));
115
-
116
- // Get content, handling potential null
117
- const content = data.message.content || data.message.thinking || '';
118
-
119
- const result: LLMChatResponse = {
120
- message: {
121
- role: 'assistant',
122
- content,
123
- tool_calls: toolCalls,
124
- },
125
- reasoning: data.message.content ? data.message.thinking : undefined,
126
- usage,
127
- provider: 'ollama',
128
- };
129
-
130
- this.auditor.record({
131
- timestamp: Date.now(),
132
- type: 'response',
133
- provider: 'ollama',
134
- model: this.options.model,
135
- duration: Date.now() - start,
136
- usage,
137
- });
138
-
139
- return result;
140
- }
141
-
142
- // ========================================================================
143
- // Streaming
144
- // ========================================================================
145
-
146
- async *chatStream(
147
- messages: LLMChatMessage[],
148
- options?: ChatOptions,
149
- ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {
150
- const url = `${this.options.url}/api/chat`;
151
- const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);
152
-
153
- const body: Record<string, unknown> = {
154
- model: this.options.model,
155
- messages: this.convertMessages(messages),
156
- stream: true,
157
- options: this.buildOllamaOptions(options),
158
- };
159
-
160
- if (tools?.length) {
161
- body['tools'] = this.convertToolsToOllama(tools);
162
- }
163
-
164
- body['think'] = this.options.thinking ?? true;
165
-
166
- const start = Date.now();
167
- this.auditor.record({
168
- timestamp: start,
169
- type: 'stream_start',
170
- provider: 'ollama',
171
- model: this.options.model,
172
- });
173
-
174
- const decoder = new StandardChatDecoder(() => {});
175
- let lastResponse: OllamaResponse | undefined;
176
- const streamedToolCalls: import('../interfaces.js').LLMToolCall[] = [];
177
-
178
- // Stream idle timeout: thinking models can pause for minutes between chunks.
179
- // Ensure at least 5 minutes regardless of the base request timeout.
180
- const streamTimeout = Math.max(this.options.timeout ?? 300000, 300000);
181
-
182
- const stream = httpStream(url, {
183
- method: 'POST',
184
- headers: buildHeaders(this.options),
185
- body,
186
- timeout: streamTimeout,
187
- });
188
-
189
- for await (const chunk of parseNDJSON<OllamaResponse>(stream)) {
190
- lastResponse = chunk;
191
-
192
- if (chunk.message?.thinking) {
193
- decoder.pushReasoning(chunk.message.thinking);
194
- yield { type: 'thinking', content: chunk.message.thinking };
195
- }
196
-
197
- if (chunk.message?.content) {
198
- decoder.push(chunk.message.content);
199
- yield { type: 'text', content: chunk.message.content };
200
- }
201
-
202
- if (chunk.message?.tool_calls?.length) {
203
- const normalized = chunk.message.tool_calls.map(tc => ({
204
- ...tc,
205
- id: tc.id || this.generateToolCallId(),
206
- function: {
207
- ...tc.function,
208
- arguments: typeof tc.function.arguments === 'string'
209
- ? tc.function.arguments
210
- : JSON.stringify(tc.function.arguments),
211
- },
212
- }));
213
- streamedToolCalls.push(...normalized);
214
- yield { type: 'tool_call', calls: normalized };
215
- }
216
- }
217
-
218
- decoder.flush();
219
-
220
- const usage: TokenUsageInfo | undefined = lastResponse?.prompt_eval_count
221
- ? {
222
- inputTokens: lastResponse.prompt_eval_count ?? 0,
223
- outputTokens: lastResponse.eval_count ?? 0,
224
- totalTokens: (lastResponse.prompt_eval_count ?? 0) + (lastResponse.eval_count ?? 0),
225
- }
226
- : undefined;
227
-
228
- this.auditor.record({
229
- timestamp: Date.now(),
230
- type: 'stream_end',
231
- provider: 'ollama',
232
- model: this.options.model,
233
- duration: Date.now() - start,
234
- usage,
235
- });
236
-
237
- return {
238
- message: {
239
- role: 'assistant',
240
- content: decoder.getCleanContent(),
241
- tool_calls: streamedToolCalls.length > 0 ? streamedToolCalls : undefined,
242
- },
243
- reasoning: decoder.getReasoning(),
244
- usage,
245
- provider: 'ollama',
246
- };
247
- }
248
-
249
- // ========================================================================
250
- // Embeddings
251
- // ========================================================================
252
-
253
- async embed(text: string): Promise<number[]> {
254
- const url = `${this.options.url}/api/embed`;
255
- const response = await httpRequest<{ embeddings: number[][] }>(url, {
256
- method: 'POST',
257
- headers: buildHeaders(this.options),
258
- body: { model: this.options.model, input: text },
259
- timeout: this.options.timeout ?? 30000,
260
- });
261
- return response.data.embeddings[0] ?? [];
262
- }
263
-
264
- override async embedArray(texts: string[]): Promise<number[][]> {
265
- const url = `${this.options.url}/api/embed`;
266
- const response = await httpRequest<{ embeddings: number[][] }>(url, {
267
- method: 'POST',
268
- headers: buildHeaders(this.options),
269
- body: { model: this.options.model, input: texts },
270
- timeout: this.options.timeout ?? 30000,
271
- });
272
- return response.data.embeddings;
273
- }
274
-
275
- // ========================================================================
276
- // Model Discovery
277
- // ========================================================================
278
-
279
- async getModels(): Promise<string[]> {
280
- const url = `${this.options.url}/api/tags`;
281
- const response = await httpRequest<{ models: OllamaModelInfo[] }>(url, {
282
- timeout: 5000,
283
- });
284
- return response.data.models.map(m => m.name);
285
- }
286
-
287
- override async getModelInfo(modelName?: string): Promise<ModelMetadata> {
288
- const url = `${this.options.url}/api/show`;
289
- try {
290
- const targetModel = modelName ?? this.options.model;
291
- const response = await httpRequest<Record<string, unknown>>(url, {
292
- method: 'POST',
293
- body: { name: targetModel },
294
- timeout: 5000,
295
- });
296
-
297
- const modelInfo = response.data['model_info'] as Record<string, unknown> | undefined;
298
- if (!modelInfo) return { contextLength: 8192 };
299
-
300
- // Extract architecture-specific context length
301
- const arch = modelInfo['general.architecture'] as string | undefined;
302
- let contextLength = 8192;
303
-
304
- if (arch) {
305
- const ctxKey = `${arch}.context_length`;
306
- const ctxValue = modelInfo[ctxKey] as number | undefined;
307
- if (ctxValue) contextLength = ctxValue;
308
- }
309
-
310
- // Prefer the live deployment context when available. /api/show reports
311
- // the trained maximum; /api/ps reports what the daemon has actually loaded.
312
- try {
313
- const psResponse = await httpRequest<{ models?: Array<{ name?: string; context_length?: number }> }>(
314
- `${this.options.url}/api/ps`,
315
- { timeout: 5000 },
316
- );
317
- const liveModel = psResponse.data.models?.find(
318
- model => model.name?.toLowerCase() === targetModel.toLowerCase(),
319
- );
320
- if (liveModel?.context_length && liveModel.context_length > 0) {
321
- contextLength = Math.min(contextLength, liveModel.context_length);
322
- }
323
- } catch {
324
- // Ignore /api/ps failures /api/show is still a valid fallback
325
- }
326
-
327
- const paramCountRaw = modelInfo['general.parameter_count'] as number | undefined;
328
- const capabilities = response.data['capabilities'] as string[] | undefined;
329
-
330
- return {
331
- model: targetModel,
332
- contextLength,
333
- architecture: arch,
334
- parameterCount: paramCountRaw,
335
- capabilities,
336
- };
337
- } catch {
338
- return { contextLength: 8192 };
339
- }
340
- }
341
-
342
- // ========================================================================
343
- // Readiness
344
- // ========================================================================
345
-
346
- /** Ensure model is available, pull if missing */
347
- async ensureReady(): Promise<void> {
348
- try {
349
- await this.getModelInfo();
350
- } catch {
351
- // Try pulling the model
352
- this.debugLog(`Model not found, attempting pull: ${this.options.model}`);
353
- await httpRequest(`${this.options.url}/api/pull`, {
354
- method: 'POST',
355
- body: { name: this.options.model },
356
- timeout: 300000, // 5 min for pull
357
- });
358
- }
359
- }
360
-
361
- // ========================================================================
362
- // Internals
363
- // ========================================================================
364
-
365
- private convertMessages(messages: LLMChatMessage[]): Record<string, unknown>[] {
366
- return messages.map(msg => {
367
- const converted: Record<string, unknown> = { role: msg.role };
368
-
369
- // Handle multimodal content (array of text + image parts)
370
- if (Array.isArray(msg.content)) {
371
- const textParts: string[] = [];
372
- const images: string[] = [];
373
-
374
- for (const part of msg.content) {
375
- if (part.type === 'text') {
376
- textParts.push(part.text);
377
- } else if (part.type === 'audio') {
378
- this.debugLog('Ollama: skipping audio content (not supported)');
379
- } else if (part.type === 'image_url' && part.image_url?.url) {
380
- // Extract base64 data from data URL or use raw base64
381
- const url = part.image_url.url;
382
- if (url.startsWith('data:')) {
383
- // data:image/jpeg;base64,XXXX → extract XXXX
384
- const base64Data = url.split(',')[1];
385
- if (base64Data) images.push(base64Data);
386
- } else if (url.startsWith('http')) {
387
- // Ollama doesn't support URLs directly — skip
388
- // (caller should download and convert to base64)
389
- this.debugLog('Ollama vision: skipping URL image, use base64 instead');
390
- } else {
391
- // Assume raw base64
392
- images.push(url);
393
- }
394
- }
395
- }
396
-
397
- converted['content'] = textParts.join('\n');
398
- if (images.length > 0) {
399
- converted['images'] = images;
400
- }
401
- } else {
402
- converted['content'] = msg.content ?? '';
403
- }
404
-
405
- // Ollama needs tool call arguments as objects, not strings
406
- if (msg.tool_calls?.length) {
407
- converted['tool_calls'] = msg.tool_calls.map(tc => ({
408
- ...tc,
409
- function: {
410
- ...tc.function,
411
- arguments: typeof tc.function.arguments === 'string'
412
- ? (() => { try { return JSON.parse(tc.function.arguments); } catch { return tc.function.arguments; } })()
413
- : tc.function.arguments,
414
- },
415
- }));
416
- }
417
-
418
- // Preserve tool_call_id for tool result messages
419
- if (msg.tool_call_id) {
420
- converted['tool_call_id'] = msg.tool_call_id;
421
- }
422
-
423
- return converted;
424
- });
425
- }
426
-
427
- private convertToolsToOllama(tools: LLMToolDefinition[]): unknown[] {
428
- return tools.map(t => ({
429
- type: 'function',
430
- function: {
431
- name: t.function.name,
432
- description: t.function.description,
433
- parameters: t.function.parameters,
434
- },
435
- }));
436
- }
437
-
438
- private buildOllamaOptions(options?: ChatOptions): Record<string, unknown> {
439
- const params: Record<string, unknown> = {
440
- ...this.options.defaultParameters,
441
- ...options?.parameters,
442
- };
443
- if (options?.temperature !== undefined) params['temperature'] = options.temperature;
444
- if (options?.maxTokens !== undefined) params['num_predict'] = options.maxTokens;
445
- return params;
446
- }
447
-
448
- // ========================================================================
449
- // Structured Output Helpers
450
- // ========================================================================
451
-
452
- /**
453
- * Build Ollama format parameter from schema options.
454
- * Ollama accepts:
455
- * - format: "json" for simple JSON mode
456
- * - format: { ...schema } for structured output with JSON Schema
457
- */
458
- private buildFormatParameter(options: { schemaConfig?: import('../structured-output.js').SchemaConfig<unknown>, jsonSchema?: import('../structured-output.js').JSONSchema }): string | import('../structured-output.js').JSONSchema {
459
- if (options.jsonSchema) {
460
- return normalizeJsonSchema(options.jsonSchema);
461
- }
462
-
463
- if (options.schemaConfig) {
464
- return getJsonSchemaFromConfig(options.schemaConfig);
465
- }
466
-
467
- return 'json';
468
- }
469
- }
1
+ /**
2
+ * Universal LLM Client v3 — Ollama Provider
3
+ *
4
+ * Implements BaseLLMClient for Ollama's native API.
5
+ * Supports chat, streaming (NDJSON), embeddings, model discovery,
6
+ * context length detection via /api/show, and structured output.
7
+ *
8
+ * Structured Output Assertions:
9
+ * - VAL-PROVIDER-OLLAMA-001: format parameter with JSON Schema
10
+ * - VAL-PROVIDER-OLLAMA-003: Vision with base64 extraction alongside format
11
+ * - VAL-PROVIDER-OLLAMA-004: format "json" vs schema modes
12
+ */
13
+
14
+ import { BaseLLMClient } from '../client.js';
15
+ import { resolveThinking } from '../thinking.js';
16
+ import { httpRequest, httpStream, parseNDJSON, buildHeaders } from '../http.js';
17
+ import { StandardChatDecoder } from '../stream-decoder.js';
18
+ import {
19
+ normalizeJsonSchema,
20
+ getJsonSchemaFromConfig,
21
+ } from '../structured-output.js';
22
+ import { extractGemmaThoughtChannels } from '../gemma-channel.js';
23
+ import type {
24
+ LLMClientOptions,
25
+ LLMChatMessage,
26
+ LLMChatResponse,
27
+ ChatOptions,
28
+ ModelMetadata,
29
+ OllamaResponse,
30
+ OllamaModelInfo,
31
+ LLMToolDefinition,
32
+ LLMToolCall,
33
+ TokenUsageInfo,
34
+ } from '../interfaces.js';
35
+ import type { DecodedEvent } from '../stream-decoder.js';
36
+ import type { Auditor } from '../auditor.js';
37
+
38
+ export class OllamaClient extends BaseLLMClient {
39
+ constructor(options: LLMClientOptions, auditor?: Auditor) {
40
+ super({
41
+ ...options,
42
+ url: (options.url || 'http://localhost:11434').replace(/\/+$/, ''),
43
+ }, auditor);
44
+ }
45
+
46
+ // ========================================================================
47
+ // Chat
48
+ // ========================================================================
49
+
50
+ async chat(
51
+ messages: LLMChatMessage[],
52
+ options?: ChatOptions,
53
+ ): Promise<LLMChatResponse> {
54
+ // Structured output and tools can now be used together.\n // The provider sends both format and tools in the request.\n // The Router handles skipping validation when the response contains tool calls.
55
+
56
+ const url = `${this.options.url}/api/chat`;
57
+ const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);
58
+
59
+ const body: Record<string, unknown> = {
60
+ model: this.options.model,
61
+ messages: this.convertMessages(messages),
62
+ stream: false,
63
+ options: this.buildOllamaOptions(options),
64
+ };
65
+
66
+ if (tools?.length) {
67
+ body['tools'] = this.convertToolsToOllama(tools);
68
+ }
69
+
70
+ // Enable native thinking by default — thinking models produce better
71
+ // tool selections and reasoning when allowed to think before acting.
72
+ // Ollama `think` is on/off (no levels); default on for thinking models.
73
+ body['think'] = resolveThinking(options?.thinking, this.options.thinking)?.enabled ?? true;
74
+
75
+ // Handle structured output via format parameter
76
+ const schemaOptions = this.extractSchemaOptions(options);
77
+ if (schemaOptions) {
78
+ body['format'] = this.buildFormatParameter(schemaOptions);
79
+ } else if (options?.responseFormat) {
80
+ // Legacy json_object mode - map to Ollama's "json" format
81
+ body['format'] = 'json';
82
+ }
83
+
84
+ const start = Date.now();
85
+ this.auditor.record({
86
+ timestamp: start,
87
+ type: 'request',
88
+ provider: 'ollama',
89
+ model: this.options.model,
90
+ });
91
+
92
+ const response = await httpRequest<OllamaResponse>(url, {
93
+ method: 'POST',
94
+ headers: buildHeaders(this.options),
95
+ body,
96
+ timeout: this.options.timeout ?? 30000,
97
+ });
98
+
99
+ const data = response.data;
100
+ const usage: TokenUsageInfo | undefined = (data.prompt_eval_count || data.eval_count)
101
+ ? {
102
+ inputTokens: data.prompt_eval_count ?? 0,
103
+ outputTokens: data.eval_count ?? 0,
104
+ totalTokens: (data.prompt_eval_count ?? 0) + (data.eval_count ?? 0),
105
+ // Ollama reports server-precise timing in nanoseconds.
106
+ durationMs: data.total_duration ? data.total_duration / 1e6 : undefined,
107
+ tokensPerSecond: data.eval_duration && data.eval_count
108
+ ? data.eval_count / (data.eval_duration / 1e9)
109
+ : undefined,
110
+ }
111
+ : undefined;
112
+
113
+ // Normalize tool calls (Ollama sometimes omits IDs and empty args).
114
+ const toolCalls = data.message.tool_calls?.map(tc => this.normalizeToolCall(tc));
115
+
116
+ const gemmaContent = extractGemmaThoughtChannels(data.message.content || '');
117
+ const reasoning = [data.message.thinking, gemmaContent.reasoning].filter(Boolean).join('\n\n') || undefined;
118
+
119
+ const result: LLMChatResponse = {
120
+ message: {
121
+ role: 'assistant',
122
+ content: gemmaContent.content,
123
+ tool_calls: toolCalls,
124
+ },
125
+ finishReason: data.done_reason,
126
+ reasoning,
127
+ usage,
128
+ provider: 'ollama',
129
+ };
130
+
131
+ this.auditor.record({
132
+ timestamp: Date.now(),
133
+ type: 'response',
134
+ provider: 'ollama',
135
+ model: this.options.model,
136
+ duration: Date.now() - start,
137
+ usage,
138
+ });
139
+
140
+ return result;
141
+ }
142
+
143
+ // ========================================================================
144
+ // Streaming
145
+ // ========================================================================
146
+
147
+ async *chatStream(
148
+ messages: LLMChatMessage[],
149
+ options?: ChatOptions,
150
+ ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {
151
+ const url = `${this.options.url}/api/chat`;
152
+ const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);
153
+
154
+ const body: Record<string, unknown> = {
155
+ model: this.options.model,
156
+ messages: this.convertMessages(messages),
157
+ stream: true,
158
+ options: this.buildOllamaOptions(options),
159
+ };
160
+
161
+ if (tools?.length) {
162
+ body['tools'] = this.convertToolsToOllama(tools);
163
+ }
164
+
165
+ // Ollama `think` is on/off (no levels); default on for thinking models.
166
+ body['think'] = resolveThinking(options?.thinking, this.options.thinking)?.enabled ?? true;
167
+
168
+ const start = Date.now();
169
+ this.auditor.record({
170
+ timestamp: start,
171
+ type: 'stream_start',
172
+ provider: 'ollama',
173
+ model: this.options.model,
174
+ });
175
+
176
+ const decoderEvents: DecodedEvent[] = [];
177
+ const decoder = new StandardChatDecoder(event => decoderEvents.push(event));
178
+ let lastResponse: OllamaResponse | undefined;
179
+ const streamedToolCalls: import('../interfaces.js').LLMToolCall[] = [];
180
+
181
+ // Stream idle timeout: thinking models can pause for minutes between chunks.
182
+ // Ensure at least 5 minutes regardless of the base request timeout.
183
+ const streamTimeout = Math.max(this.options.timeout ?? 300000, 300000);
184
+
185
+ const stream = httpStream(url, {
186
+ method: 'POST',
187
+ headers: buildHeaders(this.options),
188
+ body,
189
+ timeout: streamTimeout,
190
+ });
191
+
192
+ for await (const chunk of parseNDJSON<OllamaResponse>(stream)) {
193
+ lastResponse = chunk;
194
+
195
+ if (chunk.message?.thinking) {
196
+ decoder.pushReasoning(chunk.message.thinking);
197
+ const pending = decoderEvents.splice(0);
198
+ for (const event of pending) {
199
+ yield event;
200
+ }
201
+ }
202
+
203
+ if (chunk.message?.content) {
204
+ decoder.push(chunk.message.content);
205
+ const pending = decoderEvents.splice(0);
206
+ for (const event of pending) {
207
+ yield event;
208
+ }
209
+ }
210
+
211
+ if (chunk.message?.tool_calls?.length) {
212
+ const normalized = chunk.message.tool_calls.map(tc => this.normalizeToolCall(tc));
213
+ streamedToolCalls.push(...normalized);
214
+ yield { type: 'tool_call', calls: normalized };
215
+ }
216
+ }
217
+
218
+ decoder.flush();
219
+ const pending = decoderEvents.splice(0);
220
+ for (const event of pending) {
221
+ yield event;
222
+ }
223
+
224
+ const usage: TokenUsageInfo | undefined = lastResponse?.prompt_eval_count
225
+ ? {
226
+ inputTokens: lastResponse.prompt_eval_count ?? 0,
227
+ outputTokens: lastResponse.eval_count ?? 0,
228
+ totalTokens: (lastResponse.prompt_eval_count ?? 0) + (lastResponse.eval_count ?? 0),
229
+ durationMs: lastResponse.total_duration ? lastResponse.total_duration / 1e6 : undefined,
230
+ tokensPerSecond: lastResponse.eval_duration && lastResponse.eval_count
231
+ ? lastResponse.eval_count / (lastResponse.eval_duration / 1e9)
232
+ : undefined,
233
+ }
234
+ : undefined;
235
+
236
+ this.auditor.record({
237
+ timestamp: Date.now(),
238
+ type: 'stream_end',
239
+ provider: 'ollama',
240
+ model: this.options.model,
241
+ duration: Date.now() - start,
242
+ usage,
243
+ });
244
+
245
+ return {
246
+ message: {
247
+ role: 'assistant',
248
+ content: decoder.getCleanContent(),
249
+ tool_calls: streamedToolCalls.length > 0 ? streamedToolCalls : undefined,
250
+ },
251
+ finishReason: lastResponse?.done_reason,
252
+ reasoning: decoder.getReasoning(),
253
+ usage,
254
+ provider: 'ollama',
255
+ };
256
+ }
257
+
258
+ private normalizeToolCall(
259
+ toolCall: Partial<LLMToolCall> & { function?: Partial<LLMToolCall['function']> },
260
+ ): LLMToolCall {
261
+ return {
262
+ ...toolCall,
263
+ id: toolCall.id || this.generateToolCallId(),
264
+ type: 'function',
265
+ function: {
266
+ ...toolCall.function,
267
+ name: toolCall.function?.name || '',
268
+ arguments: this.normalizeToolArguments(toolCall.function?.arguments),
269
+ },
270
+ };
271
+ }
272
+
273
+ private normalizeToolArguments(args: unknown): string {
274
+ if (typeof args === 'string') {
275
+ return args.trim().length > 0 ? args : '{}';
276
+ }
277
+ if (args == null) {
278
+ return '{}';
279
+ }
280
+ return JSON.stringify(args) ?? '{}';
281
+ }
282
+
283
+ // ========================================================================
284
+ // Embeddings
285
+ // ========================================================================
286
+
287
+ async embed(text: string): Promise<number[]> {
288
+ const url = `${this.options.url}/api/embed`;
289
+ const response = await httpRequest<{ embeddings: number[][] }>(url, {
290
+ method: 'POST',
291
+ headers: buildHeaders(this.options),
292
+ body: { model: this.options.model, input: text },
293
+ timeout: this.options.timeout ?? 30000,
294
+ });
295
+ return response.data.embeddings[0] ?? [];
296
+ }
297
+
298
+ override async embedArray(texts: string[]): Promise<number[][]> {
299
+ const url = `${this.options.url}/api/embed`;
300
+ const response = await httpRequest<{ embeddings: number[][] }>(url, {
301
+ method: 'POST',
302
+ headers: buildHeaders(this.options),
303
+ body: { model: this.options.model, input: texts },
304
+ timeout: this.options.timeout ?? 30000,
305
+ });
306
+ return response.data.embeddings;
307
+ }
308
+
309
+ // ========================================================================
310
+ // Model Discovery
311
+ // ========================================================================
312
+
313
+ async getModels(): Promise<string[]> {
314
+ const url = `${this.options.url}/api/tags`;
315
+ const response = await httpRequest<{ models: OllamaModelInfo[] }>(url, {
316
+ timeout: 5000,
317
+ });
318
+ return response.data.models.map(m => m.name);
319
+ }
320
+
321
+ override async getModelInfo(modelName?: string): Promise<ModelMetadata> {
322
+ const url = `${this.options.url}/api/show`;
323
+ try {
324
+ const targetModel = modelName ?? this.options.model;
325
+ const response = await httpRequest<Record<string, unknown>>(url, {
326
+ method: 'POST',
327
+ body: { name: targetModel },
328
+ timeout: 5000,
329
+ });
330
+
331
+ const modelInfo = response.data['model_info'] as Record<string, unknown> | undefined;
332
+ if (!modelInfo) return { contextLength: 8192 };
333
+
334
+ // Extract architecture-specific context length
335
+ const arch = modelInfo['general.architecture'] as string | undefined;
336
+ let contextLength = 8192;
337
+
338
+ if (arch) {
339
+ const ctxKey = `${arch}.context_length`;
340
+ const ctxValue = modelInfo[ctxKey] as number | undefined;
341
+ if (ctxValue) contextLength = ctxValue;
342
+ }
343
+
344
+ // Prefer the live deployment context when available. /api/show reports
345
+ // the trained maximum; /api/ps reports what the daemon has actually loaded.
346
+ try {
347
+ const psResponse = await httpRequest<{ models?: Array<{ name?: string; context_length?: number }> }>(
348
+ `${this.options.url}/api/ps`,
349
+ { timeout: 5000 },
350
+ );
351
+ const liveModel = psResponse.data.models?.find(
352
+ model => model.name?.toLowerCase() === targetModel.toLowerCase(),
353
+ );
354
+ if (liveModel?.context_length && liveModel.context_length > 0) {
355
+ contextLength = Math.min(contextLength, liveModel.context_length);
356
+ }
357
+ } catch {
358
+ // Ignore /api/ps failures — /api/show is still a valid fallback
359
+ }
360
+
361
+ const paramCountRaw = modelInfo['general.parameter_count'] as number | undefined;
362
+ const capabilities = response.data['capabilities'] as string[] | undefined;
363
+
364
+ return {
365
+ model: targetModel,
366
+ contextLength,
367
+ architecture: arch,
368
+ parameterCount: paramCountRaw,
369
+ capabilities,
370
+ };
371
+ } catch {
372
+ return { contextLength: 8192 };
373
+ }
374
+ }
375
+
376
+ // ========================================================================
377
+ // Readiness
378
+ // ========================================================================
379
+
380
+ /** Ensure model is available, pull if missing */
381
+ async ensureReady(): Promise<void> {
382
+ try {
383
+ await this.getModelInfo();
384
+ } catch {
385
+ // Try pulling the model
386
+ this.debugLog(`Model not found, attempting pull: ${this.options.model}`);
387
+ await httpRequest(`${this.options.url}/api/pull`, {
388
+ method: 'POST',
389
+ body: { name: this.options.model },
390
+ timeout: 300000, // 5 min for pull
391
+ });
392
+ }
393
+ }
394
+
395
+ // ========================================================================
396
+ // Internals
397
+ // ========================================================================
398
+
399
+ private convertMessages(messages: LLMChatMessage[]): Record<string, unknown>[] {
400
+ return messages.map(msg => {
401
+ const converted: Record<string, unknown> = { role: msg.role };
402
+
403
+ // Handle multimodal content (array of text + image parts)
404
+ if (Array.isArray(msg.content)) {
405
+ const textParts: string[] = [];
406
+ const images: string[] = [];
407
+
408
+ for (const part of msg.content) {
409
+ if (part.type === 'text') {
410
+ textParts.push(part.text);
411
+ } else if (part.type === 'audio') {
412
+ this.debugLog('Ollama: skipping audio content (not supported)');
413
+ } else if (part.type === 'image_url' && part.image_url?.url) {
414
+ // Extract base64 data from data URL or use raw base64
415
+ const url = part.image_url.url;
416
+ if (url.startsWith('data:')) {
417
+ // data:image/jpeg;base64,XXXX → extract XXXX
418
+ const base64Data = url.split(',')[1];
419
+ if (base64Data) images.push(base64Data);
420
+ } else if (url.startsWith('http')) {
421
+ // Ollama doesn't support URLs directly — skip
422
+ // (caller should download and convert to base64)
423
+ this.debugLog('Ollama vision: skipping URL image, use base64 instead');
424
+ } else {
425
+ // Assume raw base64
426
+ images.push(url);
427
+ }
428
+ }
429
+ }
430
+
431
+ converted['content'] = textParts.join('\n');
432
+ if (images.length > 0) {
433
+ converted['images'] = images;
434
+ }
435
+ } else {
436
+ converted['content'] = msg.content ?? '';
437
+ }
438
+
439
+ // Ollama needs tool call arguments as objects, not strings
440
+ if (msg.tool_calls?.length) {
441
+ converted['tool_calls'] = msg.tool_calls.map(tc => ({
442
+ ...tc,
443
+ function: {
444
+ ...tc.function,
445
+ arguments: typeof tc.function.arguments === 'string'
446
+ ? (() => { try { return JSON.parse(tc.function.arguments); } catch { return tc.function.arguments; } })()
447
+ : tc.function.arguments,
448
+ },
449
+ }));
450
+ }
451
+
452
+ // Preserve tool_call_id for tool result messages
453
+ if (msg.tool_call_id) {
454
+ converted['tool_call_id'] = msg.tool_call_id;
455
+ }
456
+
457
+ return converted;
458
+ });
459
+ }
460
+
461
+ private convertToolsToOllama(tools: LLMToolDefinition[]): unknown[] {
462
+ return tools.map(t => ({
463
+ type: 'function',
464
+ function: {
465
+ name: t.function.name,
466
+ description: t.function.description,
467
+ parameters: t.function.parameters,
468
+ },
469
+ }));
470
+ }
471
+
472
+ private buildOllamaOptions(options?: ChatOptions): Record<string, unknown> {
473
+ const params: Record<string, unknown> = {
474
+ ...this.options.defaultParameters,
475
+ ...options?.parameters,
476
+ };
477
+ if (options?.temperature !== undefined) params['temperature'] = options.temperature;
478
+ if (options?.maxTokens !== undefined) params['num_predict'] = options.maxTokens;
479
+ return params;
480
+ }
481
+
482
+ // ========================================================================
483
+ // Structured Output Helpers
484
+ // ========================================================================
485
+
486
+ /**
487
+ * Build Ollama format parameter from schema options.
488
+ * Ollama accepts:
489
+ * - format: "json" for simple JSON mode
490
+ * - format: { ...schema } for structured output with JSON Schema
491
+ */
492
+ private buildFormatParameter(options: { schemaConfig?: import('../structured-output.js').SchemaConfig<unknown>, jsonSchema?: import('../structured-output.js').JSONSchema }): string | import('../structured-output.js').JSONSchema {
493
+ if (options.jsonSchema) {
494
+ return normalizeJsonSchema(options.jsonSchema);
495
+ }
496
+
497
+ if (options.schemaConfig) {
498
+ return getJsonSchemaFromConfig(options.schemaConfig);
499
+ }
500
+
501
+ return 'json';
502
+ }
503
+ }