@hyperspaceng/neural-ai 0.60.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 (2) hide show
  1. package/README.md +1229 -0
  2. package/package.json +114 -0
package/README.md ADDED
@@ -0,0 +1,1229 @@
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
+ `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.
523
+
524
+ ## Error Handling
525
+
526
+ When a request ends with an error (including aborts and tool call validation errors), the streaming API emits an error event:
527
+
528
+ ```typescript
529
+ // In streaming
530
+ for await (const event of stream) {
531
+ if (event.type === 'error') {
532
+ // event.reason is either "error" or "aborted"
533
+ // event.error is the AssistantMessage with partial content
534
+ console.error(`Error (${event.reason}):`, event.error.errorMessage);
535
+ console.log('Partial content:', event.error.content);
536
+ }
537
+ }
538
+
539
+ // The final message will have the error details
540
+ const message = await stream.result();
541
+ if (message.stopReason === 'error' || message.stopReason === 'aborted') {
542
+ console.error('Request failed:', message.errorMessage);
543
+ // message.content contains any partial content received before the error
544
+ // message.usage contains partial token counts and costs
545
+ }
546
+ ```
547
+
548
+ ### Aborting Requests
549
+
550
+ The abort signal allows you to cancel in-progress requests. Aborted requests have `stopReason === 'aborted'`:
551
+
552
+ ```typescript
553
+ import { getModel, stream } from '@mariozechner/pi-ai';
554
+
555
+ const model = getModel('openai', 'gpt-4o-mini');
556
+ const controller = new AbortController();
557
+
558
+ // Abort after 2 seconds
559
+ setTimeout(() => controller.abort(), 2000);
560
+
561
+ const s = stream(model, {
562
+ messages: [{ role: 'user', content: 'Write a long story' }]
563
+ }, {
564
+ signal: controller.signal
565
+ });
566
+
567
+ for await (const event of s) {
568
+ if (event.type === 'text_delta') {
569
+ process.stdout.write(event.delta);
570
+ } else if (event.type === 'error') {
571
+ // event.reason tells you if it was "error" or "aborted"
572
+ console.log(`${event.reason === 'aborted' ? 'Aborted' : 'Error'}:`, event.error.errorMessage);
573
+ }
574
+ }
575
+
576
+ // Get results (may be partial if aborted)
577
+ const response = await s.result();
578
+ if (response.stopReason === 'aborted') {
579
+ console.log('Request was aborted:', response.errorMessage);
580
+ console.log('Partial content received:', response.content);
581
+ console.log('Tokens used:', response.usage);
582
+ }
583
+ ```
584
+
585
+ ### Continuing After Abort
586
+
587
+ Aborted messages can be added to the conversation context and continued in subsequent requests:
588
+
589
+ ```typescript
590
+ const context = {
591
+ messages: [
592
+ { role: 'user', content: 'Explain quantum computing in detail' }
593
+ ]
594
+ };
595
+
596
+ // First request gets aborted after 2 seconds
597
+ const controller1 = new AbortController();
598
+ setTimeout(() => controller1.abort(), 2000);
599
+
600
+ const partial = await complete(model, context, { signal: controller1.signal });
601
+
602
+ // Add the partial response to context
603
+ context.messages.push(partial);
604
+ context.messages.push({ role: 'user', content: 'Please continue' });
605
+
606
+ // Continue the conversation
607
+ const continuation = await complete(model, context);
608
+ ```
609
+
610
+ ### Debugging Provider Payloads
611
+
612
+ 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.
613
+
614
+ ```typescript
615
+ const response = await complete(model, context, {
616
+ onPayload: (payload) => {
617
+ console.log('Provider payload:', JSON.stringify(payload, null, 2));
618
+ }
619
+ });
620
+ ```
621
+
622
+ The callback is supported by `stream`, `complete`, `streamSimple`, and `completeSimple`.
623
+
624
+ ## APIs, Models, and Providers
625
+
626
+ The library uses a registry of API implementations. Built-in APIs include:
627
+
628
+ - **`anthropic-messages`**: Anthropic Messages API (`streamAnthropic`, `AnthropicOptions`)
629
+ - **`google-generative-ai`**: Google Generative AI API (`streamGoogle`, `GoogleOptions`)
630
+ - **`google-gemini-cli`**: Google Cloud Code Assist API (`streamGoogleGeminiCli`, `GoogleGeminiCliOptions`)
631
+ - **`google-vertex`**: Google Vertex AI API (`streamGoogleVertex`, `GoogleVertexOptions`)
632
+ - **`mistral-conversations`**: Mistral Conversations API (`streamMistral`, `MistralOptions`)
633
+ - **`openai-completions`**: OpenAI Chat Completions API (`streamOpenAICompletions`, `OpenAICompletionsOptions`)
634
+ - **`openai-responses`**: OpenAI Responses API (`streamOpenAIResponses`, `OpenAIResponsesOptions`)
635
+ - **`openai-codex-responses`**: OpenAI Codex Responses API (`streamOpenAICodexResponses`, `OpenAICodexResponsesOptions`)
636
+ - **`azure-openai-responses`**: Azure OpenAI Responses API (`streamAzureOpenAIResponses`, `AzureOpenAIResponsesOptions`)
637
+ - **`bedrock-converse-stream`**: Amazon Bedrock Converse API (`streamBedrock`, `BedrockOptions`)
638
+
639
+ ### Providers and Models
640
+
641
+ A **provider** offers models through a specific API. For example:
642
+ - **Anthropic** models use the `anthropic-messages` API
643
+ - **Google** models use the `google-generative-ai` API
644
+ - **OpenAI** models use the `openai-responses` API
645
+ - **Mistral** models use the `mistral-conversations` API
646
+ - **xAI, Cerebras, Groq, etc.** models use the `openai-completions` API (OpenAI-compatible)
647
+
648
+ ### Querying Providers and Models
649
+
650
+ ```typescript
651
+ import { getProviders, getModels, getModel } from '@mariozechner/pi-ai';
652
+
653
+ // Get all available providers
654
+ const providers = getProviders();
655
+ console.log(providers); // ['openai', 'anthropic', 'google', 'xai', 'groq', ...]
656
+
657
+ // Get all models from a provider (fully typed)
658
+ const anthropicModels = getModels('anthropic');
659
+ for (const model of anthropicModels) {
660
+ console.log(`${model.id}: ${model.name}`);
661
+ console.log(` API: ${model.api}`); // 'anthropic-messages'
662
+ console.log(` Context: ${model.contextWindow} tokens`);
663
+ console.log(` Vision: ${model.input.includes('image')}`);
664
+ console.log(` Reasoning: ${model.reasoning}`);
665
+ }
666
+
667
+ // Get a specific model (both provider and model ID are auto-completed in IDEs)
668
+ const model = getModel('openai', 'gpt-4o-mini');
669
+ console.log(`Using ${model.name} via ${model.api} API`);
670
+ ```
671
+
672
+ ### Custom Models
673
+
674
+ You can create custom models for local inference servers or custom endpoints:
675
+
676
+ ```typescript
677
+ import { Model, stream } from '@mariozechner/pi-ai';
678
+
679
+ // Example: Ollama using OpenAI-compatible API
680
+ const ollamaModel: Model<'openai-completions'> = {
681
+ id: 'llama-3.1-8b',
682
+ name: 'Llama 3.1 8B (Ollama)',
683
+ api: 'openai-completions',
684
+ provider: 'ollama',
685
+ baseUrl: 'http://localhost:11434/v1',
686
+ reasoning: false,
687
+ input: ['text'],
688
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
689
+ contextWindow: 128000,
690
+ maxTokens: 32000
691
+ };
692
+
693
+ // Example: LiteLLM proxy with explicit compat settings
694
+ const litellmModel: Model<'openai-completions'> = {
695
+ id: 'gpt-4o',
696
+ name: 'GPT-4o (via LiteLLM)',
697
+ api: 'openai-completions',
698
+ provider: 'litellm',
699
+ baseUrl: 'http://localhost:4000/v1',
700
+ reasoning: false,
701
+ input: ['text', 'image'],
702
+ cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 },
703
+ contextWindow: 128000,
704
+ maxTokens: 16384,
705
+ compat: {
706
+ supportsStore: false, // LiteLLM doesn't support the store field
707
+ }
708
+ };
709
+
710
+ // Example: Custom endpoint with headers (bypassing Cloudflare bot detection)
711
+ const proxyModel: Model<'anthropic-messages'> = {
712
+ id: 'claude-sonnet-4',
713
+ name: 'Claude Sonnet 4 (Proxied)',
714
+ api: 'anthropic-messages',
715
+ provider: 'custom-proxy',
716
+ baseUrl: 'https://proxy.example.com/v1',
717
+ reasoning: true,
718
+ input: ['text', 'image'],
719
+ cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
720
+ contextWindow: 200000,
721
+ maxTokens: 8192,
722
+ headers: {
723
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
724
+ 'X-Custom-Auth': 'bearer-token-here'
725
+ }
726
+ };
727
+
728
+ // Use the custom model
729
+ const response = await stream(ollamaModel, context, {
730
+ apiKey: 'dummy' // Ollama doesn't need a real key
731
+ });
732
+ ```
733
+
734
+ 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.
735
+
736
+ This commonly applies to Ollama, vLLM, SGLang, and similar OpenAI-compatible servers. You can set `compat` at the provider level or per model.
737
+
738
+ ```typescript
739
+ const ollamaReasoningModel: Model<'openai-completions'> = {
740
+ id: 'gpt-oss:20b',
741
+ name: 'GPT-OSS 20B (Ollama)',
742
+ api: 'openai-completions',
743
+ provider: 'ollama',
744
+ baseUrl: 'http://localhost:11434/v1',
745
+ reasoning: true,
746
+ input: ['text'],
747
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
748
+ contextWindow: 131072,
749
+ maxTokens: 32000,
750
+ compat: {
751
+ supportsDeveloperRole: false,
752
+ supportsReasoningEffort: false,
753
+ }
754
+ };
755
+ ```
756
+
757
+ ### OpenAI Compatibility Settings
758
+
759
+ 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.
760
+
761
+ ```typescript
762
+ interface OpenAICompletionsCompat {
763
+ supportsStore?: boolean; // Whether provider supports the `store` field (default: true)
764
+ supportsDeveloperRole?: boolean; // Whether provider supports `developer` role vs `system` (default: true)
765
+ supportsReasoningEffort?: boolean; // Whether provider supports `reasoning_effort` (default: true)
766
+ supportsUsageInStreaming?: boolean; // Whether provider supports `stream_options: { include_usage: true }` (default: true)
767
+ supportsStrictMode?: boolean; // Whether provider supports `strict` in tool definitions (default: true)
768
+ maxTokensField?: 'max_completion_tokens' | 'max_tokens'; // Which field name to use (default: max_completion_tokens)
769
+ requiresToolResultName?: boolean; // Whether tool results require the `name` field (default: false)
770
+ requiresAssistantAfterToolResult?: boolean; // Whether tool results must be followed by an assistant message (default: false)
771
+ requiresThinkingAsText?: boolean; // Whether thinking blocks must be converted to text (default: false)
772
+ thinkingFormat?: 'openai' | 'zai' | 'qwen'; // Format for reasoning param: 'openai' uses reasoning_effort, 'zai' uses thinking: { type: "enabled" }, 'qwen' uses enable_thinking: boolean (default: openai)
773
+ openRouterRouting?: OpenRouterRouting; // OpenRouter routing preferences (default: {})
774
+ vercelGatewayRouting?: VercelGatewayRouting; // Vercel AI Gateway routing preferences (default: {})
775
+ }
776
+
777
+ interface OpenAIResponsesCompat {
778
+ // Reserved for future use
779
+ }
780
+ ```
781
+
782
+ 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:
783
+
784
+ - **LiteLLM proxies**: May not support `store` field
785
+ - **Custom inference servers**: May use non-standard field names
786
+ - **Self-hosted endpoints**: May have different feature support
787
+
788
+ ### Type Safety
789
+
790
+ 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.
791
+
792
+ ```typescript
793
+ import { streamAnthropic, type AnthropicOptions } from '@mariozechner/pi-ai';
794
+
795
+ // TypeScript knows this is an Anthropic model
796
+ const claude = getModel('anthropic', 'claude-sonnet-4-20250514');
797
+
798
+ const options: AnthropicOptions = {
799
+ thinkingEnabled: true,
800
+ thinkingBudgetTokens: 2048
801
+ };
802
+
803
+ await streamAnthropic(claude, context, options);
804
+ ```
805
+
806
+ ## Cross-Provider Handoffs
807
+
808
+ 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.
809
+
810
+ ### How It Works
811
+
812
+ When messages from one provider are sent to a different provider, the library automatically transforms them for compatibility:
813
+
814
+ - **User and tool result messages** are passed through unchanged
815
+ - **Assistant messages from the same provider/API** are preserved as-is
816
+ - **Assistant messages from different providers** have their thinking blocks converted to text with `<thinking>` tags
817
+ - **Tool calls and regular text** are preserved unchanged
818
+
819
+ ### Example: Multi-Provider Conversation
820
+
821
+ ```typescript
822
+ import { getModel, complete, Context } from '@mariozechner/pi-ai';
823
+
824
+ // Start with Claude
825
+ const claude = getModel('anthropic', 'claude-sonnet-4-20250514');
826
+ const context: Context = {
827
+ messages: []
828
+ };
829
+
830
+ context.messages.push({ role: 'user', content: 'What is 25 * 18?' });
831
+ const claudeResponse = await complete(claude, context, {
832
+ thinkingEnabled: true
833
+ });
834
+ context.messages.push(claudeResponse);
835
+
836
+ // Switch to GPT-5 - it will see Claude's thinking as <thinking> tagged text
837
+ const gpt5 = getModel('openai', 'gpt-5-mini');
838
+ context.messages.push({ role: 'user', content: 'Is that calculation correct?' });
839
+ const gptResponse = await complete(gpt5, context);
840
+ context.messages.push(gptResponse);
841
+
842
+ // Switch to Gemini
843
+ const gemini = getModel('google', 'gemini-2.5-flash');
844
+ context.messages.push({ role: 'user', content: 'What was the original question?' });
845
+ const geminiResponse = await complete(gemini, context);
846
+ ```
847
+
848
+ ### Provider Compatibility
849
+
850
+ All providers can handle messages from other providers, including:
851
+ - Text content
852
+ - Tool calls and tool results (including images in tool results)
853
+ - Thinking/reasoning blocks (transformed to tagged text for cross-provider compatibility)
854
+ - Aborted messages with partial content
855
+
856
+ This enables flexible workflows where you can:
857
+ - Start with a fast model for initial responses
858
+ - Switch to a more capable model for complex reasoning
859
+ - Use specialized models for specific tasks
860
+ - Maintain conversation continuity across provider outages
861
+
862
+ ## Context Serialization
863
+
864
+ 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:
865
+
866
+ ```typescript
867
+ import { Context, getModel, complete } from '@mariozechner/pi-ai';
868
+
869
+ // Create and use a context
870
+ const context: Context = {
871
+ systemPrompt: 'You are a helpful assistant.',
872
+ messages: [
873
+ { role: 'user', content: 'What is TypeScript?' }
874
+ ]
875
+ };
876
+
877
+ const model = getModel('openai', 'gpt-4o-mini');
878
+ const response = await complete(model, context);
879
+ context.messages.push(response);
880
+
881
+ // Serialize the entire context
882
+ const serialized = JSON.stringify(context);
883
+ console.log('Serialized context size:', serialized.length, 'bytes');
884
+
885
+ // Save to database, localStorage, file, etc.
886
+ localStorage.setItem('conversation', serialized);
887
+
888
+ // Later: deserialize and continue the conversation
889
+ const restored: Context = JSON.parse(localStorage.getItem('conversation')!);
890
+ restored.messages.push({ role: 'user', content: 'Tell me more about its type system' });
891
+
892
+ // Continue with any model
893
+ const newModel = getModel('anthropic', 'claude-3-5-haiku-20241022');
894
+ const continuation = await complete(newModel, restored);
895
+ ```
896
+
897
+ > **Note**: If the context contains images (encoded as base64 as shown in the Image Input section), those will also be serialized.
898
+
899
+ ## Browser Usage
900
+
901
+ The library supports browser environments. You must pass the API key explicitly since environment variables are not available in browsers:
902
+
903
+ ```typescript
904
+ import { getModel, complete } from '@mariozechner/pi-ai';
905
+
906
+ // API key must be passed explicitly in browser
907
+ const model = getModel('anthropic', 'claude-3-5-haiku-20241022');
908
+
909
+ const response = await complete(model, {
910
+ messages: [{ role: 'user', content: 'Hello!' }]
911
+ }, {
912
+ apiKey: 'your-api-key'
913
+ });
914
+ ```
915
+
916
+ > **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.
917
+
918
+ ### Browser Compatibility Notes
919
+
920
+ - Amazon Bedrock (`bedrock-converse-stream`) is not supported in browser environments.
921
+ - OAuth login flows are not supported in browser environments. Use the `@mariozechner/pi-ai/oauth` entry point in Node.js.
922
+ - In browser builds, Bedrock can still appear in model lists. Calls to Bedrock models fail at runtime.
923
+ - Use a server-side proxy or backend service if you need Bedrock or OAuth-based auth from a web app.
924
+
925
+ ### Environment Variables (Node.js only)
926
+
927
+ In Node.js environments, you can set environment variables to avoid passing API keys:
928
+
929
+ | Provider | Environment Variable(s) |
930
+ |----------|------------------------|
931
+ | OpenAI | `OPENAI_API_KEY` |
932
+ | 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`) |
933
+ | Anthropic | `ANTHROPIC_API_KEY` or `ANTHROPIC_OAUTH_TOKEN` |
934
+ | Google | `GEMINI_API_KEY` |
935
+ | Vertex AI | `GOOGLE_CLOUD_API_KEY` or `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) + `GOOGLE_CLOUD_LOCATION` + ADC |
936
+ | Mistral | `MISTRAL_API_KEY` |
937
+ | Groq | `GROQ_API_KEY` |
938
+ | Cerebras | `CEREBRAS_API_KEY` |
939
+ | xAI | `XAI_API_KEY` |
940
+ | OpenRouter | `OPENROUTER_API_KEY` |
941
+ | Vercel AI Gateway | `AI_GATEWAY_API_KEY` |
942
+ | zAI | `ZAI_API_KEY` |
943
+ | MiniMax | `MINIMAX_API_KEY` |
944
+ | OpenCode Zen / OpenCode Go | `OPENCODE_API_KEY` |
945
+ | Kimi For Coding | `KIMI_API_KEY` |
946
+ | GitHub Copilot | `COPILOT_GITHUB_TOKEN` or `GH_TOKEN` or `GITHUB_TOKEN` |
947
+
948
+ When set, the library automatically uses these keys:
949
+
950
+ ```typescript
951
+ // Uses OPENAI_API_KEY from environment
952
+ const model = getModel('openai', 'gpt-4o-mini');
953
+ const response = await complete(model, context);
954
+
955
+ // Or override with explicit key
956
+ const response = await complete(model, context, {
957
+ apiKey: 'sk-different-key'
958
+ });
959
+ ```
960
+
961
+ #### Antigravity Version Override
962
+
963
+ Set `PI_AI_ANTIGRAVITY_VERSION` to override the Antigravity User-Agent version when Google updates their requirements:
964
+
965
+ ```bash
966
+ export PI_AI_ANTIGRAVITY_VERSION="1.23.0"
967
+ ```
968
+
969
+ #### Cache Retention
970
+
971
+ Set `PI_CACHE_RETENTION=long` to extend prompt cache retention:
972
+
973
+ | Provider | Default | With `PI_CACHE_RETENTION=long` |
974
+ |----------|---------|-------------------------------|
975
+ | Anthropic | 5 minutes | 1 hour |
976
+ | OpenAI | in-memory | 24 hours |
977
+
978
+ This only affects direct API calls to `api.anthropic.com` and `api.openai.com`. Proxies and other providers are unaffected.
979
+
980
+ > **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.
981
+
982
+ ### Checking Environment Variables
983
+
984
+ ```typescript
985
+ import { getEnvApiKey } from '@mariozechner/pi-ai';
986
+
987
+ // Check if an API key is set in environment variables
988
+ const key = getEnvApiKey('openai'); // checks OPENAI_API_KEY
989
+ ```
990
+
991
+ ## OAuth Providers
992
+
993
+ Several providers require OAuth authentication instead of static API keys:
994
+
995
+ - **Anthropic** (Claude Pro/Max subscription)
996
+ - **OpenAI Codex** (ChatGPT Plus/Pro subscription, access to GPT-5.x Codex models)
997
+ - **GitHub Copilot** (Copilot subscription)
998
+ - **Google Gemini CLI** (Gemini 2.0/2.5 via Google Cloud Code Assist; free tier or paid subscription)
999
+ - **Antigravity** (Free Gemini 3, Claude, GPT-OSS via Google Cloud)
1000
+
1001
+ For paid Cloud Code Assist subscriptions, set `GOOGLE_CLOUD_PROJECT` or `GOOGLE_CLOUD_PROJECT_ID` to your project ID.
1002
+
1003
+ ### Vertex AI
1004
+
1005
+ Vertex AI models support either a Google Cloud API key or Application Default Credentials (ADC):
1006
+
1007
+ - **API key**: Set `GOOGLE_CLOUD_API_KEY` or pass `apiKey` in the call options.
1008
+ - **Local development (ADC)**: Run `gcloud auth application-default login`
1009
+ - **CI/Production (ADC)**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to a service account JSON key file
1010
+
1011
+ 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.
1012
+
1013
+ Example:
1014
+
1015
+ ```bash
1016
+ # Local (uses your user credentials)
1017
+ gcloud auth application-default login
1018
+ export GOOGLE_CLOUD_PROJECT="my-project"
1019
+ export GOOGLE_CLOUD_LOCATION="us-central1"
1020
+
1021
+ # CI/Production (service account key file)
1022
+ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
1023
+ ```
1024
+
1025
+ ```typescript
1026
+ import { getModel, complete } from '@mariozechner/pi-ai';
1027
+
1028
+ (async () => {
1029
+ const model = getModel('google-vertex', 'gemini-2.5-flash');
1030
+ const response = await complete(model, {
1031
+ messages: [{ role: 'user', content: 'Hello from Vertex AI' }]
1032
+ }, {
1033
+ apiKey: process.env.GOOGLE_CLOUD_API_KEY,
1034
+ });
1035
+
1036
+ for (const block of response.content) {
1037
+ if (block.type === 'text') console.log(block.text);
1038
+ }
1039
+ })().catch(console.error);
1040
+ ```
1041
+
1042
+ Official docs: [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials)
1043
+
1044
+ ### CLI Login
1045
+
1046
+ The quickest way to authenticate:
1047
+
1048
+ ```bash
1049
+ npx @mariozechner/pi-ai login # interactive provider selection
1050
+ npx @mariozechner/pi-ai login anthropic # login to specific provider
1051
+ npx @mariozechner/pi-ai list # list available providers
1052
+ ```
1053
+
1054
+ Credentials are saved to `auth.json` in the current directory.
1055
+
1056
+ ### Programmatic OAuth
1057
+
1058
+ The library provides login and token refresh functions via the `@mariozechner/pi-ai/oauth` entry point. Credential storage is the caller's responsibility.
1059
+
1060
+ ```typescript
1061
+ import {
1062
+ // Login functions (return credentials, do not store)
1063
+ loginAnthropic,
1064
+ loginOpenAICodex,
1065
+ loginGitHubCopilot,
1066
+ loginGeminiCli,
1067
+ loginAntigravity,
1068
+
1069
+ // Token management
1070
+ refreshOAuthToken, // (provider, credentials) => new credentials
1071
+ getOAuthApiKey, // (provider, credentialsMap) => { newCredentials, apiKey } | null
1072
+
1073
+ // Types
1074
+ type OAuthProvider, // 'anthropic' | 'openai-codex' | 'github-copilot' | 'google-gemini-cli' | 'google-antigravity'
1075
+ type OAuthCredentials,
1076
+ } from '@mariozechner/pi-ai/oauth';
1077
+ ```
1078
+
1079
+ ### Login Flow Example
1080
+
1081
+ ```typescript
1082
+ import { loginGitHubCopilot } from '@mariozechner/pi-ai/oauth';
1083
+ import { writeFileSync } from 'fs';
1084
+
1085
+ const credentials = await loginGitHubCopilot({
1086
+ onAuth: (url, instructions) => {
1087
+ console.log(`Open: ${url}`);
1088
+ if (instructions) console.log(instructions);
1089
+ },
1090
+ onPrompt: async (prompt) => {
1091
+ return await getUserInput(prompt.message);
1092
+ },
1093
+ onProgress: (message) => console.log(message)
1094
+ });
1095
+
1096
+ // Store credentials yourself
1097
+ const auth = { 'github-copilot': { type: 'oauth', ...credentials } };
1098
+ writeFileSync('auth.json', JSON.stringify(auth, null, 2));
1099
+ ```
1100
+
1101
+ ### Using OAuth Tokens
1102
+
1103
+ Use `getOAuthApiKey()` to get an API key, automatically refreshing if expired:
1104
+
1105
+ ```typescript
1106
+ import { getModel, complete } from '@mariozechner/pi-ai';
1107
+ import { getOAuthApiKey } from '@mariozechner/pi-ai/oauth';
1108
+ import { readFileSync, writeFileSync } from 'fs';
1109
+
1110
+ // Load your stored credentials
1111
+ const auth = JSON.parse(readFileSync('auth.json', 'utf-8'));
1112
+
1113
+ // Get API key (refreshes if expired)
1114
+ const result = await getOAuthApiKey('github-copilot', auth);
1115
+ if (!result) throw new Error('Not logged in');
1116
+
1117
+ // Save refreshed credentials
1118
+ auth['github-copilot'] = { type: 'oauth', ...result.newCredentials };
1119
+ writeFileSync('auth.json', JSON.stringify(auth, null, 2));
1120
+
1121
+ // Use the API key
1122
+ const model = getModel('github-copilot', 'gpt-4o');
1123
+ const response = await complete(model, {
1124
+ messages: [{ role: 'user', content: 'Hello!' }]
1125
+ }, { apiKey: result.apiKey });
1126
+ ```
1127
+
1128
+ ### Provider Notes
1129
+
1130
+ **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.
1131
+
1132
+ **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.
1133
+
1134
+ **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".
1135
+
1136
+ **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.
1137
+
1138
+ ## Development
1139
+
1140
+ ### Adding a New Provider
1141
+
1142
+ Adding a new LLM provider requires changes across multiple files. This checklist covers all necessary steps:
1143
+
1144
+ #### 1. Core Types (`src/types.ts`)
1145
+
1146
+ - Add the API identifier to `KnownApi` (for example `"bedrock-converse-stream"`)
1147
+ - Create an options interface extending `StreamOptions` (for example `BedrockOptions`)
1148
+ - Add the provider name to `KnownProvider` (for example `"amazon-bedrock"`)
1149
+
1150
+ #### 2. Provider Implementation (`src/providers/`)
1151
+
1152
+ Create a new provider file (for example `amazon-bedrock.ts`) that exports:
1153
+
1154
+ - `stream<Provider>()` function returning `AssistantMessageEventStream`
1155
+ - `streamSimple<Provider>()` for `SimpleStreamOptions` mapping
1156
+ - Provider-specific options interface
1157
+ - Message conversion functions to transform `Context` to provider format
1158
+ - Tool conversion if the provider supports tools
1159
+ - Response parsing to emit standardized events (`text`, `tool_call`, `thinking`, `usage`, `stop`)
1160
+
1161
+ #### 3. API Registry Integration (`src/providers/register-builtins.ts`)
1162
+
1163
+ - Register the API with `registerApiProvider()`
1164
+ - Add a package subpath export in `package.json` for the provider module (`./dist/providers/<provider>.js`)
1165
+ - Add lazy loader wrappers in `src/providers/register-builtins.ts`, do not statically import provider implementation modules there
1166
+ - Add any root-level `export type` re-exports in `src/index.ts` that should remain available from `@mariozechner/pi-ai`
1167
+ - Add credential detection in `env-api-keys.ts` for the new provider
1168
+ - Ensure `streamSimple` handles auth lookup via `getEnvApiKey()` or provider-specific auth
1169
+
1170
+ #### 4. Model Generation (`scripts/generate-models.ts`)
1171
+
1172
+ - Add logic to fetch and parse models from the provider's source (e.g., models.dev API)
1173
+ - Map provider model data to the standardized `Model` interface
1174
+ - Handle provider-specific quirks (pricing format, capability flags, model ID transformations)
1175
+
1176
+ #### 5. Tests (`test/`)
1177
+
1178
+ Create or update test files to cover the new provider:
1179
+
1180
+ - `stream.test.ts` - Basic streaming and tool use
1181
+ - `tokens.test.ts` - Token usage reporting
1182
+ - `abort.test.ts` - Request cancellation
1183
+ - `empty.test.ts` - Empty message handling
1184
+ - `context-overflow.test.ts` - Context limit errors
1185
+ - `image-limits.test.ts` - Image support (if applicable)
1186
+ - `unicode-surrogate.test.ts` - Unicode handling
1187
+ - `tool-call-without-result.test.ts` - Orphaned tool calls
1188
+ - `image-tool-result.test.ts` - Images in tool results
1189
+ - `total-tokens.test.ts` - Token counting accuracy
1190
+ - `cross-provider-handoff.test.ts` - Cross-provider context replay
1191
+
1192
+ 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.
1193
+
1194
+ For providers with non-standard auth (AWS, Google Vertex), create a utility like `bedrock-utils.ts` with credential detection helpers.
1195
+
1196
+ #### 6. Coding Agent Integration (`../coding-agent/`)
1197
+
1198
+ Update `src/core/model-resolver.ts`:
1199
+
1200
+ - Add a default model ID for the provider in `DEFAULT_MODELS`
1201
+
1202
+ Update `src/cli/args.ts`:
1203
+
1204
+ - Add environment variable documentation in the help text
1205
+
1206
+ Update `README.md`:
1207
+
1208
+ - Add the provider to the providers section with setup instructions
1209
+
1210
+ #### 7. Documentation
1211
+
1212
+ Update `packages/ai/README.md`:
1213
+
1214
+ - Add to the Supported Providers table
1215
+ - Document any provider-specific options or authentication requirements
1216
+ - Add environment variable to the Environment Variables section
1217
+
1218
+ #### 8. Changelog
1219
+
1220
+ Add an entry to `packages/ai/CHANGELOG.md` under `## [Unreleased]`:
1221
+
1222
+ ```markdown
1223
+ ### Added
1224
+ - Added support for [Provider Name] provider ([#PR](link) by [@author](link))
1225
+ ```
1226
+
1227
+ ## License
1228
+
1229
+ MIT
package/package.json ADDED
@@ -0,0 +1,114 @@
1
+ {
2
+ "name": "@hyperspaceng/neural-ai",
3
+ "version": "0.60.0",
4
+ "description": "Unified LLM API with automatic model discovery and provider configuration",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./anthropic": {
14
+ "types": "./dist/providers/anthropic.d.ts",
15
+ "import": "./dist/providers/anthropic.js"
16
+ },
17
+ "./azure-openai-responses": {
18
+ "types": "./dist/providers/azure-openai-responses.d.ts",
19
+ "import": "./dist/providers/azure-openai-responses.js"
20
+ },
21
+ "./google": {
22
+ "types": "./dist/providers/google.d.ts",
23
+ "import": "./dist/providers/google.js"
24
+ },
25
+ "./google-gemini-cli": {
26
+ "types": "./dist/providers/google-gemini-cli.d.ts",
27
+ "import": "./dist/providers/google-gemini-cli.js"
28
+ },
29
+ "./google-vertex": {
30
+ "types": "./dist/providers/google-vertex.d.ts",
31
+ "import": "./dist/providers/google-vertex.js"
32
+ },
33
+ "./mistral": {
34
+ "types": "./dist/providers/mistral.d.ts",
35
+ "import": "./dist/providers/mistral.js"
36
+ },
37
+ "./openai-codex-responses": {
38
+ "types": "./dist/providers/openai-codex-responses.d.ts",
39
+ "import": "./dist/providers/openai-codex-responses.js"
40
+ },
41
+ "./openai-completions": {
42
+ "types": "./dist/providers/openai-completions.d.ts",
43
+ "import": "./dist/providers/openai-completions.js"
44
+ },
45
+ "./openai-responses": {
46
+ "types": "./dist/providers/openai-responses.d.ts",
47
+ "import": "./dist/providers/openai-responses.js"
48
+ },
49
+ "./oauth": {
50
+ "types": "./dist/oauth.d.ts",
51
+ "import": "./dist/oauth.js"
52
+ },
53
+ "./bedrock-provider": {
54
+ "types": "./dist/bedrock-provider.d.ts",
55
+ "import": "./dist/bedrock-provider.js"
56
+ }
57
+ },
58
+ "bin": {
59
+ "neural-ai": "./dist/cli.js"
60
+ },
61
+ "files": [
62
+ "dist",
63
+ "README.md"
64
+ ],
65
+ "scripts": {
66
+ "clean": "shx rm -rf dist",
67
+ "generate-models": "npx tsx scripts/generate-models.ts",
68
+ "build": "npm run generate-models && tsgo -p tsconfig.build.json",
69
+ "dev": "tsgo -p tsconfig.build.json --watch --preserveWatchOutput",
70
+ "dev:tsc": "tsgo -p tsconfig.build.json --watch --preserveWatchOutput",
71
+ "test": "vitest --run",
72
+ "prepublishOnly": "npm run clean && npm run build"
73
+ },
74
+ "dependencies": {
75
+ "@anthropic-ai/sdk": "^0.73.0",
76
+ "@aws-sdk/client-bedrock-runtime": "^3.983.0",
77
+ "@google/genai": "^1.40.0",
78
+ "@mistralai/mistralai": "1.14.1",
79
+ "@sinclair/typebox": "^0.34.41",
80
+ "ajv": "^8.17.1",
81
+ "ajv-formats": "^3.0.1",
82
+ "chalk": "^5.6.2",
83
+ "openai": "6.26.0",
84
+ "partial-json": "^0.1.7",
85
+ "proxy-agent": "^6.5.0",
86
+ "undici": "^7.19.1",
87
+ "zod-to-json-schema": "^3.24.6"
88
+ },
89
+ "keywords": [
90
+ "ai",
91
+ "llm",
92
+ "openai",
93
+ "anthropic",
94
+ "gemini",
95
+ "bedrock",
96
+ "unified",
97
+ "api"
98
+ ],
99
+ "author": "Hyperspace Technologies <hyperspace@hyperspace.ng>",
100
+ "license": "MIT",
101
+ "repository": {
102
+ "type": "git",
103
+ "url": "git+https://github.com/badlogic/pi-mono.git",
104
+ "directory": "packages/ai"
105
+ },
106
+ "engines": {
107
+ "node": ">=20.0.0"
108
+ },
109
+ "devDependencies": {
110
+ "@types/node": "^24.3.0",
111
+ "canvas": "^3.2.0",
112
+ "vitest": "^3.2.4"
113
+ }
114
+ }