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