Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

config.ts

137 lines4.6 KB

1import { getApiKeyFromEnv } from '@tanstack/ai-utils'
2import type { Ai, GatewayOptions } from '@cloudflare/workers-types'
3import type { ClientOptions } from 'openai'
4import type { OpenAIBaseTextAdapterOptions } from '@tanstack/openai-base'
5​
6/**
7 * AI Gateway routing options. `id` is the gateway id (use `"default"` for the
8 * account's auto-created gateway). The remaining fields are per-request
9 * gateway controls (cache, logging, retries) and map to `cf-aig-*` headers on
10 * the REST path or to the `gateway` run option on the binding path.
11 */
12export type CloudflareGatewayOptions = GatewayOptions
13​
14export type FetchLike = NonNullable<ClientOptions['fetch']>
15​
16/**
17 * Run through the Workers AI binding (`env.AI`) inside a Cloudflare Worker.
18 * No API token is needed.
19 */
20export interface CloudflareBindingConfig {
21 binding: Ai
22 gateway?: CloudflareGatewayOptions
23 /**
24 * Workers AI request headers, such as `x-session-affinity` for prompt
25 * caching. Sent on every run as the binding's `extraHeaders` option.
26 */
27 defaultHeaders?: Record<string, string>
28 accountId?: never
29 apiKey?: never
31​
32/** Run through the Cloudflare REST API from any runtime. */
33export interface CloudflareRestConfig {
34 accountId: string
35 apiKey: string
36 gateway?: CloudflareGatewayOptions
37 /** Custom fetch for every request. */
38 fetch?: FetchLike
39 binding?: never
41​
42/**
43 * REST config for the chat surface. Also accepts the OpenAI SDK client
44 * options (`baseURL`, `defaultHeaders`, `timeout`, `maxRetries`, ...), which
45 * only the text and summarize adapters read.
46 */
47export interface CloudflareTextRestConfig
48 extends CloudflareRestConfig, Omit<ClientOptions, 'apiKey' | 'fetch'> {}
49​
50export type CloudflareConfig = CloudflareBindingConfig | CloudflareRestConfig
51​
52export type CloudflareTextConfig = (
53 | CloudflareBindingConfig
54 | CloudflareTextRestConfig
55) &
56 OpenAIBaseTextAdapterOptions
57​
58/**
59 * What the env-reading factories accept: a binding, or REST fields with any
60 * missing ones read from `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`.
61 */
62export type CloudflareConfigInput<
63 TRest extends CloudflareRestConfig = CloudflareRestConfig,
64> = CloudflareBindingConfig | Partial<TRest>
65​
66export const CLOUDFLARE_API_BASE = 'https://api.cloudflare.com/client/v4'
67​
68export function isBindingConfig(config: {
69 binding?: Ai
70}): config is CloudflareBindingConfig {
71 return config.binding !== undefined
73​
74/** Base URL for the OpenAI-compatible chat surface of an account. */
75export function restChatBaseURL(config: CloudflareTextRestConfig): string {
76 return (
77 config.baseURL ||
78 `${CLOUDFLARE_API_BASE}/accounts/${config.accountId}/ai/v1`
79 )
81​
82/**
83 * Translates gateway options into the `cf-aig-*` request headers the REST
84 * API reads. Retries are not mapped: set them on the gateway itself.
85 */
86export function gatewayHeaders(
87 gateway: CloudflareGatewayOptions | undefined,
88): Record<string, string> {
89 if (!gateway) return {}
90 const headers: Record<string, string> = { 'cf-aig-gateway-id': gateway.id }
91 if (gateway.skipCache !== undefined) {
92 headers['cf-aig-skip-cache'] = String(gateway.skipCache)
93 }
94 if (gateway.cacheTtl !== undefined) {
95 headers['cf-aig-cache-ttl'] = String(gateway.cacheTtl)
96 }
97 if (gateway.cacheKey !== undefined) {
98 headers['cf-aig-cache-key'] = gateway.cacheKey
99 }
100 if (gateway.collectLog !== undefined) {
101 headers['cf-aig-collect-log'] = String(gateway.collectLog)
102 }
103 if (gateway.eventId !== undefined) {
104 headers['cf-aig-event-id'] = gateway.eventId
105 }
106 if (gateway.requestTimeoutMs !== undefined) {
107 headers['cf-aig-request-timeout'] = String(gateway.requestTimeoutMs)
108 }
109 if (gateway.metadata !== undefined) {
110 headers['cf-aig-metadata'] = JSON.stringify(gateway.metadata)
111 }
112 return headers
114​
115/**
116 * Resolves a config for the env-reading factories: a binding config passes
117 * through, anything else is filled from `CLOUDFLARE_ACCOUNT_ID` and
118 * `CLOUDFLARE_API_TOKEN`.
119 */
120export function resolveConfigFromEnv<TRest extends CloudflareRestConfig>(
121 config: CloudflareConfigInput<TRest> | undefined,
122): CloudflareBindingConfig | (Partial<TRest> & CloudflareRestConfig) {
123 if (config && isBindingConfig(config)) return config
124 const rest: Partial<TRest> = config ?? {}
125 try {
126 return {
127 ...rest,
128 accountId: rest.accountId ?? getApiKeyFromEnv('CLOUDFLARE_ACCOUNT_ID'),
129 apiKey: rest.apiKey ?? getApiKeyFromEnv('CLOUDFLARE_API_TOKEN'),
130 }
131 } catch (cause) {
132 throw new Error(
133 'CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are required. Set them in your environment, pass { accountId, apiKey }, or pass { binding: env.AI } inside a Worker.',
134 { cause },
135 )
136 }