workers-ai-provider 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -15
- package/dist/anthropic.d.mts +1 -1
- package/dist/{gateway-delegate-BfaUTwDZ.d.mts → gateway-delegate-BAALxuBO.d.mts} +75 -11
- package/dist/{gateway-provider-1USFWm7c.mjs → gateway-provider-BjPLZLob.mjs} +560 -168
- package/dist/gateway-provider-BjPLZLob.mjs.map +1 -0
- package/dist/gateway-provider.mjs +1 -1
- package/dist/google.d.mts +1 -1
- package/dist/index.d.mts +4 -3
- package/dist/index.mjs +388 -279
- package/dist/index.mjs.map +1 -1
- package/dist/openai.d.mts +1 -1
- package/package.json +5 -4
- package/src/gateway-delegate.ts +290 -86
- package/src/gateway-provider.ts +10 -34
- package/src/gateway-providers.ts +13 -455
- package/src/index.ts +144 -8
- package/src/resumable-stream.ts +9 -221
- package/src/streaming.ts +1 -41
- package/src/utils.ts +40 -125
- package/src/workersai-chat-language-model.ts +37 -16
- package/src/workersai-embedding-model.ts +22 -11
- package/src/workersai-error.ts +70 -0
- package/src/workersai-image-model.ts +19 -11
- package/src/workersai-reranking-model.ts +16 -5
- package/src/workersai-speech-model.ts +35 -13
- package/src/workersai-transcription-model.ts +15 -4
- package/dist/gateway-provider-1USFWm7c.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
[Workers AI](https://developers.cloudflare.com/workers-ai/) provider for the [AI SDK](https://sdk.vercel.ai/). Run Cloudflare's models for chat, embeddings, image generation, transcription, text-to-speech, reranking, and [AI Search](https://developers.cloudflare.com/ai-search/) — all from a single provider. It can also route **third-party** models (OpenAI, Anthropic, Google, …) through [AI Gateway](https://developers.cloudflare.com/ai-gateway/) — see [Third-party models](#third-party-models-via-ai-gateway).
|
|
4
4
|
|
|
5
|
+
> 📚 In-depth guides and the AI Gateway **delegate** reference (unified catalog,
|
|
6
|
+
> resumable streaming _(coming soon)_, server-side fallback) live in
|
|
7
|
+
> [`docs/workers-ai-provider`](../../docs/workers-ai-provider/README.md).
|
|
8
|
+
|
|
5
9
|
## Quick start
|
|
6
10
|
|
|
7
11
|
```bash
|
|
@@ -333,7 +337,7 @@ Streaming works the same way — use `streamText` instead of `generateText`.
|
|
|
333
337
|
|
|
334
338
|
> **⚠️ Experimental.** Everything in this section (routing third-party models via `createWorkersAI({ providers })`, the provider plugins, the registry, the resume layer, and `createGatewayFetch`/`createGatewayProvider`) is a new and substantial addition — well beyond the package's original job of wrapping Workers AI. Treat the whole surface as experimental: APIs may change, and several behaviors depend on undocumented AI Gateway internals (the `cf-aig-run-id` resume buffer, per-provider run-path wire formats). It does **not** affect the stable Workers AI / AI Search APIs above. Bug reports and feedback are very welcome.
|
|
335
339
|
|
|
336
|
-
Route **third-party** catalog models — OpenAI, Anthropic, Google, xAI/Grok, Groq, and the OpenAI-compatible long tail — through [AI Gateway](https://developers.cloudflare.com/ai-gateway/) using the same `env.AI` binding, with resumable streaming, BYOK, caching, and fallback.
|
|
340
|
+
Route **third-party** catalog models — OpenAI, Anthropic, Google, xAI/Grok, Groq, and the OpenAI-compatible long tail — through [AI Gateway](https://developers.cloudflare.com/ai-gateway/) using the same `env.AI` binding, with resumable streaming _(coming soon)_, BYOK, caching, and fallback.
|
|
337
341
|
|
|
338
342
|
Install only the wire-format plugins you actually use. They're **optional** peer dependencies:
|
|
339
343
|
|
|
@@ -360,7 +364,7 @@ const workersai = createWorkersAI({
|
|
|
360
364
|
// gateway unless you set one, e.g. gateway: { id: "my-gateway" }.
|
|
361
365
|
});
|
|
362
366
|
|
|
363
|
-
workersai("@cf/
|
|
367
|
+
workersai("@cf/zai-org/glm-5.2"); // Workers AI (unchanged)
|
|
364
368
|
|
|
365
369
|
const result = streamText({
|
|
366
370
|
model: workersai("openai/gpt-5", { resume: true }), // routed through AI Gateway
|
|
@@ -389,10 +393,10 @@ The registry covers every provider in the [AI Gateway provider directory](https:
|
|
|
389
393
|
|
|
390
394
|
The transport is chosen automatically from the options you pass:
|
|
391
395
|
|
|
392
|
-
| Transport | Backed by | Resume (`cf-aig-run-id`) | Caching | Server fallback | Billing |
|
|
393
|
-
| ----------------- | ---------------------------- |
|
|
394
|
-
| **run** (default) | `env.AI.run(...)` | ✅
|
|
395
|
-
| **gateway** | `env.AI.gateway(id).run([])` | ❌
|
|
396
|
+
| Transport | Backed by | Resume _(coming soon)_ (`cf-aig-run-id`) | Caching | Server fallback | Billing |
|
|
397
|
+
| ----------------- | ---------------------------- | ---------------------------------------- | ------- | --------------- | ----------------- |
|
|
398
|
+
| **run** (default) | `env.AI.run(...)` | ✅ | ❌ | ❌ | Unified billing |
|
|
399
|
+
| **gateway** | `env.AI.gateway(id).run([])` | ❌ | ✅ | ✅ | BYOK / stored key |
|
|
396
400
|
|
|
397
401
|
Run-catalog providers (OpenAI, Anthropic, Google, xAI, Groq, plus the unified-catalog chat providers Alibaba/Qwen and MiniMax) default to the resumable **run path**. BYOK-only providers (deepseek, mistral, perplexity, …) always use the **gateway path**. Asking for an impossible combination (e.g. `resume: true` with `fallback.mode: "server"`) throws a `GatewayDelegateError`.
|
|
398
402
|
|
|
@@ -447,6 +451,11 @@ workersai("openai/gpt-5", {
|
|
|
447
451
|
|
|
448
452
|
### Resume after disconnect
|
|
449
453
|
|
|
454
|
+
> **🚧 Coming soon.** Resumable streaming is not generally available yet — the AI
|
|
455
|
+
> Gateway resume backend is still rolling out. The options here are in place so
|
|
456
|
+
> you can adopt them early, but treat resume as experimental until the rollout
|
|
457
|
+
> completes.
|
|
458
|
+
|
|
450
459
|
The run path wraps the response stream so a transient mid-stream drop reconnects through the gateway resume endpoint transparently. For cross-invocation recovery (e.g. a Durable Object re-attaching after eviction), persist `{ runId, eventOffset }` via `onDispatch` + `onProgress` and re-attach with `createResumableStream`:
|
|
451
460
|
|
|
452
461
|
```ts
|
|
@@ -482,15 +491,15 @@ The provider id is detected from the request URL (or pass `provider` explicitly)
|
|
|
482
491
|
|
|
483
492
|
### `createWorkersAI(options)`
|
|
484
493
|
|
|
485
|
-
| Option | Type | Description
|
|
486
|
-
| ----------------- | ------------------------------- |
|
|
487
|
-
| `binding` | `Ai` | Workers AI binding (`env.AI`). Use this OR credentials.
|
|
488
|
-
| `accountId` | `string` | Cloudflare account ID. Required with `apiKey`.
|
|
489
|
-
| `apiKey` | `string` | Cloudflare API token. Required with `accountId`.
|
|
490
|
-
| `gateway` | `GatewayOptions` | Optional [AI Gateway](https://developers.cloudflare.com/ai-gateway/) config.
|
|
491
|
-
| `providers` | `ProviderPlugin[]` | _Experimental._ Wire-format plugins that enable routing `"<provider>/<model>"` slugs via gateway.
|
|
492
|
-
| `resume` | `boolean` | _Experimental._ Default resume behavior for gateway-routed catalog models. Defaults to `true`.
|
|
493
|
-
| `onResumeExpired` | `"error"` \| `"accept-partial"` | _Experimental._ Default policy when the gateway resume buffer expires. Defaults to `"error"`.
|
|
494
|
+
| Option | Type | Description |
|
|
495
|
+
| ----------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
496
|
+
| `binding` | `Ai` | Workers AI binding (`env.AI`). Use this OR credentials. |
|
|
497
|
+
| `accountId` | `string` | Cloudflare account ID. Required with `apiKey`. |
|
|
498
|
+
| `apiKey` | `string` | Cloudflare API token. Required with `accountId`. |
|
|
499
|
+
| `gateway` | `GatewayOptions` | Optional [AI Gateway](https://developers.cloudflare.com/ai-gateway/) config. |
|
|
500
|
+
| `providers` | `ProviderPlugin[]` | _Experimental._ Wire-format plugins that enable routing `"<provider>/<model>"` slugs via gateway. |
|
|
501
|
+
| `resume` | `boolean` | _Experimental — coming soon._ Default resume behavior for gateway-routed catalog models. Defaults to `true`. |
|
|
502
|
+
| `onResumeExpired` | `"error"` \| `"accept-partial"` | _Experimental — coming soon._ Default policy when the gateway resume buffer expires. Defaults to `"error"`. |
|
|
494
503
|
|
|
495
504
|
Returns a provider with model factories. Each factory accepts an optional second argument for per-model settings:
|
|
496
505
|
|
package/dist/anthropic.d.mts
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
import { LanguageModelV3 } from "@ai-sdk/provider";
|
|
2
2
|
|
|
3
|
+
//#region ../gateway-core/dist/index.d.mts
|
|
4
|
+
//#region src/errors.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Error type shared by the gateway delegate and the resumable-stream engine.
|
|
7
|
+
*
|
|
8
|
+
* Lives in `@cloudflare/gateway-core` because the resume engine (here) and the
|
|
9
|
+
* delegate (in `workers-ai-provider`) both throw it. Note: since each consumer
|
|
10
|
+
* inlines this source into its own bundle, `instanceof GatewayDelegateError`
|
|
11
|
+
* only matches within a single package's bundle — match on `.name`/`.kind`
|
|
12
|
+
* across package boundaries.
|
|
13
|
+
*/
|
|
14
|
+
type GatewayDelegateErrorKind = "config" | "dispatch" | "provider" | "resume-expired";
|
|
15
|
+
declare class GatewayDelegateError extends Error {
|
|
16
|
+
readonly kind: GatewayDelegateErrorKind;
|
|
17
|
+
readonly cause?: unknown;
|
|
18
|
+
constructor(kind: GatewayDelegateErrorKind, message: string, cause?: unknown);
|
|
19
|
+
} //#endregion
|
|
20
|
+
//#region src/gateway-fetch.d.ts
|
|
21
|
+
/**
|
|
22
|
+
* Shared AI Gateway dispatch primitives: the `cf-aig-*` header builder, the
|
|
23
|
+
* provider-key / hop-by-hop header strip, body decoding, and universal-endpoint
|
|
24
|
+
* entry construction.
|
|
25
|
+
*
|
|
26
|
+
* These are consumed by `workers-ai-provider` (the gateway-path `createGatewayFetch`
|
|
27
|
+
* and the delegate's `makeGatewayFetch`/`makeRunFetch`) and by `@cloudflare/tanstack-ai`
|
|
28
|
+
* (its REST/binding `createGatewayFetch`), so there's a single place that knows how
|
|
29
|
+
* to translate caching/metadata/log options into gateway headers.
|
|
30
|
+
*/
|
|
31
|
+
/** Metadata values the gateway accepts (`bigint` is serialized to a string). */
|
|
32
|
+
//#endregion
|
|
3
33
|
//#region src/gateway-providers.d.ts
|
|
4
34
|
/**
|
|
5
35
|
* Registry of Cloudflare AI Gateway providers.
|
|
@@ -92,8 +122,7 @@ declare function findProviderBySlug(resolverKey: string): GatewayProviderInfo |
|
|
|
92
122
|
/** Detect the gateway provider from a wrapped provider's request URL (BYOG). */
|
|
93
123
|
declare function detectProviderByUrl(url: string): GatewayProviderInfo | undefined;
|
|
94
124
|
/** All slug keys with a built-in parser (auto-wireable by the slug delegate). */
|
|
95
|
-
declare function wireableProviders(): GatewayProviderInfo[];
|
|
96
|
-
//#endregion
|
|
125
|
+
declare function wireableProviders(): GatewayProviderInfo[]; //#endregion
|
|
97
126
|
//#region src/resumable-stream.d.ts
|
|
98
127
|
type ResumeExpiredPolicy = "error" | "accept-partial";
|
|
99
128
|
interface ResumableStreamOptions {
|
|
@@ -127,8 +156,35 @@ interface ResumableStreamOptions {
|
|
|
127
156
|
* re-attach (throttle your own writes — this can fire per chunk).
|
|
128
157
|
*/
|
|
129
158
|
onProgress?: (eventOffset: number) => void;
|
|
159
|
+
/**
|
|
160
|
+
* Abort signal for the consuming request. When it aborts (or the downstream
|
|
161
|
+
* consumer cancels the wrapped stream), the engine stops **without**
|
|
162
|
+
* reconnecting — an intentional cancel must never trigger a resume reconnect.
|
|
163
|
+
* The signal is also forwarded to the resume fetch.
|
|
164
|
+
*/
|
|
165
|
+
signal?: AbortSignal;
|
|
130
166
|
}
|
|
131
|
-
declare function createResumableStream(options: ResumableStreamOptions): ReadableStream<Uint8Array>;
|
|
167
|
+
declare function createResumableStream(options: ResumableStreamOptions): ReadableStream<Uint8Array>; //#endregion
|
|
168
|
+
//#region src/workers-ai.d.ts
|
|
169
|
+
/**
|
|
170
|
+
* Shared, framework-agnostic Workers AI helpers.
|
|
171
|
+
*
|
|
172
|
+
* These are the pieces that `workers-ai-provider` (native `LanguageModelV3`) and
|
|
173
|
+
* `@cloudflare/tanstack-ai` (OpenAI-SDK shim) both need: the SSE byte decoder,
|
|
174
|
+
* message normalization for the binding's stricter schema, response-text
|
|
175
|
+
* extraction across WAI's response shapes, and the gpt-oss forced-tool-call
|
|
176
|
+
* salvage.
|
|
177
|
+
*
|
|
178
|
+
* IMPORTANT — id/dependency decoupling: nothing here depends on the `ai` package
|
|
179
|
+
* or mints framework tool-call ids. `parseLeakedToolCalls` returns neutral
|
|
180
|
+
* `{ toolName, input }` records; each consumer assigns its own ids and adapts to
|
|
181
|
+
* its own tool-call shape. This keeps `gateway-core` free of an `ai` dependency.
|
|
182
|
+
*/
|
|
183
|
+
/**
|
|
184
|
+
* TransformStream that decodes a raw byte stream into SSE `data:` payloads.
|
|
185
|
+
* Each output chunk is the string content after `data: ` (one per SSE event),
|
|
186
|
+
* with line buffering for partial chunks.
|
|
187
|
+
*/
|
|
132
188
|
//#endregion
|
|
133
189
|
//#region src/errors.d.ts
|
|
134
190
|
/**
|
|
@@ -340,6 +396,20 @@ interface DelegateCallOptions {
|
|
|
340
396
|
* delegate strips provider auth headers so unified billing applies.
|
|
341
397
|
*/
|
|
342
398
|
byok?: boolean;
|
|
399
|
+
/**
|
|
400
|
+
* Gateway path only: BYOK stored-key alias to authenticate with
|
|
401
|
+
* (`cf-aig-byok-alias`). Selects a non-`default` key you configured for the
|
|
402
|
+
* provider on the gateway. Independent of `byok` (which controls whether the
|
|
403
|
+
* caller's own provider auth header is forwarded vs. stripped).
|
|
404
|
+
*/
|
|
405
|
+
byokAlias?: string;
|
|
406
|
+
/**
|
|
407
|
+
* Per-request Zero Data Retention override (`cf-aig-zdr`), Unified Billing
|
|
408
|
+
* only: `true` forces ZDR-capable upstreams, `false` disables it for this
|
|
409
|
+
* request. Overrides the gateway-level ZDR default. Applied on both transports
|
|
410
|
+
* (run path: passed through gateway options as a header; gateway path: entry header).
|
|
411
|
+
*/
|
|
412
|
+
zdr?: boolean;
|
|
343
413
|
/** Override the delegate's gateway for this model. */
|
|
344
414
|
gateway?: GatewayOptions | string;
|
|
345
415
|
/**
|
|
@@ -374,12 +444,6 @@ interface Selection {
|
|
|
374
444
|
* requested.
|
|
375
445
|
*/
|
|
376
446
|
declare function selectTransport(opts: DelegateCallOptions, resumeExplicitlyTrue: boolean, runCatalog?: boolean, gatewayAvailable?: boolean): Selection;
|
|
377
|
-
type GatewayDelegateErrorKind = "config" | "dispatch" | "provider" | "resume-expired";
|
|
378
|
-
declare class GatewayDelegateError extends Error {
|
|
379
|
-
readonly kind: GatewayDelegateErrorKind;
|
|
380
|
-
readonly cause?: unknown;
|
|
381
|
-
constructor(kind: GatewayDelegateErrorKind, message: string, cause?: unknown);
|
|
382
|
-
}
|
|
383
447
|
//#endregion
|
|
384
|
-
export {
|
|
385
|
-
//# sourceMappingURL=gateway-delegate-
|
|
448
|
+
export { createResumableStream as C, wireableProviders as E, WireFormat as S, findProviderBySlug as T, GATEWAY_PROVIDERS as _, ProviderPlugin as a, ResumableStreamOptions as b, selectTransport as c, FallbackAttempt as d, GatewayErrorCode as f, Billing as g, WorkersAIGatewayError as h, ParsedSlug as i, FallbackLeg as l, WorkersAIFallbackError as m, DispatchInfo as n, Transport as o, GatewayErrorContext as p, FallbackOptions as r, parseSlug as s, DelegateCallOptions as t, createClientFallbackModel as u, GatewayDelegateError as v, detectProviderByUrl as w, ResumeExpiredPolicy as x, GatewayProviderInfo as y };
|
|
449
|
+
//# sourceMappingURL=gateway-delegate-BAALxuBO.d.mts.map
|