Cloudflare AI Gateway
The Cloudflare AI Gateway Provider is a library that integrates Cloudflare's AI Gateway with the Vercel AI SDK. It enables seamless access to multiple AI models from various providers through a unified interface, with automatic fallback for high availability.
Features
- Runtime Agnostic: Compatible with Node.js, Edge Runtime, and other JavaScript runtimes supported by the Vercel AI SDK.
- Automatic Fallback: Automatically switches to the next available model if one fails, ensuring resilience.
- Multi-Provider Support: Supports models from OpenAI, Anthropic, DeepSeek, Google AI Studio, Grok, Mistral, Perplexity AI, Replicate, and Groq.
- Cloudflare AI Gateway Integration: Leverages Cloudflare's AI Gateway for request management, caching, and rate limiting.
- Simplified Configuration: Easy setup with support for API key authentication or Cloudflare AI bindings.
Setup
The Cloudflare AI Gateway Provider is available in the ai-gateway-provider module. Install it with:
$ pnpm add ai-gateway-provider
$ npm install ai-gateway-provider
$ yarn add ai-gateway-provider
$ bun add ai-gateway-provider
Provider Instance
Create an aigateway provider instance using the createAiGateway function. You can authenticate using an API key or a Cloudflare AI binding.
API Key Authentication
Cloudflare AI Binding
This method is only available inside Cloudflare Workers.
Configure an AI binding in your wrangler.toml:
In your worker, create a new instance using the binding:
Language Models
Create a model instance by passing an array of models to the aigateway provider. The provider will attempt to use the models in order, falling back to the next if one fails.
Request Options
Customize Cloudflare AI Gateway settings per request:
cacheKey: Custom cache key for the request.cacheTtl: Cache time-to-live in seconds.skipCache: Bypass caching.metadata: Custom metadata for the request.collectLog: Enable/disable log collection.eventId: Custom event identifier.requestTimeoutMs: Request timeout in milliseconds.retries:maxAttempts: Number of retry attempts (1-5).retryDelayMs: Delay between retries.backoff: Retry strategy (constant,linear,exponential).
Example:
Examples
generateText
Generate non-streaming text using the Cloudflare AI Gateway Provider:
streamText
Stream text responses using the Cloudflare AI Gateway Provider:
Supported Providers
- OpenAI
- Anthropic
- DeepSeek
- Google AI Studio
- Grok
- Mistral
- Perplexity AI
- Replicate
- Groq
Error Handling
The provider throws the following custom errors:
AiGatewayUnauthorizedError: Invalid or missing API key when authentication is enabled.AiGatewayDoesNotExist: Specified Cloudflare AI Gateway does not exist.