{"_id":"@ai-stats/ai-sdk-provider","_rev":"2-394b1b0f2e9ca2d82517902eede54677","name":"@ai-stats/ai-sdk-provider","dist-tags":{"latest":"1.0.1"},"versions":{"1.0.1":{"name":"@ai-stats/ai-sdk-provider","version":"1.0.1","keywords":["ai","ai-sdk","vercel","ai-stats","gateway","llm","openai","anthropic","language-model"],"license":"MIT","_id":"@ai-stats/ai-sdk-provider@1.0.1","maintainers":[{"name":"daniel-aistats","email":"danielbutler500@gmail.com"}],"homepage":"https://github.com/AI-Stats/AI-Stats#readme","bugs":{"url":"https://github.com/AI-Stats/AI-Stats/issues"},"dist":{"shasum":"4f8d93207a9ae44e0ad6aabfb0ef5a09fd0720af","tarball":"https://registry.npmjs.org/@ai-stats/ai-sdk-provider/-/ai-sdk-provider-1.0.1.tgz","fileCount":70,"integrity":"sha512-IabRawPEzeAEoCH/hr9rRmfGAfaG+1oC+dVRMMxAL2QaT6aK0/wocmPvhj0nOBxM21UFkz50iLtzBREvZjCmZQ==","signatures":[{"sig":"MEYCIQCA5zsBdkpqUM5yy2U2Iag4AZnNWDj5xSx6v2EHuT4sCQIhAO3UtZ4TPH+luDyV5SGHs/RHDl4VmCT2QtJlkEZZIdMy","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@ai-stats%2fai-sdk-provider@1.0.1","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":115746},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"1e942d6bbb7130f475fd5027ff72a4658eacb0b5","scripts":{"dev":"tsc -p tsconfig.build.json --watch","test":"dotenv -e ../../../.env.local -- vitest run","build":"tsc -p tsconfig.build.json","clean":"rimraf dist","test:watch":"vitest","postinstall":"node ../../sdk/scripts/postinstall-viewer-prompt.cjs @ai-stats/ai-sdk-provider","prepublishOnly":"pnpm build"},"_npmUser":{"name":"daniel-aistats","email":"danielbutler500@gmail.com"},"repository":{"url":"git+https://github.com/AI-Stats/AI-Stats.git","type":"git","directory":"packages/integrations/ai-sdk-ai-stats"},"_npmVersion":"10.9.4","description":"AI Stats Gateway provider for Vercel AI SDK","directories":{},"_nodeVersion":"22.22.0","dependencies":{"@ai-sdk/provider":"^3.0.8","@ai-sdk/provider-utils":"^4.0.14"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"ai":"^6.0.5","zod":"^3.23.8","rimraf":"^6.0.1","vitest":"^4.0.18","typescript":"^5.9.3","@types/node":"^22.19.10","@vitest/coverage-v8":"^4.0.18"},"peerDependencies":{"ai":"^6.0.0"},"_npmOperationalInternal":{"tmp":"tmp/ai-sdk-provider_1.0.1_1770911523499_0.5709004314984722","host":"s3://npm-registry-packages-npm-production"},"deprecated":"AI Stats is now Phaseo. Please migrate to @phaseo/ai-sdk-provider."}},"time":{"created":"2026-02-12T15:52:03.359Z","modified":"2026-07-04T10:44:15.724Z","1.0.1":"2026-02-12T15:52:03.639Z"},"bugs":{"url":"https://github.com/AI-Stats/AI-Stats/issues"},"license":"MIT","homepage":"https://github.com/AI-Stats/AI-Stats#readme","keywords":["ai","ai-sdk","vercel","ai-stats","gateway","llm","openai","anthropic","language-model"],"repository":{"url":"git+https://github.com/AI-Stats/AI-Stats.git","type":"git","directory":"packages/integrations/ai-sdk-ai-stats"},"description":"AI Stats Gateway provider for Vercel AI SDK","maintainers":[{"name":"daniel-aistats","email":"danielbutler500@gmail.com"}],"readme":"# AI Stats Gateway Provider for Vercel AI SDK\n\nOfficial [Vercel AI SDK](https://sdk.vercel.ai/docs) provider for [AI Stats Gateway](https://ai-stats.phaseo.app/), enabling access to 55+ AI providers through a unified interface.\n\n## Features\n\n✨ **Unified Access** - Use 55+ AI providers (OpenAI, Anthropic, Google, Mistral, DeepSeek, and more) through a single SDK\n🔄 **Full AI SDK v6 Support** - Works with all Vercel AI SDK primitives:\n\n-   Text: `generateText`, `streamText`, `generateObject`, `streamObject`\n-   Embeddings: `embed`, `embedMany`\n-   Images: `generateImage`\n-   Audio: `transcribe` (STT), `speak` (TTS)\n    🛠️ **Tool Calling** - Complete support for function/tool calling with parallel execution\n    📦 **Structured Output** - Generate typed objects with JSON schemas\n    🔢 **Embeddings** - Generate vector embeddings for semantic search and similarity\n    🖼️ **Image Generation** - Create images from text prompts (DALL-E, Flux, etc.)\n    🎙️ **Speech & Transcription** - Text-to-speech and speech-to-text capabilities\n    ⚡ **Streaming** - Real-time token streaming with usage tracking\n    🔐 **Type-Safe** - Full TypeScript support with strict types\n    🌐 **Provider Routing** - Automatic health-aware routing and failover\n\n## Installation\n\n```bash\nnpm install @ai-stats/ai-sdk-provider ai@^6\n```\n\n## Quick Start\n\n### Basic Usage\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { generateText } from \"ai\";\n\nconst result = await generateText({\n\tmodel: aiStats(\"openai/gpt-4o\"),\n\tprompt: \"Explain quantum computing in simple terms\",\n});\n\nconsole.log(result.text);\n```\n\n### Streaming\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { streamText } from \"ai\";\n\nconst { textStream } = await streamText({\n\tmodel: aiStats(\"anthropic/claude-3-5-sonnet\"),\n\tprompt: \"Write a poem about TypeScript\",\n});\n\nfor await (const chunk of textStream) {\n\tprocess.stdout.write(chunk);\n}\n```\n\n### Tool Calling\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { generateText } from \"ai\";\nimport { z } from \"zod\";\n\nconst result = await generateText({\n\tmodel: aiStats(\"openai/gpt-4o\"),\n\tprompt: \"What is the weather in San Francisco?\",\n\ttools: {\n\t\tgetWeather: {\n\t\t\tdescription: \"Get weather for a location\",\n\t\t\tparameters: z.object({\n\t\t\t\tlocation: z.string(),\n\t\t\t}),\n\t\t\texecute: async ({ location }) => ({\n\t\t\t\ttemperature: 72,\n\t\t\t\tconditions: \"sunny\",\n\t\t\t}),\n\t\t},\n\t},\n});\n```\n\n### Structured Output\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { generateObject } from \"ai\";\nimport { z } from \"zod\";\n\nconst { object } = await generateObject({\n\tmodel: aiStats(\"openai/gpt-4o\"),\n\tschema: z.object({\n\t\tname: z.string(),\n\t\tage: z.number(),\n\t\temail: z.string().email(),\n\t}),\n\tprompt: \"Generate a sample user profile\",\n});\n```\n\n### Embeddings\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { embed, embedMany } from \"ai\";\n\n// Single embedding\nconst { embedding } = await embed({\n\tmodel: aiStats.textEmbeddingModel(\"openai/text-embedding-3-small\"),\n\tvalue: \"Hello, world!\",\n});\n\n// Batch embeddings\nconst { embeddings } = await embedMany({\n\tmodel: aiStats.textEmbeddingModel(\"openai/text-embedding-3-small\"),\n\tvalues: [\"First text\", \"Second text\", \"Third text\"],\n});\n```\n\n### Image Generation\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { generateImage } from \"ai\";\n\nconst { images } = await generateImage({\n\tmodel: aiStats.imageModel(\"openai/dall-e-3\"),\n\tprompt: \"A serene landscape with mountains at sunset\",\n\tsize: \"1024x1024\",\n});\n\nconsole.log(images[0].url); // Image URL or base64\n```\n\n### Audio Transcription (Speech-to-Text)\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { transcribe } from \"ai\";\nimport { readFileSync } from \"fs\";\n\nconst audioData = readFileSync(\"./audio.mp3\");\n\nconst { text, segments } = await transcribe({\n\tmodel: aiStats.transcriptionModel(\"openai/whisper-1\"),\n\taudioData: new Blob([audioData], { type: \"audio/mp3\" }),\n\tlanguage: \"en\", // optional\n});\n\nconsole.log(text); // Transcribed text\n```\n\n### Text-to-Speech\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { speak } from \"ai\";\nimport { writeFileSync } from \"fs\";\n\nconst { audio } = await speak({\n\tmodel: aiStats.speechModel(\"openai/tts-1\"),\n\ttext: \"Hello, this is text to speech!\",\n\tvoice: \"alloy\", // alloy, echo, fable, onyx, nova, shimmer\n\toutputFormat: \"mp3\",\n});\n\nwriteFileSync(\"./speech.mp3\", audio);\n```\n\n## Configuration\n\n### Environment Variable\n\nSet your API key as an environment variable:\n\n```bash\nexport AI_STATS_API_KEY=your_api_key_here\n```\n\nThen use the default instance:\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\n\nconst result = await generateText({\n\tmodel: aiStats(\"openai/gpt-4o\"),\n\tprompt: \"Hello!\",\n});\n```\n\n### Custom Configuration\n\n```typescript\nimport { createAIStats } from \"@ai-stats/ai-sdk-provider\";\n\nconst aiStats = createAIStats({\n\tapiKey: \"your_api_key\",\n\tbaseURL: \"https://api.phaseo.app/v1\", // optional\n\theaders: {\n\t\t\"X-Custom-Header\": \"value\", // optional\n\t},\n});\n```\n\n### Model Settings\n\nConfigure model-specific parameters:\n\n```typescript\nconst result = await generateText({\n\tmodel: aiStats(\"openai/gpt-4o\"),\n\tprompt: \"Hello!\",\n\ttemperature: 0.7,\n\tmaxTokens: 1000,\n\ttopP: 0.9,\n\tfrequencyPenalty: 0.5,\n\tpresencePenalty: 0.5,\n\tseed: 12345, // for deterministic output\n});\n```\n\n## Supported Providers\n\nAccess 55+ AI providers through the gateway:\n\n### Major Providers\n\n-   **OpenAI**: `openai/gpt-4o`, `openai/gpt-4-turbo`, `openai/gpt-3.5-turbo`\n-   **Anthropic**: `anthropic/claude-3-5-sonnet`, `anthropic/claude-3-opus`, `anthropic/claude-3-haiku`\n-   **Google**: `google/gemini-2.5-pro-latest`, `google/gemini-2.5-flash-latest`\n-   **Mistral**: `mistral/mistral-large`, `mistral/mistral-small`\n-   **X.AI**: `x-ai/grok-3`, `x-ai/grok-2`\n\n### Open Source Models\n\n-   **DeepSeek**: `deepseek/deepseek-chat`, `deepseek/deepseek-coder`\n-   **Qwen**: `qwen/qwen-3-235b`, `qwen/qwen-3-32b`\n-   **Meta**: `meta/llama-3.3-70b`, `meta/llama-3.1-405b`\n\n### Specialized Providers\n\n-   **Groq**: Ultra-fast inference for Llama, Mixtral, Gemma\n-   **Together AI**: Open source models with fast inference\n-   **Fireworks**: Optimized inference for open models\n-   **Cerebras**: Extremely fast inference\n\n[View all supported models →](https://ai-stats.phaseo.app/api-providers)\n\n## Model ID Format\n\nModels use the format `provider/model-id`:\n\n```typescript\n// OpenAI models\naiStats(\"openai/gpt-4o\");\naiStats(\"openai/gpt-4-turbo\");\n\n// Anthropic models\naiStats(\"anthropic/claude-3-5-sonnet\");\naiStats(\"anthropic/claude-3-opus\");\n\n// Google models\naiStats(\"google/gemini-2.5-pro-latest\");\n\n// DeepSeek models\naiStats(\"deepseek/deepseek-chat\");\n```\n\n## API Reference\n\n### `createAIStats(settings?)`\n\nCreates a new AI Stats provider instance.\n\n**Parameters:**\n\n-   `settings.apiKey` (string, optional) - API key for authentication. Defaults to `AI_STATS_API_KEY` env var.\n-   `settings.baseURL` (string, optional) - Gateway base URL. Default: `https://api.phaseo.app/v1`\n-   `settings.headers` (object, optional) - Additional headers to include in requests\n-   `settings.fetch` (function, optional) - Custom fetch implementation\n\n**Returns:** Provider function `(modelId: string, settings?: ModelSettings) => LanguageModelV3`\n\n### `aiStats(modelId, settings?)`\n\nDefault provider instance using `AI_STATS_API_KEY` environment variable.\n\n**Parameters:**\n\n-   `modelId` (string, required) - Model ID in format `provider/model`\n-   `settings` (object, optional) - Model-specific settings\n\n**Model Settings:**\n\n-   `temperature` (number) - Sampling temperature (0-2)\n-   `maxTokens` (number) - Maximum tokens to generate\n-   `topP` (number) - Nucleus sampling threshold (0-1)\n-   `topK` (number) - Top-K sampling threshold\n-   `frequencyPenalty` (number) - Frequency penalty (-2.0 to 2.0)\n-   `presencePenalty` (number) - Presence penalty (-2.0 to 2.0)\n-   `seed` (number) - Random seed for deterministic output\n-   `user` (string) - User identifier for tracking\n\n## Examples\n\nSee the [`examples/`](./examples) directory for complete working examples:\n\n**Text & Language:**\n\n-   [basic-text.ts](./examples/basic-text.ts) - Simple text generation\n-   [streaming.ts](./examples/streaming.ts) - Streaming text generation\n-   [tools.ts](./examples/tools.ts) - Function/tool calling\n-   [structured-output.ts](./examples/structured-output.ts) - Generating structured data\n\n**Embeddings & Search:**\n\n-   [embeddings.ts](./examples/embeddings.ts) - Vector embeddings and similarity\n\n**Images:**\n\n-   [image-generation.ts](./examples/image-generation.ts) - Generate images from text\n\n**Audio:**\n\n-   [audio-transcription.ts](./examples/audio-transcription.ts) - Speech-to-text\n-   [text-to-speech.ts](./examples/text-to-speech.ts) - Text-to-speech\n\n**Multi-Provider:**\n\n-   [multi-provider.ts](./examples/multi-provider.ts) - Comparing multiple providers\n\n## Testing\n\nThe package includes comprehensive test coverage using Vitest and AI SDK mock models:\n\n### Run Mock Tests (Free - No API Calls)\n\n```bash\ncd packages/integrations/ai-sdk-ai-stats\npnpm test\n```\n\nMock tests use `MockLanguageModelV3` and `MockEmbeddingModelV3` from `ai/test` to validate functionality without making actual API calls.\n\n### Run Integration Tests (Requires API Key)\n\n```bash\nAI_STATS_API_KEY=your_key pnpm test\n```\n\nIntegration tests make real calls to the AI Stats Gateway and are automatically enabled when an API key is present.\n\n### Test Coverage\n\n```bash\npnpm test -- --coverage\n```\n\n**Test files:**\n\n-   `tests/language-model.test.ts` - Text generation, streaming, tools, structured output (mocked)\n-   `tests/embedding-model.test.ts` - Embeddings generation and similarity (mocked)\n-   `tests/gateway-integration.test.ts` - Real gateway tests (requires API key)\n\n## Advanced Usage\n\n### Custom Fetch Implementation\n\n```typescript\nimport { createAIStats } from \"@ai-stats/ai-sdk-provider\";\n\nconst aiStats = createAIStats({\n\tfetch: async (url, init) => {\n\t\tconsole.log(\"Request:\", url);\n\t\tconst response = await fetch(url, init);\n\t\tconsole.log(\"Response:\", response.status);\n\t\treturn response;\n\t},\n});\n```\n\n### Error Handling\n\n```typescript\nimport { aiStats } from \"@ai-stats/ai-sdk-provider\";\nimport { generateText } from \"ai\";\n\ntry {\n\tconst result = await generateText({\n\t\tmodel: aiStats(\"openai/gpt-4o\"),\n\t\tprompt: \"Hello!\",\n\t});\n} catch (error: any) {\n\tif (error.status === 401) {\n\t\tconsole.error(\"Invalid API key\");\n\t} else if (error.status === 429) {\n\t\tconsole.error(\"Rate limit exceeded\");\n\t} else if (error.status >= 500) {\n\t\tconsole.error(\"Server error, will retry\");\n\t} else {\n\t\tconsole.error(\"Error:\", error.message);\n\t}\n}\n```\n\n### Usage Tracking\n\n```typescript\nconst result = await generateText({\n\tmodel: aiStats(\"openai/gpt-4o\"),\n\tprompt: \"Hello!\",\n});\n\nconsole.log(\"Prompt tokens:\", result.usage.promptTokens);\nconsole.log(\"Completion tokens:\", result.usage.completionTokens);\nconsole.log(\n\t\"Total tokens:\",\n\tresult.usage.promptTokens + result.usage.completionTokens\n);\n```\n\n## How It Works\n\n1. **Provider Selection**: You specify a model using `provider/model` format\n2. **Gateway Routing**: The AI Stats Gateway routes your request to the appropriate provider\n3. **Health-Aware Failover**: If a provider fails, the gateway automatically tries alternatives\n4. **Response Normalization**: Responses are normalized to AI SDK format\n5. **Usage Tracking**: Token usage and costs are tracked automatically\n\n## Benefits of Using AI Stats Gateway\n\n-   **Unified Billing**: Pay once, use multiple providers\n-   **Automatic Failover**: High availability with provider redundancy\n-   **Cost Optimization**: Gateway routes to the most cost-effective provider\n-   **Usage Analytics**: Detailed analytics and usage tracking\n-   **Rate Limit Management**: Gateway handles rate limiting across providers\n-   **Model Aliasing**: Use virtual model names that map to real models\n\n## Troubleshooting\n\n### \"AI Stats API key is required\"\n\nMake sure you've set the `AI_STATS_API_KEY` environment variable or passed `apiKey` to `createAIStats()`.\n\n### \"Gateway request failed: 401\"\n\nYour API key is invalid. Check that you're using the correct key from your AI Stats account.\n\n### \"Gateway request failed: 429\"\n\nYou've exceeded your rate limit. Wait a moment and try again, or upgrade your plan.\n\n### Streaming not working\n\nEnsure you're using `streamText` or `streamObject` from the AI SDK, not `generateText` or `generateObject`.\n\n### Tool calls not being executed\n\nMake sure you've provided the `execute` function in your tool definition. The AI SDK handles execution automatically.\n\n## TypeScript Support\n\nThis package is written in TypeScript and provides full type definitions:\n\n```typescript\nimport type {\n\tAIStatsSettings,\n\tAIStatsModelSettings,\n} from \"@ai-stats/ai-sdk-provider\";\n\nconst settings: AIStatsSettings = {\n\tapiKey: \"your_key\",\n\tbaseURL: \"https://api.phaseo.app/v1\",\n};\n```\n\n## Contributing\n\nContributions are welcome! Please see [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.\n\n## License\n\nMIT License - see [LICENSE](../../LICENSE) for details.\n\n## Links\n\n-   [AI Stats Gateway](https://ai-stats.phaseo.app/)\n-   [Vercel AI SDK](https://sdk.vercel.ai/docs)\n-   [Documentation](https://ai-stats.phaseo.app/docs)\n-   [API Reference](https://ai-stats.phaseo.app/docs/api)\n-   [GitHub](https://github.com/ai-stats/ai-stats)\n\n## Support\n\n-   **Documentation**: https://ai-stats.phaseo.app/docs\n-   **Discord**: Join our community\n-   **Email**: support@ai-stats.phaseo.app\n\n---\n\nMade with ❤️ by the AI Stats team\n","readmeFilename":"README.md"}