@openadapter/koda-ai 1.0.0-beta.3

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 (110) hide show
  1. package/README.md +1385 -0
  2. package/dist/api-registry.d.ts +19 -0
  3. package/dist/api-registry.js +1 -0
  4. package/dist/bedrock-provider.d.ts +4 -0
  5. package/dist/bedrock-provider.js +1 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +24 -0
  8. package/dist/env-api-keys.d.ts +17 -0
  9. package/dist/env-api-keys.js +1 -0
  10. package/dist/image-models.d.ts +9 -0
  11. package/dist/image-models.generated.d.ts +454 -0
  12. package/dist/image-models.generated.js +1 -0
  13. package/dist/image-models.js +1 -0
  14. package/dist/images-api-registry.d.ts +13 -0
  15. package/dist/images-api-registry.js +1 -0
  16. package/dist/images.d.ts +3 -0
  17. package/dist/images.js +1 -0
  18. package/dist/index.d.ts +31 -0
  19. package/dist/index.js +1 -0
  20. package/dist/models.d.ts +17 -0
  21. package/dist/models.generated.d.ts +18136 -0
  22. package/dist/models.generated.js +1 -0
  23. package/dist/models.js +1 -0
  24. package/dist/oauth.d.ts +1 -0
  25. package/dist/oauth.js +1 -0
  26. package/dist/providers/amazon-bedrock.d.ts +37 -0
  27. package/dist/providers/amazon-bedrock.js +1 -0
  28. package/dist/providers/anthropic.d.ts +70 -0
  29. package/dist/providers/anthropic.js +5 -0
  30. package/dist/providers/azure-openai-responses.d.ts +14 -0
  31. package/dist/providers/azure-openai-responses.js +1 -0
  32. package/dist/providers/cloudflare.d.ts +12 -0
  33. package/dist/providers/cloudflare.js +1 -0
  34. package/dist/providers/faux.d.ts +55 -0
  35. package/dist/providers/faux.js +6 -0
  36. package/dist/providers/github-copilot-headers.d.ts +7 -0
  37. package/dist/providers/github-copilot-headers.js +1 -0
  38. package/dist/providers/google-shared.d.ts +69 -0
  39. package/dist/providers/google-shared.js +2 -0
  40. package/dist/providers/google-vertex.d.ts +14 -0
  41. package/dist/providers/google-vertex.js +1 -0
  42. package/dist/providers/google.d.ts +12 -0
  43. package/dist/providers/google.js +1 -0
  44. package/dist/providers/images/openrouter.d.ts +2 -0
  45. package/dist/providers/images/openrouter.js +1 -0
  46. package/dist/providers/images/register-builtins.d.ts +3 -0
  47. package/dist/providers/images/register-builtins.js +1 -0
  48. package/dist/providers/mistral.d.ts +24 -0
  49. package/dist/providers/mistral.js +3 -0
  50. package/dist/providers/openai-codex-responses.d.ts +29 -0
  51. package/dist/providers/openai-codex-responses.js +7 -0
  52. package/dist/providers/openai-completions.d.ts +18 -0
  53. package/dist/providers/openai-completions.js +6 -0
  54. package/dist/providers/openai-prompt-cache.d.ts +2 -0
  55. package/dist/providers/openai-prompt-cache.js +1 -0
  56. package/dist/providers/openai-responses-shared.d.ts +17 -0
  57. package/dist/providers/openai-responses-shared.js +12 -0
  58. package/dist/providers/openai-responses.d.ts +12 -0
  59. package/dist/providers/openai-responses.js +1 -0
  60. package/dist/providers/register-builtins.d.ts +34 -0
  61. package/dist/providers/register-builtins.js +1 -0
  62. package/dist/providers/simple-options.d.ts +7 -0
  63. package/dist/providers/simple-options.js +1 -0
  64. package/dist/providers/transform-messages.d.ts +7 -0
  65. package/dist/providers/transform-messages.js +1 -0
  66. package/dist/session-resources.d.ts +3 -0
  67. package/dist/session-resources.js +1 -0
  68. package/dist/stream.d.ts +7 -0
  69. package/dist/stream.js +1 -0
  70. package/dist/types.d.ts +513 -0
  71. package/dist/types.js +0 -0
  72. package/dist/utils/abort-signals.d.ts +5 -0
  73. package/dist/utils/abort-signals.js +1 -0
  74. package/dist/utils/diagnostics.d.ts +18 -0
  75. package/dist/utils/diagnostics.js +1 -0
  76. package/dist/utils/event-stream.d.ts +20 -0
  77. package/dist/utils/event-stream.js +1 -0
  78. package/dist/utils/hash.d.ts +2 -0
  79. package/dist/utils/hash.js +1 -0
  80. package/dist/utils/headers.d.ts +1 -0
  81. package/dist/utils/headers.js +1 -0
  82. package/dist/utils/json-parse.d.ts +15 -0
  83. package/dist/utils/json-parse.js +2 -0
  84. package/dist/utils/node-http-proxy.d.ts +9 -0
  85. package/dist/utils/node-http-proxy.js +1 -0
  86. package/dist/utils/oauth/anthropic.d.ts +24 -0
  87. package/dist/utils/oauth/anthropic.js +1 -0
  88. package/dist/utils/oauth/device-code.d.ts +20 -0
  89. package/dist/utils/oauth/device-code.js +1 -0
  90. package/dist/utils/oauth/github-copilot.d.ts +29 -0
  91. package/dist/utils/oauth/github-copilot.js +1 -0
  92. package/dist/utils/oauth/index.d.ts +57 -0
  93. package/dist/utils/oauth/index.js +1 -0
  94. package/dist/utils/oauth/oauth-page.d.ts +2 -0
  95. package/dist/utils/oauth/oauth-page.js +74 -0
  96. package/dist/utils/oauth/openai-codex.d.ts +42 -0
  97. package/dist/utils/oauth/openai-codex.js +1 -0
  98. package/dist/utils/oauth/pkce.d.ts +12 -0
  99. package/dist/utils/oauth/pkce.js +1 -0
  100. package/dist/utils/oauth/types.d.ts +63 -0
  101. package/dist/utils/oauth/types.js +0 -0
  102. package/dist/utils/overflow.d.ts +56 -0
  103. package/dist/utils/overflow.js +1 -0
  104. package/dist/utils/sanitize-unicode.d.ts +21 -0
  105. package/dist/utils/sanitize-unicode.js +1 -0
  106. package/dist/utils/typebox-helpers.d.ts +16 -0
  107. package/dist/utils/typebox-helpers.js +1 -0
  108. package/dist/utils/validation.d.ts +17 -0
  109. package/dist/utils/validation.js +6 -0
  110. package/package.json +114 -0
package/README.md ADDED
@@ -0,0 +1,1385 @@
1
+ # @openadapter/koda-ai
2
+
3
+ Unified LLM API with automatic model discovery, provider configuration, token and cost tracking, and simple context persistence and hand-off to other models mid-session.
4
+
5
+ **Note**: This library only includes models that support tool calling (function calling), as this is essential for agentic workflows.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Supported Providers](#supported-providers)
10
+ - [Installation](#installation)
11
+ - [Quick Start](#quick-start)
12
+ - [Tools](#tools)
13
+ - [Defining Tools](#defining-tools)
14
+ - [Handling Tool Calls](#handling-tool-calls)
15
+ - [Streaming Tool Calls with Partial JSON](#streaming-tool-calls-with-partial-json)
16
+ - [Validating Tool Arguments](#validating-tool-arguments)
17
+ - [Complete Event Reference](#complete-event-reference)
18
+ - [Image Input](#image-input)
19
+ - [Image Generation](#image-generation)
20
+ - [Basic Image Generation](#basic-image-generation)
21
+ - [Notes and Limitations](#notes-and-limitations)
22
+ - [Thinking/Reasoning](#thinkingreasoning)
23
+ - [Unified Interface](#unified-interface-streamsimplecompletesimple)
24
+ - [Provider-Specific Options](#provider-specific-options-streamcomplete)
25
+ - [Streaming Thinking Content](#streaming-thinking-content)
26
+ - [Stop Reasons](#stop-reasons)
27
+ - [Error Handling](#error-handling)
28
+ - [Aborting Requests](#aborting-requests)
29
+ - [Continuing After Abort](#continuing-after-abort)
30
+ - [APIs, Models, and Providers](#apis-models-and-providers)
31
+ - [Providers and Models](#providers-and-models)
32
+ - [Querying Providers and Models](#querying-providers-and-models)
33
+ - [Custom Models](#custom-models)
34
+ - [OpenAI Compatibility Settings](#openai-compatibility-settings)
35
+ - [Type Safety](#type-safety)
36
+ - [Cross-Provider Handoffs](#cross-provider-handoffs)
37
+ - [Context Serialization](#context-serialization)
38
+ - [Browser Usage](#browser-usage)
39
+ - [Browser Compatibility Notes](#browser-compatibility-notes)
40
+ - [Environment Variables](#environment-variables-nodejs-only)
41
+ - [Checking Environment Variables](#checking-environment-variables)
42
+ - [OAuth Providers](#oauth-providers)
43
+ - [Vertex AI](#vertex-ai)
44
+ - [CLI Login](#cli-login)
45
+ - [Programmatic OAuth](#programmatic-oauth)
46
+ - [Login Flow Example](#login-flow-example)
47
+ - [Using OAuth Tokens](#using-oauth-tokens)
48
+ - [Provider Notes](#provider-notes)
49
+ - [License](#license)
50
+
51
+ ## Supported Providers
52
+
53
+ - **OpenAI**
54
+ - **Azure OpenAI (Responses)**
55
+ - **OpenAI Codex** (ChatGPT Plus/Pro subscription, requires OAuth, see below)
56
+ - **DeepSeek**
57
+ - **NVIDIA NIM**
58
+ - **Anthropic**
59
+ - **Google**
60
+ - **Vertex AI** (Gemini via Vertex AI)
61
+ - **Mistral**
62
+ - **Groq**
63
+ - **Cerebras**
64
+ - **Cloudflare AI Gateway**
65
+ - **Cloudflare Workers AI**
66
+ - **xAI**
67
+ - **OpenRouter**
68
+ - **Vercel AI Gateway**
69
+ - **MiniMax**
70
+ - **Together AI**
71
+ - **GitHub Copilot** (requires OAuth, see below)
72
+ - **Amazon Bedrock**
73
+ - **OpenCode Zen**
74
+ - **OpenCode Go**
75
+ - **Fireworks** (uses Anthropic-compatible API)
76
+ - **Kimi For Coding** (Moonshot AI, uses Anthropic-compatible API)
77
+ - **Xiaomi MiMo** (uses Anthropic-compatible API; defaults to API billing endpoint, with separate Token Plan providers for `cn`/`ams`/`sgp` regions)
78
+ - **Any OpenAI-compatible API**: Ollama, vLLM, LM Studio, etc.
79
+
80
+ ## Installation
81
+
82
+ ```bash
83
+ npm install @openadapter/koda-ai
84
+ ```
85
+
86
+ TypeBox exports are re-exported from `@openadapter/koda-ai`: `Type`, `Static`, and `TSchema`.
87
+
88
+ ## Quick Start
89
+
90
+ ```typescript
91
+ import { Type, getModel, stream, complete, Context, Tool, StringEnum } from '@openadapter/koda-ai';
92
+
93
+ // Fully typed with auto-complete support for both providers and models
94
+ const model = getModel('openai', 'gpt-4o-mini');
95
+
96
+ // Define tools with TypeBox schemas for type safety and validation
97
+ const tools: Tool[] = [{
98
+ name: 'get_time',
99
+ description: 'Get the current time',
100
+ parameters: Type.Object({
101
+ timezone: Type.Optional(Type.String({ description: 'Optional timezone (e.g., America/New_York)' }))
102
+ })
103
+ }];
104
+
105
+ // Build a conversation context (easily serializable and transferable between models)
106
+ const context: Context = {
107
+ systemPrompt: 'You are a helpful assistant.',
108
+ messages: [{ role: 'user', content: 'What time is it?' }],
109
+ tools
110
+ };
111
+
112
+ // Option 1: Streaming with all event types
113
+ const s = stream(model, context);
114
+
115
+ for await (const event of s) {
116
+ switch (event.type) {
117
+ case 'start':
118
+ console.log(`Starting with ${event.partial.model}`);
119
+ break;
120
+ case 'text_start':
121
+ console.log('\n[Text started]');
122
+ break;
123
+ case 'text_delta':
124
+ process.stdout.write(event.delta);
125
+ break;
126
+ case 'text_end':
127
+ console.log('\n[Text ended]');
128
+ break;
129
+ case 'thinking_start':
130
+ console.log('[Model is thinking...]');
131
+ break;
132
+ case 'thinking_delta':
133
+ process.stdout.write(event.delta);
134
+ break;
135
+ case 'thinking_end':
136
+ console.log('[Thinking complete]');
137
+ break;
138
+ case 'toolcall_start':
139
+ console.log(`\n[Tool call started: index ${event.contentIndex}]`);
140
+ break;
141
+ case 'toolcall_delta':
142
+ // Partial tool arguments are being streamed
143
+ const partialCall = event.partial.content[event.contentIndex];
144
+ if (partialCall.type === 'toolCall') {
145
+ console.log(`[Streaming args for ${partialCall.name}]`);
146
+ }
147
+ break;
148
+ case 'toolcall_end':
149
+ console.log(`\nTool called: ${event.toolCall.name}`);
150
+ console.log(`Arguments: ${JSON.stringify(event.toolCall.arguments)}`);
151
+ break;
152
+ case 'done':
153
+ console.log(`\nFinished: ${event.reason}`);
154
+ break;
155
+ case 'error':
156
+ console.error(`Error: ${event.error}`);
157
+ break;
158
+ }
159
+ }
160
+
161
+ // Get the final message after streaming, add it to the context
162
+ const finalMessage = await s.result();
163
+ context.messages.push(finalMessage);
164
+
165
+ // Handle tool calls if any
166
+ const toolCalls = finalMessage.content.filter(b => b.type === 'toolCall');
167
+ for (const call of toolCalls) {
168
+ // Execute the tool
169
+ const result = call.name === 'get_time'
170
+ ? new Date().toLocaleString('en-US', {
171
+ timeZone: call.arguments.timezone || 'UTC',
172
+ dateStyle: 'full',
173
+ timeStyle: 'long'
174
+ })
175
+ : 'Unknown tool';
176
+
177
+ // Add tool result to context (supports text and images)
178
+ context.messages.push({
179
+ role: 'toolResult',
180
+ toolCallId: call.id,
181
+ toolName: call.name,
182
+ content: [{ type: 'text', text: result }],
183
+ isError: false,
184
+ timestamp: Date.now()
185
+ });
186
+ }
187
+
188
+ // Continue if there were tool calls
189
+ if (toolCalls.length > 0) {
190
+ const continuation = await complete(model, context);
191
+ context.messages.push(continuation);
192
+ console.log('After tool execution:', continuation.content);
193
+ }
194
+
195
+ console.log(`Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`);
196
+ console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
197
+
198
+ // Option 2: Get complete response without streaming
199
+ const response = await complete(model, context);
200
+
201
+ for (const block of response.content) {
202
+ if (block.type === 'text') {
203
+ console.log(block.text);
204
+ } else if (block.type === 'toolCall') {
205
+ console.log(`Tool: ${block.name}(${JSON.stringify(block.arguments)})`);
206
+ }
207
+ }
208
+ ```
209
+
210
+ ## Tools
211
+
212
+ Tools enable LLMs to interact with external systems. This library uses TypeBox schemas for type-safe tool definitions with automatic validation using TypeBox's built-in validator and value conversion utilities. TypeBox schemas can be serialized and deserialized as plain JSON, making them ideal for distributed systems.
213
+
214
+ ### Defining Tools
215
+
216
+ ```typescript
217
+ import { Type, Tool, StringEnum } from '@openadapter/koda-ai';
218
+
219
+ // Define tool parameters with TypeBox
220
+ const weatherTool: Tool = {
221
+ name: 'get_weather',
222
+ description: 'Get current weather for a location',
223
+ parameters: Type.Object({
224
+ location: Type.String({ description: 'City name or coordinates' }),
225
+ units: StringEnum(['celsius', 'fahrenheit'], { default: 'celsius' })
226
+ })
227
+ };
228
+
229
+ // Note: For Google API compatibility, use StringEnum helper instead of Type.Enum
230
+ // Type.Enum generates anyOf/const patterns that Google doesn't support
231
+
232
+ const bookMeetingTool: Tool = {
233
+ name: 'book_meeting',
234
+ description: 'Schedule a meeting',
235
+ parameters: Type.Object({
236
+ title: Type.String({ minLength: 1 }),
237
+ startTime: Type.String({ format: 'date-time' }),
238
+ endTime: Type.String({ format: 'date-time' }),
239
+ attendees: Type.Array(Type.String({ format: 'email' }), { minItems: 1 })
240
+ })
241
+ };
242
+ ```
243
+
244
+ ### Handling Tool Calls
245
+
246
+ Tool results use content blocks and can include both text and images:
247
+
248
+ ```typescript
249
+ import { readFileSync } from 'fs';
250
+
251
+ const context: Context = {
252
+ messages: [{ role: 'user', content: 'What is the weather in London?' }],
253
+ tools: [weatherTool]
254
+ };
255
+
256
+ const response = await complete(model, context);
257
+
258
+ // Check for tool calls in the response
259
+ for (const block of response.content) {
260
+ if (block.type === 'toolCall') {
261
+ // Execute your tool with the arguments
262
+ // See "Validating Tool Arguments" section for validation
263
+ const result = await executeWeatherApi(block.arguments);
264
+
265
+ // Add tool result with text content
266
+ context.messages.push({
267
+ role: 'toolResult',
268
+ toolCallId: block.id,
269
+ toolName: block.name,
270
+ content: [{ type: 'text', text: JSON.stringify(result) }],
271
+ isError: false,
272
+ timestamp: Date.now()
273
+ });
274
+ }
275
+ }
276
+
277
+ // Tool results can also include images (for vision-capable models)
278
+ const imageBuffer = readFileSync('chart.png');
279
+ context.messages.push({
280
+ role: 'toolResult',
281
+ toolCallId: 'tool_xyz',
282
+ toolName: 'generate_chart',
283
+ content: [
284
+ { type: 'text', text: 'Generated chart showing temperature trends' },
285
+ { type: 'image', data: imageBuffer.toString('base64'), mimeType: 'image/png' }
286
+ ],
287
+ isError: false,
288
+ timestamp: Date.now()
289
+ });
290
+ ```
291
+
292
+ ### Streaming Tool Calls with Partial JSON
293
+
294
+ During streaming, tool call arguments are progressively parsed as they arrive. This enables real-time UI updates before the complete arguments are available:
295
+
296
+ ```typescript
297
+ const s = stream(model, context);
298
+
299
+ for await (const event of s) {
300
+ if (event.type === 'toolcall_delta') {
301
+ const toolCall = event.partial.content[event.contentIndex];
302
+
303
+ // toolCall.arguments contains partially parsed JSON during streaming
304
+ // This allows for progressive UI updates
305
+ if (toolCall.type === 'toolCall' && toolCall.arguments) {
306
+ // BE DEFENSIVE: arguments may be incomplete
307
+ // Example: Show file path being written even before content is complete
308
+ if (toolCall.name === 'write_file' && toolCall.arguments.path) {
309
+ console.log(`Writing to: ${toolCall.arguments.path}`);
310
+
311
+ // Content might be partial or missing
312
+ if (toolCall.arguments.content) {
313
+ console.log(`Content preview: ${toolCall.arguments.content.substring(0, 100)}...`);
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ if (event.type === 'toolcall_end') {
320
+ // Here toolCall.arguments is complete (but not yet validated)
321
+ const toolCall = event.toolCall;
322
+ console.log(`Tool completed: ${toolCall.name}`, toolCall.arguments);
323
+ }
324
+ }
325
+ ```
326
+
327
+ **Important notes about partial tool arguments:**
328
+ - During `toolcall_delta` events, `arguments` contains the best-effort parse of partial JSON
329
+ - Fields may be missing or incomplete - always check for existence before use
330
+ - String values may be truncated mid-word
331
+ - Arrays may be incomplete
332
+ - Nested objects may be partially populated
333
+ - At minimum, `arguments` will be an empty object `{}`, never `undefined`
334
+ - The Google provider does not support function call streaming. Instead, you will receive a single `toolcall_delta` event with the full arguments.
335
+
336
+ ### Validating Tool Arguments
337
+
338
+ When using `agentLoop`, tool arguments are automatically validated against your TypeBox schemas before execution. If validation fails, the error is returned to the model as a tool result, allowing it to retry.
339
+
340
+ When implementing your own tool execution loop with `stream()` or `complete()`, use `validateToolCall` to validate arguments before passing them to your tools:
341
+
342
+ ```typescript
343
+ import { stream, validateToolCall, Tool } from '@openadapter/koda-ai';
344
+
345
+ const tools: Tool[] = [weatherTool, calculatorTool];
346
+ const s = stream(model, { messages, tools });
347
+
348
+ for await (const event of s) {
349
+ if (event.type === 'toolcall_end') {
350
+ const toolCall = event.toolCall;
351
+
352
+ try {
353
+ // Validate arguments against the tool's schema (throws on invalid args)
354
+ const validatedArgs = validateToolCall(tools, toolCall);
355
+ const result = await executeMyTool(toolCall.name, validatedArgs);
356
+ // ... add tool result to context
357
+ } catch (error) {
358
+ // Validation failed - return error as tool result so model can retry
359
+ context.messages.push({
360
+ role: 'toolResult',
361
+ toolCallId: toolCall.id,
362
+ toolName: toolCall.name,
363
+ content: [{ type: 'text', text: error.message }],
364
+ isError: true,
365
+ timestamp: Date.now()
366
+ });
367
+ }
368
+ }
369
+ }
370
+ ```
371
+
372
+ ### Complete Event Reference
373
+
374
+ All streaming events emitted during assistant message generation:
375
+
376
+ | Event Type | Description | Key Properties |
377
+ |------------|-------------|----------------|
378
+ | `start` | Stream begins | `partial`: Initial assistant message structure |
379
+ | `text_start` | Text block starts | `contentIndex`: Position in content array |
380
+ | `text_delta` | Text chunk received | `delta`: New text, `contentIndex`: Position |
381
+ | `text_end` | Text block complete | `content`: Full text, `contentIndex`: Position |
382
+ | `thinking_start` | Thinking block starts | `contentIndex`: Position in content array |
383
+ | `thinking_delta` | Thinking chunk received | `delta`: New text, `contentIndex`: Position |
384
+ | `thinking_end` | Thinking block complete | `content`: Full thinking, `contentIndex`: Position |
385
+ | `toolcall_start` | Tool call begins | `contentIndex`: Position in content array |
386
+ | `toolcall_delta` | Tool arguments streaming | `delta`: JSON chunk, `partial.content[contentIndex].arguments`: Partial parsed args |
387
+ | `toolcall_end` | Tool call complete | `toolCall`: Complete validated tool call with `id`, `name`, `arguments` |
388
+ | `done` | Stream complete | `reason`: Stop reason ("stop", "length", "toolUse"), `message`: Final assistant message |
389
+ | `error` | Error occurred | `reason`: Error type ("error" or "aborted"), `error`: AssistantMessage with partial content |
390
+
391
+ Streaming events for different content blocks are not guaranteed to be contiguous. Providers may emit deltas for text, thinking, and tool calls in the same upstream chunk, and pi may surface corresponding events interleaved, for example `text_start`, `text_delta`, `toolcall_start`, `text_delta`, `toolcall_delta`. Consumers must use `contentIndex` to associate each delta/end event with its block and must not assume that a block's `*_start`/`*_delta`/`*_end` sequence is uninterrupted by events for other blocks.
392
+
393
+ ## Image Input
394
+
395
+ Models with vision capabilities can process images. You can check if a model supports images via the `input` property. If you pass images to a non-vision model, they are silently ignored.
396
+
397
+ ```typescript
398
+ import { readFileSync } from 'fs';
399
+ import { getModel, complete } from '@openadapter/koda-ai';
400
+
401
+ const model = getModel('openai', 'gpt-4o-mini');
402
+
403
+ // Check if model supports images
404
+ if (model.input.includes('image')) {
405
+ console.log('Model supports vision');
406
+ }
407
+
408
+ const imageBuffer = readFileSync('image.png');
409
+ const base64Image = imageBuffer.toString('base64');
410
+
411
+ const response = await complete(model, {
412
+ messages: [{
413
+ role: 'user',
414
+ content: [
415
+ { type: 'text', text: 'What is in this image?' },
416
+ { type: 'image', data: base64Image, mimeType: 'image/png' }
417
+ ]
418
+ }]
419
+ });
420
+
421
+ // Access the response
422
+ for (const block of response.content) {
423
+ if (block.type === 'text') {
424
+ console.log(block.text);
425
+ }
426
+ }
427
+ ```
428
+
429
+ ## Image Generation
430
+
431
+ Image generation uses a separate API surface from text/chat generation. Use `getImageModel()` / `getImageModels()` / `getImageProviders()` to discover image-generation models, and `generateImages()` to get the final result.
432
+
433
+ Do not use `stream()` or `complete()` for image generation. Image generation is a one-shot API: `generateImages()` waits for the provider response and returns the final `AssistantImages` result.
434
+
435
+ ### Basic Image Generation
436
+
437
+ ```typescript
438
+ import { getImageModel, generateImages } from '@mariozechner/pi-ai';
439
+
440
+ const model = getImageModel('openrouter', 'google/gemini-2.5-flash-image');
441
+
442
+ const result = await generateImages(model, {
443
+ input: [{ type: 'text', text: 'Generate a red circle on a plain white background.' }]
444
+ }, {
445
+ apiKey: process.env.OPENROUTER_API_KEY
446
+ });
447
+
448
+ for (const block of result.output) {
449
+ if (block.type === 'text') {
450
+ console.log(block.text);
451
+ } else if (block.type === 'image') {
452
+ console.log(block.mimeType);
453
+ console.log(block.data.substring(0, 32));
454
+ }
455
+ }
456
+ ```
457
+
458
+ Some models also support image input:
459
+
460
+ ```typescript
461
+ import { readFileSync } from 'fs';
462
+
463
+ const imageBuffer = readFileSync('input.png');
464
+ const result = await generateImages(model, {
465
+ input: [
466
+ { type: 'text', text: 'Create a variation of this image with a blue background.' },
467
+ { type: 'image', data: imageBuffer.toString('base64'), mimeType: 'image/png' }
468
+ ]
469
+ }, {
470
+ apiKey: process.env.OPENROUTER_API_KEY
471
+ });
472
+ ```
473
+
474
+ Check capabilities on the model metadata:
475
+
476
+ ```typescript
477
+ console.log(model.input); // ['text', 'image']
478
+ console.log(model.output); // ['image'] or ['image', 'text']
479
+ ```
480
+
481
+ ### Notes and Limitations
482
+
483
+ - Use `getImageModel(...)`, not `getModel(...)`.
484
+ - Use `generateImages()`, not `stream()` / `complete()`.
485
+ - Image-generation models do not participate in tool calling.
486
+ - Outputs are returned in `AssistantImages.output` and can include both base64-encoded `ImageContent` blocks and `TextContent` blocks.
487
+ - Some models return only images, others return images plus text. Check `model.output`.
488
+ - Some models accept image input, others are text-to-image only. Check `model.input`.
489
+ - Like the streaming APIs, image generation supports options such as `apiKey`, `signal`, `headers`, `onPayload`, and `onResponse`, and results may include `stopReason`, `responseId`, and `usage`.
490
+ - If you want a model to analyze images in a conversation or call tools, use the regular `stream()` / `complete()` APIs with a model that supports image input.
491
+ - At the moment, image generation is available through only one provider, OpenRouter.
492
+
493
+ ## Thinking/Reasoning
494
+
495
+ Many models support thinking/reasoning capabilities where they can show their internal thought process. You can check if a model supports reasoning via the `reasoning` property. If you pass reasoning options to a non-reasoning model, they are silently ignored.
496
+
497
+ ### Unified Interface (streamSimple/completeSimple)
498
+
499
+ ```typescript
500
+ import { getModel, streamSimple, completeSimple } from '@openadapter/koda-ai';
501
+
502
+ // Many models across providers support thinking/reasoning
503
+ const model = getModel('anthropic', 'claude-sonnet-4-20250514');
504
+ // or getModel('openai', 'gpt-5-mini');
505
+ // or getModel('google', 'gemini-2.5-flash');
506
+ // or getModel('xai', 'grok-code-fast-1');
507
+ // or getModel('groq', 'openai/gpt-oss-20b');
508
+ // or getModel('cerebras', 'gpt-oss-120b');
509
+ // or getModel('openrouter', 'z-ai/glm-4.5v');
510
+
511
+ // Check if model supports reasoning
512
+ if (model.reasoning) {
513
+ console.log('Model supports reasoning/thinking');
514
+ }
515
+
516
+ // Use the simplified reasoning option
517
+ const response = await completeSimple(model, {
518
+ messages: [{ role: 'user', content: 'Solve: 2x + 5 = 13' }]
519
+ }, {
520
+ reasoning: 'medium' // 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'
521
+ });
522
+
523
+ // Access thinking and text blocks
524
+ for (const block of response.content) {
525
+ if (block.type === 'thinking') {
526
+ console.log('Thinking:', block.thinking);
527
+ } else if (block.type === 'text') {
528
+ console.log('Response:', block.text);
529
+ }
530
+ }
531
+ ```
532
+
533
+ ### Provider-Specific Options (stream/complete)
534
+
535
+ For fine-grained control, use the provider-specific options:
536
+
537
+ ```typescript
538
+ import { getModel, complete } from '@openadapter/koda-ai';
539
+
540
+ // OpenAI Reasoning (o1, o3, gpt-5)
541
+ const openaiModel = getModel('openai', 'gpt-5-mini');
542
+ await complete(openaiModel, context, {
543
+ reasoningEffort: 'medium',
544
+ reasoningSummary: 'detailed' // OpenAI Responses API only
545
+ });
546
+
547
+ // Anthropic Thinking (Claude Sonnet 4)
548
+ const anthropicModel = getModel('anthropic', 'claude-sonnet-4-20250514');
549
+ await complete(anthropicModel, context, {
550
+ thinkingEnabled: true,
551
+ thinkingBudgetTokens: 8192 // Optional token limit
552
+ });
553
+
554
+ // Google Gemini Thinking
555
+ const googleModel = getModel('google', 'gemini-2.5-flash');
556
+ await complete(googleModel, context, {
557
+ thinking: {
558
+ enabled: true,
559
+ budgetTokens: 8192 // -1 for dynamic, 0 to disable
560
+ }
561
+ });
562
+ ```
563
+
564
+ ### Streaming Thinking Content
565
+
566
+ When streaming, thinking content is delivered through specific events:
567
+
568
+ ```typescript
569
+ const s = streamSimple(model, context, { reasoning: 'high' });
570
+
571
+ for await (const event of s) {
572
+ switch (event.type) {
573
+ case 'thinking_start':
574
+ console.log('[Model started thinking]');
575
+ break;
576
+ case 'thinking_delta':
577
+ process.stdout.write(event.delta); // Stream thinking content
578
+ break;
579
+ case 'thinking_end':
580
+ console.log('\n[Thinking complete]');
581
+ break;
582
+ }
583
+ }
584
+ ```
585
+
586
+ ## Stop Reasons
587
+
588
+ Every `AssistantMessage` includes a `stopReason` field that indicates how the generation ended:
589
+
590
+ - `"stop"` - Normal completion, the model finished its response
591
+ - `"length"` - Output hit the maximum token limit
592
+ - `"toolUse"` - Model is calling tools and expects tool results
593
+ - `"error"` - An error occurred during generation
594
+ - `"aborted"` - Request was cancelled via abort signal
595
+
596
+ `AssistantMessage` may also include `responseId`, a provider-specific upstream response or message identifier when the underlying API exposes one. Do not assume it is always present across providers.
597
+
598
+ ## Error Handling
599
+
600
+ When a request ends with an error (including aborts and tool call validation errors), the streaming API emits an error event:
601
+
602
+ ```typescript
603
+ // In streaming
604
+ for await (const event of stream) {
605
+ if (event.type === 'error') {
606
+ // event.reason is either "error" or "aborted"
607
+ // event.error is the AssistantMessage with partial content
608
+ console.error(`Error (${event.reason}):`, event.error.errorMessage);
609
+ console.log('Partial content:', event.error.content);
610
+ }
611
+ }
612
+
613
+ // The final message will have the error details
614
+ const message = await stream.result();
615
+ if (message.stopReason === 'error' || message.stopReason === 'aborted') {
616
+ console.error('Request failed:', message.errorMessage);
617
+ // message.content contains any partial content received before the error
618
+ // message.usage contains partial token counts and costs
619
+ }
620
+ ```
621
+
622
+ ### Aborting Requests
623
+
624
+ The abort signal allows you to cancel in-progress requests. Aborted requests have `stopReason === 'aborted'`:
625
+
626
+ ```typescript
627
+ import { getModel, stream } from '@openadapter/koda-ai';
628
+
629
+ const model = getModel('openai', 'gpt-4o-mini');
630
+ const controller = new AbortController();
631
+
632
+ // Abort after 2 seconds
633
+ setTimeout(() => controller.abort(), 2000);
634
+
635
+ const s = stream(model, {
636
+ messages: [{ role: 'user', content: 'Write a long story' }]
637
+ }, {
638
+ signal: controller.signal
639
+ });
640
+
641
+ for await (const event of s) {
642
+ if (event.type === 'text_delta') {
643
+ process.stdout.write(event.delta);
644
+ } else if (event.type === 'error') {
645
+ // event.reason tells you if it was "error" or "aborted"
646
+ console.log(`${event.reason === 'aborted' ? 'Aborted' : 'Error'}:`, event.error.errorMessage);
647
+ }
648
+ }
649
+
650
+ // Get results (may be partial if aborted)
651
+ const response = await s.result();
652
+ if (response.stopReason === 'aborted') {
653
+ console.log('Request was aborted:', response.errorMessage);
654
+ console.log('Partial content received:', response.content);
655
+ console.log('Tokens used:', response.usage);
656
+ }
657
+ ```
658
+
659
+ ### Continuing After Abort
660
+
661
+ Aborted messages can be added to the conversation context and continued in subsequent requests:
662
+
663
+ ```typescript
664
+ const context = {
665
+ messages: [
666
+ { role: 'user', content: 'Explain quantum computing in detail' }
667
+ ]
668
+ };
669
+
670
+ // First request gets aborted after 2 seconds
671
+ const controller1 = new AbortController();
672
+ setTimeout(() => controller1.abort(), 2000);
673
+
674
+ const partial = await complete(model, context, { signal: controller1.signal });
675
+
676
+ // Add the partial response to context
677
+ context.messages.push(partial);
678
+ context.messages.push({ role: 'user', content: 'Please continue' });
679
+
680
+ // Continue the conversation
681
+ const continuation = await complete(model, context);
682
+ ```
683
+
684
+ ### Debugging Provider Payloads
685
+
686
+ Use the `onPayload` callback to inspect the request payload sent to the provider. This is useful for debugging request formatting issues or provider validation errors.
687
+
688
+ ```typescript
689
+ const response = await complete(model, context, {
690
+ onPayload: (payload) => {
691
+ console.log('Provider payload:', JSON.stringify(payload, null, 2));
692
+ }
693
+ });
694
+ ```
695
+
696
+ The callback is supported by `stream`, `complete`, `streamSimple`, and `completeSimple`.
697
+
698
+ ## APIs, Models, and Providers
699
+
700
+ The library uses a registry of API implementations. Built-in APIs include:
701
+
702
+ - **`anthropic-messages`**: Anthropic Messages API (`streamAnthropic`, `AnthropicOptions`)
703
+ - **`google-generative-ai`**: Google Generative AI API (`streamGoogle`, `GoogleOptions`)
704
+ - **`google-vertex`**: Google Vertex AI API (`streamGoogleVertex`, `GoogleVertexOptions`)
705
+ - **`mistral-conversations`**: Mistral Conversations API (`streamMistral`, `MistralOptions`)
706
+ - **`openai-completions`**: OpenAI Chat Completions API (`streamOpenAICompletions`, `OpenAICompletionsOptions`)
707
+ - **`openai-responses`**: OpenAI Responses API (`streamOpenAIResponses`, `OpenAIResponsesOptions`)
708
+ - **`openai-codex-responses`**: OpenAI Codex Responses API (`streamOpenAICodexResponses`, `OpenAICodexResponsesOptions`)
709
+ - **`azure-openai-responses`**: Azure OpenAI Responses API (`streamAzureOpenAIResponses`, `AzureOpenAIResponsesOptions`)
710
+ - **`bedrock-converse-stream`**: Amazon Bedrock Converse API (`streamBedrock`, `BedrockOptions`)
711
+
712
+ ### Faux provider for tests
713
+
714
+ `registerFauxProvider()` registers a temporary in-memory provider for tests and demos. It is opt-in and not part of the built-in provider set.
715
+
716
+ ```typescript
717
+ import {
718
+ complete,
719
+ fauxAssistantMessage,
720
+ fauxText,
721
+ fauxThinking,
722
+ fauxToolCall,
723
+ registerFauxProvider,
724
+ stream,
725
+ } from '@openadapter/koda-ai';
726
+
727
+ const registration = registerFauxProvider({
728
+ tokensPerSecond: 50 // optional
729
+ });
730
+
731
+ const model = registration.getModel();
732
+ const context = {
733
+ messages: [{ role: 'user', content: 'Summarize package.json and then call echo', timestamp: Date.now() }]
734
+ };
735
+
736
+ registration.setResponses([
737
+ fauxAssistantMessage([
738
+ fauxThinking('Need to inspect package metadata first.'),
739
+ fauxToolCall('echo', { text: 'package.json' })
740
+ ], { stopReason: 'toolUse' })
741
+ ]);
742
+
743
+ const first = await complete(model, context, {
744
+ sessionId: 'session-1',
745
+ cacheRetention: 'short'
746
+ });
747
+ context.messages.push(first);
748
+
749
+ context.messages.push({
750
+ role: 'toolResult',
751
+ toolCallId: first.content.find((block) => block.type === 'toolCall')!.id,
752
+ toolName: 'echo',
753
+ content: [{ type: 'text', text: 'package.json contents here' }],
754
+ isError: false,
755
+ timestamp: Date.now()
756
+ });
757
+
758
+ registration.setResponses([
759
+ fauxAssistantMessage([
760
+ fauxThinking('Now I can summarize the tool output.'),
761
+ fauxText('Here is the summary.')
762
+ ])
763
+ ]);
764
+
765
+ const s = stream(model, context);
766
+ for await (const event of s) {
767
+ console.log(event.type);
768
+ }
769
+
770
+ // Optional: register multiple faux models for model-switching tests
771
+ const multiModel = registerFauxProvider({
772
+ models: [
773
+ { id: 'faux-fast', reasoning: false },
774
+ { id: 'faux-thinker', reasoning: true }
775
+ ]
776
+ });
777
+ const thinker = multiModel.getModel('faux-thinker');
778
+
779
+ console.log(thinker?.reasoning);
780
+ console.log(registration.getPendingResponseCount());
781
+ console.log(registration.state.callCount);
782
+ registration.unregister();
783
+ multiModel.unregister();
784
+ ```
785
+
786
+ Notes:
787
+ - Responses are consumed from a queue in request start order.
788
+ - If the queue is empty, the faux provider returns an assistant error message with `errorMessage: "No more faux responses queued"`.
789
+ - Use `registration.setResponses([...])` to replace the remaining queue and `registration.appendResponses([...])` to add more responses.
790
+ - `registration.models` exposes all registered faux models. `registration.getModel()` returns the first one, and `registration.getModel(id)` returns a specific one.
791
+ - Use `fauxAssistantMessage(...)` for scripted assistant replies. Use `fauxText(...)`, `fauxThinking(...)`, and `fauxToolCall(...)` to build content blocks without filling in low-level fields manually.
792
+ - `registration.unregister()` removes the temporary provider from the global API registry.
793
+ - Usage is estimated at roughly 1 token per 4 characters. When `sessionId` is present and `cacheRetention` is not `"none"`, prompt cache reads and writes are simulated automatically.
794
+ - Tool call arguments stream incrementally via `toolcall_delta` chunks.
795
+ - By default, each streamed chunk is emitted on its own microtask. Set `tokensPerSecond` to pace chunk delivery in real time.
796
+ - The intended use is one deterministic scripted flow per registration. If you need independent concurrent flows, register separate faux providers.
797
+
798
+ ### Providers and Models
799
+
800
+ A **provider** offers models through a specific API. For example:
801
+ - **Anthropic** models use the `anthropic-messages` API
802
+ - **Google** models use the `google-generative-ai` API
803
+ - **OpenAI** models use the `openai-responses` API
804
+ - **Mistral** models use the `mistral-conversations` API
805
+ - **xAI, Cerebras, Groq, NVIDIA NIM, Together AI, etc.** models use the `openai-completions` API (OpenAI-compatible)
806
+
807
+ ### Querying Providers and Models
808
+
809
+ ```typescript
810
+ import { getProviders, getModels, getModel } from '@openadapter/koda-ai';
811
+
812
+ // Get all available providers
813
+ const providers = getProviders();
814
+ console.log(providers); // ['openai', 'anthropic', 'google', 'xai', 'groq', ...]
815
+
816
+ // Get all models from a provider (fully typed)
817
+ const anthropicModels = getModels('anthropic');
818
+ for (const model of anthropicModels) {
819
+ console.log(`${model.id}: ${model.name}`);
820
+ console.log(` API: ${model.api}`); // 'anthropic-messages'
821
+ console.log(` Context: ${model.contextWindow} tokens`);
822
+ console.log(` Vision: ${model.input.includes('image')}`);
823
+ console.log(` Reasoning: ${model.reasoning}`);
824
+ }
825
+
826
+ // Get a specific model (both provider and model ID are auto-completed in IDEs)
827
+ const model = getModel('openai', 'gpt-4o-mini');
828
+ console.log(`Using ${model.name} via ${model.api} API`);
829
+ ```
830
+
831
+ ### Custom Models
832
+
833
+ You can create custom models for local inference servers or custom endpoints:
834
+
835
+ ```typescript
836
+ import { Model, stream } from '@openadapter/koda-ai';
837
+
838
+ // Example: Ollama using OpenAI-compatible API
839
+ const ollamaModel: Model<'openai-completions'> = {
840
+ id: 'llama-3.1-8b',
841
+ name: 'Llama 3.1 8B (Ollama)',
842
+ api: 'openai-completions',
843
+ provider: 'ollama',
844
+ baseUrl: 'http://localhost:11434/v1',
845
+ reasoning: false,
846
+ input: ['text'],
847
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
848
+ contextWindow: 128000,
849
+ maxTokens: 32000
850
+ };
851
+
852
+ // Example: LiteLLM proxy with explicit compat settings
853
+ const litellmModel: Model<'openai-completions'> = {
854
+ id: 'gpt-4o',
855
+ name: 'GPT-4o (via LiteLLM)',
856
+ api: 'openai-completions',
857
+ provider: 'litellm',
858
+ baseUrl: 'http://localhost:4000/v1',
859
+ reasoning: false,
860
+ input: ['text', 'image'],
861
+ cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 },
862
+ contextWindow: 128000,
863
+ maxTokens: 16384,
864
+ compat: {
865
+ supportsStore: false, // LiteLLM doesn't support the store field
866
+ }
867
+ };
868
+
869
+ // Example: Custom endpoint with headers (bypassing Cloudflare bot detection)
870
+ const proxyModel: Model<'anthropic-messages'> = {
871
+ id: 'claude-sonnet-4',
872
+ name: 'Claude Sonnet 4 (Proxied)',
873
+ api: 'anthropic-messages',
874
+ provider: 'custom-proxy',
875
+ baseUrl: 'https://proxy.example.com/v1',
876
+ reasoning: true,
877
+ input: ['text', 'image'],
878
+ cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
879
+ contextWindow: 200000,
880
+ maxTokens: 8192,
881
+ headers: {
882
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
883
+ 'X-Custom-Auth': 'bearer-token-here'
884
+ }
885
+ };
886
+
887
+ // Use the custom model
888
+ const response = await stream(ollamaModel, context, {
889
+ apiKey: 'dummy' // Ollama doesn't need a real key
890
+ });
891
+ ```
892
+
893
+ Some OpenAI-compatible servers do not understand the `developer` role used for reasoning-capable models. For those providers, set `compat.supportsDeveloperRole` to `false` so the system prompt is sent as a `system` message instead. If the server also does not support `reasoning_effort`, set `compat.supportsReasoningEffort` to `false` too.
894
+
895
+ Use model-level `thinkingLevelMap` to describe model-specific thinking controls. Keys are pi thinking levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`). Missing keys use provider defaults, string values are sent to the provider, and `null` marks a level unsupported.
896
+
897
+ This commonly applies to Ollama, vLLM, SGLang, and similar OpenAI-compatible servers. You can set `compat` at the provider level or per model.
898
+
899
+ ```typescript
900
+ const ollamaReasoningModel: Model<'openai-completions'> = {
901
+ id: 'gpt-oss:20b',
902
+ name: 'GPT-OSS 20B (Ollama)',
903
+ api: 'openai-completions',
904
+ provider: 'ollama',
905
+ baseUrl: 'http://localhost:11434/v1',
906
+ reasoning: true,
907
+ input: ['text'],
908
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
909
+ contextWindow: 131072,
910
+ maxTokens: 32000,
911
+ thinkingLevelMap: {
912
+ minimal: null,
913
+ low: null,
914
+ medium: null,
915
+ high: 'high',
916
+ xhigh: null,
917
+ },
918
+ compat: {
919
+ supportsDeveloperRole: false,
920
+ supportsReasoningEffort: false,
921
+ }
922
+ };
923
+ ```
924
+
925
+ ### OpenAI Compatibility Settings
926
+
927
+ The `openai-completions` API is implemented by many providers with minor differences. By default, the library auto-detects compatibility settings based on `baseUrl` for a small set of known OpenAI-compatible providers (Cerebras, xAI, Chutes, DeepSeek, NVIDIA NIM, Together AI, zAi, OpenCode, Cloudflare Workers AI, etc.). For custom proxies or unknown endpoints, you can override these settings via the `compat` field. For `openai-responses` models, the compat field only supports Responses-specific flags.
928
+
929
+ ```typescript
930
+ interface OpenAICompletionsCompat {
931
+ supportsStore?: boolean; // Whether provider supports the `store` field (default: true)
932
+ supportsDeveloperRole?: boolean; // Whether provider supports `developer` role vs `system` (default: true)
933
+ supportsReasoningEffort?: boolean; // Whether provider supports `reasoning_effort` (default: true)
934
+ supportsUsageInStreaming?: boolean; // Whether provider supports `stream_options: { include_usage: true }` (default: true)
935
+ supportsStrictMode?: boolean; // Whether provider supports `strict` in tool definitions (default: true)
936
+ sendSessionAffinityHeaders?: boolean; // Whether to send `session_id`, `x-client-request-id`, and `x-session-affinity` from `sessionId` when caching is enabled (default: false)
937
+ maxTokensField?: 'max_completion_tokens' | 'max_tokens'; // Which field name to use (default: max_completion_tokens)
938
+ requiresToolResultName?: boolean; // Whether tool results require the `name` field (default: false)
939
+ requiresAssistantAfterToolResult?: boolean; // Whether tool results must be followed by an assistant message (default: false)
940
+ requiresThinkingAsText?: boolean; // Whether thinking blocks must be converted to text (default: false)
941
+ requiresReasoningContentOnAssistantMessages?: boolean; // Whether all replayed assistant messages must include empty reasoning_content when reasoning is enabled (default: auto-detected for DeepSeek)
942
+ thinkingFormat?: 'openai' | 'openrouter' | 'deepseek' | 'together' | 'zai' | 'qwen' | 'qwen-chat-template'; // Format for reasoning param: 'openai' uses reasoning_effort, 'openrouter' uses reasoning: { effort }, 'deepseek' uses thinking: { type } plus reasoning_effort when supported, 'together' uses reasoning: { enabled } plus reasoning_effort when supported, 'zai' uses enable_thinking, 'qwen' uses enable_thinking, 'qwen-chat-template' uses chat_template_kwargs.enable_thinking (default: openai)
943
+ cacheControlFormat?: 'anthropic'; // Anthropic-style cache_control on system prompt, last tool, and last user/assistant text content
944
+ openRouterRouting?: OpenRouterRouting; // OpenRouter routing preferences (default: {})
945
+ vercelGatewayRouting?: VercelGatewayRouting; // Vercel AI Gateway routing preferences (default: {})
946
+ }
947
+
948
+ interface OpenAIResponsesCompat {
949
+ // Reserved for future use
950
+ }
951
+ ```
952
+
953
+ If `compat` is not set, the library falls back to URL-based detection. If `compat` is partially set, unspecified fields use the detected defaults. This is useful for:
954
+
955
+ - **LiteLLM proxies**: May not support `store` field
956
+ - **Custom inference servers**: May use non-standard field names
957
+ - **Self-hosted endpoints**: May have different feature support
958
+
959
+ ### Type Safety
960
+
961
+ Models are typed by their API, which keeps the model metadata accurate. Provider-specific option types are enforced when you call the provider functions directly. The generic `stream` and `complete` functions accept `StreamOptions` with additional provider fields.
962
+
963
+ ```typescript
964
+ import { streamAnthropic, type AnthropicOptions } from '@openadapter/koda-ai';
965
+
966
+ // TypeScript knows this is an Anthropic model
967
+ const claude = getModel('anthropic', 'claude-sonnet-4-20250514');
968
+
969
+ const options: AnthropicOptions = {
970
+ thinkingEnabled: true,
971
+ thinkingBudgetTokens: 2048
972
+ };
973
+
974
+ await streamAnthropic(claude, context, options);
975
+ ```
976
+
977
+ ## Cross-Provider Handoffs
978
+
979
+ The library supports seamless handoffs between different LLM providers within the same conversation. This allows you to switch models mid-conversation while preserving context, including thinking blocks, tool calls, and tool results.
980
+
981
+ ### How It Works
982
+
983
+ When messages from one provider are sent to a different provider, the library automatically transforms them for compatibility:
984
+
985
+ - **User and tool result messages** are passed through unchanged
986
+ - **Assistant messages from the same provider/API** are preserved as-is
987
+ - **Assistant messages from different providers** have their thinking blocks converted to text with `<thinking>` tags
988
+ - **Tool calls and regular text** are preserved unchanged
989
+
990
+ ### Example: Multi-Provider Conversation
991
+
992
+ ```typescript
993
+ import { getModel, complete, Context } from '@openadapter/koda-ai';
994
+
995
+ // Start with Claude
996
+ const claude = getModel('anthropic', 'claude-sonnet-4-20250514');
997
+ const context: Context = {
998
+ messages: []
999
+ };
1000
+
1001
+ context.messages.push({ role: 'user', content: 'What is 25 * 18?' });
1002
+ const claudeResponse = await complete(claude, context, {
1003
+ thinkingEnabled: true
1004
+ });
1005
+ context.messages.push(claudeResponse);
1006
+
1007
+ // Switch to GPT-5 - it will see Claude's thinking as <thinking> tagged text
1008
+ const gpt5 = getModel('openai', 'gpt-5-mini');
1009
+ context.messages.push({ role: 'user', content: 'Is that calculation correct?' });
1010
+ const gptResponse = await complete(gpt5, context);
1011
+ context.messages.push(gptResponse);
1012
+
1013
+ // Switch to Gemini
1014
+ const gemini = getModel('google', 'gemini-2.5-flash');
1015
+ context.messages.push({ role: 'user', content: 'What was the original question?' });
1016
+ const geminiResponse = await complete(gemini, context);
1017
+ ```
1018
+
1019
+ ### Provider Compatibility
1020
+
1021
+ All providers can handle messages from other providers, including:
1022
+ - Text content
1023
+ - Tool calls and tool results (including images in tool results)
1024
+ - Thinking/reasoning blocks (transformed to tagged text for cross-provider compatibility)
1025
+ - Aborted messages with partial content
1026
+
1027
+ This enables flexible workflows where you can:
1028
+ - Start with a fast model for initial responses
1029
+ - Switch to a more capable model for complex reasoning
1030
+ - Use specialized models for specific tasks
1031
+ - Maintain conversation continuity across provider outages
1032
+
1033
+ ## Context Serialization
1034
+
1035
+ The `Context` object can be easily serialized and deserialized using standard JSON methods, making it simple to persist conversations, implement chat history, or transfer contexts between services:
1036
+
1037
+ ```typescript
1038
+ import { Context, getModel, complete } from '@openadapter/koda-ai';
1039
+
1040
+ // Create and use a context
1041
+ const context: Context = {
1042
+ systemPrompt: 'You are a helpful assistant.',
1043
+ messages: [
1044
+ { role: 'user', content: 'What is TypeScript?' }
1045
+ ]
1046
+ };
1047
+
1048
+ const model = getModel('openai', 'gpt-4o-mini');
1049
+ const response = await complete(model, context);
1050
+ context.messages.push(response);
1051
+
1052
+ // Serialize the entire context
1053
+ const serialized = JSON.stringify(context);
1054
+ console.log('Serialized context size:', serialized.length, 'bytes');
1055
+
1056
+ // Save to database, localStorage, file, etc.
1057
+ localStorage.setItem('conversation', serialized);
1058
+
1059
+ // Later: deserialize and continue the conversation
1060
+ const restored: Context = JSON.parse(localStorage.getItem('conversation')!);
1061
+ restored.messages.push({ role: 'user', content: 'Tell me more about its type system' });
1062
+
1063
+ // Continue with any model
1064
+ const newModel = getModel('anthropic', 'claude-3-5-haiku-20241022');
1065
+ const continuation = await complete(newModel, restored);
1066
+ ```
1067
+
1068
+ > **Note**: If the context contains images (encoded as base64 as shown in the Image Input section), those will also be serialized.
1069
+
1070
+ ## Browser Usage
1071
+
1072
+ The library supports browser environments. You must pass the API key explicitly since environment variables are not available in browsers:
1073
+
1074
+ ```typescript
1075
+ import { getModel, complete } from '@openadapter/koda-ai';
1076
+
1077
+ // API key must be passed explicitly in browser
1078
+ const model = getModel('anthropic', 'claude-3-5-haiku-20241022');
1079
+
1080
+ const response = await complete(model, {
1081
+ messages: [{ role: 'user', content: 'Hello!' }]
1082
+ }, {
1083
+ apiKey: 'your-api-key'
1084
+ });
1085
+ ```
1086
+
1087
+ > **Security Warning**: Exposing API keys in frontend code is dangerous. Anyone can extract and abuse your keys. Only use this approach for internal tools or demos. For production applications, use a backend proxy that keeps your API keys secure.
1088
+
1089
+ ### Browser Compatibility Notes
1090
+
1091
+ - Amazon Bedrock (`bedrock-converse-stream`) is not supported in browser environments.
1092
+ - OAuth login flows are not supported in browser environments. Use the `@openadapter/koda-ai/oauth` entry point in Node.js.
1093
+ - In browser builds, Bedrock can still appear in model lists. Calls to Bedrock models fail at runtime.
1094
+ - Use a server-side proxy or backend service if you need Bedrock or OAuth-based auth from a web app.
1095
+
1096
+ ### Environment Variables (Node.js only)
1097
+
1098
+ In Node.js environments, you can set environment variables to avoid passing API keys:
1099
+
1100
+ | Provider | Environment Variable(s) |
1101
+ |----------|------------------------|
1102
+ | OpenAI | `OPENAI_API_KEY` |
1103
+ | Azure OpenAI | `AZURE_OPENAI_API_KEY` + `AZURE_OPENAI_BASE_URL` (e.g. `https://{resource}.openai.azure.com`) or `AZURE_OPENAI_RESOURCE_NAME`. Supports `*.openai.azure.com` and `*.cognitiveservices.azure.com`; root endpoints auto-normalize to `/openai/v1`. Optional: `AZURE_OPENAI_API_VERSION` (default `v1`), `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`. |
1104
+ | Anthropic | `ANTHROPIC_API_KEY` or `ANTHROPIC_OAUTH_TOKEN` |
1105
+ | DeepSeek | `DEEPSEEK_API_KEY` |
1106
+ | NVIDIA NIM | `NVIDIA_API_KEY` |
1107
+ | Google | `GEMINI_API_KEY` |
1108
+ | Vertex AI | `GOOGLE_CLOUD_API_KEY` or `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) + `GOOGLE_CLOUD_LOCATION` + ADC |
1109
+ | Mistral | `MISTRAL_API_KEY` |
1110
+ | Groq | `GROQ_API_KEY` |
1111
+ | Cerebras | `CEREBRAS_API_KEY` |
1112
+ | Cloudflare AI Gateway | `CLOUDFLARE_API_KEY` + `CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_GATEWAY_ID` |
1113
+ | Cloudflare Workers AI | `CLOUDFLARE_API_KEY` + `CLOUDFLARE_ACCOUNT_ID` |
1114
+ | xAI | `XAI_API_KEY` |
1115
+ | Fireworks | `FIREWORKS_API_KEY` |
1116
+ | Together AI | `TOGETHER_API_KEY` |
1117
+ | OpenRouter | `OPENROUTER_API_KEY` |
1118
+ | Vercel AI Gateway | `AI_GATEWAY_API_KEY` |
1119
+ | zAI | `ZAI_API_KEY` |
1120
+ | MiniMax | `MINIMAX_API_KEY` |
1121
+ | OpenCode Zen / OpenCode Go | `OPENCODE_API_KEY` |
1122
+ | Kimi For Coding | `KIMI_API_KEY` |
1123
+ | Xiaomi MiMo (API billing) | `XIAOMI_API_KEY` |
1124
+ | Xiaomi MiMo Token Plan (China) | `XIAOMI_TOKEN_PLAN_CN_API_KEY` |
1125
+ | Xiaomi MiMo Token Plan (Amsterdam) | `XIAOMI_TOKEN_PLAN_AMS_API_KEY` |
1126
+ | Xiaomi MiMo Token Plan (Singapore) | `XIAOMI_TOKEN_PLAN_SGP_API_KEY` |
1127
+ | GitHub Copilot | `COPILOT_GITHUB_TOKEN` |
1128
+
1129
+ When set, the library automatically uses these keys:
1130
+
1131
+ ```typescript
1132
+ // Uses OPENAI_API_KEY from environment
1133
+ const model = getModel('openai', 'gpt-4o-mini');
1134
+ const response = await complete(model, context);
1135
+
1136
+ // Or override with explicit key
1137
+ const response = await complete(model, context, {
1138
+ apiKey: 'sk-different-key'
1139
+ });
1140
+ ```
1141
+
1142
+ ### Checking Environment Variables
1143
+
1144
+ ```typescript
1145
+ import { getEnvApiKey } from '@openadapter/koda-ai';
1146
+
1147
+ // Check if an API key is set in environment variables
1148
+ const key = getEnvApiKey('openai'); // checks OPENAI_API_KEY
1149
+ ```
1150
+
1151
+ ## OAuth Providers
1152
+
1153
+ Several providers require OAuth authentication instead of static API keys:
1154
+
1155
+ - **Anthropic** (Claude Pro/Max subscription)
1156
+ - **OpenAI Codex** (ChatGPT Plus/Pro subscription, access to GPT-5.x Codex models)
1157
+ - **GitHub Copilot** (Copilot subscription)
1158
+
1159
+ For paid Cloud Code Assist subscriptions, set `GOOGLE_CLOUD_PROJECT` or `GOOGLE_CLOUD_PROJECT_ID` to your project ID.
1160
+
1161
+ ### Vertex AI
1162
+
1163
+ Vertex AI models support either a Google Cloud API key or Application Default Credentials (ADC):
1164
+
1165
+ - **API key**: Set `GOOGLE_CLOUD_API_KEY` or pass `apiKey` in the call options.
1166
+ - **Local development (ADC)**: Run `gcloud auth application-default login`
1167
+ - **CI/Production (ADC)**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to a service account JSON key file
1168
+
1169
+ When using ADC, also set `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) and `GOOGLE_CLOUD_LOCATION`. You can also pass `project`/`location` in the call options. When using `GOOGLE_CLOUD_API_KEY`, `project` and `location` are not required.
1170
+
1171
+ Example:
1172
+
1173
+ ```bash
1174
+ # Local (uses your user credentials)
1175
+ gcloud auth application-default login
1176
+ export GOOGLE_CLOUD_PROJECT="my-project"
1177
+ export GOOGLE_CLOUD_LOCATION="us-central1"
1178
+
1179
+ # CI/Production (service account key file)
1180
+ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
1181
+ ```
1182
+
1183
+ ```typescript
1184
+ import { getModel, complete } from '@openadapter/koda-ai';
1185
+
1186
+ (async () => {
1187
+ const model = getModel('google-vertex', 'gemini-2.5-flash');
1188
+ const response = await complete(model, {
1189
+ messages: [{ role: 'user', content: 'Hello from Vertex AI' }]
1190
+ }, {
1191
+ apiKey: process.env.GOOGLE_CLOUD_API_KEY,
1192
+ });
1193
+
1194
+ for (const block of response.content) {
1195
+ if (block.type === 'text') console.log(block.text);
1196
+ }
1197
+ })().catch(console.error);
1198
+ ```
1199
+
1200
+ Official docs: [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials)
1201
+
1202
+ ### CLI Login
1203
+
1204
+ The quickest way to authenticate:
1205
+
1206
+ ```bash
1207
+ npx @openadapter/koda-ai login # interactive provider selection
1208
+ npx @openadapter/koda-ai login anthropic # login to specific provider
1209
+ npx @openadapter/koda-ai list # list available providers
1210
+ ```
1211
+
1212
+ Credentials are saved to `auth.json` in the current directory.
1213
+
1214
+ ### Programmatic OAuth
1215
+
1216
+ The library provides login and token refresh functions via the `@openadapter/koda-ai/oauth` entry point. Credential storage is the caller's responsibility.
1217
+
1218
+ ```typescript
1219
+ import {
1220
+ // Login functions (return credentials, do not store)
1221
+ loginAnthropic,
1222
+ loginOpenAICodex,
1223
+ loginGitHubCopilot,
1224
+ loginGeminiCli,
1225
+
1226
+ // Token management
1227
+ refreshOAuthToken, // (provider, credentials) => new credentials
1228
+ getOAuthApiKey, // (provider, credentialsMap) => { newCredentials, apiKey } | null
1229
+
1230
+ // Types
1231
+ type OAuthProvider,
1232
+ type OAuthCredentials,
1233
+ } from '@openadapter/koda-ai/oauth';
1234
+ ```
1235
+
1236
+ ### Login Flow Example
1237
+
1238
+ ```typescript
1239
+ import { loginGitHubCopilot } from '@openadapter/koda-ai/oauth';
1240
+ import { writeFileSync } from 'fs';
1241
+
1242
+ const credentials = await loginGitHubCopilot({
1243
+ onAuth: (url, instructions) => {
1244
+ console.log(`Open: ${url}`);
1245
+ if (instructions) console.log(instructions);
1246
+ },
1247
+ onPrompt: async (prompt) => {
1248
+ return await getUserInput(prompt.message);
1249
+ },
1250
+ onProgress: (message) => console.log(message)
1251
+ });
1252
+
1253
+ // Store credentials yourself
1254
+ const auth = { 'github-copilot': { type: 'oauth', ...credentials } };
1255
+ writeFileSync('auth.json', JSON.stringify(auth, null, 2));
1256
+ ```
1257
+
1258
+ ### Using OAuth Tokens
1259
+
1260
+ Use `getOAuthApiKey()` to get an API key, automatically refreshing if expired:
1261
+
1262
+ ```typescript
1263
+ import { getModel, complete } from '@openadapter/koda-ai';
1264
+ import { getOAuthApiKey } from '@openadapter/koda-ai/oauth';
1265
+ import { readFileSync, writeFileSync } from 'fs';
1266
+
1267
+ // Load your stored credentials
1268
+ const auth = JSON.parse(readFileSync('auth.json', 'utf-8'));
1269
+
1270
+ // Get API key (refreshes if expired)
1271
+ const result = await getOAuthApiKey('github-copilot', auth);
1272
+ if (!result) throw new Error('Not logged in');
1273
+
1274
+ // Save refreshed credentials
1275
+ auth['github-copilot'] = { type: 'oauth', ...result.newCredentials };
1276
+ writeFileSync('auth.json', JSON.stringify(auth, null, 2));
1277
+
1278
+ // Use the API key
1279
+ const model = getModel('github-copilot', 'gpt-4o');
1280
+ const response = await complete(model, {
1281
+ messages: [{ role: 'user', content: 'Hello!' }]
1282
+ }, { apiKey: result.apiKey });
1283
+ ```
1284
+
1285
+ ### Provider Notes
1286
+
1287
+ **OpenAI Codex**: Requires a ChatGPT Plus or Pro subscription. Provides access to GPT-5.x Codex models with extended context windows and reasoning capabilities. The library automatically handles session-based prompt caching when `sessionId` is provided in stream options. You can set `transport` in stream options to `"sse"`, `"websocket"`, or `"auto"` for Codex Responses transport selection. When using WebSocket with a `sessionId`, connections are reused per session and expire after 5 minutes of inactivity.
1288
+
1289
+ **Azure OpenAI (Responses)**: Uses the Responses API only. Set `AZURE_OPENAI_API_KEY` and either `AZURE_OPENAI_BASE_URL` or `AZURE_OPENAI_RESOURCE_NAME`. `AZURE_OPENAI_BASE_URL` supports both `https://<resource>.openai.azure.com` and `https://<resource>.cognitiveservices.azure.com`; root endpoints are normalized to `.../openai/v1` automatically. Use `AZURE_OPENAI_API_VERSION` (defaults to `v1`) to override the API version if needed. Deployment names are treated as model IDs by default, override with `azureDeploymentName` or `AZURE_OPENAI_DEPLOYMENT_NAME_MAP` using comma-separated `model-id=deployment` pairs (for example `gpt-4o-mini=my-deployment,gpt-4o=prod`). Legacy deployment-based URLs are intentionally unsupported.
1290
+
1291
+ **GitHub Copilot**: If you get "The requested model is not supported" error, enable the model manually in VS Code: open Copilot Chat, click the model selector, select the model (warning icon), and click "Enable".
1292
+
1293
+ ## Development
1294
+
1295
+ ### Adding a New Provider
1296
+
1297
+ Adding a new LLM provider requires changes across multiple files. This checklist covers all necessary steps:
1298
+
1299
+ #### 1. Core Types (`src/types.ts`)
1300
+
1301
+ - Add the API identifier to `KnownApi` (for example `"bedrock-converse-stream"`)
1302
+ - Create an options interface extending `StreamOptions` (for example `BedrockOptions`)
1303
+ - Add the provider name to `KnownProvider` (for example `"amazon-bedrock"`)
1304
+
1305
+ #### 2. Provider Implementation (`src/providers/`)
1306
+
1307
+ Create a new provider file (for example `amazon-bedrock.ts`) that exports:
1308
+
1309
+ - `stream<Provider>()` function returning `AssistantMessageEventStream`
1310
+ - `streamSimple<Provider>()` for `SimpleStreamOptions` mapping
1311
+ - Provider-specific options interface
1312
+ - Message conversion functions to transform `Context` to provider format
1313
+ - Tool conversion if the provider supports tools
1314
+ - Response parsing to emit standardized events (`text`, `tool_call`, `thinking`, `usage`, `stop`)
1315
+
1316
+ #### 3. API Registry Integration (`src/providers/register-builtins.ts`)
1317
+
1318
+ - Register the API with `registerApiProvider()`
1319
+ - Add a package subpath export in `package.json` for the provider module (`./dist/providers/<provider>.js`)
1320
+ - Add lazy loader wrappers in `src/providers/register-builtins.ts`, do not statically import provider implementation modules there
1321
+ - Add any root-level `export type` re-exports in `src/index.ts` that should remain available from `@openadapter/koda-ai`
1322
+ - Add credential detection in `env-api-keys.ts` for the new provider
1323
+ - Ensure `streamSimple` handles auth lookup via `getEnvApiKey()` or provider-specific auth
1324
+
1325
+ #### 4. Model Generation (`scripts/generate-models.ts`, `scripts/generate-image-models.ts`)
1326
+
1327
+ - Add logic to fetch and parse models from the provider's source (e.g., models.dev API)
1328
+ - Map chat/tool-capable provider model data to the standardized `Model` interface via `scripts/generate-models.ts`
1329
+ - Map image-generation provider model data to the standardized `ImagesModel` interface via `scripts/generate-image-models.ts`
1330
+ - Handle provider-specific quirks (pricing format, capability flags, model ID transformations)
1331
+
1332
+ #### 5. Tests (`test/`)
1333
+
1334
+ Create or update test files to cover the new provider:
1335
+
1336
+ - `stream.test.ts` - Basic streaming and tool use
1337
+ - `tokens.test.ts` - Token usage reporting
1338
+ - `abort.test.ts` - Request cancellation
1339
+ - `empty.test.ts` - Empty message handling
1340
+ - `context-overflow.test.ts` - Context limit errors
1341
+ - `image-limits.test.ts` - Image support (if applicable)
1342
+ - `unicode-surrogate.test.ts` - Unicode handling
1343
+ - `tool-call-without-result.test.ts` - Orphaned tool calls
1344
+ - `image-tool-result.test.ts` - Images in tool results
1345
+ - `total-tokens.test.ts` - Token counting accuracy
1346
+ - `cross-provider-handoff.test.ts` - Cross-provider context replay
1347
+
1348
+ For `cross-provider-handoff.test.ts`, add at least one provider/model pair. If the provider exposes multiple model families (for example GPT and Claude), add at least one pair per family.
1349
+
1350
+ For providers with non-standard auth (AWS, Google Vertex), create a utility like `bedrock-utils.ts` with credential detection helpers.
1351
+
1352
+ #### 6. Coding Agent Integration (`../coding-agent/`)
1353
+
1354
+ Update `src/core/model-resolver.ts`:
1355
+
1356
+ - Add a default model ID for the provider in `DEFAULT_MODELS`
1357
+
1358
+ Update `src/cli/args.ts`:
1359
+
1360
+ - Add environment variable documentation in the help text
1361
+
1362
+ Update `README.md`:
1363
+
1364
+ - Add the provider to the providers section with setup instructions
1365
+
1366
+ #### 7. Documentation
1367
+
1368
+ Update `packages/ai/README.md`:
1369
+
1370
+ - Add to the Supported Providers table
1371
+ - Document any provider-specific options or authentication requirements
1372
+ - Add environment variable to the Environment Variables section
1373
+
1374
+ #### 8. Changelog
1375
+
1376
+ Add an entry to `packages/ai/CHANGELOG.md` under `## [Unreleased]`:
1377
+
1378
+ ```markdown
1379
+ ### Added
1380
+ - Added support for [Provider Name] provider ([#PR](link) by [@author](link))
1381
+ ```
1382
+
1383
+ ## License
1384
+
1385
+ MIT