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

config.ts

132 lines4.4 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 accountId?: never
24 apiKey?: never
26​
27/** Run through the Cloudflare REST API from any runtime. */
28export interface CloudflareRestConfig {
29 accountId: string
30 apiKey: string
31 gateway?: CloudflareGatewayOptions
32 /** Custom fetch for every request. */
33 fetch?: FetchLike
34 binding?: never
36​
37/**
38 * REST config for the chat surface. Also accepts the OpenAI SDK client
39 * options (`baseURL`, `defaultHeaders`, `timeout`, `maxRetries`, ...), which
40 * only the text and summarize adapters read.
41 */
42export interface CloudflareTextRestConfig
43 extends CloudflareRestConfig, Omit<ClientOptions, 'apiKey' | 'fetch'> {}
44​
45export type CloudflareConfig = CloudflareBindingConfig | CloudflareRestConfig
46​
47export type CloudflareTextConfig = (
48 | CloudflareBindingConfig
49 | CloudflareTextRestConfig
50) &
51 OpenAIBaseTextAdapterOptions
52​
53/**
54 * What the env-reading factories accept: a binding, or REST fields with any
55 * missing ones read from `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`.
56 */
57export type CloudflareConfigInput<
58 TRest extends CloudflareRestConfig = CloudflareRestConfig,
59> = CloudflareBindingConfig | Partial<TRest>
60​
61export const CLOUDFLARE_API_BASE = 'https://api.cloudflare.com/client/v4'
62​
63export function isBindingConfig(config: {
64 binding?: Ai
65}): config is CloudflareBindingConfig {
66 return config.binding !== undefined
68​
69/** Base URL for the OpenAI-compatible chat surface of an account. */
70export function restChatBaseURL(config: CloudflareTextRestConfig): string {
71 return (
72 config.baseURL ||
73 `${CLOUDFLARE_API_BASE}/accounts/${config.accountId}/ai/v1`
74 )
76​
77/**
78 * Translates gateway options into the `cf-aig-*` request headers the REST
79 * API reads. Retries are not mapped: set them on the gateway itself.
80 */
81export function gatewayHeaders(
82 gateway: CloudflareGatewayOptions | undefined,
83): Record<string, string> {
84 if (!gateway) return {}
85 const headers: Record<string, string> = { 'cf-aig-gateway-id': gateway.id }
86 if (gateway.skipCache !== undefined) {
87 headers['cf-aig-skip-cache'] = String(gateway.skipCache)
88 }
89 if (gateway.cacheTtl !== undefined) {
90 headers['cf-aig-cache-ttl'] = String(gateway.cacheTtl)
91 }
92 if (gateway.cacheKey !== undefined) {
93 headers['cf-aig-cache-key'] = gateway.cacheKey
94 }
95 if (gateway.collectLog !== undefined) {
96 headers['cf-aig-collect-log'] = String(gateway.collectLog)
97 }
98 if (gateway.eventId !== undefined) {
99 headers['cf-aig-event-id'] = gateway.eventId
100 }
101 if (gateway.requestTimeoutMs !== undefined) {
102 headers['cf-aig-request-timeout'] = String(gateway.requestTimeoutMs)
103 }
104 if (gateway.metadata !== undefined) {
105 headers['cf-aig-metadata'] = JSON.stringify(gateway.metadata)
106 }
107 return headers
109​
110/**
111 * Resolves a config for the env-reading factories: a binding config passes
112 * through, anything else is filled from `CLOUDFLARE_ACCOUNT_ID` and
113 * `CLOUDFLARE_API_TOKEN`.
114 */
115export function resolveConfigFromEnv<TRest extends CloudflareRestConfig>(
116 config: CloudflareConfigInput<TRest> | undefined,
117): CloudflareBindingConfig | (Partial<TRest> & CloudflareRestConfig) {
118 if (config && isBindingConfig(config)) return config
119 const rest: Partial<TRest> = config ?? {}
120 try {
121 return {
122 ...rest,
123 accountId: rest.accountId ?? getApiKeyFromEnv('CLOUDFLARE_ACCOUNT_ID'),
124 apiKey: rest.apiKey ?? getApiKeyFromEnv('CLOUDFLARE_API_TOKEN'),
125 }
126 } catch (cause) {
127 throw new Error(
128 '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.',
129 { cause },
130 )
131 }