Open History to see the last commit
1import OpenAI from 'openai'
2import type { ClientOptions } from 'openai'
3import { OpenAIBaseChatCompletionsTextAdapter } from '@tanstack/openai-base'
4import { resolveReasoning } from '@tanstack/ai/adapter-internals'
5import { CLOUDFLARE_MODEL_REASONING } from '../utils/models'
6import {
7 gatewayHeaders,
8 isBindingConfig,
9 resolveConfigFromEnv,
10 restChatBaseURL,
11} from '../utils/config'
12import { createBindingFetch, createRestFetch } from '../utils/fetch'
13import type {
14 ChatCompletionChunk,
15 ChatCompletionMessageParam,
16} from 'openai/resources/chat/completions/completions'
17import type {
18 CloudflareConfigInput,
19 CloudflareTextConfig,
20 CloudflareTextRestConfig,
21} from '../utils/config'
22import type {
23 CloudflareModelReasoningByName,
24 CloudflareTextModel,
25} from '../utils/models'
26import type {
27 DefaultMessageMetadataByModality,
28 Modality,
29 ModelMessage,
30 TextOptions,
31} from '@tanstack/ai'
32
33/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
34type ResolveReasoning<TModel extends string> =
35 TModel extends keyof CloudflareModelReasoningByName
36 ? CloudflareModelReasoningByName[TModel]
37 : never
38
39/**
40 * Chat Completions parameters forwarded verbatim to Workers AI. Reasoning
41 * effort is set with `chat({ reasoning })`; reasoning models (GLM, Kimi,
42 * gpt-oss, QwQ) also read `chat_template_kwargs`.
43 */
44export interface CloudflareTextProviderOptions {
45 temperature?: number
46 max_tokens?: number
47 top_p?: number
48 top_k?: number
49 seed?: number
50 repetition_penalty?: number
51 frequency_penalty?: number
52 presence_penalty?: number
53 chat_template_kwargs?: {
54 enable_thinking?: boolean
55 clear_thinking?: boolean
56 }
57}
58
59function clientOptions(config: CloudflareTextConfig): ClientOptions {
60 if (isBindingConfig(config)) {
61 return {
62 // The binding authenticates by itself; the SDK only requires a value.
63 apiKey: 'cloudflare-binding',
64 fetch: createBindingFetch(config.binding, config.gateway),
65 }
66 }
67 const {
68 accountId: _accountId,
69 binding: _binding,
70 gateway,
71 ...options
72 } = config
73 return {
74 ...options,
75 baseURL: restChatBaseURL(config),
76 defaultHeaders: {
77 ...gatewayHeaders(gateway),
78 ...options.defaultHeaders,
79 },
80 fetch: createRestFetch(options.fetch),
81 }
82}
83
84/**
85 * Cloudflare text (chat) adapter.
86 *
87 * Drives Workers AI's OpenAI-compatible Chat Completions surface with the
88 * OpenAI SDK. Inside a Worker pass `{ binding: env.AI }`; anywhere else pass
89 * `{ accountId, apiKey }`. Add `gateway` to route through AI Gateway. Any
90 * catalog model works, including third-party `provider/model` ids billed
91 * through AI Gateway.
92 */
93export class CloudflareTextAdapter<
94 TModel extends CloudflareTextModel,
95 TProviderOptions extends Record<string, any> = CloudflareTextProviderOptions,
96> extends OpenAIBaseChatCompletionsTextAdapter<
97 TModel,
98 TProviderOptions,
99 ReadonlyArray<Modality>,
100 DefaultMessageMetadataByModality,
101 ReadonlyArray<string>,
102 ResolveReasoning<TModel>
103> {
104 override readonly kind = 'text' as const
105 override readonly name = 'cloudflare' as const
106
107 constructor(config: CloudflareTextConfig, model: TModel) {
108 const options = clientOptions(config)
109 super(model, 'cloudflare', new OpenAI(options), {
110 ...config,
111 fetch: options.fetch,
112 })
113 }
114
115 /** Workers AI reports a context overflow as error code 5021. */
116 protected override isContextOverflow(error: {
117 message: string
118 code: string | undefined
119 }): boolean {
120 return super.isContextOverflow(error) || error.code === '5021'
121 }
122
123 /**
124 * `chat({ reasoning })` as `reasoning_effort`. Workers AI turns reasoning
125 * off with `null`, so `off` sends `null`, not the model's off value.
126 */
127 protected override mapOptionsToRequest(options: TextOptions) {
128 const request = super.mapOptionsToRequest(options)
129 const resolved = resolveReasoning(
130 options.reasoning,
131 CLOUDFLARE_MODEL_REASONING[options.model],
132 )
133 if (resolved) {
134 Object.assign(request, {
135 reasoning_effort: resolved.level === 'off' ? null : resolved.value,
136 })
137 }
138 return request
139 }
140
141 /**
142 * Workers AI validates `messages[].content` as a string, so a tool-call-only
143 * assistant turn (which OpenAI accepts as `content: null`) is sent as `''`.
144 */
145 protected override convertMessage(
146 message: ModelMessage,
147 ): ChatCompletionMessageParam {
148 const converted = super.convertMessage(message)
149 if (converted.role === 'assistant' && converted.content == null) {
150 return { ...converted, content: '' }
151 }
152 return converted
153 }
154
155 /**
156 * Workers AI accepts `response_format` next to `tools` but its models answer
157 * the tool follow-up turn in prose, so structured output with tools runs as
158 * a separate finalization request instead.
159 */
160 override supportsCombinedToolsAndSchema(): boolean {
161 return false
162 }
163
164 /** Workers AI reasoning models stream thinking as `reasoning_content` (some as `reasoning`). */
165 protected override extractReasoning(
166 chunk: ChatCompletionChunk,
167 ): { text: string } | undefined {
168 const delta = chunk.choices[0]?.delta as
169 | { reasoning?: unknown; reasoning_content?: unknown }
170 | undefined
171 const raw = delta?.reasoning_content ?? delta?.reasoning
172 return typeof raw === 'string' && raw.length > 0 ? { text: raw } : undefined
173 }
174}
175
176/**
177 * Creates a Cloudflare text adapter with explicit configuration.
178 *
179 * @example
180 * ```typescript
181 * // Inside a Worker
182 * const adapter = createCloudflareText('@cf/zai-org/glm-5.3-flash', { binding: env.AI })
183 * // Anywhere, over REST
184 * const adapter = createCloudflareText('@cf/zai-org/glm-5.3-flash', { accountId, apiKey })
185 * ```
186 */
187export function createCloudflareText<TModel extends CloudflareTextModel>(
188 model: TModel,
189 config: CloudflareTextConfig,
190): CloudflareTextAdapter<TModel> {
191 return new CloudflareTextAdapter(config, model)
192}
193
194/**
195 * Creates a Cloudflare text adapter, reading `CLOUDFLARE_ACCOUNT_ID` and
196 * `CLOUDFLARE_API_TOKEN` from the environment unless a binding is passed.
197 */
198export function cloudflareText<TModel extends CloudflareTextModel>(
199 model: TModel,
200 config?: CloudflareConfigInput<CloudflareTextRestConfig>,
201): CloudflareTextAdapter<TModel> {
202 return new CloudflareTextAdapter(resolveConfigFromEnv(config), model)
203}