Open History to see the last commit
1import { gatewayHeaders } from './utils/config'
2import type { AIGatewayProviders } from '@cloudflare/workers-types'
3import type { CloudflareGatewayOptions } from './utils/config'
4
5export interface CloudflareGatewayTarget extends Omit<
6 CloudflareGatewayOptions,
7 'id'
8> {
9 accountId: string
10 gatewayId: string
11 /** Cloudflare API token, needed when the gateway has authentication on. */
12 cfApiKey?: string
13}
14
15/**
16 * Gateway endpoints mirror each vendor's own path after the host, and most
17 * vendor SDKs already append their version segment (Anthropic `/v1/messages`,
18 * Mistral `/v1/...`, Cohere `/v1/chat`). OpenAI-style SDKs append only
19 * `/chat/completions`, which matches Cloudflare's `openai`, `groq`,
20 * `perplexity-ai`, `deepseek`, and `cerebras` endpoints. xAI is the exception:
21 * Cloudflare serves it at `/grok/v1/...`, so its base URL keeps the `/v1`.
22 */
23const PROVIDER_PATH_SUFFIX: Record<string, string> = { grok: '/v1' }
24
25/**
26 * Builds the `baseURL` and headers that point any provider adapter at that
27 * provider's endpoint on your AI Gateway. Pass them through the adapter's
28 * client options (`baseURL` + `defaultHeaders` for OpenAI-style SDKs).
29 *
30 * The headers carry the per-request `cf-aig-*` options plus
31 * `cf-aig-authorization: Bearer <cfApiKey>` when `cfApiKey` is set. The
32 * gateway id lives in the URL, so no `cf-aig-gateway-id` header is sent.
33 *
34 * @example
35 * ```typescript
36 * const gateway = cloudflareGateway('openai', { accountId, gatewayId: 'prod' })
37 * const adapter = createOpenaiChat('gpt-5.5', process.env.OPENAI_API_KEY!, {
38 * baseURL: gateway.baseURL,
39 * defaultHeaders: gateway.headers,
40 * })
41 * ```
42 */
43export function cloudflareGateway(
44 provider: AIGatewayProviders | 'compat' | (string & {}),
45 target: CloudflareGatewayTarget,
46): { baseURL: string; headers: Record<string, string> } {
47 const { accountId, gatewayId, cfApiKey, ...options } = target
48 const { 'cf-aig-gateway-id': _id, ...headers } = gatewayHeaders({
49 id: gatewayId,
50 ...options,
51 })
52 if (cfApiKey) headers['cf-aig-authorization'] = `Bearer ${cfApiKey}`
53 return {
54 baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/${provider}${PROVIDER_PATH_SUFFIX[provider] ?? ''}`,
55 headers,
56 }
57}