@sammorrowdrums/mcpi-ai 0.70.0

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