@f5-sales-demo/pi-ai 19.51.2

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