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