@oh-my-pi/pi-ai 0.1.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.
package/README.md ADDED
@@ -0,0 +1,959 @@
1
+ # @oh-my-pi/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
+ ## Supported Providers
8
+
9
+ - **OpenAI**
10
+ - **Anthropic**
11
+ - **Google**
12
+ - **Mistral**
13
+ - **Groq**
14
+ - **Cerebras**
15
+ - **xAI**
16
+ - **OpenRouter**
17
+ - **GitHub Copilot** (requires OAuth, see below)
18
+ - **Any OpenAI-compatible API**: Ollama, vLLM, LM Studio, etc.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install @oh-my-pi/pi-ai
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ ```typescript
29
+ import { Type, getModel, stream, complete, Context, Tool, StringEnum } from "@oh-my-pi/pi-ai";
30
+
31
+ // Fully typed with auto-complete support for both providers and models
32
+ const model = getModel("openai", "gpt-4o-mini");
33
+
34
+ // Define tools with TypeBox schemas for type safety and validation
35
+ const tools: Tool[] = [
36
+ {
37
+ name: "get_time",
38
+ description: "Get the current time",
39
+ parameters: Type.Object({
40
+ timezone: Type.Optional(Type.String({ description: "Optional timezone (e.g., America/New_York)" })),
41
+ }),
42
+ },
43
+ ];
44
+
45
+ // Build a conversation context (easily serializable and transferable between models)
46
+ const context: Context = {
47
+ systemPrompt: "You are a helpful assistant.",
48
+ messages: [{ role: "user", content: "What time is it?" }],
49
+ tools,
50
+ };
51
+
52
+ // Option 1: Streaming with all event types
53
+ const s = stream(model, context);
54
+
55
+ for await (const event of s) {
56
+ switch (event.type) {
57
+ case "start":
58
+ console.log(`Starting with ${event.partial.model}`);
59
+ break;
60
+ case "text_start":
61
+ console.log("\n[Text started]");
62
+ break;
63
+ case "text_delta":
64
+ process.stdout.write(event.delta);
65
+ break;
66
+ case "text_end":
67
+ console.log("\n[Text ended]");
68
+ break;
69
+ case "thinking_start":
70
+ console.log("[Model is thinking...]");
71
+ break;
72
+ case "thinking_delta":
73
+ process.stdout.write(event.delta);
74
+ break;
75
+ case "thinking_end":
76
+ console.log("[Thinking complete]");
77
+ break;
78
+ case "toolcall_start":
79
+ console.log(`\n[Tool call started: index ${event.contentIndex}]`);
80
+ break;
81
+ case "toolcall_delta":
82
+ // Partial tool arguments are being streamed
83
+ const partialCall = event.partial.content[event.contentIndex];
84
+ if (partialCall.type === "toolCall") {
85
+ console.log(`[Streaming args for ${partialCall.name}]`);
86
+ }
87
+ break;
88
+ case "toolcall_end":
89
+ console.log(`\nTool called: ${event.toolCall.name}`);
90
+ console.log(`Arguments: ${JSON.stringify(event.toolCall.arguments)}`);
91
+ break;
92
+ case "done":
93
+ console.log(`\nFinished: ${event.reason}`);
94
+ break;
95
+ case "error":
96
+ console.error(`Error: ${event.error}`);
97
+ break;
98
+ }
99
+ }
100
+
101
+ // Get the final message after streaming, add it to the context
102
+ const finalMessage = await s.result();
103
+ context.messages.push(finalMessage);
104
+
105
+ // Handle tool calls if any
106
+ const toolCalls = finalMessage.content.filter((b) => b.type === "toolCall");
107
+ for (const call of toolCalls) {
108
+ // Execute the tool
109
+ const result =
110
+ call.name === "get_time"
111
+ ? new Date().toLocaleString("en-US", {
112
+ timeZone: call.arguments.timezone || "UTC",
113
+ dateStyle: "full",
114
+ timeStyle: "long",
115
+ })
116
+ : "Unknown tool";
117
+
118
+ // Add tool result to context (supports text and images)
119
+ context.messages.push({
120
+ role: "toolResult",
121
+ toolCallId: call.id,
122
+ toolName: call.name,
123
+ content: [{ type: "text", text: result }],
124
+ timestamp: Date.now(),
125
+ });
126
+ }
127
+
128
+ // Continue if there were tool calls
129
+ if (toolCalls.length > 0) {
130
+ const continuation = await complete(model, context);
131
+ context.messages.push(continuation);
132
+ console.log("After tool execution:", continuation.content);
133
+ }
134
+
135
+ console.log(`Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`);
136
+ console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
137
+
138
+ // Option 2: Get complete response without streaming
139
+ const response = await complete(model, context);
140
+
141
+ for (const block of response.content) {
142
+ if (block.type === "text") {
143
+ console.log(block.text);
144
+ } else if (block.type === "toolCall") {
145
+ console.log(`Tool: ${block.name}(${JSON.stringify(block.arguments)})`);
146
+ }
147
+ }
148
+ ```
149
+
150
+ ## Tools
151
+
152
+ 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.
153
+
154
+ ### Defining Tools
155
+
156
+ ```typescript
157
+ import { Type, Tool, StringEnum } from "@oh-my-pi/pi-ai";
158
+
159
+ // Define tool parameters with TypeBox
160
+ const weatherTool: Tool = {
161
+ name: "get_weather",
162
+ description: "Get current weather for a location",
163
+ parameters: Type.Object({
164
+ location: Type.String({ description: "City name or coordinates" }),
165
+ units: StringEnum(["celsius", "fahrenheit"], { default: "celsius" }),
166
+ }),
167
+ };
168
+
169
+ // Note: For Google API compatibility, use StringEnum helper instead of Type.Enum
170
+ // Type.Enum generates anyOf/const patterns that Google doesn't support
171
+
172
+ const bookMeetingTool: Tool = {
173
+ name: "book_meeting",
174
+ description: "Schedule a meeting",
175
+ parameters: Type.Object({
176
+ title: Type.String({ minLength: 1 }),
177
+ startTime: Type.String({ format: "date-time" }),
178
+ endTime: Type.String({ format: "date-time" }),
179
+ attendees: Type.Array(Type.String({ format: "email" }), { minItems: 1 }),
180
+ }),
181
+ };
182
+ ```
183
+
184
+ ### Handling Tool Calls
185
+
186
+ Tool results use content blocks and can include both text and images:
187
+
188
+ ```typescript
189
+ import { readFileSync } from "fs";
190
+
191
+ const context: Context = {
192
+ messages: [{ role: "user", content: "What is the weather in London?" }],
193
+ tools: [weatherTool],
194
+ };
195
+
196
+ const response = await complete(model, context);
197
+
198
+ // Check for tool calls in the response
199
+ for (const block of response.content) {
200
+ if (block.type === "toolCall") {
201
+ // Execute your tool with the arguments
202
+ // See "Validating Tool Arguments" section for validation
203
+ const result = await executeWeatherApi(block.arguments);
204
+
205
+ // Add tool result with text content
206
+ context.messages.push({
207
+ role: "toolResult",
208
+ toolCallId: block.id,
209
+ toolName: block.name,
210
+ content: [{ type: "text", text: JSON.stringify(result) }],
211
+ timestamp: Date.now(),
212
+ });
213
+ }
214
+ }
215
+
216
+ // Tool results can also include images (for vision-capable models)
217
+ const imageBuffer = readFileSync("chart.png");
218
+ context.messages.push({
219
+ role: "toolResult",
220
+ toolCallId: "tool_xyz",
221
+ toolName: "generate_chart",
222
+ content: [
223
+ { type: "text", text: "Generated chart showing temperature trends" },
224
+ { type: "image", data: imageBuffer.toString("base64"), mimeType: "image/png" },
225
+ ],
226
+ timestamp: Date.now(),
227
+ });
228
+ ```
229
+
230
+ ### Streaming Tool Calls with Partial JSON
231
+
232
+ During streaming, tool call arguments are progressively parsed as they arrive. This enables real-time UI updates before the complete arguments are available:
233
+
234
+ ```typescript
235
+ const s = stream(model, context);
236
+
237
+ for await (const event of s) {
238
+ if (event.type === "toolcall_delta") {
239
+ const toolCall = event.partial.content[event.contentIndex];
240
+
241
+ // toolCall.arguments contains partially parsed JSON during streaming
242
+ // This allows for progressive UI updates
243
+ if (toolCall.type === "toolCall" && toolCall.arguments) {
244
+ // BE DEFENSIVE: arguments may be incomplete
245
+ // Example: Show file path being written even before content is complete
246
+ if (toolCall.name === "write_file" && toolCall.arguments.path) {
247
+ console.log(`Writing to: ${toolCall.arguments.path}`);
248
+
249
+ // Content might be partial or missing
250
+ if (toolCall.arguments.content) {
251
+ console.log(`Content preview: ${toolCall.arguments.content.substring(0, 100)}...`);
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ if (event.type === "toolcall_end") {
258
+ // Here toolCall.arguments is complete (but not yet validated)
259
+ const toolCall = event.toolCall;
260
+ console.log(`Tool completed: ${toolCall.name}`, toolCall.arguments);
261
+ }
262
+ }
263
+ ```
264
+
265
+ **Important notes about partial tool arguments:**
266
+
267
+ - During `toolcall_delta` events, `arguments` contains the best-effort parse of partial JSON
268
+ - Fields may be missing or incomplete - always check for existence before use
269
+ - String values may be truncated mid-word
270
+ - Arrays may be incomplete
271
+ - Nested objects may be partially populated
272
+ - At minimum, `arguments` will be an empty object `{}`, never `undefined`
273
+ - The Google provider does not support function call streaming. Instead, you will receive a single `toolcall_delta` event with the full arguments.
274
+
275
+ ### Validating Tool Arguments
276
+
277
+ 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.
278
+
279
+ When implementing your own tool execution loop with `stream()` or `complete()`, use `validateToolCall` to validate arguments before passing them to your tools:
280
+
281
+ ```typescript
282
+ import { stream, validateToolCall, Tool } from "@oh-my-pi/pi-ai";
283
+
284
+ const tools: Tool[] = [weatherTool, calculatorTool];
285
+ const s = stream(model, { messages, tools });
286
+
287
+ for await (const event of s) {
288
+ if (event.type === "toolcall_end") {
289
+ const toolCall = event.toolCall;
290
+
291
+ try {
292
+ // Validate arguments against the tool's schema (throws on invalid args)
293
+ const validatedArgs = validateToolCall(tools, toolCall);
294
+ const result = await executeMyTool(toolCall.name, validatedArgs);
295
+ // ... add tool result to context
296
+ } catch (error) {
297
+ // Validation failed - return error as tool result so model can retry
298
+ context.messages.push({
299
+ role: "toolResult",
300
+ toolCallId: toolCall.id,
301
+ toolName: toolCall.name,
302
+ content: [{ type: "text", text: error.message }],
303
+ isError: true,
304
+ timestamp: Date.now(),
305
+ });
306
+ }
307
+ }
308
+ }
309
+ ```
310
+
311
+ ### Complete Event Reference
312
+
313
+ All streaming events emitted during assistant message generation:
314
+
315
+ | Event Type | Description | Key Properties |
316
+ | ---------------- | ------------------------ | ------------------------------------------------------------------------------------------- |
317
+ | `start` | Stream begins | `partial`: Initial assistant message structure |
318
+ | `text_start` | Text block starts | `contentIndex`: Position in content array |
319
+ | `text_delta` | Text chunk received | `delta`: New text, `contentIndex`: Position |
320
+ | `text_end` | Text block complete | `content`: Full text, `contentIndex`: Position |
321
+ | `thinking_start` | Thinking block starts | `contentIndex`: Position in content array |
322
+ | `thinking_delta` | Thinking chunk received | `delta`: New text, `contentIndex`: Position |
323
+ | `thinking_end` | Thinking block complete | `content`: Full thinking, `contentIndex`: Position |
324
+ | `toolcall_start` | Tool call begins | `contentIndex`: Position in content array |
325
+ | `toolcall_delta` | Tool arguments streaming | `delta`: JSON chunk, `partial.content[contentIndex].arguments`: Partial parsed args |
326
+ | `toolcall_end` | Tool call complete | `toolCall`: Complete validated tool call with `id`, `name`, `arguments` |
327
+ | `done` | Stream complete | `reason`: Stop reason ("stop", "length", "toolUse"), `message`: Final assistant message |
328
+ | `error` | Error occurred | `reason`: Error type ("error" or "aborted"), `error`: AssistantMessage with partial content |
329
+
330
+ ## Image Input
331
+
332
+ 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.
333
+
334
+ ```typescript
335
+ import { readFileSync } from "fs";
336
+ import { getModel, complete } from "@oh-my-pi/pi-ai";
337
+
338
+ const model = getModel("openai", "gpt-4o-mini");
339
+
340
+ // Check if model supports images
341
+ if (model.input.includes("image")) {
342
+ console.log("Model supports vision");
343
+ }
344
+
345
+ const imageBuffer = readFileSync("image.png");
346
+ const base64Image = imageBuffer.toString("base64");
347
+
348
+ const response = await complete(model, {
349
+ messages: [
350
+ {
351
+ role: "user",
352
+ content: [
353
+ { type: "text", text: "What is in this image?" },
354
+ { type: "image", data: base64Image, mimeType: "image/png" },
355
+ ],
356
+ },
357
+ ],
358
+ });
359
+
360
+ // Access the response
361
+ for (const block of response.content) {
362
+ if (block.type === "text") {
363
+ console.log(block.text);
364
+ }
365
+ }
366
+ ```
367
+
368
+ ## Thinking/Reasoning
369
+
370
+ 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.
371
+
372
+ ### Unified Interface (streamSimple/completeSimple)
373
+
374
+ ```typescript
375
+ import { getModel, streamSimple, completeSimple } from "@oh-my-pi/pi-ai";
376
+
377
+ // Many models across providers support thinking/reasoning
378
+ const model = getModel("anthropic", "claude-sonnet-4-20250514");
379
+ // or getModel('openai', 'gpt-5-mini');
380
+ // or getModel('google', 'gemini-2.5-flash');
381
+ // or getModel('xai', 'grok-code-fast-1');
382
+ // or getModel('groq', 'openai/gpt-oss-20b');
383
+ // or getModel('cerebras', 'gpt-oss-120b');
384
+ // or getModel('openrouter', 'z-ai/glm-4.5v');
385
+
386
+ // Check if model supports reasoning
387
+ if (model.reasoning) {
388
+ console.log("Model supports reasoning/thinking");
389
+ }
390
+
391
+ // Use the simplified reasoning option
392
+ const response = await completeSimple(
393
+ model,
394
+ {
395
+ messages: [{ role: "user", content: "Solve: 2x + 5 = 13" }],
396
+ },
397
+ {
398
+ reasoning: "medium", // 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' (xhigh maps to high on non-OpenAI providers)
399
+ }
400
+ );
401
+
402
+ // Access thinking and text blocks
403
+ for (const block of response.content) {
404
+ if (block.type === "thinking") {
405
+ console.log("Thinking:", block.thinking);
406
+ } else if (block.type === "text") {
407
+ console.log("Response:", block.text);
408
+ }
409
+ }
410
+ ```
411
+
412
+ ### Provider-Specific Options (stream/complete)
413
+
414
+ For fine-grained control, use the provider-specific options:
415
+
416
+ ```typescript
417
+ import { getModel, complete } from "@oh-my-pi/pi-ai";
418
+
419
+ // OpenAI Reasoning (o1, o3, gpt-5)
420
+ const openaiModel = getModel("openai", "gpt-5-mini");
421
+ await complete(openaiModel, context, {
422
+ reasoningEffort: "medium",
423
+ reasoningSummary: "detailed", // OpenAI Responses API only
424
+ });
425
+
426
+ // Anthropic Thinking (Claude Sonnet 4)
427
+ const anthropicModel = getModel("anthropic", "claude-sonnet-4-20250514");
428
+ await complete(anthropicModel, context, {
429
+ thinkingEnabled: true,
430
+ thinkingBudgetTokens: 8192, // Optional token limit
431
+ });
432
+
433
+ // Google Gemini Thinking
434
+ const googleModel = getModel("google", "gemini-2.5-flash");
435
+ await complete(googleModel, context, {
436
+ thinking: {
437
+ enabled: true,
438
+ budgetTokens: 8192, // -1 for dynamic, 0 to disable
439
+ },
440
+ });
441
+ ```
442
+
443
+ ### Streaming Thinking Content
444
+
445
+ When streaming, thinking content is delivered through specific events:
446
+
447
+ ```typescript
448
+ const s = streamSimple(model, context, { reasoning: "high" });
449
+
450
+ for await (const event of s) {
451
+ switch (event.type) {
452
+ case "thinking_start":
453
+ console.log("[Model started thinking]");
454
+ break;
455
+ case "thinking_delta":
456
+ process.stdout.write(event.delta); // Stream thinking content
457
+ break;
458
+ case "thinking_end":
459
+ console.log("\n[Thinking complete]");
460
+ break;
461
+ }
462
+ }
463
+ ```
464
+
465
+ ## Stop Reasons
466
+
467
+ Every `AssistantMessage` includes a `stopReason` field that indicates how the generation ended:
468
+
469
+ - `"stop"` - Normal completion, the model finished its response
470
+ - `"length"` - Output hit the maximum token limit
471
+ - `"toolUse"` - Model is calling tools and expects tool results
472
+ - `"error"` - An error occurred during generation
473
+ - `"aborted"` - Request was cancelled via abort signal
474
+
475
+ ## Error Handling
476
+
477
+ When a request ends with an error (including aborts and tool call validation errors), the streaming API emits an error event:
478
+
479
+ ```typescript
480
+ // In streaming
481
+ for await (const event of stream) {
482
+ if (event.type === "error") {
483
+ // event.reason is either "error" or "aborted"
484
+ // event.error is the AssistantMessage with partial content
485
+ console.error(`Error (${event.reason}):`, event.error.errorMessage);
486
+ console.log("Partial content:", event.error.content);
487
+ }
488
+ }
489
+
490
+ // The final message will have the error details
491
+ const message = await stream.result();
492
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
493
+ console.error("Request failed:", message.errorMessage);
494
+ // message.content contains any partial content received before the error
495
+ // message.usage contains partial token counts and costs
496
+ }
497
+ ```
498
+
499
+ ### Aborting Requests
500
+
501
+ The abort signal allows you to cancel in-progress requests. Aborted requests have `stopReason === 'aborted'`:
502
+
503
+ ```typescript
504
+ import { getModel, stream } from "@oh-my-pi/pi-ai";
505
+
506
+ const model = getModel("openai", "gpt-4o-mini");
507
+ const controller = new AbortController();
508
+
509
+ // Abort after 2 seconds
510
+ setTimeout(() => controller.abort(), 2000);
511
+
512
+ const s = stream(
513
+ model,
514
+ {
515
+ messages: [{ role: "user", content: "Write a long story" }],
516
+ },
517
+ {
518
+ signal: controller.signal,
519
+ }
520
+ );
521
+
522
+ for await (const event of s) {
523
+ if (event.type === "text_delta") {
524
+ process.stdout.write(event.delta);
525
+ } else if (event.type === "error") {
526
+ // event.reason tells you if it was "error" or "aborted"
527
+ console.log(`${event.reason === "aborted" ? "Aborted" : "Error"}:`, event.error.errorMessage);
528
+ }
529
+ }
530
+
531
+ // Get results (may be partial if aborted)
532
+ const response = await s.result();
533
+ if (response.stopReason === "aborted") {
534
+ console.log("Request was aborted:", response.errorMessage);
535
+ console.log("Partial content received:", response.content);
536
+ console.log("Tokens used:", response.usage);
537
+ }
538
+ ```
539
+
540
+ ### Continuing After Abort
541
+
542
+ Aborted messages can be added to the conversation context and continued in subsequent requests:
543
+
544
+ ```typescript
545
+ const context = {
546
+ messages: [{ role: "user", content: "Explain quantum computing in detail" }],
547
+ };
548
+
549
+ // First request gets aborted after 2 seconds
550
+ const controller1 = new AbortController();
551
+ setTimeout(() => controller1.abort(), 2000);
552
+
553
+ const partial = await complete(model, context, { signal: controller1.signal });
554
+
555
+ // Add the partial response to context
556
+ context.messages.push(partial);
557
+ context.messages.push({ role: "user", content: "Please continue" });
558
+
559
+ // Continue the conversation
560
+ const continuation = await complete(model, context);
561
+ ```
562
+
563
+ ## APIs, Models, and Providers
564
+
565
+ The library implements 4 API interfaces, each with its own streaming function and options:
566
+
567
+ - **`anthropic-messages`**: Anthropic's Messages API (`streamAnthropic`, `AnthropicOptions`)
568
+ - **`google-generative-ai`**: Google's Generative AI API (`streamGoogle`, `GoogleOptions`)
569
+ - **`openai-completions`**: OpenAI's Chat Completions API (`streamOpenAICompletions`, `OpenAICompletionsOptions`)
570
+ - **`openai-responses`**: OpenAI's Responses API (`streamOpenAIResponses`, `OpenAIResponsesOptions`)
571
+
572
+ ### Providers and Models
573
+
574
+ A **provider** offers models through a specific API. For example:
575
+
576
+ - **Anthropic** models use the `anthropic-messages` API
577
+ - **Google** models use the `google-generative-ai` API
578
+ - **OpenAI** models use the `openai-responses` API
579
+ - **Mistral, xAI, Cerebras, Groq, etc.** models use the `openai-completions` API (OpenAI-compatible)
580
+
581
+ ### Querying Providers and Models
582
+
583
+ ```typescript
584
+ import { getProviders, getModels, getModel } from "@oh-my-pi/pi-ai";
585
+
586
+ // Get all available providers
587
+ const providers = getProviders();
588
+ console.log(providers); // ['openai', 'anthropic', 'google', 'xai', 'groq', ...]
589
+
590
+ // Get all models from a provider (fully typed)
591
+ const anthropicModels = getModels("anthropic");
592
+ for (const model of anthropicModels) {
593
+ console.log(`${model.id}: ${model.name}`);
594
+ console.log(` API: ${model.api}`); // 'anthropic-messages'
595
+ console.log(` Context: ${model.contextWindow} tokens`);
596
+ console.log(` Vision: ${model.input.includes("image")}`);
597
+ console.log(` Reasoning: ${model.reasoning}`);
598
+ }
599
+
600
+ // Get a specific model (both provider and model ID are auto-completed in IDEs)
601
+ const model = getModel("openai", "gpt-4o-mini");
602
+ console.log(`Using ${model.name} via ${model.api} API`);
603
+ ```
604
+
605
+ ### Custom Models
606
+
607
+ You can create custom models for local inference servers or custom endpoints:
608
+
609
+ ```typescript
610
+ import { Model, stream } from "@oh-my-pi/pi-ai";
611
+
612
+ // Example: Ollama using OpenAI-compatible API
613
+ const ollamaModel: Model<"openai-completions"> = {
614
+ id: "llama-3.1-8b",
615
+ name: "Llama 3.1 8B (Ollama)",
616
+ api: "openai-completions",
617
+ provider: "ollama",
618
+ baseUrl: "http://localhost:11434/v1",
619
+ reasoning: false,
620
+ input: ["text"],
621
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
622
+ contextWindow: 128000,
623
+ maxTokens: 32000,
624
+ };
625
+
626
+ // Example: LiteLLM proxy with explicit compat settings
627
+ const litellmModel: Model<"openai-completions"> = {
628
+ id: "gpt-4o",
629
+ name: "GPT-4o (via LiteLLM)",
630
+ api: "openai-completions",
631
+ provider: "litellm",
632
+ baseUrl: "http://localhost:4000/v1",
633
+ reasoning: false,
634
+ input: ["text", "image"],
635
+ cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 },
636
+ contextWindow: 128000,
637
+ maxTokens: 16384,
638
+ compat: {
639
+ supportsStore: false, // LiteLLM doesn't support the store field
640
+ },
641
+ };
642
+
643
+ // Example: Custom endpoint with headers (bypassing Cloudflare bot detection)
644
+ const proxyModel: Model<"anthropic-messages"> = {
645
+ id: "claude-sonnet-4",
646
+ name: "Claude Sonnet 4 (Proxied)",
647
+ api: "anthropic-messages",
648
+ provider: "custom-proxy",
649
+ baseUrl: "https://proxy.example.com/v1",
650
+ reasoning: true,
651
+ input: ["text", "image"],
652
+ cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
653
+ contextWindow: 200000,
654
+ maxTokens: 8192,
655
+ headers: {
656
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
657
+ "X-Custom-Auth": "bearer-token-here",
658
+ },
659
+ };
660
+
661
+ // Use the custom model
662
+ const response = await stream(ollamaModel, context, {
663
+ apiKey: "dummy", // Ollama doesn't need a real key
664
+ });
665
+ ```
666
+
667
+ ### OpenAI Compatibility Settings
668
+
669
+ The `openai-completions` API is implemented by many providers with minor differences. By default, the library auto-detects compatibility settings based on `baseUrl` for known providers (Cerebras, xAI, Mistral, Chutes, etc.). For custom proxies or unknown endpoints, you can override these settings via the `compat` field:
670
+
671
+ ```typescript
672
+ interface OpenAICompat {
673
+ supportsStore?: boolean; // Whether provider supports the `store` field (default: true)
674
+ supportsDeveloperRole?: boolean; // Whether provider supports `developer` role vs `system` (default: true)
675
+ supportsReasoningEffort?: boolean; // Whether provider supports `reasoning_effort` (default: true)
676
+ maxTokensField?: "max_completion_tokens" | "max_tokens"; // Which field name to use (default: max_completion_tokens)
677
+ }
678
+ ```
679
+
680
+ 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:
681
+
682
+ - **LiteLLM proxies**: May not support `store` field
683
+ - **Custom inference servers**: May use non-standard field names
684
+ - **Self-hosted endpoints**: May have different feature support
685
+
686
+ ### Type Safety
687
+
688
+ Models are typed by their API, ensuring type-safe options:
689
+
690
+ ```typescript
691
+ // TypeScript knows this is an Anthropic model
692
+ const claude = getModel("anthropic", "claude-sonnet-4-20250514");
693
+
694
+ // So these options are type-checked for AnthropicOptions
695
+ await stream(claude, context, {
696
+ thinkingEnabled: true, // ✓ Valid for anthropic-messages
697
+ thinkingBudgetTokens: 2048, // ✓ Valid for anthropic-messages
698
+ // reasoningEffort: 'high' // ✗ TypeScript error: not valid for anthropic-messages
699
+ });
700
+ ```
701
+
702
+ ## Cross-Provider Handoffs
703
+
704
+ 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.
705
+
706
+ ### How It Works
707
+
708
+ When messages from one provider are sent to a different provider, the library automatically transforms them for compatibility:
709
+
710
+ - **User and tool result messages** are passed through unchanged
711
+ - **Assistant messages from the same provider/API** are preserved as-is
712
+ - **Assistant messages from different providers** have their thinking blocks converted to text with `<thinking>` tags
713
+ - **Tool calls and regular text** are preserved unchanged
714
+
715
+ ### Example: Multi-Provider Conversation
716
+
717
+ ```typescript
718
+ import { getModel, complete, Context } from "@oh-my-pi/pi-ai";
719
+
720
+ // Start with Claude
721
+ const claude = getModel("anthropic", "claude-sonnet-4-20250514");
722
+ const context: Context = {
723
+ messages: [],
724
+ };
725
+
726
+ context.messages.push({ role: "user", content: "What is 25 * 18?" });
727
+ const claudeResponse = await complete(claude, context, {
728
+ thinkingEnabled: true,
729
+ });
730
+ context.messages.push(claudeResponse);
731
+
732
+ // Switch to GPT-5 - it will see Claude's thinking as <thinking> tagged text
733
+ const gpt5 = getModel("openai", "gpt-5-mini");
734
+ context.messages.push({ role: "user", content: "Is that calculation correct?" });
735
+ const gptResponse = await complete(gpt5, context);
736
+ context.messages.push(gptResponse);
737
+
738
+ // Switch to Gemini
739
+ const gemini = getModel("google", "gemini-2.5-flash");
740
+ context.messages.push({ role: "user", content: "What was the original question?" });
741
+ const geminiResponse = await complete(gemini, context);
742
+ ```
743
+
744
+ ### Provider Compatibility
745
+
746
+ All providers can handle messages from other providers, including:
747
+
748
+ - Text content
749
+ - Tool calls and tool results (including images in tool results)
750
+ - Thinking/reasoning blocks (transformed to tagged text for cross-provider compatibility)
751
+ - Aborted messages with partial content
752
+
753
+ This enables flexible workflows where you can:
754
+
755
+ - Start with a fast model for initial responses
756
+ - Switch to a more capable model for complex reasoning
757
+ - Use specialized models for specific tasks
758
+ - Maintain conversation continuity across provider outages
759
+
760
+ ## Context Serialization
761
+
762
+ 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:
763
+
764
+ ```typescript
765
+ import { Context, getModel, complete } from "@oh-my-pi/pi-ai";
766
+
767
+ // Create and use a context
768
+ const context: Context = {
769
+ systemPrompt: "You are a helpful assistant.",
770
+ messages: [{ role: "user", content: "What is TypeScript?" }],
771
+ };
772
+
773
+ const model = getModel("openai", "gpt-4o-mini");
774
+ const response = await complete(model, context);
775
+ context.messages.push(response);
776
+
777
+ // Serialize the entire context
778
+ const serialized = JSON.stringify(context);
779
+ console.log("Serialized context size:", serialized.length, "bytes");
780
+
781
+ // Save to database, localStorage, file, etc.
782
+ localStorage.setItem("conversation", serialized);
783
+
784
+ // Later: deserialize and continue the conversation
785
+ const restored: Context = JSON.parse(localStorage.getItem("conversation")!);
786
+ restored.messages.push({ role: "user", content: "Tell me more about its type system" });
787
+
788
+ // Continue with any model
789
+ const newModel = getModel("anthropic", "claude-3-5-haiku-20241022");
790
+ const continuation = await complete(newModel, restored);
791
+ ```
792
+
793
+ > **Note**: If the context contains images (encoded as base64 as shown in the Image Input section), those will also be serialized.
794
+
795
+ ## Browser Usage
796
+
797
+ The library supports browser environments. You must pass the API key explicitly since environment variables are not available in browsers:
798
+
799
+ ```typescript
800
+ import { getModel, complete } from "@oh-my-pi/pi-ai";
801
+
802
+ // API key must be passed explicitly in browser
803
+ const model = getModel("anthropic", "claude-3-5-haiku-20241022");
804
+
805
+ const response = await complete(
806
+ model,
807
+ {
808
+ messages: [{ role: "user", content: "Hello!" }],
809
+ },
810
+ {
811
+ apiKey: "your-api-key",
812
+ }
813
+ );
814
+ ```
815
+
816
+ > **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.
817
+
818
+ ### Environment Variables (Node.js only)
819
+
820
+ In Node.js environments, you can set environment variables to avoid passing API keys:
821
+
822
+ ```bash
823
+ OPENAI_API_KEY=sk-...
824
+ ANTHROPIC_API_KEY=sk-ant-...
825
+ GEMINI_API_KEY=...
826
+ MISTRAL_API_KEY=...
827
+ GROQ_API_KEY=gsk_...
828
+ CEREBRAS_API_KEY=csk-...
829
+ XAI_API_KEY=xai-...
830
+ ZAI_API_KEY=...
831
+ OPENROUTER_API_KEY=sk-or-...
832
+ ```
833
+
834
+ When set, the library automatically uses these keys:
835
+
836
+ ```typescript
837
+ // Uses OPENAI_API_KEY from environment
838
+ const model = getModel("openai", "gpt-4o-mini");
839
+ const response = await complete(model, context);
840
+
841
+ // Or override with explicit key
842
+ const response = await complete(model, context, {
843
+ apiKey: "sk-different-key",
844
+ });
845
+ ```
846
+
847
+ ### Checking Environment Variables
848
+
849
+ ```typescript
850
+ import { getEnvApiKey } from "@oh-my-pi/pi-ai";
851
+
852
+ // Check if an API key is set in environment variables
853
+ const key = getEnvApiKey("openai"); // checks OPENAI_API_KEY
854
+ ```
855
+
856
+ ## OAuth Providers
857
+
858
+ Several providers require OAuth authentication instead of static API keys:
859
+
860
+ - **Anthropic** (Claude Pro/Max subscription)
861
+ - **GitHub Copilot** (Copilot subscription)
862
+ - **Google Gemini CLI** (Free Gemini 2.0/2.5 via Google Cloud Code Assist)
863
+ - **Antigravity** (Free Gemini 3, Claude, GPT-OSS via Google Cloud)
864
+
865
+ ### CLI Login
866
+
867
+ The quickest way to authenticate:
868
+
869
+ ```bash
870
+ npx @oh-my-pi/pi-ai login # interactive provider selection
871
+ npx @oh-my-pi/pi-ai login anthropic # login to specific provider
872
+ npx @oh-my-pi/pi-ai list # list available providers
873
+ ```
874
+
875
+ Credentials are saved to `auth.json` in the current directory.
876
+
877
+ ### Programmatic OAuth
878
+
879
+ The library provides login and token refresh functions. Credential storage is the caller's responsibility.
880
+
881
+ ```typescript
882
+ import {
883
+ // Login functions (return credentials, do not store)
884
+ loginAnthropic,
885
+ loginGitHubCopilot,
886
+ loginGeminiCli,
887
+ loginAntigravity,
888
+
889
+ // Token management
890
+ refreshOAuthToken, // (provider, credentials) => new credentials
891
+ getOAuthApiKey, // (provider, credentialsMap) => { newCredentials, apiKey } | null
892
+
893
+ // Types
894
+ type OAuthProvider, // 'anthropic' | 'github-copilot' | 'google-gemini-cli' | 'google-antigravity'
895
+ type OAuthCredentials,
896
+ } from "@oh-my-pi/pi-ai";
897
+ ```
898
+
899
+ ### Login Flow Example
900
+
901
+ ```typescript
902
+ import { loginGitHubCopilot } from "@oh-my-pi/pi-ai";
903
+ import { writeFileSync } from "fs";
904
+
905
+ const credentials = await loginGitHubCopilot({
906
+ onAuth: (url, instructions) => {
907
+ console.log(`Open: ${url}`);
908
+ if (instructions) console.log(instructions);
909
+ },
910
+ onPrompt: async (prompt) => {
911
+ return await getUserInput(prompt.message);
912
+ },
913
+ onProgress: (message) => console.log(message),
914
+ });
915
+
916
+ // Store credentials yourself
917
+ const auth = { "github-copilot": { type: "oauth", ...credentials } };
918
+ writeFileSync("auth.json", JSON.stringify(auth, null, 2));
919
+ ```
920
+
921
+ ### Using OAuth Tokens
922
+
923
+ Use `getOAuthApiKey()` to get an API key, automatically refreshing if expired:
924
+
925
+ ```typescript
926
+ import { getModel, complete, getOAuthApiKey } from "@oh-my-pi/pi-ai";
927
+ import { readFileSync, writeFileSync } from "fs";
928
+
929
+ // Load your stored credentials
930
+ const auth = JSON.parse(readFileSync("auth.json", "utf-8"));
931
+
932
+ // Get API key (refreshes if expired)
933
+ const result = await getOAuthApiKey("github-copilot", auth);
934
+ if (!result) throw new Error("Not logged in");
935
+
936
+ // Save refreshed credentials
937
+ auth["github-copilot"] = { type: "oauth", ...result.newCredentials };
938
+ writeFileSync("auth.json", JSON.stringify(auth, null, 2));
939
+
940
+ // Use the API key
941
+ const model = getModel("github-copilot", "gpt-4o");
942
+ const response = await complete(
943
+ model,
944
+ {
945
+ messages: [{ role: "user", content: "Hello!" }],
946
+ },
947
+ { apiKey: result.apiKey }
948
+ );
949
+ ```
950
+
951
+ ### Provider Notes
952
+
953
+ **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".
954
+
955
+ **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.
956
+
957
+ ## License
958
+
959
+ MIT