@threadwell/ai 0.0.1

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