@zyro-sec/ai 0.0.0-stage → 1.0.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.
Files changed (2) hide show
  1. package/README.md +1810 -2
  2. package/package.json +195 -4
package/README.md CHANGED
@@ -1,3 +1,1811 @@
1
- # Temporary Holding Version
1
+ # @zyro-sec/ai
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Schema-first APIs for text, images, video, decisions, and embeddings, built with Effect. Speech, transcription,
4
+ extraction, and realtime voice are [experimental](#experimental).
5
+
6
+ `@zyro-sec/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
7
+ and `ai.write` load `node:fs/promises` on first use, so no Effect `FileSystem` is needed:
8
+
9
+ ```ts
10
+ import { ai } from "@zyro-sec/ai"
11
+ import { OpenAI } from "@zyro-sec/ai/providers"
12
+
13
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
14
+
15
+ const input = { model: openai.responses("gpt-4o-mini"), prompt: "Say hello." }
16
+ const response = await ai.generate(input)
17
+ console.log(response.text)
18
+ const generated = await ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" })
19
+ await ai.write(generated.images[0], "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
20
+ for await (const event of ai.stream(ai.request(input))) {
21
+ // LLMEvent
22
+ }
23
+ ```
24
+
25
+ The Effect API lives at `@zyro-sec/ai/effect`. Its `ai` has the same namespaces and methods, returning `Effect` or
26
+ `Stream`:
27
+
28
+ ```ts
29
+ import { Effect } from "effect"
30
+ import { ai, AIClient } from "@zyro-sec/ai/effect"
31
+ import { OpenAI } from "@zyro-sec/ai/providers"
32
+
33
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
34
+
35
+ const program = Effect.gen(function* () {
36
+ const response = yield* ai.generate({
37
+ model: openai.responses("gpt-4o-mini"), // `.chat(...)` selects the Chat Completions API instead
38
+ system: "You are concise.",
39
+ prompt: "Say hello in one short sentence.",
40
+ maxTokens: 40,
41
+ })
42
+ console.log(response.text)
43
+ })
44
+
45
+ // Every modality client plus the HTTP request executor; `AIClient.layerWith(executor)` swaps the executor.
46
+ await Effect.runPromise(program.pipe(Effect.provide(AIClient.layer)))
47
+ ```
48
+
49
+ Run `ai.stream(...)` instead of `generate` when you want incremental `LLMEvent`s. Both accept input or a prebuilt
50
+ `ai.request(...)`. Input takes either `prompt`, a single user message, or `messages`, the whole conversation, never
51
+ both; `system` goes with either. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
52
+ Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
53
+
54
+ ### Tool loop
55
+
56
+ `stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling
57
+ tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs (an error result when
58
+ it fails). Each step ends with its own `step-finish`; one `finish` ends the loop, carrying the final step's reason
59
+ and the usage summed across steps. `until` is checked
60
+ after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running
61
+ them. Tools are an array, sent in the order given so the provider can reuse its cached prompt prefix. Each tool has a
62
+ `name`, and two tools with the same name fail the request. Tool arguments that are not valid JSON go back to the model
63
+ as an error result so it can retry. A step that hits the output token limit ends the loop without running its tool
64
+ calls, which may be cut off. A forced `toolChoice` applies to the first step only; later steps use `auto`. `tool` takes
65
+ a plain `async` execute; a throw or rejection goes back to the model as an error result, and `signal` aborts when the
66
+ loop is interrupted.
67
+ `input` is an Effect Schema that decodes and types the arguments, or a raw JSON Schema object, such as an MCP tool's,
68
+ whose arguments arrive as `unknown` (pair it with an optional JSON Schema `outputSchema`). `tool` from
69
+ `@zyro-sec/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
70
+
71
+ ```ts
72
+ import { readFile } from "node:fs/promises"
73
+ import { Schema } from "effect"
74
+ import { ai, tool } from "@zyro-sec/ai"
75
+
76
+ const read_file = tool({
77
+ name: "read_file",
78
+ description: "Read a UTF-8 file.",
79
+ input: Schema.Struct({ path: Schema.String }),
80
+ execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
81
+ })
82
+
83
+ const events = ai.loop({
84
+ model,
85
+ prompt: "Summarize package.json.",
86
+ tools: [read_file],
87
+ until: ({ steps }) => steps.length >= 8,
88
+ })
89
+ for await (const event of events) {
90
+ if (event.type === "text-delta") process.stdout.write(event.text)
91
+ }
92
+ ```
93
+
94
+ The terminal `finish` carries the final assistant `message` and `usage`. To skip the events, `ai.collect` folds a
95
+ stream from `stream` or `loop` into one result: `text` of the final step, `steps` (one `LLMResponse` per call),
96
+ `messages` (each step's assistant message and its tool results, ready to append to the next request), the total
97
+ `usage`, `finishReason`, and `object` with `schema`.
98
+
99
+ ```ts
100
+ const result = await ai.collect(ai.loop({ model, prompt: "Summarize package.json.", tools: { read_file } }))
101
+ // Effect: const result = yield* ai.collect(ai.loop({ ... }))
102
+ console.log(result.text, result.usage?.totalTokens)
103
+ ```
104
+
105
+ ### Freeform tools
106
+
107
+ A tool with exactly one required string parameter can set `freeform`, so the model writes that parameter as raw text
108
+ instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `lark` grammar.
109
+
110
+ ```ts
111
+ const run_code = tool({
112
+ name: "run_code",
113
+ description: "Run JavaScript",
114
+ input: Schema.Struct({ code: Schema.String }),
115
+ freeform: { type: "lark", grammar: JS_GRAMMAR },
116
+ execute: ({ code }) => runCode(code),
117
+ })
118
+ ```
119
+
120
+ OpenAI Responses and Chat Completions, and every provider that reuses them, send it as a
121
+ [custom tool](https://platform.openai.com/docs/guides/function-calling#custom-tools). Other protocols send the normal
122
+ JSON tool. Only set `freeform` for models that accept custom tools in that format; nothing checks this or falls back
123
+ to JSON, so an unsupported model returns the provider's error. Calls, tool input events, results and history always
124
+ use the `{ code }` object, and past calls replay the way the tool is declared in the current request, so the same
125
+ history works with or without `freeform`.
126
+
127
+ ### Structured output
128
+
129
+ Pass `schema` to `generate`, `stream` or `loop`. The model must answer through a hidden tool call, decoded into
130
+ `object` (typed from an Effect Schema, or an unvalidated `unknown` for a raw JSON Schema object):
131
+
132
+ ```ts
133
+ const res = await ai.generate({ model, prompt: "Pick a city.", schema: Schema.Struct({ city: Schema.String }) })
134
+ res.object.city
135
+ ```
136
+
137
+ `stream` puts `object` on its `finish` event; `loop` runs tools first and puts it on the loop's `finish`. A
138
+ decode failure is an `AIError` whose `partial` holds the response.
139
+
140
+ ### Errors
141
+
142
+ Every failure is an `AIError`. `reason._tag` names the kind (`RateLimit`, `InvalidRequest`, `Transport`, ...), and
143
+ getters read the common fields without digging into `reason` or the raw body:
144
+
145
+ ```ts
146
+ try {
147
+ await ai.generate({ model, prompt: "Hi" })
148
+ } catch (error) {
149
+ if (!(error instanceof AIError)) throw error
150
+ error.status // HTTP status, when the failure came from a response
151
+ error.code // provider error code such as "model_not_found", when known
152
+ error.isRetryable // whether sending the same request again may succeed
153
+ error.retryAfterMs // delay the provider asked for, when known
154
+ }
155
+ ```
156
+
157
+ ### Raw provider events
158
+
159
+ Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
160
+ before the events parsed from that frame. `data` is the parsed JSON frame, so frames this package doesn't handle yet
161
+ are visible too. Raw events are off by default, and `generate` ignores them. `RawEvent` is the event's type. Act on a
162
+ frame with a stream map:
163
+
164
+ ```ts
165
+ import { Effect, Stream } from "effect"
166
+ import { ai, AIError, ContentPolicyError } from "@zyro-sec/ai/effect"
167
+
168
+ const flagged = (data: unknown) =>
169
+ typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
170
+
171
+ const events = ai
172
+ .stream({ model, prompt: "Say hello.", includeRaw: true })
173
+ .pipe(
174
+ Stream.mapEffect((event) =>
175
+ event.type === "raw" && flagged(event.data)
176
+ ? Effect.fail(new AIError({ reason: new ContentPolicyError({ message: "Flagged by moderation" }) }))
177
+ : Effect.succeed(event),
178
+ ),
179
+ )
180
+ ```
181
+
182
+ ### Google Interactions
183
+
184
+ `Google.configure({ apiKey }).interactions(modelID)` selects the Interactions API; `.model(modelID)` still selects
185
+ GenerateContent. The package entrypoint is `@zyro-sec/ai/providers/google/interactions`.
186
+
187
+ For Vertex AI, use `GoogleVertexInteractions.configure({ project, location: "global" }).model(modelID)` or
188
+ `@zyro-sec/ai/providers/google-vertex/interactions`. It uses Application Default Credentials by default, accepts
189
+ an explicit `accessToken` or `auth` override, and supports Express mode with `apiKey`. Vertex metadata and raw usage
190
+ live under `providerMetadata.vertex`. The default is still full-history replay with `store: false`.
191
+
192
+ ```ts
193
+ const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
194
+ const response =
195
+ yield *
196
+ ai.generate({
197
+ model,
198
+ prompt: "Say hello.",
199
+ providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
200
+ })
201
+ ```
202
+
203
+ Interactions supports text output, streamed function calls, native tool results, thought signatures, and multimodal
204
+ input. Full-history replay is the default (`store: false`); implicit caching works without retained interactions.
205
+ For server-side continuation, set `store: true` on the predecessor, read `interactionId` from the final event's
206
+ `providerMetadata.google`, and pass `previousInteractionId` on the next request with **only new messages**. Repeat
207
+ the system instructions and tool declarations on each request. Set `store: true` on each response you intend to
208
+ continue from. The package does not automatically select or persist continuation IDs.
209
+
210
+ Raw usage is preserved in `usage.providerMetadata.google`. `inputTokens` follows Google's top-level accounting;
211
+ `contextTokens` uses its full `raw_prompt_token` count when supplied. These can differ substantially with server-side
212
+ continuation. Explicit caches, hosted tools, and generated media are not supported by this initial protocol.
213
+
214
+ The same configured facade names image and video models (and the experimental speech and transcription models).
215
+ `ai.image.generate` resolves the provider's image route from the model and returns `Media.Asset`s with lazily decoded bytes:
216
+
217
+ ```ts
218
+ import { NodeFileSystem } from "@effect/platform-node"
219
+ import { ai, Media } from "@zyro-sec/ai/effect"
220
+
221
+ const image = Effect.gen(function* () {
222
+ const response = yield* ai.image.generate({
223
+ model: openai.image("gpt-image-2"),
224
+ prompt: "A robot tending a rooftop garden",
225
+ aspect: "1:1",
226
+ resolution: "1K",
227
+ providerOptions: { quality: "high" }, // typed per image model
228
+ })
229
+ yield* Media.write(response.images[0], "./garden.png")
230
+ })
231
+
232
+ // `Media.file` / `Media.write` use the Effect `FileSystem` service; provide your platform's layer.
233
+ await Effect.runPromise(image.pipe(Effect.provide(AIClient.layer), Effect.provide(NodeFileSystem.layer)))
234
+ ```
235
+
236
+ Advanced: each client also has its own `layer`, which requires `RequestExecutor.Service`. Compose client layers with
237
+ `Layer.provideMerge`, not `Layer.provide`: `asset.bytes()`, `Media.write`, and Gemini's `media` output parts need the
238
+ executor too, and hiding it fails type-checking with `RequestExecutorService` left in the requirements.
239
+
240
+ To share a policy such as logging across every client, wrap the executor once with `RequestExecutor.middleware`:
241
+
242
+ ```ts
243
+ import { RequestExecutor } from "@zyro-sec/ai/route"
244
+
245
+ const logged = RequestExecutor.middleware((request, next) =>
246
+ Effect.log(`${request.method} ${request.url}`).pipe(Effect.andThen(next(request))),
247
+ )
248
+
249
+ const everything = AIClient.layerWith(logged) // or AI.make({ layer: logged })
250
+ ```
251
+
252
+ To hook only some calls, such as adding a per-user header, scope middleware to them. It runs on every provider request
253
+ they make, whatever the modality: submits, polls, results and cancels. Executor-wide middleware wraps it.
254
+
255
+ ```ts
256
+ const signed: HttpMiddleware = (request, next) => next(HttpClientRequest.setHeader(request, "x-user", "user-1"))
257
+
258
+ // Effect: an Effect or a Stream
259
+ const video =
260
+ yield *
261
+ Effect.gen(function* () {
262
+ const job = yield* ai.video.start({ model, prompt: "A red balloon floats up" })
263
+ return yield* ai.video.result(model, job.id)
264
+ }).pipe(RequestExecutor.withMiddleware(signed))
265
+
266
+ // Promise: `http` on any call's options; a handle it returns keeps it
267
+ await AI.ai.video.start({ model, prompt: "A red balloon floats up" }, { http: signed })
268
+ ```
269
+
270
+ Downloading a `url` asset never uses the caller's scoped middleware, so hooks that add credentials can't reach another
271
+ host such as a CDN or a presigned storage URL. A result URL on the provider's own origin carries the middleware of the
272
+ call that returned it (`asset.middleware`), so it downloads the same way later. Set `middleware` yourself with
273
+ `Media.url(url, { middleware })`.
274
+
275
+ ## Venice AI
276
+
277
+ `Venice` provides native Chat Completions with streaming tools and reasoning. `model` and `chat`
278
+ select the same API, and `responses` selects its Responses API; credentials default to `VENICE_API_KEY`.
279
+
280
+ ```ts
281
+ import { ai } from "@zyro-sec/ai/effect"
282
+ import { Venice } from "@zyro-sec/ai/providers"
283
+ import { Effect } from "effect"
284
+
285
+ const program = Effect.gen(function* () {
286
+ const response = yield* ai.generate({
287
+ model: Venice.configure({ apiKey: process.env.VENICE_API_KEY }).chat("qwen3-6-27b"),
288
+ prompt: "Explain this design.",
289
+ providerOptions: {
290
+ reasoningEffort: "high",
291
+ veniceParameters: { includeVeniceSystemPrompt: false },
292
+ },
293
+ })
294
+ console.log(response.text)
295
+ })
296
+ ```
297
+
298
+ Effort lowers to `reasoning.effort`; `reasoning.enabled` and `reasoning.summary` are also available.
299
+ Supported effort levels and toggles depend on the selected model. Omitted controls preserve its defaults.
300
+ Venice's added system prompt is disabled by default, matching the previous OpenCode Venice SDK behavior.
301
+
302
+ Replay complete `response.message` values to retain signed/encrypted reasoning and Gemini thought
303
+ signatures, including per-tool signatures. Venice's encrypted scalar trailers are excluded from visible
304
+ reasoning but retained in provider metadata for replay. Cache affinity uses `promptCacheKey`, and cache-write
305
+ usage reads Venice's `cache_creation_input_tokens` field.
306
+
307
+ The native package entrypoints are `@zyro-sec/ai/providers/venice` and `@zyro-sec/ai/providers/venice/responses`.
308
+ Image generation, embeddings, and client-side E2EE are not implemented by this provider.
309
+
310
+ ## Decisions
311
+
312
+ Decision models answer typed questions about an input: a yes/no `predicate` (a probability), a `choice` from listed
313
+ values, or a `score` on ordered levels, each with the probability of every option.
314
+
315
+ ```ts
316
+ import { Effect } from "effect"
317
+ import { ai, DecisionClient, Media } from "@zyro-sec/ai/effect"
318
+ import { OpenAI } from "@zyro-sec/ai/providers"
319
+
320
+ const program = ai.decision.generate({
321
+ model: OpenAI.configure().decision("gpt-6-luna"),
322
+ input: [
323
+ { type: "text", text: "I was charged twice. Please refund the duplicate payment." },
324
+ { type: "media", media: Media.url("https://example.com/receipt.png", { mediaType: "image/png" }) },
325
+ ],
326
+ questions: [
327
+ { name: "refund", type: "predicate", instructions: "Is the customer asking for a refund?" },
328
+ {
329
+ name: "department",
330
+ type: "choice",
331
+ instructions: "Which team should handle this?",
332
+ choices: [{ value: "billing", description: "Payments and refunds" }, { value: "technical" }],
333
+ },
334
+ {
335
+ name: "urgency",
336
+ type: "score",
337
+ instructions: "How urgent is this?",
338
+ levels: [{ label: "Can wait" }, { label: "Needs prompt attention" }, { label: "Blocking revenue" }],
339
+ },
340
+ ],
341
+ })
342
+
343
+ const response = await Effect.runPromise(program.pipe(Effect.provide(DecisionClient.fetchLayer)))
344
+ const [refund, department] = response.answers
345
+ ```
346
+
347
+ `input` is a JSON object or an ordered list of `text`, `json` and `media` parts. Answers come back in question order.
348
+ A `predicate` can say what counts as true and as false with `criteria: { true, false }`; hosts without a criteria field
349
+ read them appended to the instructions.
350
+ A question the host declines is `{ name, type: "error", reason, message? }`, with `reason` such as `"refusal"`; the
351
+ other answers still come back.
352
+ `response.usage` has `inputTokens`, `outputTokens`, `totalTokens` and the host's reported `cost` when it sends one;
353
+ the host's raw usage stays in `providerMetadata`.
354
+ Media goes wherever the host reads it, and a kind the host has no place for fails the call. Host-specific fields go in
355
+ `providerOptions`, typed by the selected model (OpenAI `promptCacheKey` and `safetyIdentifier`, OpenRouter
356
+ `provider` routing, Baseten `max_len`).
357
+
358
+ ```ts
359
+ import {
360
+ Baseten,
361
+ CloudflareAIGateway,
362
+ CloudflareWorkersAI,
363
+ DigitalOcean,
364
+ OpenCode,
365
+ OpenRouter,
366
+ TypeSafeAI,
367
+ VercelAIGateway,
368
+ } from "@zyro-sec/ai/providers"
369
+
370
+ TypeSafeAI.configure().decision("jev-latest")
371
+ OpenCode.configure().decision("jev-1.13")
372
+ OpenRouter.configure().decision("typesafe/jev-1.13")
373
+ VercelAIGateway.configure().decision("typesafe-ai/jev")
374
+ Baseten.configure().decision("decision-models/baseten-elephant-9b-latest")
375
+ DigitalOcean.configure().decision("typesafe-jev-1.13.0")
376
+ CloudflareWorkersAI.configure({ accountId }).decision("@cf/cloudflare/clef")
377
+ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev")
378
+ ```
379
+
380
+ OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and
381
+ DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`.
382
+
383
+ ## Embeddings
384
+
385
+ Embedding models turn each value into a vector, returned in value order.
386
+
387
+ ```ts
388
+ import { ai } from "@zyro-sec/ai"
389
+ import { OpenAI } from "@zyro-sec/ai/providers"
390
+
391
+ const response = await ai.embedding.generate({
392
+ model: OpenAI.configure().embedding("text-embedding-3-small"),
393
+ values: ["I was charged twice.", "How do I reset my password?"],
394
+ dimensions: 256,
395
+ inputType: "document",
396
+ })
397
+ const [charge, password] = response.embeddings
398
+ ```
399
+
400
+ A string value is text; media values are an `Asset` (or bytes or a URL) for hosts that embed images or documents.
401
+ `dimensions` asks models that can shorten their vectors for that length. `inputType` says whether the values are
402
+ search queries or stored documents; hosts with no such field (OpenAI's `/embeddings` API) ignore it, and host-specific
403
+ task types go in `providerOptions` (NVIDIA's `input_type: "passage"`). `response.usage.inputTokens` is the host's
404
+ token count, and its raw usage stays in `providerMetadata`. Media values fail the call on hosts that only embed text.
405
+
406
+ ```ts
407
+ import {
408
+ Alibaba,
409
+ Azure,
410
+ Cohere,
411
+ DeepInfra,
412
+ DigitalOcean,
413
+ Fireworks,
414
+ OpenAICompatible,
415
+ OpenRouter,
416
+ VercelAIGateway,
417
+ } from "@zyro-sec/ai/providers"
418
+
419
+ OpenRouter.configure().embedding("openai/text-embedding-3-small")
420
+ VercelAIGateway.configure().embedding("openai/text-embedding-3-small")
421
+ Cohere.configure().embedding("embed-v4.0")
422
+ DeepInfra.configure().embedding("BAAI/bge-m3")
423
+ Fireworks.configure().embedding("nomic-ai/nomic-embed-text-v1.5")
424
+ DigitalOcean.configure().embedding("bge-m3")
425
+ Alibaba.configure({ region: "ap-southeast-1" }).embedding("text-embedding-v4")
426
+ Azure.configure({ resourceName }).embedding("text-embedding-3-small")
427
+ OpenAICompatible.configure({ provider: "nvidia", baseURL: "https://integrate.api.nvidia.com/v1" }).embedding(
428
+ "nvidia/nemotron-3.5-embed-1b",
429
+ )
430
+ ```
431
+
432
+ Every host here uses OpenAI's `/embeddings` API; Cohere through its compatibility API
433
+ (`https://api.cohere.ai/compatibility/v1`). Package entry points are `@zyro-sec/ai/providers/<provider>/embeddings`.
434
+
435
+ Google embeds through `embedContent`, which also takes images, audio, video and PDFs on `gemini-embedding-2`. Each
436
+ value is its own content and gets its own vector (several parts in one content would be averaged into one). `dimensions`
437
+ is `outputDimensionality`, `inputType` becomes `taskType` `RETRIEVAL_QUERY` or `RETRIEVAL_DOCUMENT`, and `taskType` or
438
+ `title` in `providerOptions` replace or add to it. `gemini-embedding-2` ignores task types; Google recommends writing the
439
+ task into the text instead (`task: search result | query: …`, `title: none | text: …`).
440
+
441
+ ```ts
442
+ import { Google, GoogleVertex } from "@zyro-sec/ai/providers"
443
+
444
+ const response = await ai.embedding.generate({
445
+ model: Google.configure().embedding("gemini-embedding-2"),
446
+ values: [await ai.file("./receipt.png"), "A receipt for two coffees."],
447
+ dimensions: 768,
448
+ })
449
+
450
+ GoogleVertex.configure({ project, location: "global" }).embedding("gemini-embedding-2")
451
+ ```
452
+
453
+ `GoogleVertex.configure().embedding(id)` picks the API from the model id: `gemini-embedding-2*` uses `embedContent`,
454
+ and every other model (`gemini-embedding-001`, `text-embedding-005`, `text-multilingual-embedding-002`) uses the
455
+ text-only `:predict` API, which also works with Express Mode keys. On `:predict`, `inputType` and the `taskType` and
456
+ `title` options go on each instance (`task_type`, `title`), and `dimensions`, `autoTruncate` and other options go under
457
+ `parameters`.
458
+
459
+ ```ts
460
+ GoogleVertex.configure({ apiKey }).embedding("text-embedding-005")
461
+ GoogleVertex.configure({ apiKey }).embedding("gemini-embedding-001")
462
+ ```
463
+
464
+ The Gemini API sends up to 100 values per `batchEmbedContents` request, and Vertex `:predict` up to 250 per request
465
+ (one for `gemini-embedding-001`, as Google documents). Vertex `embedContent` takes one value per request, so a call
466
+ sends one request per value, four at a time, and needs project credentials: Vertex Express Mode API keys can't call
467
+ `embedContent`. `gemini-embedding-2` runs in the `global`, `us` and `eu` Vertex locations. When a call
468
+ is split into several requests, the vectors stay in value order, `usage.inputTokens` is their sum, and each request's
469
+ metadata is listed in order under `providerMetadata.<provider>.responses`. The package entry points are
470
+ `@zyro-sec/ai/providers/google/embeddings` and `@zyro-sec/ai/providers/google-vertex/embeddings`.
471
+
472
+ ## Alibaba Cloud Model Studio
473
+
474
+ `Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select
475
+ Chat Completions (`.model` or `.chat`), Anthropic-compatible Messages (`.messages`), or OpenAI-compatible
476
+ Responses (`.responses`). These routes use HTTP/SSE.
477
+
478
+ ```ts
479
+ import { ai } from "@zyro-sec/ai/effect"
480
+ import { Alibaba } from "@zyro-sec/ai/providers"
481
+
482
+ const alibaba = Alibaba.configure({
483
+ region: "ap-southeast-1", // Singapore
484
+ apiKey: process.env.DASHSCOPE_API_KEY,
485
+ // workspaceID: "llm-your-workspace", // use a workspace-dedicated endpoint
486
+ })
487
+
488
+ const request = ai.request({
489
+ model: alibaba.model("qwen3.8-max"),
490
+ prompt: "Explain this design.",
491
+ providerOptions: { reasoningEffort: "medium" },
492
+ })
493
+ ```
494
+
495
+ ### Regions and credentials
496
+
497
+ | Region | `region` | Shared host when `workspaceID` is omitted |
498
+ | ------------------- | ---------------- | ----------------------------------------- |
499
+ | Singapore | `ap-southeast-1` | `dashscope-intl.aliyuncs.com` |
500
+ | China (Beijing) | `cn-beijing` | `dashscope.aliyuncs.com` |
501
+ | China (Hong Kong) | `cn-hongkong` | `cn-hongkong.dashscope.aliyuncs.com` |
502
+ | US (Virginia) | `us-east-1` | `dashscope-us.aliyuncs.com` |
503
+ | Germany (Frankfurt) | `eu-central-1` | Supply `workspaceID` or `baseURL` |
504
+ | Japan (Tokyo) | `ap-northeast-1` | Supply `workspaceID` or `baseURL` |
505
+
506
+ With `workspaceID`, the host is `{workspaceID}.{region}.maas.aliyuncs.com`. A complete `baseURL`
507
+ overrides regional setup, including the API prefix: `/compatible-mode/v1` for Chat/Responses,
508
+ or `/apps/anthropic/v1` for Messages. The selector appends its operation path.
509
+
510
+ Keys and model availability are region-specific. Auth resolves from explicit `auth` or `apiKey`,
511
+ then `DASHSCOPE_API_KEY`, then `ALIBABA_API_KEY`.
512
+
513
+ The access region and inference scope differ: Virginia's `-us` model IDs request US-only inference;
514
+ some regions select scope through their workspace. Model IDs pass through unchanged.
515
+ Alibaba's [regional guide](https://www.alibabacloud.com/help/en/model-studio/regions) and
516
+ [base URL table](https://www.alibabacloud.com/help/en/model-studio/base-url) disagree about Virginia's
517
+ shared host; the entry above follows the base URL table. Dedicated hosts can be copied from the console.
518
+
519
+ ### Native options
520
+
521
+ - **Chat:** `reasoningEffort` → `reasoning_effort`, `enableThinking` → `enable_thinking`,
522
+ `thinkingBudget` → `thinking_budget`, and `preserveThinking` → `preserve_thinking`.
523
+ Replay complete `response.message` values to retain `reasoning_content` separately from answer text.
524
+ Qwen 3.8 defaults to preserving thinking; older models have different defaults.
525
+ Additional options include `toolStream`, `parallelToolCalls`, `repetitionPenalty`, `responseFormat`,
526
+ `enableSearch`, and native `searchOptions`. `topK` lowers to `top_k`.
527
+ `clearThinking` is a hosted GLM control, and `thinking.type` is available for hosted MiniMax models.
528
+ - **Messages:** `effort` → `output_config.effort`. `thinking.type` accepts enabled/disabled with an
529
+ optional `budgetTokens` (or native `budget_tokens`). `outputConfig.format` accepts a JSON schema.
530
+ Model Studio's empty thinking signatures are accepted; supplied signatures are replayed unchanged.
531
+ - **Responses:** `reasoningEffort` → `reasoning.effort`, plus `enableThinking`, `store`,
532
+ `previousResponseId`, and `conversation`. Omitted `store` retains the API's default (`true`);
533
+ set it to `false` for client-managed history. `previousResponseId` requires a stored response.
534
+ Hosted tools are `Alibaba.webSearch()`, `Alibaba.webExtractor()`, and `Alibaba.codeInterpreter()`.
535
+ Web extraction is used together with web search. Hosted calls/results carry `providerExecuted: true`.
536
+
537
+ Omitted options preserve provider defaults. Effort values pass through unchanged and accept future
538
+ strings. Qwen 3.8 Chat rejects requests combining a thinking budget with effort.
539
+
540
+ Package entrypoints are `@zyro-sec/ai/providers/alibaba`, `alibaba/chat`, `alibaba/messages`,
541
+ and `alibaba/responses`. Live recordings cover all three APIs in Singapore; regional URL construction
542
+ is unit-tested for all six regions.
543
+
544
+ ### Images
545
+
546
+ `alibaba.image(...)` uses the native multimodal generation API (`/api/v1/services/aigc/multimodal-generation/generation`)
547
+ for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `aspect` and
548
+ `resolution` lower to a `W*H` size, `providerOptions.size` sets it exactly, and `images` are sent as URLs or data URLs
549
+ for editing. Native `parameters` include `size`, `seed`, `negativePrompt`, `promptExtend`, `watermark`, `thinkingMode`,
550
+ and `enableSequential`; raw keys such as `bbox_list` pass through. Results are URLs that Model Studio keeps for 24
551
+ hours. A complete `baseURL` for images includes `/api/v1`.
552
+
553
+ ## Z.AI
554
+
555
+ `ZAI` uses the standard API. Chat Completions is the default language-model API;
556
+ the existing `.image(...)` selector provides image generation.
557
+
558
+ ```ts
559
+ import { ai } from "@zyro-sec/ai/effect"
560
+ import { ZAI, ZAICodingPlan } from "@zyro-sec/ai/providers"
561
+
562
+ const zai = ZAI.configure({ apiKey: process.env.ZAI_API_KEY })
563
+ const request = ai.request({
564
+ model: zai.model("glm-5.3"), // also zai.chat("glm-5.3")
565
+ prompt: "Explain this design.",
566
+ providerOptions: {
567
+ reasoningEffort: "high",
568
+ thinking: { type: "enabled", clear_thinking: false },
569
+ },
570
+ })
571
+
572
+ const coding = ZAICodingPlan.configure({ apiKey: process.env.ZAI_API_KEY })
573
+ const messages = ai.request({
574
+ model: coding.messages("glm-5.3"),
575
+ prompt: "Explain this design.",
576
+ providerOptions: { effort: "high" },
577
+ })
578
+ ```
579
+
580
+ The products have distinct provider identities and endpoints:
581
+
582
+ | Provider | Selector | Default base URL |
583
+ | ----------------------------------- | --------------------------- | ------------------------------------- |
584
+ | `ZAI` (`zai`) | `.model`, `.chat`, `.image` | `https://api.z.ai/api/paas/v4` |
585
+ | `ZAICodingPlan` (`zai-coding-plan`) | `.model`, `.chat` | `https://api.z.ai/api/coding/paas/v4` |
586
+ | `ZAICodingPlan` | `.messages` | `https://api.z.ai/api/anthropic/v1` |
587
+ | `ZAICodingPlan` | `.responses` | `https://api.z.ai/api/v1` |
588
+
589
+ Both read `ZAI_API_KEY` when `apiKey` is omitted and support an explicit `auth` override.
590
+ Coding Plan requires an active subscription. `baseURL` overrides the selected API's
591
+ complete base, including its version prefix. Language-model routes use HTTP/SSE.
592
+
593
+ Options retain the selected API's native semantics:
594
+
595
+ - Chat `reasoningEffort` lowers to `reasoning_effort`; Responses lowers it to `reasoning.effort`.
596
+ Messages `effort` lowers to `output_config.effort`. Omission preserves provider defaults.
597
+ - Chat `thinking` passes `type` and `clear_thinking` through unchanged. Set
598
+ `clear_thinking: false` and replay complete `response.message` values to preserve reasoning
599
+ across user messages and tool loops. The standard API defaults to clearing historical thinking;
600
+ Coding Plan documents preservation by default.
601
+ - Messages accepts `thinking: { type: "enabled" | "adaptive" | "disabled" }` without requiring
602
+ an Anthropic token budget. Coding Plan documents a disabled toggle as low-effort thinking
603
+ for GLM-5.3, with explicit effort taking precedence.
604
+ - Chat also offers `toolStream`, `doSample`, `responseFormat`, `requestID`, and `userID`.
605
+ Tool-argument streaming is enabled when tools are present on GLM-4.6/4.7/5.x;
606
+ `toolStream: false` explicitly disables it. Older model families omit the opt-in.
607
+ - Effort and thinking values remain forward-compatible strings. Their meaning is model-specific:
608
+ GLM-5.3 accepts `low`, `high`, and `max` effort and rejects disabled thinking with HTTP 400;
609
+ the direct GLM-5.2 recordings returned reasoning even with `none` and `minimal` effort,
610
+ whereas explicit `thinking.type: "disabled"` disabled it on GLM-5.2 and GLM-4.7.
611
+
612
+ Standard API recordings cover GLM-5.3 efforts and a full preserved-reasoning tool loop with
613
+ a subsequent user follow-up, GLM-5.2 efforts, older-model thinking toggles, GLM-4.5 tool calls,
614
+ GLM-5.3-Flash image input, and JSON output. Coding Plan has unit coverage for routing,
615
+ request options, and reasoning replay; successful live recordings are pending.
616
+
617
+ Package entrypoints are `@zyro-sec/ai/providers/zai`, `zai/chat`, `zai-coding-plan`,
618
+ `zai-coding-plan/chat`, `zai-coding-plan/messages`, and `zai-coding-plan/responses`.
619
+
620
+ ## Moonshot
621
+
622
+ Moonshot defaults to Chat Completions, with Messages and Responses selectors for Kimi K3:
623
+
624
+ ```ts
625
+ import { ai } from "@zyro-sec/ai/effect"
626
+ import { Moonshot } from "@zyro-sec/ai/providers"
627
+
628
+ const moonshot = Moonshot.configure({ apiKey: process.env.MOONSHOT_API_KEY })
629
+
630
+ const request = ai.request({
631
+ model: moonshot.model("kimi-k3"), // also moonshot.chat("kimi-k3")
632
+ prompt: "Explain the tradeoffs in this design.",
633
+ providerOptions: { reasoningEffort: "high" },
634
+ })
635
+
636
+ const messages = ai.request({
637
+ model: moonshot.messages("kimi-k3"),
638
+ prompt: "Explain the tradeoffs in this design.",
639
+ providerOptions: { effort: "high" },
640
+ })
641
+
642
+ const responses = ai.request({
643
+ model: moonshot.responses("kimi-k3"),
644
+ prompt: "Explain the tradeoffs in this design.",
645
+ providerOptions: { reasoningEffort: "high" },
646
+ })
647
+ ```
648
+
649
+ When `apiKey` is omitted, authentication reads `MOONSHOT_API_KEY`, then `MOONSHOTAI_API_KEY`.
650
+ Chat and Responses use `https://api.moonshot.ai/v1`; Messages uses
651
+ `https://api.moonshot.ai/anthropic/v1`. `baseURL` overrides the selected API's complete base,
652
+ including the version prefix, for regional endpoints or gateways. Each endpoint requires its own valid credentials.
653
+ All three routes use HTTP/SSE.
654
+
655
+ Reasoning options stay native to the selected API and model:
656
+
657
+ | Model/API | Provider options |
658
+ | --------------------------- | --------------------------------------------------------------------------------------- |
659
+ | K3 Chat / Responses | `reasoningEffort: "low" \| "high" \| "max"`; default is `max` |
660
+ | K3 Messages | `effort: "low" \| "high" \| "max"`; default is `max` |
661
+ | K2.6 Chat | `thinking: { type: "enabled" \| "disabled", keep?: "all" \| null }`; default is enabled |
662
+ | K2.7 Code / high-speed Chat | Omit `thinking` to use always-on, preserved reasoning |
663
+
664
+ Omitting options preserves the model's defaults. K3 uses effort rather than the K2.x `thinking`
665
+ parameter. Known effort values have autocomplete while future strings remain accepted.
666
+ For K2.6, `thinking.keep: "all"` enables preservation of reasoning across user messages.
667
+ K3 and both K2.7 Code variants always preserve reasoning. Continue with the returned
668
+ `response.message` and matching tool results so reasoning content and any Messages signatures are retained.
669
+ Leave sampling options such as `temperature` unset to use these models' fixed defaults.
670
+
671
+ The recorded suite covers all three K3 APIs, default and explicit efforts, K2.6 thinking modes,
672
+ both K2.7 Code variants, generated tool loops with a subsequent user follow-up, required/disabled
673
+ tool choice, image-byte input, and native structured output through `http.body` overlays.
674
+ K3 Chat and Messages accept required and disabled tool choice. Responses supports automatic tool
675
+ choice only; explicit `required` and `none` produce a provider `InvalidRequest` error, also covered by recordings.
676
+ The provider targets the Moonshot Open Platform; Kimi Code is a separate product and endpoint.
677
+
678
+ Package entrypoints are `@zyro-sec/ai/providers/moonshot`, `moonshot/chat`, `moonshot/messages`,
679
+ and `moonshot/responses`; each exports `model(modelID, settings)`.
680
+
681
+ ## MiniMax
682
+
683
+ MiniMax defaults to its Messages API and reads `MINIMAX_API_KEY` when `apiKey` is omitted:
684
+
685
+ ```ts
686
+ import { Effect } from "effect"
687
+ import { ai, AIClient } from "@zyro-sec/ai/effect"
688
+ import { MiniMax } from "@zyro-sec/ai/providers"
689
+
690
+ const minimax = MiniMax.configure({ apiKey: process.env.MINIMAX_API_KEY })
691
+ const request = ai.request({
692
+ model: minimax.model("MiniMax-M3"), // also minimax.messages("MiniMax-M3")
693
+ prompt: "What is 173 multiplied by 219?",
694
+ providerOptions: { thinking: { type: "adaptive" } },
695
+ maxTokens: 1536,
696
+ })
697
+
698
+ const response = await Effect.runPromise(ai.generate(request).pipe(Effect.provide(AIClient.layer)))
699
+ console.log(response.text)
700
+ ```
701
+
702
+ Select `minimax.chat("MiniMax-M3")` or `minimax.responses("MiniMax-M3")` for MiniMax's native Chat Completions
703
+ and Responses APIs. The matching package entrypoints are `@zyro-sec/ai/providers/minimax/messages`,
704
+ `@zyro-sec/ai/providers/minimax/chat`, and `@zyro-sec/ai/providers/minimax/responses`.
705
+
706
+ - **Messages:** M3 thinking defaults off. Set `thinking: { type: "adaptive" }` to enable it or
707
+ `thinking: { type: "disabled" }` to disable it.
708
+ - **Chat:** M3 thinking defaults on and uses the same `thinking` control. The provider enables `reasoning_split`
709
+ by default so reasoning is separate from answer text; `reasoningSplit: false` selects native `<think>`-tagged text.
710
+ - **Responses:** M3 reasoning defaults off. `reasoningEffort: "none"` disables it; `"minimal"`, `"low"`,
711
+ `"medium"`, and `"high"` enable reasoning without changing its depth.
712
+
713
+ M2.x models always think, even when a disabling option is supplied. For tool continuations, retain the complete
714
+ `response.message` in history before adding `Message.tool(...)` results; this preserves reasoning and any signatures.
715
+
716
+ The default API bases are `https://api.minimax.io/anthropic/v1` for Messages and `https://api.minimax.io/v1` for
717
+ Chat, Responses and Images. `configure({ baseURL })` replaces the selected API's base, including its version prefix;
718
+ use `https://api.minimax.cn/v1` for the mainland China platform. `minimax.image("image-01")` (also
719
+ `@zyro-sec/ai/providers/minimax/images`) generates images; see [MiniMax images](#minimax-images).
720
+
721
+ ## Meta
722
+
723
+ Use Meta's direct [Model API](https://dev.meta.ai/docs/overview) with `META_API_KEY`:
724
+
725
+ ```ts
726
+ import { Meta } from "@zyro-sec/ai/providers"
727
+
728
+ const meta = Meta.configure() // or Meta.configure({ apiKey })
729
+ const request = ai.request({
730
+ model: meta.responses("muse-spark-1.3"), // meta.model(...) also selects Responses
731
+ prompt: "What is 173 multiplied by 219? Reply with the integer.",
732
+ providerOptions: { reasoningEffort: "low" },
733
+ maxTokens: 1024,
734
+ })
735
+ ```
736
+
737
+ `meta.chat("muse-spark-1.3")` selects Chat Completions; `meta.messages("muse-spark-1.3")` selects
738
+ the Anthropic-compatible Messages API. All use `https://api.meta.ai/v1`. The package entrypoints
739
+ `@zyro-sec/ai/providers/meta/responses`, `meta/chat`, and `meta/messages` expose `model(modelID, settings)`.
740
+
741
+ [Muse Spark](https://dev.meta.ai/docs/models) supports `minimal`, `low`, `medium`, `high`, and
742
+ `xhigh` reasoning effort; standard-tier 1.3 also supports `max`. Omitting effort uses the model's
743
+ default. Muse Spark always reasons and rejects `none`. The output-token budget includes private reasoning.
744
+
745
+ Responses defaults to `store: false` and `include: ["reasoning.encrypted_content"]`. Preserve
746
+ `response.message` along with matching `Message.tool(...)` results in subsequent requests to replay
747
+ reasoning through tool loops. Optional `reasoningSummary: "auto"` requests a readable summary.
748
+ For server-managed history, override `store: true, include: []` and send the response ID through
749
+ `http: { body: { previous_response_id: responseID } }` with only the new input.
750
+ Chat Completions redacts private reasoning and cannot carry it between calls.
751
+ Responses and Chat support only `toolChoice: "auto"` (the default). Messages also accepts `"none"`;
752
+ its documented forced `"any"` choice currently returns HTTP 400. Messages defaults to adaptive thinking
753
+ with `display: "omitted"`, preserving encrypted `redacted_thinking` in `response.message`. Use
754
+ `providerOptions: { effort: "low" }` for depth or `thinking: { type: "enabled", budgetTokens: 1024 }`
755
+ for budget compatibility (with `maxTokens > 1024`).
756
+
757
+ Add `tools: [Meta.webSearch()]` to a Spark Responses or Messages request for hosted web search.
758
+ Responses exposes hosted results and URL citations in text-part `providerMetadata.meta.annotations`.
759
+ To include search result lists, set `include: ["reasoning.encrypted_content", "web_search_call.results"]`.
760
+ Messages exposes hosted search calls; the recorded Messages API stream does not supply structured
761
+ citations or separate result blocks. Retain `response.message` for either API's continuation.
762
+
763
+ Use `ai.image.generate` for one-off generation or editing:
764
+
765
+ ```ts
766
+ import { ai, Media } from "@zyro-sec/ai/effect"
767
+
768
+ const generation = ai.image.generate({
769
+ model: meta.image("muse-image-1.0"),
770
+ prompt: "A flat black square on a white background.",
771
+ n: 1,
772
+ providerOptions: { reasoningStrength: "low" },
773
+ })
774
+
775
+ const edit = ai.image.generate({
776
+ model: meta.image("muse-image-1.0"),
777
+ prompt: "Make the square purple.",
778
+ images: [Media.bytes(imageBytes, "image/webp")],
779
+ providerOptions: { reasoningStrength: "low", outputFormat: "png" },
780
+ })
781
+ ```
782
+
783
+ The default image format is WEBP; `outputFormat` also accepts PNG/JPEG and `responseFormat: "url"`
784
+ returns a signed URL. `aspect` lowers to Meta's `size`, which is only an aspect-ratio hint: Meta renders about 2.5
785
+ megapixels whatever you ask, so `resolution` is ignored. For conversational images, select
786
+ `meta.responses("muse-image-1.0")` with `tools: [Meta.imageGeneration({ reasoningStrength: "low" })]`.
787
+ Generated images are provider-executed tool results with file content. Retain `response.message` to
788
+ replay the signed image handle on the next request. Muse Image accepts only the `image_generation` tool.
789
+
790
+ Meta Responses is explicitly HTTP/SSE-only and does not use WebSockets, even when a caller supplies
791
+ `StreamOptions.webSocket`. The public `/v1/responses` endpoint rejects WebSocket upgrades with HTTP 405 (`Allow: POST`).
792
+
793
+ ## Image generation
794
+
795
+ Use `ai.image.generate` with an image model for direct asset generation. `ai.image.request` mirrors `ai.request`: the
796
+ model comes from the facade's `.image(...)` selector (mirroring `.responses(...)`), common fields
797
+ (`images`, `n`, `aspect`, `resolution`) lower natively or fail typed, and `providerOptions` is inferred from the
798
+ selected model. `aspect` is a ratio such as `"16:9"`; `resolution` is a size tier (`"1K"` is about 1024×1024 pixels
799
+ at that ratio, `"2K"` about 2048×2048). Exact sizes, seeds, masks, and output formats are provider options:
800
+
801
+ ```ts
802
+ import { ai, Media } from "@zyro-sec/ai/effect"
803
+ import { OpenAI } from "@zyro-sec/ai/providers"
804
+
805
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
806
+
807
+ const program = Effect.gen(function* () {
808
+ const response = yield* ai.image.generate({
809
+ model: openai.image("gpt-image-2"),
810
+ prompt: "A robot tending a rooftop garden",
811
+ n: 2,
812
+ aspect: "16:9",
813
+ resolution: "2K",
814
+ providerOptions: {
815
+ outputFormat: "webp",
816
+ quality: "high", // inferred from the OpenAI image model
817
+ future_option: true, // unknown native options pass through unchanged
818
+ },
819
+ })
820
+
821
+ return response.images // Media.Asset[] with owned bytes or a provider URL
822
+ })
823
+ ```
824
+
825
+ Common fields are portable in shape, not in support. Some routes approximate `aspect` or `resolution` with the nearest
826
+ size they offer; others fail with a typed `AIError` before any network call rather than dropping them, so check this
827
+ table before swapping only the `model`:
828
+
829
+ | Provider | `n` | `aspect` | `resolution` | `images` | Moved to `providerOptions` |
830
+ | --------------------- | --- | ------------------ | ------------------- | -------------------- | ----------------------------------------- |
831
+ | OpenAI | ✓¹ | nearest size | nearest size | ✓ | `size`, `outputFormat`, `mask` |
832
+ | Google (Gemini) | 1 | ✓ | ✓ (`0.5K` as `512`) | ✓ (no public URLs) | `seed` |
833
+ | xAI | ✓ | ✓ | `1k`/`2k` | ✓ | none |
834
+ | Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
835
+ | Z.ai | ✗ | width × height | width × height | ✗ | `size` |
836
+ | Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
837
+ | MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
838
+ | Vercel AI Gateway | ✓ | as OpenAI³ | as OpenAI³ | per model | as OpenAI |
839
+ | OpenRouter | ✓ | ✓ (`aspect_ratio`) | tier⁵ | per model⁵ | `size`, `outputFormat` (no `mask`) |
840
+ | Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
841
+
842
+ ✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. "width × height"
843
+ computes a size the provider accepts and fails when the request falls outside its limits. ¹ `ai.image.stream` on OpenAI
844
+ generates one image. On OpenAI, `gpt-image-2` and later get a computed size; older models get the nearest of their
845
+ fixed sizes. `providerOptions.size` replaces `aspect` and `resolution`, so setting both fails. Vercel AI Gateway
846
+ forwards `outputFormat` but does not apply it, so the returned bytes keep the upstream model's own format. ² Workers AI
847
+ `@cf/black-forest-labs/flux-1-schnell` takes no size, and the provider rejects it. ³ Non-OpenAI gateway models
848
+ (`bfl/flux-2-pro`) get a computed width × height, which the gateway passes through; models with a fixed list, such as
849
+ Recraft, reject sizes outside it. Grok (`spacexai/*`, `xai/*`) ignores `size`, so it gets `providerOptions.xai`
850
+ `aspect_ratio` and `1k`/`2k` instead. ⁴ MiniMax sends its `aspect_ratio` preset for a preset aspect at about `1K` and an
851
+ exact width × height (512–2048 px, steps of 8) otherwise; `image-01-live` takes only the presets, minus `21:9`.
852
+ ⁵ OpenRouter takes `512`, `768`, `1K`, `1.5K`, `2K` or `4K` rather than pixels; other values are left out. It has no
853
+ edits endpoint, so input images go to `/images/generations` as `input_references` (data URLs or http(s) URLs).
854
+
855
+ `Media.Asset` is the one asset type shared by image requests, image responses, LLM messages, and tool results.
856
+ `asset.source` is the serializable `Media.Source` (`bytes`, `base64`, `url`, or `ref`); `asset.bytes()`,
857
+ `asset.base64()`, and `asset.dataUrl()` decode or download lazily and cache; `asset.materialize()` pulls a `url`
858
+ asset into owned bytes before the provider URL expires. Construct assets with `Media.bytes`, `Media.base64`,
859
+ `Media.url`, `Media.ref(provider, id)`, `Media.fromDataUrl`, or `Media.file(path)`.
860
+
861
+ File inputs (message `media` parts, image `images`, decision `media` parts) also take plain data: a `Uint8Array`,
862
+ `ArrayBuffer`, `URL`, or a string holding a data URL, an http(s) URL or base64. Bytes and base64 are sniffed from
863
+ magic bytes; pass `mediaType` when that fails:
864
+
865
+ ```ts
866
+ ai.request({
867
+ model,
868
+ prompt: [
869
+ { type: "text", text: "Summarize this report" },
870
+ { type: "media", media: pdfBase64, mediaType: "application/pdf" },
871
+ ],
872
+ })
873
+ ```
874
+
875
+ Pass ordered image inputs to the same method for editing, composition, or image-conditioned generation:
876
+
877
+ ```ts
878
+ const composed = Effect.gen(function* () {
879
+ const response = yield* ai.image.generate({
880
+ model,
881
+ prompt: "Combine these product photos into one studio scene",
882
+ images: [
883
+ Media.bytes(firstBytes, "image/png"),
884
+ Media.url("https://example.com/second.webp"),
885
+ Media.ref("openai", "file_123"),
886
+ ],
887
+ providerOptions,
888
+ http,
889
+ })
890
+ return response.images
891
+ })
892
+ ```
893
+
894
+ `Media.ref(provider, id)` represents provider file handles such as OpenAI file IDs or Gemini Files URIs; routes
895
+ only forward refs that belong to their own provider (OpenAI, xAI, and Gemini images accept them). No shipped route
896
+ returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design. Empty or omitted `images` uses
897
+ text-to-image generation; a
898
+ non-empty array selects the provider's edit behavior (see the table above for routes that limit the count). OpenAI
899
+ uses multipart for byte/data-URL edits and its JSON reference body for URL or file-ID edits. Inpainting is a
900
+ provider option on the routes that support it (OpenAI):
901
+
902
+ ```ts
903
+ const inpainted = ai.image.generate({
904
+ model: openai.image("gpt-image-2"),
905
+ prompt,
906
+ images: [Media.bytes(sourceBytes, "image/png")],
907
+ providerOptions: { mask: Media.bytes(maskBytes, "image/png") },
908
+ })
909
+ ```
910
+
911
+ On multipart requests, `http.body` can override option fields but not structural `model`, `prompt`, `image[]`,
912
+ or `mask` fields, and the transport owns the multipart `Content-Type` boundary. For JSON requests, `http.body`
913
+ remains the final raw-native overlay. Gemini does not fetch public HTTP URLs, and hosted Z.ai image generation does
914
+ not accept image inputs. These cases fail with a typed `AIError` before network I/O.
915
+
916
+ Provider-native image options belong to each request. Raw `http.body` fields have final precedence over them:
917
+
918
+ ```ts
919
+ const medium = ai.image.generate({
920
+ model: openai.image("gpt-image-2"),
921
+ prompt,
922
+ providerOptions: { quality: "medium" },
923
+ http,
924
+ })
925
+ ```
926
+
927
+ xAI image models use the same request API with xAI-native controls:
928
+
929
+ ```ts
930
+ import { XAI } from "@zyro-sec/ai/providers"
931
+
932
+ const xai = ai.image.generate({
933
+ model: XAI.configure({ apiKey }).image("any-model-id"),
934
+ prompt,
935
+ n: 2,
936
+ aspect: "16:9",
937
+ resolution: "1K",
938
+ providerOptions: {
939
+ responseFormat: "url", // defaults to "b64_json" (inline bytes)
940
+ future_option: true,
941
+ },
942
+ http,
943
+ })
944
+ ```
945
+
946
+ Google's current Gemini image models use the same direct API:
947
+
948
+ ```ts
949
+ import { Google } from "@zyro-sec/ai/providers"
950
+
951
+ const googleProgram = Effect.gen(function* () {
952
+ const response = yield* ai.image.generate({
953
+ model: Google.configure({ apiKey }).image("any-model-id"),
954
+ prompt: "A robot tending a rooftop garden",
955
+ aspect: "16:9",
956
+ resolution: "2K",
957
+ providerOptions: {
958
+ seed: 42,
959
+ thinkingLevel: "HIGH",
960
+ includeThoughts: true,
961
+ futureOption: true,
962
+ },
963
+ http,
964
+ })
965
+
966
+ return response.images
967
+ })
968
+ ```
969
+
970
+ Google image options are request-scoped and inferred from the selected model. Known fields autocomplete while
971
+ future string values and arbitrary native Gemini `generationConfig` fields remain available. Native fields override
972
+ their mapped aliases, and `http.body` is the final deep overlay. The selected model ID is sent to Gemini
973
+ `generateContent` without a local allowlist.
974
+
975
+ Z.ai image models infer open Z.ai-native options from the selected model:
976
+
977
+ ```ts
978
+ import { ZAI } from "@zyro-sec/ai/providers"
979
+
980
+ const zai = ai.image.generate({
981
+ model: ZAI.configure({ apiKey }).image("any-model-id"),
982
+ prompt,
983
+ providerOptions: {
984
+ quality: "hd",
985
+ userID: "user-123",
986
+ future_option: true,
987
+ },
988
+ http,
989
+ })
990
+ ```
991
+
992
+ Z.ai does not include trustworthy MIME metadata for output URLs, so generated images use
993
+ `application/octet-stream` until materialized. Output URLs expire after 30 days; call `asset.materialize()` and
994
+ persist the bytes promptly if they must remain available.
995
+
996
+ ### MiniMax images
997
+
998
+ ```ts
999
+ import { MiniMax } from "@zyro-sec/ai/providers"
1000
+
1001
+ const minimax = ai.image.generate({
1002
+ model: MiniMax.configure({ apiKey }).image("image-01"),
1003
+ prompt,
1004
+ n: 2,
1005
+ aspect: "16:9",
1006
+ images: [Media.url("https://example.com/portrait.jpg")], // optional subject reference
1007
+ providerOptions: { promptOptimizer: true, seed: 42 },
1008
+ })
1009
+ ```
1010
+
1011
+ The reference image is sent as a `character` subject, so it should be a single front-facing portrait. Images come
1012
+ back inline (`responseFormat: "base64"` by default); `responseFormat: "url"` returns links that expire after 24 hours
1013
+ and carry no MIME type until materialized. MiniMax status codes map to typed errors; code 1026 is a `ContentPolicy`
1014
+ error.
1015
+
1016
+ ### Partial images
1017
+
1018
+ OpenAI's GPT image models stream previews. `ai.image.stream` sends `stream: true` with `partialImages` (0–3, default 2)
1019
+ and emits `image-partial` events before each final `image`; `ai.image.generate` keeps the plain JSON request:
1020
+
1021
+ ```ts
1022
+ import { Stream } from "effect"
1023
+ import { ImageEvent } from "@zyro-sec/ai/effect"
1024
+
1025
+ const previews = ai.image
1026
+ .stream({
1027
+ model: openai.image("gpt-image-2"),
1028
+ prompt: "A lighthouse at dusk",
1029
+ providerOptions: { partialImages: 2 },
1030
+ })
1031
+ .pipe(Stream.runForEach((event) => (ImageEvent.is.imagePartial(event) ? showPreview(event.image) : Effect.void)))
1032
+ ```
1033
+
1034
+ The provider may send fewer previews than requested when the final image is ready first.
1035
+
1036
+ Imagen is not available: Google shut it down on the Gemini API, and Vertex discontinued the Imagen 4 models on
1037
+ 2026-06-30. `Google.image(...)` uses Gemini-native image models.
1038
+
1039
+ Conversational image generation remains part of the LLM interaction. OpenAI Responses exposes it through its hosted image tool:
1040
+
1041
+ ```ts
1042
+ const program = Effect.gen(function* () {
1043
+ const response = yield* ai.generate(
1044
+ ai.request({
1045
+ model: OpenAI.configure({ apiKey }).responses("gpt-5"),
1046
+ prompt: "Design a solarpunk rooftop garden, then show me.",
1047
+ tools: [OpenAI.imageGeneration({ quality: "high" })],
1048
+ }),
1049
+ )
1050
+
1051
+ return response.message
1052
+ })
1053
+ ```
1054
+
1055
+ The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes.
1056
+
1057
+ ### Image jobs
1058
+
1059
+ `ai.image.generate` and `ai.image.stream` poll a queued image route for you. To manage the job yourself, use the same
1060
+ calls as video: `start` submits it and returns `{ id }` at once, the provider's job ID as a string you can store and
1061
+ read back from another process, and `status`, `result` and `cancel` take the model and that `id`. `status` is one read;
1062
+ `result` fails with an `InvalidRequest` reason while the job is still running; `cancel` fails with an
1063
+ `UnsupportedOperation` reason when the provider has no cancel endpoint. No shipped image route is queued yet, so on
1064
+ every image model today all four fail with an `UnsupportedOperation` reason before sending anything.
1065
+
1066
+ ```ts
1067
+ const program = Effect.gen(function* () {
1068
+ const job = yield* ai.image.start({ model, prompt: "A lighthouse" })
1069
+ const status = yield* ai.image.status(model, job.id) // { status, progress? }
1070
+ if (status.status === "completed") return yield* ai.image.result(model, job.id)
1071
+ })
1072
+ ```
1073
+
1074
+ ## Video generation
1075
+
1076
+ Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
1077
+ fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's
1078
+ `id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart
1079
+ is the same call as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
1080
+ `BytePlus`, `MiniMax` and `Google` facades.
1081
+
1082
+ ```ts
1083
+ import { Effect } from "effect"
1084
+ import { ai, Media } from "@zyro-sec/ai/effect"
1085
+ import { XAI } from "@zyro-sec/ai/providers"
1086
+
1087
+ const model = XAI.configure({ apiKey: process.env.XAI_API_KEY }).video("grok-imagine-video-1.5")
1088
+
1089
+ const program = Effect.gen(function* () {
1090
+ const job = yield* ai.video.start({
1091
+ model,
1092
+ prompt: "Panning wide shot of a calico kitten sleeping in the sunshine",
1093
+ start: "https://example.com/first-frame.png", // exact first frame; `end` pins the last one
1094
+ references: [], // images, videos or audio that guide subject or style
1095
+ duration: "8 seconds",
1096
+ aspect: "16:9", // or "auto" to follow the start image
1097
+ resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
1098
+ sound: false,
1099
+ })
1100
+ job.id // the provider's job ID: store it with the provider and model ID
1101
+
1102
+ const status = yield* ai.video.status(model, job.id)
1103
+ status.status // "running" | "completed" | "error"
1104
+ status.reason // "failed" | "cancelled" | "expired", only when status is "error"
1105
+ status.progress // 0..1, only when the provider reports it
1106
+
1107
+ const response = yield* ai.video.result(model, job.id)
1108
+ yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk
1109
+ })
1110
+ ```
1111
+
1112
+ The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`;
1113
+ everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only
1114
+ fails before sending when its protocol has no way to express it, such as a reference video on xAI. `sound` is the
1115
+ exception: on models whose sound can't be switched (MiniMax H3 and Gemini Omni always have it, Hailuo never does) it
1116
+ isn't sent, and the model's own behavior applies. Values the provider
1117
+ may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
1118
+
1119
+ `start` and `end` are images. They take a URL, data URL, base64 string or bytes, or an asset built with
1120
+ `Media.image(...)`, which rejects assets known to be video, audio or documents; URLs and provider file references
1121
+ whose type isn't stated are sent and checked by the provider. `references` take any kind.
1122
+
1123
+ `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
1124
+ provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
1125
+ outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
1126
+ retry transient failures (rate limits, provider 5xx, network errors) with backoff that honors `retry-after`; `start`
1127
+ and `cancel` never retry. `cancel` fails with an `UnsupportedOperation` reason on providers without a cancel endpoint,
1128
+ such as xAI, where the job keeps running and billing. Finished videos are usually URLs that expire (`expiresAt` when the
1129
+ provider documents it): download them with `Media.write`, `asset.stream()` or `materialize()` before then.
1130
+
1131
+ Provider notes:
1132
+
1133
+ - **xAI** maps `start` to `image`, `end` to `last_frame`, image references to `reference_images`, audio references to
1134
+ `reference_audios`, and `sound` to `generate_audio`, and leaves `aspect: "auto"` out when a start frame sets the
1135
+ shape. It has no reference video input. `providerOptions.mode: "edit" | "extend"` sends a native `video: { url }`
1136
+ source to `/videos/edits` or `/videos/extensions`.
1137
+ - **OpenRouter** (`OpenRouter.configure(...).video("google/veo-3.1")`) maps `start` and `end` to `frame_images`,
1138
+ references to `input_references` by kind (`image_url`, `video_url`, `audio_url`), `sound` to `generate_audio`, and
1139
+ `resolution` to its spelling (`4k` → `4K`), and leaves `aspect: "auto"` out so models that can follow the input image do.
1140
+ Frames and references are both sent; when both are present OpenRouter keeps the frames and drops the references. It
1141
+ rejects reference videos or audio that aren't http(s) URLs (inline images work). Routing and upstream parameters go under `providerOptions.provider` (`only`, `order`,
1142
+ `options: { <slug>: {...} }`), and `providerOptions.previous_job_id` edits or extends a finished job. Results are
1143
+ OpenRouter content URLs that download with the API key, which the asset carries; there is no cancel endpoint.
1144
+ - **Seedance** (`Volcengine.configure(...).video(...)` with `ARK_API_KEY`, `BytePlus.configure(...).video(...)` with
1145
+ `BYTEPLUS_API_KEY`) builds Ark's `content[]`: the prompt as a `text` item, `start` and `end` as `image_url` items
1146
+ with roles `first_frame` and `last_frame`, and references as `reference_image`, `reference_video` or
1147
+ `reference_audio` by kind. Your own `Media.ref(...)` assets go as `asset://<id>`. `duration` goes to `duration`,
1148
+ `aspect` to `ratio` (`auto` becomes `adaptive`), `resolution` to `resolution` and `sound` to `generate_audio`. Ark
1149
+ doesn't allow frames and references in one task; that combination is sent and the provider's error comes back.
1150
+ `providerOptions.draft_task: { id }` adds a `draft_task` item; `frames`, `seed`, `watermark`, `output_format`,
1151
+ `omni_reference_task_type`, `return_last_frame` and the rest go into the body as-is. `cancel` sends `DELETE`, which
1152
+ only cancels a queued task: Ark refuses it for a running one and deletes the record of a finished one. Video URLs
1153
+ expire 24 hours after the task finished.
1154
+ - **MiniMax** (`MiniMax.configure(...).video(id)`, or `@zyro-sec/ai/providers/minimax/videos`) serves two APIs and picks
1155
+ one by model family: Hailuo and `*-01` models use v1, everything else (H3) uses v2. Video builds its `/v1` and `/v2`
1156
+ paths on the API host, so a `baseURL` shared with images or chat (`https://api.minimax.cn/v1`) loses its trailing
1157
+ `/v1`, and a bare host (`https://api.minimax.io`) works as is. On H3, `start`, `end` and `references` become `content[]` items with `first_frame`, `last_frame` and `reference_image` /
1158
+ `reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes
1159
+ `ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a
1160
+ `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound
1161
+ and has no field for it, so `sound` isn't sent. On Hailuo, `start` and `end` map to `first_frame_image` and
1162
+ `last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which
1163
+ expires after one hour. Hailuo is always silent, so `sound` isn't sent; it has no aspect field, so an explicit
1164
+ `aspect` and video or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
1165
+ such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`.
1166
+ - **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no
1167
+ role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video
1168
+ references), and `generation_config.video_config.task` is set to `image_to_video` for frames only or
1169
+ `reference_to_video` for references only; with both, the prompt decides. `duration` becomes
1170
+ `response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution
1171
+ lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the
1172
+ first frame). Omni always generates audio and has no field for it, so `sound` isn't sent. Videos come back as inline bytes. `cancel` posts to
1173
+ `/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id`
1174
+ to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`.
1175
+
1176
+ The promise client has the same calls, each accepting `{ signal }`:
1177
+
1178
+ ```ts
1179
+ import { ai } from "@zyro-sec/ai"
1180
+
1181
+ const job = await ai.video.start({ model, prompt })
1182
+ const status = await ai.video.status(model, job.id)
1183
+ if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).video, "./kite.mp4")
1184
+ ```
1185
+
1186
+ ## Public API
1187
+
1188
+ Everything below is exported from `@zyro-sec/ai/effect` unless noted.
1189
+
1190
+ - **`ai.request({...})`** — build a provider-neutral `LLMRequest`, a plain object. Accepts ergonomic inputs (`system: string`, `prompt: string`) and normalizes them into `system`, `messages` and `tools` arrays. Edit it with a spread, or pass the edited object back to `ai.request`.
1191
+ - **`ai.generate` / `ai.stream`** — run direct input or an `LLMRequest` through `LLMClient` for one-import use.
1192
+ - **`ai.loop`** — stream model calls, running `tool(...)` tools between them until the model stops calling tools.
1193
+ - **`ai.collect`** — fold a stream from `ai.stream` or `ai.loop` into its final result (`text`, `steps`, `messages`, `usage`).
1194
+ - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
1195
+ - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
1196
+ - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
1197
+ - **`ai.image.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. `start`, `status`, `result` and `cancel` address a queued job by the provider's job ID, like video; see [Image jobs](#image-jobs).
1198
+ - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
1199
+ - **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer.
1200
+ - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
1201
+ - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
1202
+ - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
1203
+ - **`ai.embedding.request` / `ai.embedding.generate`** — one vector per text or media value, with optional `dimensions` and `inputType`; `EmbeddingClient` is its Effect service and layer.
1204
+ - **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
1205
+ - **`@zyro-sec/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image`, `decision`, `embedding` and `video` (plus `experimental.speech` and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@zyro-sec/ai/effect` returns `Effect` and `Stream`.
1206
+ - **`@zyro-sec/ai/experimental`** — APIs that may change without compatibility guarantees: `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
1207
+
1208
+ ## Experimental
1209
+
1210
+ These APIs may change without compatibility guarantees. The Effect API is exported from `@zyro-sec/ai/experimental`,
1211
+ and the Promise client exposes it under `ai.experimental`.
1212
+
1213
+ - **`Speech`** and **`Transcription`** — speech generation and speech-to-text, with `SpeechClient` and
1214
+ `TranscriptionClient` as their Effect services. Promise: `ai.experimental.speech` and `.transcription`.
1215
+ - **`Extraction`** — typed values read out of text.
1216
+ - **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
1217
+ a short-lived WebSocket URL and token.
1218
+
1219
+ The provider selectors for these modalities (`.speech(...)`, `.transcription(...)`,
1220
+ `.experimental.extraction(...)`) and their protocol entrypoints (such as `@zyro-sec/ai/protocols/openai-speech`) are
1221
+ part of the same experimental surface.
1222
+
1223
+ ### Speech generation
1224
+
1225
+ Speech (text-to-speech) is one request whose response is parsed incrementally, so every route supports both
1226
+ `Speech.generate` (the whole file) and `Speech.stream` (audio chunks as they arrive). Models come from `.speech(...)`
1227
+ selectors on the `OpenAI`, `Google` (Gemini TTS), `ElevenLabs`, `Cartesia`, and `Deepgram` facades. Common fields
1228
+ (`voice`, `format`, `speed`, `language`, `instructions`, `timestamps`) lower natively or fail with a typed `AIError`
1229
+ before any network call; provider-native controls live under `providerOptions`, inferred from the selected model.
1230
+
1231
+ ```ts
1232
+ import { Media } from "@zyro-sec/ai/effect"
1233
+ import { Speech, SpeechEvent } from "@zyro-sec/ai/experimental"
1234
+ import { ElevenLabs, OpenAI } from "@zyro-sec/ai/providers"
1235
+
1236
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
1237
+
1238
+ // The whole file, written to disk.
1239
+ const program = Effect.gen(function* () {
1240
+ const response = yield* Speech.generate({
1241
+ model: openai.speech("gpt-4o-mini-tts"),
1242
+ text: "Hello from OpenCode.",
1243
+ voice: "coral",
1244
+ format: "mp3",
1245
+ instructions: "Warm and unhurried.",
1246
+ })
1247
+ response.audio // Media.Asset with bytes; headerless PCM carries info.encoding / sampleRate / channels
1248
+ response.usage // undefined: OpenAI reports tokens only on SSE streams (Gemini: tokens; ElevenLabs: credits; Deepgram: characters)
1249
+ yield* Media.write(response.audio, "hello.mp3")
1250
+ })
1251
+
1252
+ // Chunks as they arrive: audio-delta* (interleaved with timestamps) then one finish carrying the assembled asset.
1253
+ const events = Speech.stream({
1254
+ model: ElevenLabs.configure({ apiKey }).speech("eleven_flash_v2_5"),
1255
+ text: "Hello from OpenCode.",
1256
+ voice: "JBFqnCBsd6RMkjVDRZzb",
1257
+ format: "pcm",
1258
+ timestamps: true,
1259
+ }).pipe(
1260
+ Stream.tap((event) => {
1261
+ if (SpeechEvent.is.audioDelta(event)) return play(event.chunk)
1262
+ if (SpeechEvent.is.timestamps(event)) return highlight(event.items) // { text, startSeconds, endSeconds }[]
1263
+ return Effect.void
1264
+ }),
1265
+ )
1266
+ ```
1267
+
1268
+ `voice` is the provider's own identifier — a name on OpenAI and Gemini (`"coral"`, `"Kore"`), a voice id on
1269
+ ElevenLabs and Cartesia. `{ id }` selects an OpenAI custom voice (`{ id: "voice_1234" }`) and means the same as the
1270
+ plain string elsewhere. There is no cross-provider voice catalog. `format` is the container-level word (`mp3`, `wav`,
1271
+ `pcm`, `opus`, `aac`, `flac`); sample rates and bitrates live under `providerOptions`, and a value the route cannot
1272
+ produce fails as `UnsupportedOperation`. Streams buffer every chunk so `finish` can carry the whole clip.
1273
+
1274
+ Provider notes:
1275
+
1276
+ - **OpenAI** streams over SSE (`stream_format: "sse"`), which is also the only place it reports token usage; `tts-1`
1277
+ and `tts-1-hd` do not support SSE and stream the raw audio body instead. `pcm` is 24 kHz 16-bit mono. `language`
1278
+ and `timestamps` are not supported.
1279
+ - **Gemini TTS** returns the provider's default output: WAV for Gemini 3.8 TTS `generate`, raw 16-bit PCM
1280
+ (`audio/L16;codec=pcm;rate=24000`) otherwise. `pcm` is the only explicit `format` it accepts, and it fails typed on
1281
+ Gemini 3.8 `generate`; the route never wraps PCM as WAV. Style is directed in the text, so `instructions` and
1282
+ `speed` fail typed. Only `gemini-3.1-flash-tts-preview` and later support streaming. Two-speaker audio goes through
1283
+ `providerOptions.speechConfig.multiSpeakerVoiceConfig`.
1284
+ - **ElevenLabs** requires `voice` (the path voice id) and authenticates with `xi-api-key`. `format` maps to the
1285
+ `output_format` query parameter (`mp3_44100_128`, `pcm_24000`, `wav_24000`, `opus_48000_64`);
1286
+ `providerOptions.outputFormat` sets the exact string. WAV is only available from `generate`. `timestamps: true`
1287
+ selects the `with-timestamps` endpoints and yields character-level alignment. `instructions` is not supported.
1288
+ - **Cartesia** requires `voice` and pins `Cartesia-Version`. `generate` defaults to MP3 from `/tts/bytes`; streams
1289
+ and `timestamps: true` (word-level) use `/tts/sse`, which only serves raw PCM. `providerOptions.sampleRate`,
1290
+ `bitRate`, and `encoding` complete `output_format`. No usage is reported.
1291
+ - **Deepgram** Aura's voice is the model id (`aura-2-thalia-en`), so `voice` and `language` fail typed. `format`
1292
+ and `providerOptions` lower to query parameters (`encoding`, `container`, `sample_rate`, `bit_rate`); `pcm` is
1293
+ `linear16` without a container. Auth is `Authorization: Token <DEEPGRAM_API_KEY>`.
1294
+
1295
+ The promise client mirrors the Effect API; `ai.experimental.speech.stream` is an `AsyncIterable`.
1296
+
1297
+ ```ts
1298
+ import { ai } from "@zyro-sec/ai"
1299
+
1300
+ const response = await ai.experimental.speech.generate({ model, text: "Hello from OpenCode.", voice: "coral" })
1301
+ await ai.write(response.audio, "hello.mp3")
1302
+
1303
+ for await (const event of ai.experimental.speech.stream({ model, text: "Hello from OpenCode.", voice: "coral" })) {
1304
+ if (event.type === "audio-delta") player.write(event.chunk)
1305
+ }
1306
+ ```
1307
+
1308
+ ### Transcription
1309
+
1310
+ Transcription (speech-to-text) is the one modality whose providers use every route kind: OpenAI and Gemini stream,
1311
+ Deepgram and ElevenLabs answer inline, and AssemblyAI is queued. `Transcription.generate` and `Transcription.stream`
1312
+ work on all of them; `Transcription.start` / `resume` return a `Generation` on queued routes and fail with
1313
+ `UnsupportedOperation` elsewhere. Models come from `.transcription(...)` selectors on the `OpenAI`, `Google`,
1314
+ `Deepgram`, `ElevenLabs`, and `AssemblyAI` facades. Common fields (`language`, `prompt`,
1315
+ `timestamps: "none" | "segment" | "word"`, `diarize`, `speakers`) lower natively or fail with a typed `AIError` before
1316
+ any network call; a route may return more than asked.
1317
+
1318
+ ```ts
1319
+ import { Console, Effect, Stream } from "effect"
1320
+ import { Media } from "@zyro-sec/ai/effect"
1321
+ import { Transcription, TranscriptionEvent } from "@zyro-sec/ai/experimental"
1322
+ import { AssemblyAI, Deepgram, OpenAI } from "@zyro-sec/ai/providers"
1323
+
1324
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
1325
+
1326
+ const program = Effect.gen(function* () {
1327
+ const audio = yield* Media.file("./call.mp3")
1328
+
1329
+ // Speaker-labelled segments; labels are provider-native strings ("A", "0", "spk:0", "speaker_0").
1330
+ const response = yield* Transcription.generate({
1331
+ model: Deepgram.configure({ apiKey }).transcription("nova-3"),
1332
+ audio,
1333
+ diarize: true,
1334
+ timestamps: "word",
1335
+ })
1336
+ response.text // "Hello from OpenCode."
1337
+ response.segments // [{ text, startSeconds, endSeconds, speaker: "0" }]
1338
+ response.words // [{ text, startSeconds, endSeconds, speaker, confidence }]
1339
+ response.language // the provider's own value, lowercased ("en", "eng", "english", "en_us")
1340
+
1341
+ // Text deltas as the model transcribes, then one finish carrying the whole transcript.
1342
+ yield* Transcription.stream({ model: openai.transcription("gpt-4o-mini-transcribe"), audio }).pipe(
1343
+ Stream.tap((event) => (TranscriptionEvent.is.textDelta(event) ? Console.log(event.delta) : Effect.void)),
1344
+ Stream.runDrain,
1345
+ )
1346
+
1347
+ // Queued: persist the token with the provider and model ID (the token alone cannot pick the model), resume, and await.
1348
+ const model = AssemblyAI.configure({ apiKey }).transcription("universal-3-5-pro")
1349
+ const generation = yield* Transcription.start({ model, audio })
1350
+ const resumed = yield* Transcription.resume(model, JSON.parse(JSON.stringify(generation.token)))
1351
+ const transcript = yield* resumed.await({ poll: { interval: "3 seconds" } })
1352
+ })
1353
+ ```
1354
+
1355
+ Inline routes emit only `finish` from `stream` (no faked deltas); queued routes emit `generation-progress`
1356
+ before it.
1357
+
1358
+ Provider notes:
1359
+
1360
+ - **OpenAI** takes inline audio only; `diarize` needs `gpt-4o-transcribe-diarize`, timestamps need `whisper-1`, and `whisper-1` does not stream.
1361
+ - **Gemini** needs a transcribe model (`gemini-3.5-transcribe`); `prompt` and `speakers` fail typed.
1362
+ - **Deepgram** detects the language unless `language` is set; vocabulary goes in `providerOptions.keyterm`.
1363
+ - **ElevenLabs** (`scribe_v2`) uploads inline audio as the multipart `file` and sends a URL as `source_url`. Words
1364
+ always carry timestamps, and segments are speaker turns, so `diarize`, `timestamps: "segment"`, or `speakers` turns
1365
+ on diarization. `speakers` is an upper bound (`num_speakers`); `prompt` fails typed (vocabulary goes in
1366
+ `providerOptions.keyterms`), as do webhook delivery and per-channel output (`use_multi_channel` without
1367
+ `multichannel_output_style: "combined"`).
1368
+ - **AssemblyAI** uploads inline audio before submitting and treats `speakers` as the exact speaker count.
1369
+
1370
+ The promise client mirrors the Effect API:
1371
+
1372
+ ```ts
1373
+ const audio = await ai.file("./call.mp3")
1374
+ const text = (await ai.experimental.transcription.generate({ model, audio })).text
1375
+ for await (const event of ai.experimental.transcription.stream({ model, audio }))
1376
+ if (event.type === "text-delta") write(event.delta)
1377
+ const generation = await ai.experimental.transcription.start({ model: assemblyai, audio })
1378
+ const transcript = await generation.await({ poll: { interval: 3_000 } })
1379
+ ```
1380
+
1381
+ ### Extraction
1382
+
1383
+ Extraction models read typed values out of text instead of answering questions with probabilities. A field of type
1384
+ `text`, `number`, `date`, `time`, `datetime`, `duration`, `list`, `estimate` or `forecast` gets an answer typed to
1385
+ match; other types are sent and answered as-is. Only Cloudflare's Clairic serves it today.
1386
+
1387
+ ```ts
1388
+ import { ai } from "@zyro-sec/ai"
1389
+ import { Extraction } from "@zyro-sec/ai/experimental"
1390
+ import { CloudflareWorkersAI } from "@zyro-sec/ai/providers"
1391
+
1392
+ const response = await ai.run(
1393
+ Extraction.generate({
1394
+ model: CloudflareWorkersAI.configure({ accountId }).experimental.extraction("@cf/cloudflare/clairic"),
1395
+ input: "Invoice INV-2291, issued 2026-09-02, net 30. Total $1,080.00. Contact: Dana Ruiz, Priya Shah.",
1396
+ fields: {
1397
+ invoiceNumber: { type: "text" },
1398
+ dueDate: { type: "date", instructions: "Issue date plus the net payment days" },
1399
+ total: { type: "number", decimals: 2, unit: "USD" },
1400
+ contacts: { type: "list", items: "text" },
1401
+ },
1402
+ }),
1403
+ )
1404
+ response.answers.total.value // 1080, or null when the input does not say
1405
+ ```
1406
+
1407
+ Value answers carry `guess`, `nullProbability` and `confidence`; text answers carry a `span` into `input`. Estimates and
1408
+ forecasts return `median`, `p10` and `p90`. Field options other than `type`, `instructions` and `nullThreshold` go to
1409
+ Clairic as written. Effect users provide `RequestExecutor.fetchLayer` (or `AIClient.layer`). Images are not supported
1410
+ yet.
1411
+
1412
+ ## Testing
1413
+
1414
+ Use the deterministic test client from `@zyro-sec/ai/testing` to script provider-neutral responses and inspect
1415
+ the requests sent by code under test:
1416
+
1417
+ ```ts
1418
+ import { Effect } from "effect"
1419
+ import { TestLLM } from "@zyro-sec/ai/testing"
1420
+
1421
+ const programWithTestClient = Effect.gen(function* () {
1422
+ const test = yield* TestLLM.Test
1423
+ yield* test.push(TestLLM.text("Hello from the test model", "text-1"))
1424
+ const result = yield* program
1425
+ console.log(yield* test.requests())
1426
+ return result
1427
+ }).pipe(Effect.provide(TestLLM.testLayer()))
1428
+ ```
1429
+
1430
+ `testLayer()` provides the same object under `LLMClient.Service` and `TestLLM.Test`. Production consumes the
1431
+ normal client; tests use the additional controls. Each layer build has fresh state.
1432
+
1433
+ - `test.push(...)` queues one-shot responses in execution order. Each argument is one response.
1434
+ - `test.always(response)` installs a repeatable fallback. The layer's `fallback` option sets its initial value.
1435
+ - `test.serve(request => response)` installs a request-dependent fallback. `always` and `serve` replace each
1436
+ other without changing queued replies; queued replies take precedence.
1437
+ - `test.requests()` returns an array snapshot. `transformRequest` changes only the recorded observation;
1438
+ `serve` receives the original canonical request.
1439
+ - `test.wait(count)` waits for request arrivals, not output or completion, and supports concurrent waiters.
1440
+ - `test.gate()` returns a scoped gate with countable `started` notifications and a `release` Effect. Release
1441
+ unblocks all requests captured by that gate; closing its scope also releases it. Effect-aware test runners
1442
+ already provide Scope.
1443
+
1444
+ Constructing `stream()` or `generate()` does not record a request, invoke a responder, or consume a script.
1445
+ Each execution does. An exhausted queue without a fallback defects immediately rather than waiting for a
1446
+ future reply.
1447
+
1448
+ Generation responses remain canonical event arrays or arbitrary `Stream<LLMEvent, AIError>` values. The client consumes
1449
+ supplied streams directly, preserving failure identity, finalizers, incomplete output, and post-finish tails;
1450
+ it does not repair or truncate them.
1451
+
1452
+ For explicit compaction, script a `CompactionResponse` through `push`, `always`, or `serve`. Its `replacement` contains the next context window, including retained user messages. The client returns that result and usage directly, with the same lazy request recording and gates. Generation and compaction reject fixtures for the wrong operation instead of converting between response shapes.
1453
+
1454
+ For `compact(request, { mechanism: "trigger" })`, script a `CompactionCheckpointResponse` instead. It carries `checkpoint`, `responseID`, and optional `usage`. Endpoint and trigger calls reject each other's fixtures; both share the same queue, gates, lazy recording, and fallback controls.
1455
+
1456
+ Response helpers build common event arrays: `TestLLM.text(value, id)`, `textWithUsage(value, id, inputTokens)`,
1457
+ `toolCall(id, name, input)`, `stop(...events)`, `toolCalls(...events)`, and
1458
+ `complete({ reason, usage?, providerMetadata? }, ...events)`. `failAfter(error, ...events)` and `hangAfter(...events)`
1459
+ return streams that fail or never finish after the given events.
1460
+
1461
+ `compileRequest`, also from `@zyro-sec/ai/testing`, compiles an `LLMRequest` through its route without sending it, so
1462
+ tests can assert the provider payload.
1463
+
1464
+ Other modalities and the Promise client have no test double. Test them over a custom executor layer, such as
1465
+ `AI.make({ layer })`, that answers the HTTP requests.
1466
+
1467
+ ## Provider compaction
1468
+
1469
+ Compaction is opt-in. The package supports automatic compaction in OpenAI/Azure Responses and Anthropic Messages (including Claude on Vertex), and explicit compaction calls in OpenAI/Azure/xAI Responses. Model and deployment support still depends on the provider.
1470
+
1471
+ This is different from prompt caching, server-side history storage, or truncation. Compaction returns provider-owned context that must be replayed to continue the conversation.
1472
+
1473
+ ### Explicit compaction
1474
+
1475
+ `ai.compact(request)` (equivalently, `{ mechanism: "endpoint" }`) is the caller-controlled operation for OpenAI, Azure, and xAI Responses. It performs exactly one HTTP call to `/responses/compact`, using the selected route's endpoint, credentials, query, and HTTP middleware. It returns a `CompactionResponse` with `replacement: Message[]` and optional `usage`, not a normal generation response. This mechanism does not accept a WebSocket executor.
1476
+
1477
+ Prefer this operation, where supported, when the application owns compaction policy and durable context updates.
1478
+
1479
+ ```ts
1480
+ const compacted = Effect.gen(function* () {
1481
+ const result = yield* ai.compact(request)
1482
+ const next = { ...request, messages: result.replacement }
1483
+ return yield* ai.generate(next)
1484
+ })
1485
+ ```
1486
+
1487
+ From the Promise API, `await ai.compact(request)` takes the same request and options (plus `signal`) and returns the same result.
1488
+
1489
+ `replacement` replaces the complete input window. Do not append it to the original transcript or extract only the encrypted item: the provider may retain additional messages in its output. Retained user and assistant messages remain ordinary messages with typed text, media, or reasoning parts, in their original order. Provider-specific message IDs, status, and phase use `providerMetadata`, not a raw output array hidden in an assistant message. Unsupported returned item types fail explicitly.
1490
+
1491
+ The selected model carries explicit-compaction capability through request construction and updates. Calls using unsupported routes fail type checking. When the model is selected dynamically, narrow the request with `ai.canCompact(request)` before calling `ai.compact`; a model or route switch does not inherit the old capability. Runtime validation still rejects unsupported calls from untyped consumers. Capability describes the route's API, not whether every model or custom deployment supports the operation.
1492
+
1493
+ Generation-only body overlays such as `stream` and `store` are not sent to the compact endpoint. Supported compact controls such as service tier and prompt-cache settings preserve request defaults and HTTP-overlay precedence. Retained image and file detail settings survive serialization and replay.
1494
+
1495
+ The input must still fit the model's context window. Explicit compaction is not an overflow-recovery operation. Anthropic does not expose this operation in this package; its in-band compaction remains available below. Compatible routes do not inherit an explicit compact endpoint simply because they use a Responses protocol.
1496
+
1497
+ ### Streamed checkpoint compaction
1498
+
1499
+ OpenAI Responses also exposes a separate, explicitly selected mechanism:
1500
+
1501
+ ```ts
1502
+ const checkpoint = Effect.gen(function* () {
1503
+ const result = yield* ai.compact(request, {
1504
+ mechanism: "trigger",
1505
+ webSocket, // Optional: without it, the request uses HTTP/SSE.
1506
+ })
1507
+
1508
+ result.checkpoint // Successful encrypted CompactionPart.
1509
+ result.responseID
1510
+ result.usage
1511
+ })
1512
+ ```
1513
+
1514
+ This appends a native `compaction_trigger` control item to the full input and sends a normal Responses request, with tools and instructions retained, `stream: true`, `store: false`, and parallel tool calls enabled. It removes normal-answer text/output-format controls, forced tool choices, output-token/tool-call limits, and automatic `context_management`. Body overlays cannot replace `input` or supply `previous_response_id`/`conversation`; the complete canonical history is required for safe stateless replay. Request metadata, auth, headers, query parameters, service tier, and supported prompt-cache settings are preserved.
1515
+
1516
+ Only a successful `response.completed` with a response ID and exactly one logical encrypted checkpoint succeeds. Repeated item events are correlated by ID/output slot, including ID-less checkpoints. Other output is ignored, not returned as assistant text or dispatched as tools. Failed, incomplete, malformed, and interrupted responses return errors rather than partial checkpoints.
1517
+
1518
+ The result is **not a replacement window**. The caller selects retained history, combines it with `result.checkpoint`, and durably installs it before continuing. The operation does not choose a retention budget, prune messages, or modify the original request.
1519
+
1520
+ The supplied WebSocket executor can reuse a compatible append baseline for the compaction request. On completion the protocol supplies no continuation checkpoint, clearing the old baseline so the next generation sends the newly installed window in full. Validation occurs before transport completion is acknowledged. There is no operation-level retry or fallback to `/responses/compact`; existing safe transport fallback may use SSE, with full history and no connection-local response ID.
1521
+
1522
+ Trigger support is separate from endpoint support. Only the OpenAI Responses route advertises it; Azure, xAI, Chat, and compatible Responses routes do not inherit it. Untyped calls still fail before sending: missing route capabilities return `UnsupportedOperation`, while unknown mechanism names and invalid inputs return `InvalidRequest`. Dynamic callers must narrow for the selected mechanism:
1523
+
1524
+ ```ts
1525
+ const narrowed = Effect.gen(function* () {
1526
+ if (ai.canCompact(request, { mechanism: "trigger" })) {
1527
+ const result = yield* ai.compact(request, { mechanism: "trigger" })
1528
+ }
1529
+ })
1530
+ ```
1531
+
1532
+ This capability describes protocol implementation, **not universal availability on OpenAI API deployments**. The host application owns subscription/deployment eligibility, OAuth, endpoint selection, and deployment-specific headers. Local protocol/socket tests do not establish live provider support.
1533
+
1534
+ ### Advanced: in-band compaction
1535
+
1536
+ `providerOptions.contextManagement` lets the provider decide when to compact during an ordinary `generate` or `stream` call. This is an advanced option for callers that own persistence and recovery: persist the complete assistant message, including its checkpoint, before continuing. Enabling the option does not provide durable checkpoint storage, interruption recovery, or model-switch policy. Keep the prior context until a successful checkpoint has been persisted.
1537
+
1538
+ Enable OpenAI compaction with typed provider options:
1539
+
1540
+ ```ts
1541
+ import { Effect } from "effect"
1542
+ import { ai, LLMClient, Message } from "@zyro-sec/ai/effect"
1543
+ import { OpenAI } from "@zyro-sec/ai/providers"
1544
+
1545
+ const request = ai.request({
1546
+ model: OpenAI.configure({ apiKey }).responses("gpt-5.3-codex"),
1547
+ messages,
1548
+ providerOptions: {
1549
+ contextManagement: [{ type: "compaction", compactThreshold: 200_000 }],
1550
+ },
1551
+ })
1552
+ const continued = Effect.gen(function* () {
1553
+ const response = yield* LLMClient.generate(request)
1554
+ return { ...request, messages: [...request.messages, response.message, Message.user("Continue")] }
1555
+ })
1556
+ ```
1557
+
1558
+ `store: false` remains the default. Keep the entire `response.message`, not just `response.text`. Compaction events become ordered `CompactionPart`s alongside text and reasoning. The conversation contains everything needed to continue; there is no separate replay object or hidden provider transcript.
1559
+
1560
+ A compaction part has `provider` and exactly one representation: `encrypted` for Responses, or `text` for Anthropic. Responses also preserves the optional checkpoint `id`. These fields survive message serialization without becoming visible assistant text. Sending a checkpoint to another provider or an incompatible API fails rather than silently losing context.
1561
+
1562
+ ```ts
1563
+ import { CompactionPart, ProviderID } from "@zyro-sec/ai/effect"
1564
+
1565
+ CompactionPart.make({ provider: ProviderID.make("openai"), id: "cmp_123", encrypted: "..." })
1566
+ CompactionPart.make({ provider: ProviderID.make("anthropic"), text: "Summary of the conversation..." })
1567
+ ```
1568
+
1569
+ For Anthropic, use:
1570
+
1571
+ ```ts
1572
+ providerOptions: {
1573
+ contextManagement: {
1574
+ edits: [{
1575
+ type: "compact_20260112",
1576
+ trigger: { type: "input_tokens", value: 150_000 },
1577
+ pauseAfterCompaction: true,
1578
+ instructions: "Summarize the task and decisions. Do not call tools while summarizing.",
1579
+ }],
1580
+ },
1581
+ }
1582
+ ```
1583
+
1584
+ - The trigger is optional (provider default: 150,000 tokens), with a minimum of 50,000.
1585
+ - Custom instructions replace Anthropic's default summarization instructions.
1586
+ - The route adds `compact-2026-01-12` to existing beta headers, including when replaying a checkpoint without enabling new compactions.
1587
+ - A pause is exposed as `response.finishReason.raw === "compaction"`. It occurs only if the threshold triggers compaction: `pauseAfterCompaction` does not mean "compact now". The caller explicitly issues the next request; the package never automatically resumes.
1588
+ - Anthropic can return a compaction block with `content: null` when summarization fails. This becomes a compaction part with `text: null`, which is **not** a successful replacement for prior history. The package never prunes history automatically.
1589
+ - `Usage` totals include all reported Anthropic `usage.iterations`, including compaction. `contextTokens` separately reports the final message iteration's inclusive input size, when available. A compaction-only pause does not report a post-compaction context size. Raw iteration usage remains in `providerMetadata`.
1590
+
1591
+ ### Recording tests
1592
+
1593
+ Tests cover serialized round trips, real local HTTP plus a tool loop, WebSocket recovery, provider errors, malformed blocks, and usage accounting. Live provider tests are gated by `RECORD=true` and the relevant API keys:
1594
+
1595
+ ```sh
1596
+ # Run from packages/ai. Only records the selected new cassette group.
1597
+ RECORD=true RECORDED_PREFIX=openai-compaction bun test test/provider/compaction.recorded.test.ts
1598
+ RECORD=true RECORDED_PREFIX=xai-compaction bun test test/provider/compaction.recorded.test.ts
1599
+ RECORD=true RECORDED_PREFIX=anthropic-compaction bun test test/provider/compaction.recorded.test.ts
1600
+ ```
1601
+
1602
+ Provider references: [OpenAI](https://developers.openai.com/api/docs/guides/compaction), [Azure](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/responses#server-side-compaction), [Anthropic](https://platform.claude.com/docs/en/build-with-claude/compaction), [xAI](https://docs.x.ai/developers/advanced-api-usage/context-compaction).
1603
+
1604
+ ## Caching
1605
+
1606
+ Prompt caching is **on by default**. Every `LLMRequest` resolves to `cache: "auto"` unless the caller opts out with `cache: "none"`. Each protocol translates `CacheHint`s to its wire format (`cache_control` on Anthropic, `cachePoint` on Bedrock; OpenAI and Gemini do implicit caching server-side and don't need inline markers — auto is a no-op there).
1607
+
1608
+ ### Auto placement
1609
+
1610
+ `"auto"` places up to four breakpoints — the last tool definition, the first system part, the last system part when distinct, and the final message boundary. These expose successively larger reusable prefixes for tool definitions, system instructions, and the active conversation. The rolling final-message boundary advances on every request so recent conversation prefixes remain reusable during tool loops.
1611
+
1612
+ Tools precede every system and conversation block in the provider prefix, so tool definitions must remain byte-stable and deterministically ordered for downstream breakpoints to remain reusable.
1613
+
1614
+ Requests below a provider's minimum cacheable size simply do not produce a reusable cache entry.
1615
+
1616
+ ### Opting out
1617
+
1618
+ ```ts
1619
+ ai.request({
1620
+ model,
1621
+ system,
1622
+ prompt: "one-off question",
1623
+ cache: "none",
1624
+ })
1625
+ ```
1626
+
1627
+ ### Granular policy
1628
+
1629
+ ```ts
1630
+ cache: {
1631
+ tools?: boolean,
1632
+ system?: boolean,
1633
+ messages?: "latest-user-message" | "latest-assistant" | { tail: number },
1634
+ ttl?: CacheTTL, // "5m", "30m", "1h", "12h", "24h", ...
1635
+ }
1636
+ ```
1637
+
1638
+ An object with placement fields places exactly those breakpoints. An object with only `ttl` keeps automatic placement.
1639
+
1640
+ ### Cache lifetime
1641
+
1642
+ `ttl` is a duration in models.dev's format (`<number>` followed by `ms`, `s`, `m`, `h` or `d`). It is sent to the provider as given, so use one the provider accepts. Leaving it unset keeps the provider default.
1643
+
1644
+ ```ts
1645
+ ai.request({ model, system, prompt, cache: { ttl: "1h" } })
1646
+ ```
1647
+
1648
+ | Protocol | How `ttl` is sent |
1649
+ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
1650
+ | Anthropic Messages family, Meta Messages | `ttl` on every `cache_control` marker |
1651
+ | Bedrock Converse | `ttl` on every `cachePoint`; older Claude releases that only cache for 5m drop `"1h"` |
1652
+ | OpenRouter, DigitalOcean, Alibaba Chat markers | `ttl` on every `cache_control` marker |
1653
+ | OpenAI Responses (OpenAI, Azure, Cloudflare AI Gateway) | `"24h"` → `prompt_cache_retention: "24h"`; anything else → `prompt_cache_options: { ttl }` |
1654
+ | Chat Completions without markers (OpenAI-compatible, Moonshot, DeepInfra) | same mapping as OpenAI Responses |
1655
+
1656
+ OpenAI's two fields cover different models: `prompt_cache_retention` (`"in_memory"` or `"24h"`) is the only control before GPT-5.6, and GPT-5.6+ reads `prompt_cache_options.ttl` (`"30m"` or `"12h"`). Sending `prompt_cache_options` to an older model returns a 400. `"in_memory"` is not a duration; send it with an HTTP body overlay.
1657
+
1658
+ ### Manual hints
1659
+
1660
+ Inline `CacheHint` (`{ type: "ephemeral", ttl? }`) on any text / system / tool / tool-result part overrides automatic placement. The auto policy preserves manual hints, counts them against Anthropic and Bedrock's four-breakpoint limit, and only fills the remaining slots.
1661
+
1662
+ ```ts
1663
+ ai.request({
1664
+ model,
1665
+ system: [
1666
+ { type: "text", text: "stable system prompt", cache: { type: "ephemeral" } },
1667
+ ],
1668
+ ...
1669
+ })
1670
+ ```
1671
+
1672
+ ### Provider behavior table
1673
+
1674
+ | Protocol | `cache: "auto"` |
1675
+ | ----------------------- | ------------------------------------------------------------------------- |
1676
+ | Anthropic Messages | emits up to 4 `cache_control` markers (4-breakpoint cap enforced) |
1677
+ | Bedrock Converse | emits up to 4 `cachePoint` blocks (4-breakpoint cap enforced) |
1678
+ | OpenRouter | emits up to 4 `cache_control` markers |
1679
+ | OpenAI Chat / Responses | no-op (implicit caching above 1024 tokens) |
1680
+ | Gemini | no-op (implicit caching on 2.5+; explicit `CachedContent` is out-of-band) |
1681
+
1682
+ Normalized cache usage is read back into `response.usage.cacheReadInputTokens` and `cacheWriteInputTokens` across every provider.
1683
+
1684
+ ## Providers
1685
+
1686
+ Provider facades configure endpoint/auth/deployment details first, then expose model selectors that take only a model or deployment id. The selected model carries the executable route value used at runtime.
1687
+
1688
+ ```ts
1689
+ import { OpenAI, CloudflareAIGateway } from "@zyro-sec/ai/providers"
1690
+
1691
+ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }).responses("gpt-4o-mini")
1692
+ const gateway = CloudflareAIGateway.configure({
1693
+ accountId,
1694
+ gatewayApiKey: process.env.CLOUDFLARE_API_TOKEN,
1695
+ }).model("workers-ai/@cf/meta/llama-3.1-8b-instruct")
1696
+ ```
1697
+
1698
+ For a provider that needs no key, such as a local server, pass `apiKey: false`: the package skips the environment lookup and sends no auth header (Amazon Bedrock and Google Vertex keep their own auth).
1699
+
1700
+ Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock (Converse and Mantle), Azure OpenAI, Alibaba, Baseten, Cerebras, Cohere, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, DigitalOcean, Fireworks, Groq, Meta, MiniMax, Mistral, Moonshot, OpenRouter, TogetherAI, Venice, Vercel AI Gateway, xAI, Z.ai, and Z.ai Coding Plan. TypeSafe AI and OpenCode expose decision models only. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
1701
+
1702
+ Each named provider owns its module, endpoint, authentication, and route setup. Providers with the same wire format compose the shared protocol directly:
1703
+
1704
+ ```ts
1705
+ import { DeepSeek, Fireworks } from "@zyro-sec/ai/providers"
1706
+
1707
+ const deepseek = DeepSeek.configure({ apiKey }).model("deepseek-chat")
1708
+ const fireworks = Fireworks.configure({ apiKey }).model("accounts/fireworks/models/my-model")
1709
+ ```
1710
+
1711
+ The former `OpenAICompatible.baseten`, `.cerebras`, `.deepinfra`, `.deepseek`, `.fireworks`, `.groq`, and `.togetherai` presets are replaced by the top-level `Baseten`, `Cerebras`, `DeepInfra`, `DeepSeek`, `Fireworks`, `Groq`, and `TogetherAI` exports. Use `CloudflareAIGateway` and `CloudflareWorkersAI` directly; each has its own module. `OpenAICompatible` configures generic endpoints with an explicit `baseURL`.
1712
+
1713
+ ### Provider entrypoints
1714
+
1715
+ Provider modules are available through dedicated exports from `@zyro-sec/ai`. Each LLM entrypoint exports `model(modelID, settings)`, where `settings` contains provider configuration plus common `headers` and `body` overlays.
1716
+
1717
+ ```ts
1718
+ import { model } from "@zyro-sec/ai/providers/openai/responses"
1719
+
1720
+ const selected = model("gpt-5", {
1721
+ apiKey: process.env.OPENAI_API_KEY,
1722
+ headers: { "x-application": "example" },
1723
+ })
1724
+ ```
1725
+
1726
+ APIs have separate entrypoints:
1727
+
1728
+ - `@zyro-sec/ai/providers/openai/chat`
1729
+ - `@zyro-sec/ai/providers/openai/responses`
1730
+ - `@zyro-sec/ai/providers/openai-compatible/responses`
1731
+ - `@zyro-sec/ai/providers/anthropic-compatible`
1732
+ - `@zyro-sec/ai/providers/google-vertex/gemini`
1733
+ - `@zyro-sec/ai/providers/google-vertex/interactions`
1734
+ - `@zyro-sec/ai/providers/google-vertex/chat`
1735
+ - `@zyro-sec/ai/providers/google-vertex/responses`
1736
+ - `@zyro-sec/ai/providers/google-vertex/messages`
1737
+
1738
+ OpenAI Responses has one semantic route and uses HTTP by default. Advanced callers may supply a per-call WebSocket channel executor through `StreamOptions`; transport policy does not change provider settings, model identity, or route identity. The provider-neutral Open Responses implementation owns the reusable WebSocket request and event contract, while each provider opts in with its own handshake and connection policy. Azure follows the same Chat/Responses split at `providers/azure/chat` and `providers/azure/responses`. Generic OpenAI-compatible Chat remains at `providers/openai-compatible`; the Responses adapter at `providers/openai-compatible/responses` uses the provider-neutral Open Responses protocol. OpenAI Responses extends that baseline with OpenAI tools, event variants, metadata, and defaults. Generic Anthropic Messages-compatible providers use `providers/anthropic-compatible`, which the named Anthropic provider composes. Google Gemini and Amazon Bedrock expose their single native API through their existing provider paths.
1739
+
1740
+ Vertex Gemini, Vertex Interactions, Vertex Chat, Vertex Responses, and Vertex Messages are separate API entrypoints. All accept `project`, `location`, and an optional `accessToken`; when no explicit token or auth override is supplied they lazily use Google Application Default Credentials. Vertex Gemini and Interactions instead select express mode when `apiKey` or `GOOGLE_VERTEX_API_KEY` is present (explicit `project` or `location` selects ADC over an ambient key). Vertex Chat targets MaaS models through the OpenAI-compatible Chat Completions endpoint, while Vertex Responses targets Grok models and defaults `store` to `false` as required by Vertex. `providers/google-vertex` remains the default alias for `providers/google-vertex/gemini`.
1741
+
1742
+ Tuned Vertex Gemini deployments use model ids shaped like `endpoints/1234567890` and require OAuth or ADC; Vertex express-mode API keys support publisher models only.
1743
+
1744
+ ```ts
1745
+ import { model } from "@zyro-sec/ai/providers/google-vertex/gemini"
1746
+
1747
+ model("gemini-3.5-flash", { project: "my-project", location: "global" })
1748
+ ```
1749
+
1750
+ ```ts
1751
+ import { model } from "@zyro-sec/ai/providers/google-vertex/chat"
1752
+
1753
+ model("deepseek-ai/deepseek-v3.2-maas", { project: "my-project", location: "global" })
1754
+ ```
1755
+
1756
+ ```ts
1757
+ import { model } from "@zyro-sec/ai/providers/google-vertex/responses"
1758
+
1759
+ model("xai/grok-4.20-reasoning", { project: "my-project", location: "global" })
1760
+ ```
1761
+
1762
+ ```ts
1763
+ import { model } from "@zyro-sec/ai/providers/google-vertex/messages"
1764
+
1765
+ model("claude-sonnet-4-6", { project: "my-project", location: "global" })
1766
+ ```
1767
+
1768
+ Additional provider entrypoints include:
1769
+
1770
+ - `@zyro-sec/ai/providers/baseten`
1771
+ - `@zyro-sec/ai/providers/deepseek`
1772
+ - `@zyro-sec/ai/providers/fireworks`
1773
+ - `@zyro-sec/ai/providers/cloudflare-ai-gateway`
1774
+ - `@zyro-sec/ai/providers/cloudflare-workers-ai`
1775
+
1776
+ ## Provider options & HTTP overlays
1777
+
1778
+ Request options in order of stability:
1779
+
1780
+ 1. **Portable knobs** — `maxTokens`, `temperature`, `topP`, `topK`, `frequencyPenalty`, `presencePenalty`, `seed` and `stop`, at the top level of a text request. `GENERATION_KEYS` lists them.
1781
+ 2. **`promptCacheKey`** — stable cache affinity lowered by every protocol that supports it.
1782
+ 3. **`providerOptions: { ... }`** — flat options inferred from the selected model (OpenAI `store`, Anthropic `thinking`, Gemini `thinkingConfig`, OpenRouter routing).
1783
+ 4. **`http: { body, headers, query }`** — last-resort serializable overlays merged into the final HTTP request. Reach for this only when a stable typed path doesn't yet exist.
1784
+
1785
+ Route/provider defaults are overridden by request-level values for each axis.
1786
+
1787
+ The selected model supplies the provider-specific option type, so per-request overrides stay flat while the canonical runtime request remains provider-neutral:
1788
+
1789
+ ```ts
1790
+ ai.request({
1791
+ model,
1792
+ prompt,
1793
+ providerOptions: {
1794
+ reasoningEffort: "low",
1795
+ },
1796
+ })
1797
+ ```
1798
+
1799
+ ## Routes
1800
+
1801
+ Compose a route with `Route.make({ protocol, endpoint, auth, framing, ... })`. The route owns endpoint/auth/framing and the protocol owns body construction plus stream parsing. Transports receive the route's endpoint and auth when preparing requests. Unsupported request shapes fail during protocol lowering.
1802
+
1803
+ ## Effect
1804
+
1805
+ This package is built on Effect. Public methods in `@zyro-sec/ai/effect` return `Effect` or `Stream`; provide `AIClient.layer` (or `AIClient.layerWith(executor)`) for every modality, then import the provider/protocol modules for the routes you use. The example at `example/tutorial.ts` is a runnable walkthrough.
1806
+
1807
+ ## See also
1808
+
1809
+ - `AGENTS.md` — architecture, route construction, contributor guide
1810
+ - `example/tutorial.ts` — runnable end-to-end walkthrough (`bun example/tutorial.ts <example>`)
1811
+ - `test/provider/*.test.ts` — fixture-first protocol tests; `*.recorded.test.ts` files cover live cassettes