{"_rev":"4-0a0cb9a80f6780cbcda2fbc06a02c09b","time":{"created":"2026-07-06T18:02:46.412Z","modified":"2026-07-06T18:02:46.930Z","0.78.1":"2026-06-08T08:15:19.846Z","0.1.0":"2026-07-06T18:02:46.753Z"},"_id":"@aaditri-globaltech/aria-ai","name":"@aaditri-globaltech/aria-ai","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@aaditri-globaltech/aria-ai","version":"0.1.0","description":"Unified LLM API with automatic model discovery and provider configuration","type":"module","main":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./anthropic":{"types":"./dist/providers/anthropic.d.ts","import":"./dist/providers/anthropic.js"},"./azure-openai-responses":{"types":"./dist/providers/azure-openai-responses.d.ts","import":"./dist/providers/azure-openai-responses.js"},"./google":{"types":"./dist/providers/google.d.ts","import":"./dist/providers/google.js"},"./google-vertex":{"types":"./dist/providers/google-vertex.d.ts","import":"./dist/providers/google-vertex.js"},"./mistral":{"types":"./dist/providers/mistral.d.ts","import":"./dist/providers/mistral.js"},"./openai-codex-responses":{"types":"./dist/providers/openai-codex-responses.d.ts","import":"./dist/providers/openai-codex-responses.js"},"./openai-completions":{"types":"./dist/providers/openai-completions.d.ts","import":"./dist/providers/openai-completions.js"},"./openai-responses":{"types":"./dist/providers/openai-responses.d.ts","import":"./dist/providers/openai-responses.js"},"./oauth":{"types":"./dist/oauth.d.ts","import":"./dist/oauth.js"},"./bedrock-provider":{"types":"./dist/bedrock-provider.d.ts","import":"./dist/bedrock-provider.js"}},"bin":{"aria-ai":"dist/cli.js"},"scripts":{"clean":"shx rm -rf dist","generate-models":"node scripts/generate-models.ts","generate-image-models":"node scripts/generate-image-models.ts","build":"npm run generate-models && npm run generate-image-models && tsgo -p tsconfig.build.json","test":"vitest --run","prepublishOnly":"npm run clean && npm run build"},"dependencies":{"@anthropic-ai/sdk":"0.91.1","@aws-sdk/client-bedrock-runtime":"3.1048.0","@smithy/node-http-handler":"4.7.3","@google/genai":"1.52.0","@mistralai/mistralai":"2.2.1","http-proxy-agent":"7.0.2","https-proxy-agent":"7.0.6","openai":"6.26.0","partial-json":"0.1.7","typebox":"1.1.38"},"keywords":["ai","llm","openai","anthropic","gemini","bedrock","unified","api"],"author":{"name":"Kumar R Anand"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/Aaditri-GlobalTech/aria.git","directory":"packages/ai"},"engines":{"node":">=22.19.0"},"devDependencies":{"@types/node":"24.12.4","canvas":"3.2.3","vitest":"3.2.4"},"_id":"@aaditri-globaltech/aria-ai@0.1.0","gitHead":"c0ea139e82cc1be93117b4356620a15dbd5371e2","bugs":{"url":"https://github.com/Aaditri-GlobalTech/aria/issues"},"homepage":"https://github.com/Aaditri-GlobalTech/aria#readme","_nodeVersion":"22.23.1","_npmVersion":"10.9.8","dist":{"integrity":"sha512-Z75ufC6R/tgupkL9N+x0sELsbYZXsjMg3EB7e/fWM0UkX69SAV++MyB4T2JOtmx3ClLNnp6dkGN+JjPNItUy7A==","shasum":"13f409a14d9d58b84def8d3ad83fb37c3a81220c","tarball":"https://registry.npmjs.org/@aaditri-globaltech/aria-ai/-/aria-ai-0.1.0.tgz","fileCount":218,"unpackedSize":4825559,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDvosKs00kqv6OFavv3VNGrubYOdS3DdXPh5k5bloW8vwIhAP+00x/CR7nMFUQaKygzk5JigUMDcEwQIR+x5YjZgTbR"}]},"_npmUser":{"name":"kumaranand","email":"aaditriglobaltech@gmail.com"},"directories":{},"maintainers":[{"name":"kumaranand","email":"aaditriglobaltech@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/aria-ai_0.1.0_1783360966521_0.12400202947930539"},"_hasShrinkwrap":false}},"maintainers":[{"name":"kumaranand","email":"aaditriglobaltech@gmail.com"}],"description":"Unified LLM API with automatic model discovery and provider configuration","homepage":"https://github.com/Aaditri-GlobalTech/aria#readme","keywords":["ai","llm","openai","anthropic","gemini","bedrock","unified","api"],"repository":{"type":"git","url":"git+https://github.com/Aaditri-GlobalTech/aria.git","directory":"packages/ai"},"author":{"name":"Kumar R Anand"},"bugs":{"url":"https://github.com/Aaditri-GlobalTech/aria/issues"},"license":"MIT","readme":"# @aaditri-globaltech/aria-ai\n\nUnified LLM API with automatic model discovery, provider configuration, token and cost tracking, and simple context persistence and hand-off to other models mid-session.\n\n**Note**: This library only includes models that support tool calling (function calling), as this is essential for agentic workflows.\n\n## Table of Contents\n\n- [Supported Providers](#supported-providers)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Tools](#tools)\n  - [Defining Tools](#defining-tools)\n  - [Handling Tool Calls](#handling-tool-calls)\n  - [Streaming Tool Calls with Partial JSON](#streaming-tool-calls-with-partial-json)\n  - [Validating Tool Arguments](#validating-tool-arguments)\n  - [Complete Event Reference](#complete-event-reference)\n- [Image Input](#image-input)\n- [Image Generation](#image-generation)\n  - [Basic Image Generation](#basic-image-generation)\n  - [Notes and Limitations](#notes-and-limitations)\n- [Thinking/Reasoning](#thinkingreasoning)\n  - [Unified Interface](#unified-interface-streamsimplecompletesimple)\n  - [Provider-Specific Options](#provider-specific-options-streamcomplete)\n  - [Streaming Thinking Content](#streaming-thinking-content)\n- [Stop Reasons](#stop-reasons)\n- [Error Handling](#error-handling)\n  - [Aborting Requests](#aborting-requests)\n  - [Continuing After Abort](#continuing-after-abort)\n- [APIs, Models, and Providers](#apis-models-and-providers)\n  - [Providers and Models](#providers-and-models)\n  - [Querying Providers and Models](#querying-providers-and-models)\n  - [Custom Models](#custom-models)\n  - [OpenAI Compatibility Settings](#openai-compatibility-settings)\n  - [Type Safety](#type-safety)\n- [Cross-Provider Handoffs](#cross-provider-handoffs)\n- [Context Serialization](#context-serialization)\n- [Browser Usage](#browser-usage)\n  - [Browser Compatibility Notes](#browser-compatibility-notes)\n  - [Environment Variables](#environment-variables-nodejs-only)\n  - [Checking Environment Variables](#checking-environment-variables)\n- [OAuth Providers](#oauth-providers)\n  - [Vertex AI](#vertex-ai)\n  - [CLI Login](#cli-login)\n  - [Programmatic OAuth](#programmatic-oauth)\n  - [Login Flow Example](#login-flow-example)\n  - [Using OAuth Tokens](#using-oauth-tokens)\n  - [Provider Notes](#provider-notes)\n- [License](#license)\n\n## Supported Providers\n\n- **OpenAI**\n- **Ant Ling**\n- **Azure OpenAI (Responses)**\n- **OpenAI Codex** (ChatGPT Plus/Pro subscription, requires OAuth, see below)\n- **DeepSeek**\n- **NVIDIA NIM**\n- **Anthropic**\n- **Google**\n- **Vertex AI** (Gemini via Vertex AI)\n- **Mistral**\n- **Groq**\n- **Cerebras**\n- **Cloudflare AI Gateway**\n- **Cloudflare Workers AI**\n- **xAI**\n- **OpenRouter**\n- **Vercel AI Gateway**\n- **ZAI** (with separate Coding Plan China provider)\n- **MiniMax**\n- **Together AI**\n- **GitHub Copilot** (requires OAuth, see below)\n- **Amazon Bedrock**\n- **OpenCode Zen**\n- **OpenCode Go**\n- **Fireworks** (uses Anthropic-compatible API)\n- **Kimi For Coding** (Moonshot AI, uses Anthropic-compatible API)\n- **Xiaomi MiMo** (uses Anthropic-compatible API; defaults to API billing endpoint, with separate Token Plan providers for `cn`/`ams`/`sgp` regions)\n- **Any OpenAI-compatible API**: Ollama, vLLM, LM Studio, etc.\n\n## Installation\n\n```bash\nnpm install @aaditri-globaltech/aria-ai\n```\n\nTypeBox exports are re-exported from `@aaditri-globaltech/aria-ai`: `Type`, `Static`, and `TSchema`.\n\n## Quick Start\n\n```typescript\nimport { Type, getModel, stream, complete, Context, Tool, StringEnum } from '@aaditri-globaltech/aria-ai';\n\n// Fully typed with auto-complete support for both providers and models\nconst model = getModel('openai', 'gpt-4o-mini');\n\n// Define tools with TypeBox schemas for type safety and validation\nconst tools: Tool[] = [{\n  name: 'get_time',\n  description: 'Get the current time',\n  parameters: Type.Object({\n    timezone: Type.Optional(Type.String({ description: 'Optional timezone (e.g., America/New_York)' }))\n  })\n}];\n\n// Build a conversation context (easily serializable and transferable between models)\nconst context: Context = {\n  systemPrompt: 'You are a helpful assistant.',\n  messages: [{ role: 'user', content: 'What time is it?' }],\n  tools\n};\n\n// Option 1: Streaming with all event types\nconst s = stream(model, context);\n\nfor await (const event of s) {\n  switch (event.type) {\n    case 'start':\n      console.log(`Starting with ${event.partial.model}`);\n      break;\n    case 'text_start':\n      console.log('\\n[Text started]');\n      break;\n    case 'text_delta':\n      process.stdout.write(event.delta);\n      break;\n    case 'text_end':\n      console.log('\\n[Text ended]');\n      break;\n    case 'thinking_start':\n      console.log('[Model is thinking...]');\n      break;\n    case 'thinking_delta':\n      process.stdout.write(event.delta);\n      break;\n    case 'thinking_end':\n      console.log('[Thinking complete]');\n      break;\n    case 'toolcall_start':\n      console.log(`\\n[Tool call started: index ${event.contentIndex}]`);\n      break;\n    case 'toolcall_delta':\n      // Partial tool arguments are being streamed\n      const partialCall = event.partial.content[event.contentIndex];\n      if (partialCall.type === 'toolCall') {\n        console.log(`[Streaming args for ${partialCall.name}]`);\n      }\n      break;\n    case 'toolcall_end':\n      console.log(`\\nTool called: ${event.toolCall.name}`);\n      console.log(`Arguments: ${JSON.stringify(event.toolCall.arguments)}`);\n      break;\n    case 'done':\n      console.log(`\\nFinished: ${event.reason}`);\n      break;\n    case 'error':\n      console.error(`Error: ${event.error}`);\n      break;\n  }\n}\n\n// Get the final message after streaming, add it to the context\nconst finalMessage = await s.result();\ncontext.messages.push(finalMessage);\n\n// Handle tool calls if any\nconst toolCalls = finalMessage.content.filter(b => b.type === 'toolCall');\nfor (const call of toolCalls) {\n  // Execute the tool\n  const result = call.name === 'get_time'\n    ? new Date().toLocaleString('en-US', {\n        timeZone: call.arguments.timezone || 'UTC',\n        dateStyle: 'full',\n        timeStyle: 'long'\n      })\n    : 'Unknown tool';\n\n  // Add tool result to context (supports text and images)\n  context.messages.push({\n    role: 'toolResult',\n    toolCallId: call.id,\n    toolName: call.name,\n    content: [{ type: 'text', text: result }],\n    isError: false,\n    timestamp: Date.now()\n  });\n}\n\n// Continue if there were tool calls\nif (toolCalls.length > 0) {\n  const continuation = await complete(model, context);\n  context.messages.push(continuation);\n  console.log('After tool execution:', continuation.content);\n}\n\nconsole.log(`Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`);\nconsole.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);\n\n// Option 2: Get complete response without streaming\nconst response = await complete(model, context);\n\nfor (const block of response.content) {\n  if (block.type === 'text') {\n    console.log(block.text);\n  } else if (block.type === 'toolCall') {\n    console.log(`Tool: ${block.name}(${JSON.stringify(block.arguments)})`);\n  }\n}\n```\n\n## Tools\n\nTools enable LLMs to interact with external systems. This library uses TypeBox schemas for type-safe tool definitions with automatic validation using TypeBox's built-in validator and value conversion utilities. TypeBox schemas can be serialized and deserialized as plain JSON, making them ideal for distributed systems.\n\n### Defining Tools\n\n```typescript\nimport { Type, Tool, StringEnum } from '@aaditri-globaltech/aria-ai';\n\n// Define tool parameters with TypeBox\nconst weatherTool: Tool = {\n  name: 'get_weather',\n  description: 'Get current weather for a location',\n  parameters: Type.Object({\n    location: Type.String({ description: 'City name or coordinates' }),\n    units: StringEnum(['celsius', 'fahrenheit'], { default: 'celsius' })\n  })\n};\n\n// Note: For Google API compatibility, use StringEnum helper instead of Type.Enum\n// Type.Enum generates anyOf/const patterns that Google doesn't support\n\nconst bookMeetingTool: Tool = {\n  name: 'book_meeting',\n  description: 'Schedule a meeting',\n  parameters: Type.Object({\n    title: Type.String({ minLength: 1 }),\n    startTime: Type.String({ format: 'date-time' }),\n    endTime: Type.String({ format: 'date-time' }),\n    attendees: Type.Array(Type.String({ format: 'email' }), { minItems: 1 })\n  })\n};\n```\n\n### Handling Tool Calls\n\nTool results use content blocks and can include both text and images:\n\n```typescript\nimport { readFileSync } from 'fs';\n\nconst context: Context = {\n  messages: [{ role: 'user', content: 'What is the weather in London?' }],\n  tools: [weatherTool]\n};\n\nconst response = await complete(model, context);\n\n// Check for tool calls in the response\nfor (const block of response.content) {\n  if (block.type === 'toolCall') {\n    // Execute your tool with the arguments\n    // See \"Validating Tool Arguments\" section for validation\n    const result = await executeWeatherApi(block.arguments);\n\n    // Add tool result with text content\n    context.messages.push({\n      role: 'toolResult',\n      toolCallId: block.id,\n      toolName: block.name,\n      content: [{ type: 'text', text: JSON.stringify(result) }],\n      isError: false,\n      timestamp: Date.now()\n    });\n  }\n}\n\n// Tool results can also include images (for vision-capable models)\nconst imageBuffer = readFileSync('chart.png');\ncontext.messages.push({\n  role: 'toolResult',\n  toolCallId: 'tool_xyz',\n  toolName: 'generate_chart',\n  content: [\n    { type: 'text', text: 'Generated chart showing temperature trends' },\n    { type: 'image', data: imageBuffer.toString('base64'), mimeType: 'image/png' }\n  ],\n  isError: false,\n  timestamp: Date.now()\n});\n```\n\n### Streaming Tool Calls with Partial JSON\n\nDuring streaming, tool call arguments are progressively parsed as they arrive. This enables real-time UI updates before the complete arguments are available:\n\n```typescript\nconst s = stream(model, context);\n\nfor await (const event of s) {\n  if (event.type === 'toolcall_delta') {\n    const toolCall = event.partial.content[event.contentIndex];\n\n    // toolCall.arguments contains partially parsed JSON during streaming\n    // This allows for progressive UI updates\n    if (toolCall.type === 'toolCall' && toolCall.arguments) {\n      // BE DEFENSIVE: arguments may be incomplete\n      // Example: Show file path being written even before content is complete\n      if (toolCall.name === 'write_file' && toolCall.arguments.path) {\n        console.log(`Writing to: ${toolCall.arguments.path}`);\n\n        // Content might be partial or missing\n        if (toolCall.arguments.content) {\n          console.log(`Content preview: ${toolCall.arguments.content.substring(0, 100)}...`);\n        }\n      }\n    }\n  }\n\n  if (event.type === 'toolcall_end') {\n    // Here toolCall.arguments is complete (but not yet validated)\n    const toolCall = event.toolCall;\n    console.log(`Tool completed: ${toolCall.name}`, toolCall.arguments);\n  }\n}\n```\n\n**Important notes about partial tool arguments:**\n- During `toolcall_delta` events, `arguments` contains the best-effort parse of partial JSON\n- Fields may be missing or incomplete - always check for existence before use\n- String values may be truncated mid-word\n- Arrays may be incomplete\n- Nested objects may be partially populated\n- At minimum, `arguments` will be an empty object `{}`, never `undefined`\n- The Google provider does not support function call streaming. Instead, you will receive a single `toolcall_delta` event with the full arguments.\n\n### Validating Tool Arguments\n\nWhen 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.\n\nWhen implementing your own tool execution loop with `stream()` or `complete()`, use `validateToolCall` to validate arguments before passing them to your tools:\n\n```typescript\nimport { stream, validateToolCall, Tool } from '@aaditri-globaltech/aria-ai';\n\nconst tools: Tool[] = [weatherTool, calculatorTool];\nconst s = stream(model, { messages, tools });\n\nfor await (const event of s) {\n  if (event.type === 'toolcall_end') {\n    const toolCall = event.toolCall;\n\n    try {\n      // Validate arguments against the tool's schema (throws on invalid args)\n      const validatedArgs = validateToolCall(tools, toolCall);\n      const result = await executeMyTool(toolCall.name, validatedArgs);\n      // ... add tool result to context\n    } catch (error) {\n      // Validation failed - return error as tool result so model can retry\n      context.messages.push({\n        role: 'toolResult',\n        toolCallId: toolCall.id,\n        toolName: toolCall.name,\n        content: [{ type: 'text', text: error.message }],\n        isError: true,\n        timestamp: Date.now()\n      });\n    }\n  }\n}\n```\n\n### Complete Event Reference\n\nAll streaming events emitted during assistant message generation:\n\n| Event Type | Description | Key Properties |\n|------------|-------------|----------------|\n| `start` | Stream begins | `partial`: Initial assistant message structure |\n| `text_start` | Text block starts | `contentIndex`: Position in content array |\n| `text_delta` | Text chunk received | `delta`: New text, `contentIndex`: Position |\n| `text_end` | Text block complete | `content`: Full text, `contentIndex`: Position |\n| `thinking_start` | Thinking block starts | `contentIndex`: Position in content array |\n| `thinking_delta` | Thinking chunk received | `delta`: New text, `contentIndex`: Position |\n| `thinking_end` | Thinking block complete | `content`: Full thinking, `contentIndex`: Position |\n| `toolcall_start` | Tool call begins | `contentIndex`: Position in content array |\n| `toolcall_delta` | Tool arguments streaming | `delta`: JSON chunk, `partial.content[contentIndex].arguments`: Partial parsed args |\n| `toolcall_end` | Tool call complete | `toolCall`: Complete validated tool call with `id`, `name`, `arguments` |\n| `done` | Stream complete | `reason`: Stop reason (\"stop\", \"length\", \"toolUse\"), `message`: Final assistant message |\n| `error` | Error occurred | `reason`: Error type (\"error\" or \"aborted\"), `error`: AssistantMessage with partial content |\n\nStreaming events for different content blocks are not guaranteed to be contiguous. Providers may emit deltas for text, thinking, and tool calls in the same upstream chunk, and Aria may surface corresponding events interleaved, for example `text_start`, `text_delta`, `toolcall_start`, `text_delta`, `toolcall_delta`. Consumers must use `contentIndex` to associate each delta/end event with its block and must not assume that a block's `*_start`/`*_delta`/`*_end` sequence is uninterrupted by events for other blocks.\n\n## Image Input\n\nModels 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.\n\n```typescript\nimport { readFileSync } from 'fs';\nimport { getModel, complete } from '@aaditri-globaltech/aria-ai';\n\nconst model = getModel('openai', 'gpt-4o-mini');\n\n// Check if model supports images\nif (model.input.includes('image')) {\n  console.log('Model supports vision');\n}\n\nconst imageBuffer = readFileSync('image.png');\nconst base64Image = imageBuffer.toString('base64');\n\nconst response = await complete(model, {\n  messages: [{\n    role: 'user',\n    content: [\n      { type: 'text', text: 'What is in this image?' },\n      { type: 'image', data: base64Image, mimeType: 'image/png' }\n    ]\n  }]\n});\n\n// Access the response\nfor (const block of response.content) {\n  if (block.type === 'text') {\n    console.log(block.text);\n  }\n}\n```\n\n## Image Generation\n\nImage generation uses a separate API surface from text/chat generation. Use `getImageModel()` / `getImageModels()` / `getImageProviders()` to discover image-generation models, and `generateImages()` to get the final result.\n\nDo not use `stream()` or `complete()` for image generation. Image generation is a one-shot API: `generateImages()` waits for the provider response and returns the final `AssistantImages` result.\n\n### Basic Image Generation\n\n```typescript\nimport { getImageModel, generateImages } from '@aaditri-globaltech/aria-ai';\n\nconst model = getImageModel('openrouter', 'google/gemini-2.5-flash-image');\n\nconst result = await generateImages(model, {\n  input: [{ type: 'text', text: 'Generate a red circle on a plain white background.' }]\n}, {\n  apiKey: process.env.OPENROUTER_API_KEY\n});\n\nfor (const block of result.output) {\n  if (block.type === 'text') {\n    console.log(block.text);\n  } else if (block.type === 'image') {\n    console.log(block.mimeType);\n    console.log(block.data.substring(0, 32));\n  }\n}\n```\n\nSome models also support image input:\n\n```typescript\nimport { readFileSync } from 'fs';\n\nconst imageBuffer = readFileSync('input.png');\nconst result = await generateImages(model, {\n  input: [\n    { type: 'text', text: 'Create a variation of this image with a blue background.' },\n    { type: 'image', data: imageBuffer.toString('base64'), mimeType: 'image/png' }\n  ]\n}, {\n  apiKey: process.env.OPENROUTER_API_KEY\n});\n```\n\nCheck capabilities on the model metadata:\n\n```typescript\nconsole.log(model.input);   // ['text', 'image']\nconsole.log(model.output);  // ['image'] or ['image', 'text']\n```\n\n### Notes and Limitations\n\n- Use `getImageModel(...)`, not `getModel(...)`.\n- Use `generateImages()`, not `stream()` / `complete()`.\n- Image-generation models do not participate in tool calling.\n- Outputs are returned in `AssistantImages.output` and can include both base64-encoded `ImageContent` blocks and `TextContent` blocks.\n- Some models return only images, others return images plus text. Check `model.output`.\n- Some models accept image input, others are text-to-image only. Check `model.input`.\n- Like the streaming APIs, image generation supports options such as `apiKey`, `signal`, `headers`, `onPayload`, and `onResponse`, and results may include `stopReason`, `responseId`, and `usage`.\n- If you want a model to analyze images in a conversation or call tools, use the regular `stream()` / `complete()` APIs with a model that supports image input.\n- At the moment, image generation is available through only one provider, OpenRouter.\n\n## Thinking/Reasoning\n\nMany 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.\n\n### Unified Interface (streamSimple/completeSimple)\n\n```typescript\nimport { getModel, streamSimple, completeSimple } from '@aaditri-globaltech/aria-ai';\n\n// Many models across providers support thinking/reasoning\nconst model = getModel('anthropic', 'claude-sonnet-4-20250514');\n// or getModel('openai', 'gpt-5-mini');\n// or getModel('google', 'gemini-2.5-flash');\n// or getModel('xai', 'grok-code-fast-1');\n// or getModel('groq', 'openai/gpt-oss-20b');\n// or getModel('cerebras', 'gpt-oss-120b');\n// or getModel('openrouter', 'z-ai/glm-4.5v');\n\n// Check if model supports reasoning\nif (model.reasoning) {\n  console.log('Model supports reasoning/thinking');\n}\n\n// Use the simplified reasoning option\nconst response = await completeSimple(model, {\n  messages: [{ role: 'user', content: 'Solve: 2x + 5 = 13' }]\n}, {\n  reasoning: 'medium'  // 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'\n});\n\n// Access thinking and text blocks\nfor (const block of response.content) {\n  if (block.type === 'thinking') {\n    console.log('Thinking:', block.thinking);\n  } else if (block.type === 'text') {\n    console.log('Response:', block.text);\n  }\n}\n```\n\n### Provider-Specific Options (stream/complete)\n\nFor fine-grained control, use the provider-specific options:\n\n```typescript\nimport { getModel, complete } from '@aaditri-globaltech/aria-ai';\n\n// OpenAI Reasoning (o1, o3, gpt-5)\nconst openaiModel = getModel('openai', 'gpt-5-mini');\nawait complete(openaiModel, context, {\n  reasoningEffort: 'medium',\n  reasoningSummary: 'detailed'  // OpenAI Responses API only\n});\n\n// Anthropic Thinking (Claude Sonnet 4)\nconst anthropicModel = getModel('anthropic', 'claude-sonnet-4-20250514');\nawait complete(anthropicModel, context, {\n  thinkingEnabled: true,\n  thinkingBudgetTokens: 8192  // Optional token limit\n});\n\n// Google Gemini Thinking\nconst googleModel = getModel('google', 'gemini-2.5-flash');\nawait complete(googleModel, context, {\n  thinking: {\n    enabled: true,\n    budgetTokens: 8192  // -1 for dynamic, 0 to disable\n  }\n});\n```\n\n### Streaming Thinking Content\n\nWhen streaming, thinking content is delivered through specific events:\n\n```typescript\nconst s = streamSimple(model, context, { reasoning: 'high' });\n\nfor await (const event of s) {\n  switch (event.type) {\n    case 'thinking_start':\n      console.log('[Model started thinking]');\n      break;\n    case 'thinking_delta':\n      process.stdout.write(event.delta);  // Stream thinking content\n      break;\n    case 'thinking_end':\n      console.log('\\n[Thinking complete]');\n      break;\n  }\n}\n```\n\n## Stop Reasons\n\nEvery `AssistantMessage` includes a `stopReason` field that indicates how the generation ended:\n\n- `\"stop\"` - Normal completion, the model finished its response\n- `\"length\"` - Output hit the maximum token limit\n- `\"toolUse\"` - Model is calling tools and expects tool results\n- `\"error\"` - An error occurred during generation\n- `\"aborted\"` - Request was cancelled via abort signal\n\n`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.\n\n## Error Handling\n\nWhen a request ends with an error (including aborts and tool call validation errors), the streaming API emits an error event:\n\n```typescript\n// In streaming\nfor await (const event of stream) {\n  if (event.type === 'error') {\n    // event.reason is either \"error\" or \"aborted\"\n    // event.error is the AssistantMessage with partial content\n    console.error(`Error (${event.reason}):`, event.error.errorMessage);\n    console.log('Partial content:', event.error.content);\n  }\n}\n\n// The final message will have the error details\nconst message = await stream.result();\nif (message.stopReason === 'error' || message.stopReason === 'aborted') {\n  console.error('Request failed:', message.errorMessage);\n  // message.content contains any partial content received before the error\n  // message.usage contains partial token counts and costs\n}\n```\n\n### Aborting Requests\n\nThe abort signal allows you to cancel in-progress requests. Aborted requests have `stopReason === 'aborted'`:\n\n```typescript\nimport { getModel, stream } from '@aaditri-globaltech/aria-ai';\n\nconst model = getModel('openai', 'gpt-4o-mini');\nconst controller = new AbortController();\n\n// Abort after 2 seconds\nsetTimeout(() => controller.abort(), 2000);\n\nconst s = stream(model, {\n  messages: [{ role: 'user', content: 'Write a long story' }]\n}, {\n  signal: controller.signal\n});\n\nfor await (const event of s) {\n  if (event.type === 'text_delta') {\n    process.stdout.write(event.delta);\n  } else if (event.type === 'error') {\n    // event.reason tells you if it was \"error\" or \"aborted\"\n    console.log(`${event.reason === 'aborted' ? 'Aborted' : 'Error'}:`, event.error.errorMessage);\n  }\n}\n\n// Get results (may be partial if aborted)\nconst response = await s.result();\nif (response.stopReason === 'aborted') {\n  console.log('Request was aborted:', response.errorMessage);\n  console.log('Partial content received:', response.content);\n  console.log('Tokens used:', response.usage);\n}\n```\n\n### Continuing After Abort\n\nAborted messages can be added to the conversation context and continued in subsequent requests:\n\n```typescript\nconst context = {\n  messages: [\n    { role: 'user', content: 'Explain quantum computing in detail' }\n  ]\n};\n\n// First request gets aborted after 2 seconds\nconst controller1 = new AbortController();\nsetTimeout(() => controller1.abort(), 2000);\n\nconst partial = await complete(model, context, { signal: controller1.signal });\n\n// Add the partial response to context\ncontext.messages.push(partial);\ncontext.messages.push({ role: 'user', content: 'Please continue' });\n\n// Continue the conversation\nconst continuation = await complete(model, context);\n```\n\n### Debugging Provider Payloads\n\nUse the `onPayload` callback to inspect the request payload sent to the provider. This is useful for debugging request formatting issues or provider validation errors.\n\n```typescript\nconst response = await complete(model, context, {\n  onPayload: (payload) => {\n    console.log('Provider payload:', JSON.stringify(payload, null, 2));\n  }\n});\n```\n\nThe callback is supported by `stream`, `complete`, `streamSimple`, and `completeSimple`.\n\n## APIs, Models, and Providers\n\nThe library uses a registry of API implementations. Built-in APIs include:\n\n- **`anthropic-messages`**: Anthropic Messages API (`streamAnthropic`, `AnthropicOptions`)\n- **`google-generative-ai`**: Google Generative AI API (`streamGoogle`, `GoogleOptions`)\n- **`google-vertex`**: Google Vertex AI API (`streamGoogleVertex`, `GoogleVertexOptions`)\n- **`mistral-conversations`**: Mistral Conversations API (`streamMistral`, `MistralOptions`)\n- **`openai-completions`**: OpenAI Chat Completions API (`streamOpenAICompletions`, `OpenAICompletionsOptions`)\n- **`openai-responses`**: OpenAI Responses API (`streamOpenAIResponses`, `OpenAIResponsesOptions`)\n- **`openai-codex-responses`**: OpenAI Codex Responses API (`streamOpenAICodexResponses`, `OpenAICodexResponsesOptions`)\n- **`azure-openai-responses`**: Azure OpenAI Responses API (`streamAzureOpenAIResponses`, `AzureOpenAIResponsesOptions`)\n- **`bedrock-converse-stream`**: Amazon Bedrock Converse API (`streamBedrock`, `BedrockOptions`)\n\n### Faux provider for tests\n\n`registerFauxProvider()` registers a temporary in-memory provider for tests and demos. It is opt-in and not part of the built-in provider set.\n\n```typescript\nimport {\n  complete,\n  fauxAssistantMessage,\n  fauxText,\n  fauxThinking,\n  fauxToolCall,\n  registerFauxProvider,\n  stream,\n} from '@aaditri-globaltech/aria-ai';\n\nconst registration = registerFauxProvider({\n  tokensPerSecond: 50 // optional\n});\n\nconst model = registration.getModel();\nconst context = {\n  messages: [{ role: 'user', content: 'Summarize package.json and then call echo', timestamp: Date.now() }]\n};\n\nregistration.setResponses([\n  fauxAssistantMessage([\n    fauxThinking('Need to inspect package metadata first.'),\n    fauxToolCall('echo', { text: 'package.json' })\n  ], { stopReason: 'toolUse' })\n]);\n\nconst first = await complete(model, context, {\n  sessionId: 'session-1',\n  cacheRetention: 'short'\n});\ncontext.messages.push(first);\n\ncontext.messages.push({\n  role: 'toolResult',\n  toolCallId: first.content.find((block) => block.type === 'toolCall')!.id,\n  toolName: 'echo',\n  content: [{ type: 'text', text: 'package.json contents here' }],\n  isError: false,\n  timestamp: Date.now()\n});\n\nregistration.setResponses([\n  fauxAssistantMessage([\n    fauxThinking('Now I can summarize the tool output.'),\n    fauxText('Here is the summary.')\n  ])\n]);\n\nconst s = stream(model, context);\nfor await (const event of s) {\n  console.log(event.type);\n}\n\n// Optional: register multiple faux models for model-switching tests\nconst multiModel = registerFauxProvider({\n  models: [\n    { id: 'faux-fast', reasoning: false },\n    { id: 'faux-thinker', reasoning: true }\n  ]\n});\nconst thinker = multiModel.getModel('faux-thinker');\n\nconsole.log(thinker?.reasoning);\nconsole.log(registration.getPendingResponseCount());\nconsole.log(registration.state.callCount);\nregistration.unregister();\nmultiModel.unregister();\n```\n\nNotes:\n- Responses are consumed from a queue in request start order.\n- If the queue is empty, the faux provider returns an assistant error message with `errorMessage: \"No more faux responses queued\"`.\n- Use `registration.setResponses([...])` to replace the remaining queue and `registration.appendResponses([...])` to add more responses.\n- `registration.models` exposes all registered faux models. `registration.getModel()` returns the first one, and `registration.getModel(id)` returns a specific one.\n- Use `fauxAssistantMessage(...)` for scripted assistant replies. Use `fauxText(...)`, `fauxThinking(...)`, and `fauxToolCall(...)` to build content blocks without filling in low-level fields manually.\n- `registration.unregister()` removes the temporary provider from the global API registry.\n- Usage is estimated at roughly 1 token per 4 characters. When `sessionId` is present and `cacheRetention` is not `\"none\"`, prompt cache reads and writes are simulated automatically.\n- Tool call arguments stream incrementally via `toolcall_delta` chunks.\n- By default, each streamed chunk is emitted on its own microtask. Set `tokensPerSecond` to pace chunk delivery in real time.\n- The intended use is one deterministic scripted flow per registration. If you need independent concurrent flows, register separate faux providers.\n\n### Providers and Models\n\nA **provider** offers models through a specific API. For example:\n- **Anthropic** models use the `anthropic-messages` API\n- **Google** models use the `google-generative-ai` API\n- **OpenAI** models use the `openai-responses` API\n- **Mistral** models use the `mistral-conversations` API\n- **xAI, Cerebras, Groq, NVIDIA NIM, Together AI, etc.** models use the `openai-completions` API (OpenAI-compatible)\n\n### Querying Providers and Models\n\n```typescript\nimport { getProviders, getModels, getModel } from '@aaditri-globaltech/aria-ai';\n\n// Get all available providers\nconst providers = getProviders();\nconsole.log(providers); // ['openai', 'anthropic', 'google', 'xai', 'groq', ...]\n\n// Get all models from a provider (fully typed)\nconst anthropicModels = getModels('anthropic');\nfor (const model of anthropicModels) {\n  console.log(`${model.id}: ${model.name}`);\n  console.log(`  API: ${model.api}`); // 'anthropic-messages'\n  console.log(`  Context: ${model.contextWindow} tokens`);\n  console.log(`  Vision: ${model.input.includes('image')}`);\n  console.log(`  Reasoning: ${model.reasoning}`);\n}\n\n// Get a specific model (both provider and model ID are auto-completed in IDEs)\nconst model = getModel('openai', 'gpt-4o-mini');\nconsole.log(`Using ${model.name} via ${model.api} API`);\n```\n\n### Custom Models\n\nYou can create custom models for local inference servers or custom endpoints:\n\n```typescript\nimport { Model, stream } from '@aaditri-globaltech/aria-ai';\n\n// Example: Ollama using OpenAI-compatible API\nconst ollamaModel: Model<'openai-completions'> = {\n  id: 'llama-3.1-8b',\n  name: 'Llama 3.1 8B (Ollama)',\n  api: 'openai-completions',\n  provider: 'ollama',\n  baseUrl: 'http://localhost:11434/v1',\n  reasoning: false,\n  input: ['text'],\n  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n  contextWindow: 128000,\n  maxTokens: 32000\n};\n\n// Example: LiteLLM proxy with explicit compat settings\nconst litellmModel: Model<'openai-completions'> = {\n  id: 'gpt-4o',\n  name: 'GPT-4o (via LiteLLM)',\n  api: 'openai-completions',\n  provider: 'litellm',\n  baseUrl: 'http://localhost:4000/v1',\n  reasoning: false,\n  input: ['text', 'image'],\n  cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 },\n  contextWindow: 128000,\n  maxTokens: 16384,\n  compat: {\n    supportsStore: false,  // LiteLLM doesn't support the store field\n  }\n};\n\n// Example: Custom endpoint with headers (bypassing Cloudflare bot detection)\nconst proxyModel: Model<'anthropic-messages'> = {\n  id: 'claude-sonnet-4',\n  name: 'Claude Sonnet 4 (Proxied)',\n  api: 'anthropic-messages',\n  provider: 'custom-proxy',\n  baseUrl: 'https://proxy.example.com/v1',\n  reasoning: true,\n  input: ['text', 'image'],\n  cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },\n  contextWindow: 200000,\n  maxTokens: 8192,\n  headers: {\n    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',\n    'X-Custom-Auth': 'bearer-token-here'\n  }\n};\n\n// Use the custom model\nconst response = await stream(ollamaModel, context, {\n  apiKey: 'dummy' // Ollama doesn't need a real key\n});\n```\n\nSome 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.\n\nUse model-level `thinkingLevelMap` to describe model-specific thinking controls. Keys are Aria thinking levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`). Missing keys use provider defaults, string values are sent to the provider, and `null` marks a level unsupported.\n\nThis commonly applies to Ollama, vLLM, SGLang, and similar OpenAI-compatible servers. You can set `compat` at the provider level or per model.\n\n```typescript\nconst ollamaReasoningModel: Model<'openai-completions'> = {\n  id: 'gpt-oss:20b',\n  name: 'GPT-OSS 20B (Ollama)',\n  api: 'openai-completions',\n  provider: 'ollama',\n  baseUrl: 'http://localhost:11434/v1',\n  reasoning: true,\n  input: ['text'],\n  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n  contextWindow: 131072,\n  maxTokens: 32000,\n  thinkingLevelMap: {\n    minimal: null,\n    low: null,\n    medium: null,\n    high: 'high',\n    xhigh: null,\n  },\n  compat: {\n    supportsDeveloperRole: false,\n    supportsReasoningEffort: false,\n  }\n};\n```\n\n### OpenAI Compatibility Settings\n\nThe `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, NVIDIA NIM, Together AI, zAi, OpenCode, Cloudflare Workers AI, etc.). For custom proxies or unknown endpoints, you can override these settings via the `compat` field. For `openai-responses` models, the compat field supports Responses-specific flags.\n\n```typescript\ninterface OpenAICompletionsCompat {\n  supportsStore?: boolean;           // Whether provider supports the `store` field (default: true)\n  supportsDeveloperRole?: boolean;   // Whether provider supports `developer` role vs `system` (default: true)\n  supportsReasoningEffort?: boolean; // Whether provider supports `reasoning_effort` (default: true)\n  supportsUsageInStreaming?: boolean; // Whether provider supports `stream_options: { include_usage: true }` (default: true)\n  supportsStrictMode?: boolean;      // Whether provider supports `strict` in tool definitions (default: true)\n  sendSessionAffinityHeaders?: boolean; // Whether to send `session_id`, `x-client-request-id`, and `x-session-affinity` from `sessionId` when caching is enabled (default: false)\n  maxTokensField?: 'max_completion_tokens' | 'max_tokens';  // Which field name to use (default: max_completion_tokens)\n  requiresToolResultName?: boolean;  // Whether tool results require the `name` field (default: false)\n  requiresAssistantAfterToolResult?: boolean; // Whether tool results must be followed by an assistant message (default: false)\n  requiresThinkingAsText?: boolean;  // Whether thinking blocks must be converted to text (default: false)\n  requiresReasoningContentOnAssistantMessages?: boolean; // Whether all replayed assistant messages must include empty reasoning_content when reasoning is enabled (default: auto-detected for DeepSeek)\n  thinkingFormat?: 'openai' | 'openrouter' | 'deepseek' | 'together' | 'zai' | 'qwen' | 'qwen-chat-template' | 'string-thinking' | 'ant-ling'; // Format for reasoning param: 'openai' uses reasoning_effort, 'openrouter' uses reasoning: { effort }, 'deepseek' uses thinking: { type } plus reasoning_effort when supported, 'together' uses reasoning: { enabled } plus reasoning_effort when supported, 'zai' uses enable_thinking, 'qwen' uses enable_thinking, 'qwen-chat-template' uses chat_template_kwargs.enable_thinking, 'string-thinking' uses top-level thinking, 'ant-ling' uses reasoning: { effort } only for mapped efforts (default: openai)\n  cacheControlFormat?: 'anthropic';  // Anthropic-style cache_control on system prompt, last tool, and last user/assistant text content\n  openRouterRouting?: OpenRouterRouting; // OpenRouter routing preferences (default: {})\n  vercelGatewayRouting?: VercelGatewayRouting; // Vercel AI Gateway routing preferences (default: {})\n}\n\ninterface OpenAIResponsesCompat {\n  supportsDeveloperRole?: boolean;   // Whether provider supports `developer` role vs `system` (default: true)\n  sendSessionIdHeader?: boolean;     // Whether to send `session_id` from `sessionId` when caching is enabled (default: true)\n  supportsLongCacheRetention?: boolean; // Whether provider supports `prompt_cache_retention: \"24h\"` (default: true)\n}\n```\n\nIf `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:\n\n- **LiteLLM proxies**: May not support `store` field\n- **Custom inference servers**: May use non-standard field names\n- **Self-hosted endpoints**: May have different feature support\n\n### Type Safety\n\nModels 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.\n\n```typescript\nimport { streamAnthropic, type AnthropicOptions } from '@aaditri-globaltech/aria-ai';\n\n// TypeScript knows this is an Anthropic model\nconst claude = getModel('anthropic', 'claude-sonnet-4-20250514');\n\nconst options: AnthropicOptions = {\n  thinkingEnabled: true,\n  thinkingBudgetTokens: 2048\n};\n\nawait streamAnthropic(claude, context, options);\n```\n\n## Cross-Provider Handoffs\n\nThe 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.\n\n### How It Works\n\nWhen messages from one provider are sent to a different provider, the library automatically transforms them for compatibility:\n\n- **User and tool result messages** are passed through unchanged\n- **Assistant messages from the same provider/API** are preserved as-is\n- **Assistant messages from different providers** have their thinking blocks converted to text with `<thinking>` tags\n- **Tool calls and regular text** are preserved unchanged\n\n### Example: Multi-Provider Conversation\n\n```typescript\nimport { getModel, complete, Context } from '@aaditri-globaltech/aria-ai';\n\n// Start with Claude\nconst claude = getModel('anthropic', 'claude-sonnet-4-20250514');\nconst context: Context = {\n  messages: []\n};\n\ncontext.messages.push({ role: 'user', content: 'What is 25 * 18?' });\nconst claudeResponse = await complete(claude, context, {\n  thinkingEnabled: true\n});\ncontext.messages.push(claudeResponse);\n\n// Switch to GPT-5 - it will see Claude's thinking as <thinking> tagged text\nconst gpt5 = getModel('openai', 'gpt-5-mini');\ncontext.messages.push({ role: 'user', content: 'Is that calculation correct?' });\nconst gptResponse = await complete(gpt5, context);\ncontext.messages.push(gptResponse);\n\n// Switch to Gemini\nconst gemini = getModel('google', 'gemini-2.5-flash');\ncontext.messages.push({ role: 'user', content: 'What was the original question?' });\nconst geminiResponse = await complete(gemini, context);\n```\n\n### Provider Compatibility\n\nAll providers can handle messages from other providers, including:\n- Text content\n- Tool calls and tool results (including images in tool results)\n- Thinking/reasoning blocks (transformed to tagged text for cross-provider compatibility)\n- Aborted messages with partial content\n\nThis enables flexible workflows where you can:\n- Start with a fast model for initial responses\n- Switch to a more capable model for complex reasoning\n- Use specialized models for specific tasks\n- Maintain conversation continuity across provider outages\n\n## Context Serialization\n\nThe `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:\n\n```typescript\nimport { Context, getModel, complete } from '@aaditri-globaltech/aria-ai';\n\n// Create and use a context\nconst context: Context = {\n  systemPrompt: 'You are a helpful assistant.',\n  messages: [\n    { role: 'user', content: 'What is TypeScript?' }\n  ]\n};\n\nconst model = getModel('openai', 'gpt-4o-mini');\nconst response = await complete(model, context);\ncontext.messages.push(response);\n\n// Serialize the entire context\nconst serialized = JSON.stringify(context);\nconsole.log('Serialized context size:', serialized.length, 'bytes');\n\n// Save to database, localStorage, file, etc.\nlocalStorage.setItem('conversation', serialized);\n\n// Later: deserialize and continue the conversation\nconst restored: Context = JSON.parse(localStorage.getItem('conversation')!);\nrestored.messages.push({ role: 'user', content: 'Tell me more about its type system' });\n\n// Continue with any model\nconst newModel = getModel('anthropic', 'claude-3-5-haiku-20241022');\nconst continuation = await complete(newModel, restored);\n```\n\n> **Note**: If the context contains images (encoded as base64 as shown in the Image Input section), those will also be serialized.\n\n## Browser Usage\n\nThe library supports browser environments. You must pass the API key explicitly since environment variables are not available in browsers:\n\n```typescript\nimport { getModel, complete } from '@aaditri-globaltech/aria-ai';\n\n// API key must be passed explicitly in browser\nconst model = getModel('anthropic', 'claude-3-5-haiku-20241022');\n\nconst response = await complete(model, {\n  messages: [{ role: 'user', content: 'Hello!' }]\n}, {\n  apiKey: 'your-api-key'\n});\n```\n\n> **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.\n\n### Browser Compatibility Notes\n\n- Amazon Bedrock (`bedrock-converse-stream`) is not supported in browser environments.\n- OAuth login flows are not supported in browser environments. Use the `@aaditri-globaltech/aria-ai/oauth` entry point in Node.js.\n- In browser builds, Bedrock can still appear in model lists. Calls to Bedrock models fail at runtime.\n- Use a server-side proxy or backend service if you need Bedrock or OAuth-based auth from a web app.\n\n### Environment Variables (Node.js only)\n\nIn Node.js environments, you can set environment variables to avoid passing API keys:\n\n| Provider | Environment Variable(s) |\n|----------|------------------------|\n| OpenAI | `OPENAI_API_KEY` |\n| Ant Ling | `ANT_LING_API_KEY` |\n| Azure OpenAI | `AZURE_OPENAI_API_KEY` + `AZURE_OPENAI_BASE_URL` (e.g. `https://{resource}.openai.azure.com`) or `AZURE_OPENAI_RESOURCE_NAME`. Supports `*.openai.azure.com` and `*.cognitiveservices.azure.com`; root endpoints auto-normalize to `/openai/v1`. Optional: `AZURE_OPENAI_API_VERSION` (default `v1`), `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`. |\n| Anthropic | `ANTHROPIC_API_KEY` or `ANTHROPIC_OAUTH_TOKEN` |\n| DeepSeek | `DEEPSEEK_API_KEY` |\n| NVIDIA NIM | `NVIDIA_API_KEY` |\n| Google | `GEMINI_API_KEY` |\n| Vertex AI | `GOOGLE_CLOUD_API_KEY` or `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) + `GOOGLE_CLOUD_LOCATION` + ADC |\n| Mistral | `MISTRAL_API_KEY` |\n| Groq | `GROQ_API_KEY` |\n| Cerebras | `CEREBRAS_API_KEY` |\n| Cloudflare AI Gateway | `CLOUDFLARE_API_KEY` + `CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_GATEWAY_ID` |\n| Cloudflare Workers AI | `CLOUDFLARE_API_KEY` + `CLOUDFLARE_ACCOUNT_ID` |\n| xAI | `XAI_API_KEY` |\n| Fireworks | `FIREWORKS_API_KEY` |\n| Together AI | `TOGETHER_API_KEY` |\n| OpenRouter | `OPENROUTER_API_KEY` |\n| Vercel AI Gateway | `AI_GATEWAY_API_KEY` |\n| zAI | `ZAI_API_KEY` |\n| ZAI Coding Plan (China) | `ZAI_CODING_CN_API_KEY` |\n| MiniMax | `MINIMAX_API_KEY` |\n| OpenCode Zen / OpenCode Go | `OPENCODE_API_KEY` |\n| Kimi For Coding | `KIMI_API_KEY` |\n| Xiaomi MiMo (API billing) | `XIAOMI_API_KEY` |\n| Xiaomi MiMo Token Plan (China) | `XIAOMI_TOKEN_PLAN_CN_API_KEY` |\n| Xiaomi MiMo Token Plan (Amsterdam) | `XIAOMI_TOKEN_PLAN_AMS_API_KEY` |\n| Xiaomi MiMo Token Plan (Singapore) | `XIAOMI_TOKEN_PLAN_SGP_API_KEY` |\n| GitHub Copilot | `COPILOT_GITHUB_TOKEN` |\n\nWhen set, the library automatically uses these keys:\n\n```typescript\n// Uses OPENAI_API_KEY from environment\nconst model = getModel('openai', 'gpt-4o-mini');\nconst response = await complete(model, context);\n\n// Or override with explicit key\nconst response = await complete(model, context, {\n  apiKey: 'sk-different-key'\n});\n```\n\n### Checking Environment Variables\n\n```typescript\nimport { getEnvApiKey } from '@aaditri-globaltech/aria-ai';\n\n// Check if an API key is set in environment variables\nconst key = getEnvApiKey('openai');  // checks OPENAI_API_KEY\n```\n\n## OAuth Providers\n\nSeveral providers require OAuth authentication instead of static API keys:\n\n- **Anthropic** (Claude Pro/Max subscription)\n- **OpenAI Codex** (ChatGPT Plus/Pro subscription, access to GPT-5.x Codex models)\n- **GitHub Copilot** (Copilot subscription)\n\nFor paid Cloud Code Assist subscriptions, set `GOOGLE_CLOUD_PROJECT` or `GOOGLE_CLOUD_PROJECT_ID` to your project ID.\n\n### Vertex AI\n\nVertex AI models support either a Google Cloud API key or Application Default Credentials (ADC):\n\n- **API key**: Set `GOOGLE_CLOUD_API_KEY` or pass `apiKey` in the call options.\n- **Local development (ADC)**: Run `gcloud auth application-default login`\n- **CI/Production (ADC)**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to a service account JSON key file\n\nWhen 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.\n\nExample:\n\n```bash\n# Local (uses your user credentials)\ngcloud auth application-default login\nexport GOOGLE_CLOUD_PROJECT=\"my-project\"\nexport GOOGLE_CLOUD_LOCATION=\"us-central1\"\n\n# CI/Production (service account key file)\nexport GOOGLE_APPLICATION_CREDENTIALS=\"/path/to/service-account.json\"\n```\n\n```typescript\nimport { getModel, complete } from '@aaditri-globaltech/aria-ai';\n\n(async () => {\n  const model = getModel('google-vertex', 'gemini-2.5-flash');\n  const response = await complete(model, {\n    messages: [{ role: 'user', content: 'Hello from Vertex AI' }]\n  }, {\n    apiKey: process.env.GOOGLE_CLOUD_API_KEY,\n  });\n\n  for (const block of response.content) {\n    if (block.type === 'text') console.log(block.text);\n  }\n})().catch(console.error);\n```\n\nOfficial docs: [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials)\n\n### CLI Login\n\nThe quickest way to authenticate:\n\n```bash\nnpx @aaditri-globaltech/aria-ai login              # interactive provider selection\nnpx @aaditri-globaltech/aria-ai login anthropic    # login to specific provider\nnpx @aaditri-globaltech/aria-ai list               # list available providers\n```\n\nCredentials are saved to `auth.json` in the current directory.\n\n### Programmatic OAuth\n\nThe library provides login and token refresh functions via the `@aaditri-globaltech/aria-ai/oauth` entry point. Credential storage is the caller's responsibility.\n\n```typescript\nimport {\n  // Login functions (return credentials, do not store)\n  loginAnthropic,\n  loginOpenAICodex,\n  loginGitHubCopilot,\n  loginGeminiCli,\n\n  // Token management\n  refreshOAuthToken,   // (provider, credentials) => new credentials\n  getOAuthApiKey,      // (provider, credentialsMap) => { newCredentials, apiKey } | null\n\n  // Types\n  type OAuthProvider,\n  type OAuthCredentials,\n} from '@aaditri-globaltech/aria-ai/oauth';\n```\n\n### Login Flow Example\n\n```typescript\nimport { loginGitHubCopilot } from '@aaditri-globaltech/aria-ai/oauth';\nimport { writeFileSync } from 'fs';\n\nconst credentials = await loginGitHubCopilot({\n  onAuth: (url, instructions) => {\n    console.log(`Open: ${url}`);\n    if (instructions) console.log(instructions);\n  },\n  onPrompt: async (prompt) => {\n    return await getUserInput(prompt.message);\n  },\n  onProgress: (message) => console.log(message)\n});\n\n// Store credentials yourself\nconst auth = { 'github-copilot': { type: 'oauth', ...credentials } };\nwriteFileSync('auth.json', JSON.stringify(auth, null, 2));\n```\n\n### Using OAuth Tokens\n\nUse `getOAuthApiKey()` to get an API key, automatically refreshing if expired:\n\n```typescript\nimport { getModel, complete } from '@aaditri-globaltech/aria-ai';\nimport { getOAuthApiKey } from '@aaditri-globaltech/aria-ai/oauth';\nimport { readFileSync, writeFileSync } from 'fs';\n\n// Load your stored credentials\nconst auth = JSON.parse(readFileSync('auth.json', 'utf-8'));\n\n// Get API key (refreshes if expired)\nconst result = await getOAuthApiKey('github-copilot', auth);\nif (!result) throw new Error('Not logged in');\n\n// Save refreshed credentials\nauth['github-copilot'] = { type: 'oauth', ...result.newCredentials };\nwriteFileSync('auth.json', JSON.stringify(auth, null, 2));\n\n// Use the API key\nconst model = getModel('github-copilot', 'gpt-4o');\nconst response = await complete(model, {\n  messages: [{ role: 'user', content: 'Hello!' }]\n}, { apiKey: result.apiKey });\n```\n\n### Provider Notes\n\n**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.\n\n**Azure OpenAI (Responses)**: Uses the Responses API only. Set `AZURE_OPENAI_API_KEY` and either `AZURE_OPENAI_BASE_URL` or `AZURE_OPENAI_RESOURCE_NAME`. `AZURE_OPENAI_BASE_URL` supports both `https://<resource>.openai.azure.com` and `https://<resource>.cognitiveservices.azure.com`; root endpoints are normalized to `.../openai/v1` automatically. 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.\n\n**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\".\n\n## Development\n\n### Adding a New Provider\n\nAdding a new LLM provider requires changes across multiple files. This checklist covers all necessary steps:\n\n#### 1. Core Types (`src/types.ts`)\n\n- Add the API identifier to `KnownApi` (for example `\"bedrock-converse-stream\"`)\n- Create an options interface extending `StreamOptions` (for example `BedrockOptions`)\n- Add the provider name to `KnownProvider` (for example `\"amazon-bedrock\"`)\n\n#### 2. Provider Implementation (`src/providers/`)\n\nCreate a new provider file (for example `amazon-bedrock.ts`) that exports:\n\n- `stream<Provider>()` function returning `AssistantMessageEventStream`\n- `streamSimple<Provider>()` for `SimpleStreamOptions` mapping\n- Provider-specific options interface\n- Message conversion functions to transform `Context` to provider format\n- Tool conversion if the provider supports tools\n- Response parsing to emit standardized events (`text`, `tool_call`, `thinking`, `usage`, `stop`)\n\n#### 3. API Registry Integration (`src/providers/register-builtins.ts`)\n\n- Register the API with `registerApiProvider()`\n- Add a package subpath export in `package.json` for the provider module (`./dist/providers/<provider>.js`)\n- Add lazy loader wrappers in `src/providers/register-builtins.ts`, do not statically import provider implementation modules there\n- Add any root-level `export type` re-exports in `src/index.ts` that should remain available from `@aaditri-globaltech/aria-ai`\n- Add credential detection in `env-api-keys.ts` for the new provider\n- Ensure `streamSimple` handles auth lookup via `getEnvApiKey()` or provider-specific auth\n\n#### 4. Model Generation (`scripts/generate-models.ts`, `scripts/generate-image-models.ts`)\n\n- Add logic to fetch and parse models from the provider's source (e.g., models.dev API)\n- Map chat/tool-capable provider model data to the standardized `Model` interface via `scripts/generate-models.ts`\n- Map image-generation provider model data to the standardized `ImagesModel` interface via `scripts/generate-image-models.ts`\n- Handle provider-specific quirks (pricing format, capability flags, model ID transformations)\n\n#### 5. Tests (`test/`)\n\nCreate or update test files to cover the new provider:\n\n- `stream.test.ts` - Basic streaming and tool use\n- `tokens.test.ts` - Token usage reporting\n- `abort.test.ts` - Request cancellation\n- `empty.test.ts` - Empty message handling\n- `context-overflow.test.ts` - Context limit errors\n- `image-limits.test.ts` - Image support (if applicable)\n- `unicode-surrogate.test.ts` - Unicode handling\n- `tool-call-without-result.test.ts` - Orphaned tool calls\n- `image-tool-result.test.ts` - Images in tool results\n- `total-tokens.test.ts` - Token counting accuracy\n- `cross-provider-handoff.test.ts` - Cross-provider context replay\n\nFor `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.\n\nFor providers with non-standard auth (AWS, Google Vertex), create a utility like `bedrock-utils.ts` with credential detection helpers.\n\n#### 6. Coding Agent Integration (`../coding-agent/`)\n\nUpdate `src/core/model-resolver.ts`:\n\n- Add a default model ID for the provider in `DEFAULT_MODELS`\n\nUpdate `src/cli/args.ts`:\n\n- Add environment variable documentation in the help text\n\nUpdate `README.md`:\n\n- Add the provider to the providers section with setup instructions\n\n#### 7. Documentation\n\nUpdate `packages/ai/README.md`:\n\n- Add to the Supported Providers table\n- Document any provider-specific options or authentication requirements\n- Add environment variable to the Environment Variables section\n\n#### 8. Changelog\n\nAdd an entry to `packages/ai/CHANGELOG.md` under `## [Unreleased]`:\n\n```markdown\n### Added\n- Added support for [Provider Name] provider ([#PR](link) by [@author](link))\n```\n\n## License\n\nMIT\n","readmeFilename":"README.md"}