ai 7.0.171 → 7.0.173
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/dist/index.d.ts +40 -30
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +54 -27
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts +153 -55
- package/dist/internal/index.d.ts.map +1 -1
- package/dist/internal/index.js +53 -16
- package/dist/internal/index.js.map +1 -1
- package/docs/02-foundations/03-prompts.mdx +1 -1
- package/docs/03-agents/04-loop-control.mdx +1 -1
- package/docs/03-agents/06-tool-approvals.mdx +1 -1
- package/docs/03-agents/07-workflow-agent.mdx +187 -14
- package/docs/03-ai-sdk-core/05-generating-text.mdx +7 -2
- package/docs/03-ai-sdk-core/10-generating-structured-data.mdx +4 -0
- package/docs/03-ai-sdk-core/16-mcp-tools.mdx +3 -0
- package/docs/03-ai-sdk-core/26-reasoning.mdx +3 -3
- package/docs/03-ai-sdk-core/32-decisions.mdx +13 -2
- package/docs/03-ai-sdk-core/33-extractions.mdx +58 -0
- package/docs/03-ai-sdk-core/35-image-generation.mdx +2 -0
- package/docs/03-ai-sdk-core/36-transcription.mdx +3 -0
- package/docs/03-ai-sdk-core/37-speech.mdx +3 -0
- package/docs/06-advanced/11-secure-url-fetching.mdx +10 -1
- package/docs/07-reference/01-ai-sdk-core/14-decide.mdx +20 -15
- package/docs/07-reference/01-ai-sdk-core/14-extract.mdx +17 -12
- package/docs/07-reference/01-ai-sdk-core/32-validate-ui-messages.mdx +6 -0
- package/docs/07-reference/01-ai-sdk-core/33-safe-validate-ui-messages.mdx +3 -0
- package/docs/07-reference/04-ai-sdk-workflow/01-workflow-agent.mdx +115 -7
- package/package.json +11 -11
- package/src/agent/default-stop-condition.ts +28 -13
- package/src/decide/decide.ts +12 -1
- package/src/decide/decision-state.ts +29 -6
- package/src/extract/extract.ts +12 -1
- package/src/generate-text/validate-tool-approvals.ts +23 -19
|
@@ -22,7 +22,7 @@ The `stopWhen` parameter controls when to stop execution when there are tool res
|
|
|
22
22
|
|
|
23
23
|
If this default limit stops a tool loop that could otherwise continue, the SDK logs a warning with guidance on configuring `stopWhen`. Set `stopWhen` explicitly to choose a limit, even if you want to keep `isStepCount(20)`. Explicit stop conditions do not produce this warning.
|
|
24
24
|
|
|
25
|
-
`WorkflowAgent` does not apply a default step limit. It continues until the model stops calling tools or another natural termination condition is met. Configure an explicit condition such as `isStepCount(20)` when you need to bound its model calls. See [WorkflowAgent Loop Control](/docs/agents/workflow-agent#loop-control) for details.
|
|
25
|
+
`WorkflowAgent.stream()` does not apply a default step limit. It continues until the model stops calling tools or another natural termination condition is met. Configure an explicit condition such as `isStepCount(20)` when you need to bound its model calls. `WorkflowAgent.generate()` stops after 20 steps by default and logs the same warning. See [WorkflowAgent Loop Control](/docs/agents/workflow-agent#loop-control) for details.
|
|
26
26
|
|
|
27
27
|
When you provide `stopWhen`, the agent continues executing after tool calls until a stopping condition is met. When the condition is an array, execution stops when any of the conditions are met.
|
|
28
28
|
|
|
@@ -352,6 +352,6 @@ Every serverless instance that might handle a request needs the same secret, sin
|
|
|
352
352
|
|
|
353
353
|
- Use `toolApproval` with `ToolLoopAgent`, `generateText`, and `streamText`.
|
|
354
354
|
- Author approval rules as code with [Policy-Based Tool Approvals](/docs/agents/policy-tool-approvals) (`@ai-sdk/policy-opa`).
|
|
355
|
-
-
|
|
355
|
+
- [`WorkflowAgent`](/docs/agents/workflow-agent) supports `toolApproval` and `needsApproval`. Approvals suspend and resume durable workflow execution.
|
|
356
356
|
- Subagent tools cannot use `toolApproval`; see [Subagents](/docs/agents/subagents#no-tool-approvals-in-subagents).
|
|
357
357
|
- Chat SDK's `createChatTools` marks its write tools and `getUser` as needing approval. A `toolApproval` rule overrides those defaults; see [Chat Platforms](/docs/agents/chat-platforms#give-the-agent-chat-tools).
|
|
@@ -5,7 +5,7 @@ description: Build durable, resumable agents with the WorkflowAgent from @ai-sdk
|
|
|
5
5
|
|
|
6
6
|
# WorkflowAgent
|
|
7
7
|
|
|
8
|
-
The `WorkflowAgent` from `@ai-sdk/workflow` is designed for building **durable, resumable agents** that run inside a [workflow](https://vercel.com/docs/workflow). It
|
|
8
|
+
The `WorkflowAgent` from `@ai-sdk/workflow` is designed for building **durable, resumable agents** that run inside a [workflow](https://vercel.com/docs/workflow). It runs a tool loop like [`ToolLoopAgent`](/docs/agents/building-agents) and adds automatic state persistence, tool schema serialization, and tool approval flows that survive workflow step boundaries.
|
|
9
9
|
|
|
10
10
|
## Why Durable Agents?
|
|
11
11
|
|
|
@@ -33,6 +33,8 @@ A standard `ToolLoopAgent` runs entirely in memory — if the process crashes, a
|
|
|
33
33
|
|
|
34
34
|
For simpler use cases that don't need durability, use [`ToolLoopAgent`](/docs/agents/building-agents) from the `ai` package.
|
|
35
35
|
|
|
36
|
+
The two classes have different options, callbacks, and results. Read [Differences from ToolLoopAgent](#differences-from-toolloopagent) before you move code from one to the other.
|
|
37
|
+
|
|
36
38
|
## Installation
|
|
37
39
|
|
|
38
40
|
```bash
|
|
@@ -320,11 +322,11 @@ Tools without `'use step'` still work but run as regular in-memory functions wit
|
|
|
320
322
|
|
|
321
323
|
## Tool Approval
|
|
322
324
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
`
|
|
326
|
-
|
|
327
|
-
the
|
|
325
|
+
Human approval is configured on the tool definition with `needsApproval` or on
|
|
326
|
+
the agent with `toolApproval`. The `toolApproval` configuration takes precedence
|
|
327
|
+
over `needsApproval`. When a tool call needs user approval, the agent pauses and
|
|
328
|
+
emits an approval request to the writable stream. The workflow suspends until
|
|
329
|
+
the user approves or denies:
|
|
328
330
|
|
|
329
331
|
```ts
|
|
330
332
|
const agent = new WorkflowAgent({
|
|
@@ -354,6 +356,36 @@ const agent = new WorkflowAgent({
|
|
|
354
356
|
|
|
355
357
|
Because the workflow is durable, the approval request survives process restarts — the user can approve hours later and the agent will resume.
|
|
356
358
|
|
|
359
|
+
Use `toolApproval` when approval depends on the tool set, the call, or the
|
|
360
|
+
runtime context, or when a tool does not set `needsApproval`. The functions in
|
|
361
|
+
the configuration run in workflow context, outside of the durable model steps:
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
const agent = new WorkflowAgent({
|
|
365
|
+
model: 'anthropic/claude-sonnet-5.5',
|
|
366
|
+
tools: {
|
|
367
|
+
bookFlight: tool({
|
|
368
|
+
description: 'Book a flight',
|
|
369
|
+
inputSchema: z.object({ flightId: z.string() }),
|
|
370
|
+
execute: bookFlightStep,
|
|
371
|
+
}),
|
|
372
|
+
},
|
|
373
|
+
toolApproval: {
|
|
374
|
+
bookFlight: 'user-approval',
|
|
375
|
+
},
|
|
376
|
+
});
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
A call that the configuration marks as `'approved'` runs in the same step. A
|
|
380
|
+
call that it marks as `'denied'` does not run: the model receives an
|
|
381
|
+
`execution-denied` tool result and the loop continues. Neither decision pauses
|
|
382
|
+
the workflow. `step.content` records both decisions with an automatic approval
|
|
383
|
+
request and an approval response. Two details differ from `ToolLoopAgent`. The
|
|
384
|
+
tool message in `step.response.messages` holds only the tool result, while
|
|
385
|
+
`ToolLoopAgent` also adds the approval response part there. In `stream()`, the
|
|
386
|
+
approval parts follow the tool results in `step.content`, while `ToolLoopAgent`
|
|
387
|
+
places them next to the tool calls.
|
|
388
|
+
|
|
357
389
|
### Signed Tool Approvals
|
|
358
390
|
|
|
359
391
|
Client-supplied message history can be modified before it is replayed to the
|
|
@@ -399,9 +431,10 @@ The stream-level value overrides the constructor default.
|
|
|
399
431
|
|
|
400
432
|
## Loop Control
|
|
401
433
|
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
434
|
+
`stream()` does not apply a default step limit. When `stopWhen` is omitted, it
|
|
435
|
+
continues until the model stops calling tools or another natural termination
|
|
436
|
+
condition is met. `generate()` stops after 20 steps by default, like
|
|
437
|
+
`ToolLoopAgent`, and logs the same warning when it reaches that limit.
|
|
405
438
|
|
|
406
439
|
<Note>
|
|
407
440
|
A model that repeatedly calls tools can make an unlimited number of model
|
|
@@ -420,8 +453,9 @@ const result = await agent.stream({
|
|
|
420
453
|
});
|
|
421
454
|
```
|
|
422
455
|
|
|
423
|
-
|
|
424
|
-
calling tools. You can make that intent explicit with
|
|
456
|
+
With `stream()`, omitting `stopWhen` already lets the agent continue until it
|
|
457
|
+
has finished calling tools. You can make that intent explicit with
|
|
458
|
+
`isLoopFinished()`, which also removes the 20-step default of `generate()`:
|
|
425
459
|
|
|
426
460
|
```ts
|
|
427
461
|
import { isLoopFinished } from 'ai';
|
|
@@ -432,7 +466,7 @@ const result = await agent.stream({
|
|
|
432
466
|
});
|
|
433
467
|
```
|
|
434
468
|
|
|
435
|
-
`isLoopFinished()` is equivalent to omitting `stopWhen
|
|
469
|
+
For `stream()`, `isLoopFinished()` is equivalent to omitting `stopWhen`.
|
|
436
470
|
Use it with caution because a model that keeps calling tools can run
|
|
437
471
|
indefinitely and incur significant costs. See
|
|
438
472
|
[`isLoopFinished()`](/docs/reference/ai-sdk-core/loop-finished).
|
|
@@ -589,7 +623,14 @@ const agent = new WorkflowAgent({
|
|
|
589
623
|
});
|
|
590
624
|
```
|
|
591
625
|
|
|
592
|
-
|
|
626
|
+
A `model`, `toolChoice`, `activeTools`, or generation setting returned from
|
|
627
|
+
`prepareStep` applies to the current step only, as in `ToolLoopAgent`. Later
|
|
628
|
+
steps use the agent or call values again unless `prepareStep` returns an
|
|
629
|
+
override for them too. Returned `messages`, `instructions`, `runtimeContext`,
|
|
630
|
+
and `toolsContext` values stay in effect for later steps.
|
|
631
|
+
|
|
632
|
+
`prepareStep` can also be passed per call in `generate()` and `stream()`.
|
|
633
|
+
`prepareCall` is a constructor option only.
|
|
593
634
|
|
|
594
635
|
## Lifecycle Callbacks
|
|
595
636
|
|
|
@@ -668,6 +709,112 @@ const myAgent = new WorkflowAgent({
|
|
|
668
709
|
export type MyAgentUIMessage = InferWorkflowAgentUIMessage<typeof myAgent>;
|
|
669
710
|
```
|
|
670
711
|
|
|
712
|
+
## Differences from ToolLoopAgent
|
|
713
|
+
|
|
714
|
+
`WorkflowAgent` and [`ToolLoopAgent`](/docs/agents/building-agents) both run a tool loop, but they are separate implementations with separate APIs. `WorkflowAgent` does not implement the [`Agent`](/docs/reference/ai-sdk-core/agent) interface, so you cannot pass it to `createAgentUIStream`, `createAgentUIStreamResponse`, or `pipeAgentUIStreamToResponse`. Code written for one class usually needs changes before it runs on the other.
|
|
715
|
+
|
|
716
|
+
### Options that only ToolLoopAgent supports
|
|
717
|
+
|
|
718
|
+
TypeScript rejects these options on `WorkflowAgent`. If you pass them anyway, for example from JavaScript, they are ignored without an error unless the table says otherwise.
|
|
719
|
+
|
|
720
|
+
| ToolLoopAgent option | With WorkflowAgent |
|
|
721
|
+
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
722
|
+
| `toolOrder` | Not supported. Tools are sent in the order of the `tools` object. |
|
|
723
|
+
| `callOptionsSchema` and the `options` call parameter | Not supported. Pass settings to `generate()` or `stream()` directly. |
|
|
724
|
+
| `experimental_toolCallers` | Not supported. |
|
|
725
|
+
| `experimental_steering` | Not supported. To add messages between steps, return `messages` from `prepareStep`. |
|
|
726
|
+
| `experimental_transform` | Not supported. Transform `run.readable` with `pipeThrough()` where you create the response. |
|
|
727
|
+
| `onStepError` | Not supported. Use `onError`. |
|
|
728
|
+
| `onLanguageModelCallStart`, `onLanguageModelCallEnd` | Not supported. |
|
|
729
|
+
| `include` in the constructor | Pass `include` to `generate()`. `stream()` has no `include` option and does not record request data in its steps. Use `includeRawChunks` to receive raw provider chunks. |
|
|
730
|
+
| `timeout` in the constructor | Pass `timeout` to `generate()` or `stream()`. |
|
|
731
|
+
| `experimental_telemetry` | Use `telemetry`. |
|
|
732
|
+
| `experimental_onToolCallStart`, `experimental_onToolCallFinish` | Use `onToolExecutionStart` and `onToolExecutionEnd`. |
|
|
733
|
+
|
|
734
|
+
### Options with a different shape
|
|
735
|
+
|
|
736
|
+
| Option | ToolLoopAgent | WorkflowAgent |
|
|
737
|
+
| ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
738
|
+
| Generation settings, `instructions`, `toolChoice`, `activeTools`, `stopWhen`, `output`, `telemetry`, `prepareStep`, `repairToolCall` | Constructor only. Use `prepareCall` to change them per call. | Constructor, or per call in `generate()` and `stream()`. The per-call value overrides the constructor value. |
|
|
739
|
+
| `abortSignal` | Per call. | Constructor or per call. |
|
|
740
|
+
| `experimental_sandbox` | Per call. | Constructor or per call. |
|
|
741
|
+
| `timeout` | A number or an object, in the constructor or per call. | A number or an object, per call. The object has no tool timeouts, and `stepMs` covers the model call without tool execution. See [Deadlines, cancellation, and replay](#deadlines-cancellation-and-replay). |
|
|
742
|
+
| `experimental_toolApprovalSecret` | The secret, as a `string` or `Uint8Array`. | `{ environmentVariable: string }`, the name of an environment variable that holds the secret. See [Signed Tool Approvals](#signed-tool-approvals). |
|
|
743
|
+
| `runtimeContext`, `toolsContext` | Any JavaScript value. | Serializable values. See [runtimeContext and toolsContext](#runtimecontext-and-toolscontext). |
|
|
744
|
+
|
|
745
|
+
### Default step limit
|
|
746
|
+
|
|
747
|
+
| | `generate()` | `stream()` |
|
|
748
|
+
| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
|
|
749
|
+
| `ToolLoopAgent` | 20 steps. A warning is logged when the limit stops the loop. | 20 steps. A warning is logged when the limit stops the loop. |
|
|
750
|
+
| `WorkflowAgent` | 20 steps. A warning is logged when the limit stops the loop. | No limit. |
|
|
751
|
+
|
|
752
|
+
### prepareCall
|
|
753
|
+
|
|
754
|
+
In `ToolLoopAgent`, `prepareCall` receives the settings together with the `prompt` or `messages` and the typed `options` of the call, and the object it returns replaces the call settings. In `WorkflowAgent`:
|
|
755
|
+
|
|
756
|
+
- It receives `messages` and no `options`. A string `prompt` is converted to a user message first.
|
|
757
|
+
- The fields it returns are merged into the call. Fields you leave out keep their values, so you do not need the `({ options, ...rest }) => ({ ...rest })` pattern.
|
|
758
|
+
- It cannot return `tools`. The tools are fixed when the agent is created.
|
|
759
|
+
|
|
760
|
+
### prepareStep
|
|
761
|
+
|
|
762
|
+
- `messages` uses the provider prompt format (`LanguageModelV4Prompt`) in the argument and in the return value, and it includes the system message. `ToolLoopAgent` uses `ModelMessage[]` without the system message.
|
|
763
|
+
- The argument has no `responseMessages`. `initialInstructions`, `instructions`, and `initialMessages` are available.
|
|
764
|
+
- You can return `headers`. They are merged over the headers of the call, and the request keeps the `user-agent` value that identifies the agent. `ToolLoopAgent` does not accept `headers` from `prepareStep`.
|
|
765
|
+
|
|
766
|
+
### Callbacks
|
|
767
|
+
|
|
768
|
+
The callbacks have the same names, but most of them receive smaller event objects than in `ToolLoopAgent`:
|
|
769
|
+
|
|
770
|
+
| Callback | Event fields in WorkflowAgent |
|
|
771
|
+
| ---------------------- | -------------------------------------------------------------------------------------------------------------- |
|
|
772
|
+
| `onStart` | `model`, `messages`, `runtimeContext`, `toolsContext` |
|
|
773
|
+
| `onStepStart` | `stepNumber`, `model`, `messages`, `steps`, `runtimeContext`, `toolsContext` |
|
|
774
|
+
| `onToolExecutionStart` | `toolCall`, `stepNumber`, `messages`, `toolContext` |
|
|
775
|
+
| `onToolExecutionEnd` | `toolCall`, `stepNumber`, `messages`, `toolContext`, `durationMs`, `success`, and `output` or `error` |
|
|
776
|
+
| `onStepEnd` | The step result, as in `ToolLoopAgent` |
|
|
777
|
+
| `onEnd` | `steps`, `messages`, `text`, `finishReason`, `usage`, `totalUsage`, `output`, `runtimeContext`, `toolsContext` |
|
|
778
|
+
|
|
779
|
+
`ToolLoopAgent` events also carry a `callId`, and its `onToolExecutionEnd` event uses `toolExecutionMs` and `toolOutput` where `WorkflowAgent` uses `durationMs`, `success`, `output`, and `error`.
|
|
780
|
+
|
|
781
|
+
The callbacks also run at different times:
|
|
782
|
+
|
|
783
|
+
- After a failed run, `stream()` calls `onEnd` before it rejects. `generate()` and `ToolLoopAgent` do not call `onEnd` for a failed run.
|
|
784
|
+
- `onAbort` is called by `generate()` and by `stream()`, and its event has only `steps`. `ToolLoopAgent` calls `onAbort` only for `stream()`, with `callId`, `reason`, and `steps`.
|
|
785
|
+
- An aborted `stream()` call resolves with the steps that finished. An aborted `generate()` call rejects.
|
|
786
|
+
|
|
787
|
+
### Results
|
|
788
|
+
|
|
789
|
+
`generate()` returns the same result type as `ToolLoopAgent`. If a model returns its structured output separately from its text, `generate()` still parses the text of the last step.
|
|
790
|
+
|
|
791
|
+
`stream()` works differently from `ToolLoopAgent`:
|
|
792
|
+
|
|
793
|
+
- It resolves when the run has finished, with a plain object that has `messages`, `steps`, `toolCalls`, `toolResults`, `finishReason`, `totalUsage`, and `output`, plus `error` when the model stream reported one. It has none of the streams and promises of `StreamTextResult`, such as `textStream`, `fullStream`, or `text`. Stream parts go to the `writable` you pass in. Read the final text from `result.steps.at(-1)?.text`.
|
|
794
|
+
- `messages` contains the input messages followed by the generated messages. `ToolLoopAgent` returns only the generated messages, as `responseMessages`.
|
|
795
|
+
- `toolCalls` and `toolResults` describe the last step. In `ToolLoopAgent` they cover all steps.
|
|
796
|
+
- `output` is `undefined` unless you set an `output` specification. `ToolLoopAgent` defaults to the generated text.
|
|
797
|
+
- If the structured output cannot be parsed, the `stream()` call rejects. In `ToolLoopAgent`, the call resolves and only `result.output` rejects.
|
|
798
|
+
- If the model call throws, the `stream()` call rejects with that error. In `ToolLoopAgent`, the call resolves and the error is reported through the stream and `onError`.
|
|
799
|
+
- Each step is a plain object. Its `request` is empty, and its `providerMetadata` is `{}` when the provider sends none. Steps from `generate()` match `ToolLoopAgent`.
|
|
800
|
+
|
|
801
|
+
### Tools
|
|
802
|
+
|
|
803
|
+
- Approval is configured with `needsApproval` on the tool or `toolApproval` on the agent. Approval request IDs have the form `approval-<toolCallId>`. `ToolLoopAgent` generates random IDs.
|
|
804
|
+
- For a tool whose `execute` function is an async generator, the last yielded value is the tool result, as in `ToolLoopAgent`. `ToolLoopAgent` also reports the earlier values as preliminary results. `WorkflowAgent` does not send them to the `writable`.
|
|
805
|
+
- Tool timeouts (`toolMs` and `tools` in the `timeout` object) are not supported.
|
|
806
|
+
- `experimental_refineToolInput` functions run in the workflow context after the model step returns. The `tool-call` chunk that `stream()` writes to `writable` for a tool without its own runtime validator, and the input of provider-executed tool calls, keep the unrefined value.
|
|
807
|
+
|
|
808
|
+
### Requests
|
|
809
|
+
|
|
810
|
+
Requests carry `ai-sdk-agent/workflow` in the `user-agent` header. `ToolLoopAgent` sends `ai-sdk-agent/tool-loop`.
|
|
811
|
+
|
|
812
|
+
### Timeouts
|
|
813
|
+
|
|
814
|
+
- `stepMs` limits one model call. In `ToolLoopAgent` it also covers the tool calls of the step.
|
|
815
|
+
- `generate()` ignores `firstChunkMs` and `chunkMs`. `ToolLoopAgent` also logs a warning for them.
|
|
816
|
+
- A timeout value that is not a finite number, or that is larger than 2147483647, is rejected with an `InvalidArgumentError`. So is a negative `stepMs`, `firstChunkMs`, or `chunkMs`. `ToolLoopAgent` does not validate the values.
|
|
817
|
+
|
|
671
818
|
## Migrating from `DurableAgent`
|
|
672
819
|
|
|
673
820
|
`WorkflowAgent` replaces the Workflow DevKit's [`DurableAgent`](https://workflow-sdk.dev/docs/api-reference/workflow-ai/durable-agent). The two share the same core idea — a durable agent loop that runs inside a workflow — but `WorkflowAgent` moves the class into the AI SDK, tightens typing, and introduces first-class tool approval. If you are using `DurableAgent` today, follow the steps below to switch.
|
|
@@ -835,7 +982,33 @@ Local tools execute only after approval validation; denied tools produce an exec
|
|
|
835
982
|
|
|
836
983
|
#### Deadlines, cancellation, and replay
|
|
837
984
|
|
|
838
|
-
|
|
985
|
+
`timeout` accepts a number of milliseconds or an object:
|
|
986
|
+
|
|
987
|
+
```ts
|
|
988
|
+
const result = await agent.stream({
|
|
989
|
+
messages,
|
|
990
|
+
timeout: {
|
|
991
|
+
totalMs: 5 * 60_000,
|
|
992
|
+
stepMs: 60_000,
|
|
993
|
+
firstChunkMs: 15_000,
|
|
994
|
+
chunkMs: 10_000,
|
|
995
|
+
},
|
|
996
|
+
});
|
|
997
|
+
```
|
|
998
|
+
|
|
999
|
+
A number has the same meaning as `totalMs`. Inside a workflow, it sets an absolute deadline for model calls. Each model step checks it before dispatch, before SDK retry attempts, and after the provider returns. The same deadline remains in effect after a tool suspends and resumes. SDK `maxRetries` governs model retries; the durable model step does not add another retry layer. Expiration before dispatch rejects with `TimeoutError`; expiration during SDK retry backoff rejects with `AbortError`. Neither starts a new retry.
|
|
1000
|
+
|
|
1001
|
+
The other values apply to one model call and start again for the next one:
|
|
1002
|
+
|
|
1003
|
+
- `stepMs` limits the whole model call: dispatch, SDK retries, and reading the response. Tool execution is not part of it.
|
|
1004
|
+
- `firstChunkMs` limits the wait for the first output of the model call, counted from the start of the response stream.
|
|
1005
|
+
- `chunkMs` limits the wait between two outputs.
|
|
1006
|
+
|
|
1007
|
+
`firstChunkMs` and `chunkMs` are used by `stream()` only. Only generated output counts for them: files, tool calls, and text, reasoning, or tool-input deltas that are not empty. Response metadata, start and end markers, and empty deltas do not start or reset these timers.
|
|
1008
|
+
|
|
1009
|
+
When one of these limits is reached, the model call is aborted with a `TimeoutError` and the run ends like an aborted run: `stream()` resolves with the steps that finished, `generate()` rejects with the error, and both call `onAbort`. The timers run inside the durable model step. A model step that has completed is not timed again on replay.
|
|
1010
|
+
|
|
1011
|
+
Each value must be a finite number of at most 2147483647, which is about 24.8 days. A negative `timeout` or `totalMs` is a deadline that has already passed. Any other invalid value is rejected with an `InvalidArgumentError` before the first model call.
|
|
839
1012
|
|
|
840
1013
|
A model deadline does not cancel a tool waiting on a Workflow hook. The run can remain suspended after that deadline. Once the hook resumes, any subsequent model call fails before dispatch if the deadline has expired. To stop the suspended run, use the Workflow runtime's `run.cancel()` API. Cancellation does not undo external side effects that already happened.
|
|
841
1014
|
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Generating Text
|
|
3
3
|
description: Learn how to generate text with the AI SDK.
|
|
4
|
+
keywords:
|
|
5
|
+
- text generation
|
|
6
|
+
- generate text
|
|
7
|
+
- stream text
|
|
8
|
+
- streaming text
|
|
4
9
|
---
|
|
5
10
|
|
|
6
11
|
# Generating and Streaming Text
|
|
@@ -722,7 +727,7 @@ When you use `generateText`, you can access the sources using the `sources` prop
|
|
|
722
727
|
|
|
723
728
|
```ts
|
|
724
729
|
const result = await generateText({
|
|
725
|
-
model: 'google/gemini-
|
|
730
|
+
model: 'google/gemini-4-hydrogen',
|
|
726
731
|
tools: {
|
|
727
732
|
google_search: google.tools.googleSearch({}),
|
|
728
733
|
},
|
|
@@ -744,7 +749,7 @@ When you use `streamText`, you can access the sources using the `stream` propert
|
|
|
744
749
|
|
|
745
750
|
```tsx
|
|
746
751
|
const result = streamText({
|
|
747
|
-
model: 'google/gemini-
|
|
752
|
+
model: 'google/gemini-4-hydrogen',
|
|
748
753
|
tools: {
|
|
749
754
|
google_search: google.tools.googleSearch({}),
|
|
750
755
|
},
|
|
@@ -40,7 +40,7 @@ The `reasoning` parameter works the same way with `streamText`:
|
|
|
40
40
|
import { streamText } from 'ai';
|
|
41
41
|
|
|
42
42
|
const result = streamText({
|
|
43
|
-
model: 'google/gemini-
|
|
43
|
+
model: 'google/gemini-4-hydrogen',
|
|
44
44
|
reasoning: 'high',
|
|
45
45
|
prompt: 'Explain the Riemann hypothesis in simple terms.',
|
|
46
46
|
});
|
|
@@ -153,7 +153,7 @@ If you need to enforce an exact token budget (e.g. exactly 12000 tokens), keep u
|
|
|
153
153
|
|
|
154
154
|
```ts
|
|
155
155
|
const { text } = await generateText({
|
|
156
|
-
model: google('gemini-
|
|
156
|
+
model: google('gemini-4-hydrogen'),
|
|
157
157
|
providerOptions: {
|
|
158
158
|
google: {
|
|
159
159
|
thinkingConfig: { thinkingLevel: 'high', includeThoughts: true },
|
|
@@ -167,7 +167,7 @@ const { text } = await generateText({
|
|
|
167
167
|
|
|
168
168
|
```ts
|
|
169
169
|
const { text } = await generateText({
|
|
170
|
-
model: google('gemini-
|
|
170
|
+
model: google('gemini-4-hydrogen'),
|
|
171
171
|
reasoning: 'high',
|
|
172
172
|
providerOptions: {
|
|
173
173
|
google: { thinkingConfig: { includeThoughts: true } },
|
|
@@ -51,6 +51,7 @@ Combine text, structured data, and images in one state:
|
|
|
51
51
|
```ts
|
|
52
52
|
import { openai } from '@ai-sdk/openai';
|
|
53
53
|
import { experimental_decide } from 'ai';
|
|
54
|
+
import { readFile } from 'node:fs/promises';
|
|
54
55
|
|
|
55
56
|
const result = await experimental_decide({
|
|
56
57
|
model: openai.decisionModel('gpt-6-luna'),
|
|
@@ -60,7 +61,7 @@ const result = await experimental_decide({
|
|
|
60
61
|
{
|
|
61
62
|
type: 'file',
|
|
62
63
|
mediaType: 'image/png',
|
|
63
|
-
data:
|
|
64
|
+
data: await readFile('package.png'),
|
|
64
65
|
},
|
|
65
66
|
],
|
|
66
67
|
questions: {
|
|
@@ -78,9 +79,15 @@ from `ai`. A part has one of these shapes:
|
|
|
78
79
|
- `TextPart`: `{ type: 'text', text: string }`.
|
|
79
80
|
- `FilePart`: `{ type: 'file', mediaType: string, data: ... }`, using the SDK's
|
|
80
81
|
file conventions. For images, use bytes, a base64 string, or a URL. Tagged file
|
|
81
|
-
data is also supported. URLs
|
|
82
|
+
data is also supported. Remote URLs require `experimental_download` and are
|
|
83
|
+
downloaded before the model call. Without that hook they throw `DownloadError`.
|
|
82
84
|
- JSON: `{ type: 'json', value: JSONValue }`.
|
|
83
85
|
|
|
86
|
+
For untrusted file URLs, use `experimental_download: createDownload({ fetch })`
|
|
87
|
+
with a transport that validates DNS at connection time, such as `guarded-fetch`
|
|
88
|
+
on Node.js. The model's `fetch` does not cover core state downloads. See
|
|
89
|
+
[Secure URL Fetching](/docs/advanced/secure-url-fetching#core-file-downloads).
|
|
90
|
+
|
|
84
91
|
Language-model decision adapters accept image files only. The underlying model
|
|
85
92
|
must support the file data form. Gateway forwards image files to the routed
|
|
86
93
|
decision model, which must support image input. TypeSafe AI accepts text and
|
|
@@ -102,6 +109,7 @@ Use a provider's `decisionModel` factory:
|
|
|
102
109
|
| OpenAI | `openai.decisionModel('gpt-6-luna')` |
|
|
103
110
|
| Anthropic | `anthropic.decisionModel('claude-haiku-4-5-20251001')` |
|
|
104
111
|
| Google | `google.decisionModel('gemini-decision-1')` |
|
|
112
|
+
| HeyGen | `heygen.decisionModel('heygen-decision-1')` |
|
|
105
113
|
|
|
106
114
|
TypeSafe AI's [Jev](https://vercel.com/i/what-is-jev), OpenAI's
|
|
107
115
|
[Decisions API](https://developers.openai.com/api/docs/guides/decisions),
|
|
@@ -289,6 +297,9 @@ Perplexity exposes Choice/Score confidence at
|
|
|
289
297
|
Google exposes confidence for all three question types at
|
|
290
298
|
`result.providerMetadata?.google?.confidence` and Score legends at
|
|
291
299
|
`result.providerMetadata?.google?.legend`, also keyed by question ID.
|
|
300
|
+
HeyGen exposes Choice/Score confidence at
|
|
301
|
+
`result.providerMetadata?.heygen?.confidence` and Score legends at
|
|
302
|
+
`result.providerMetadata?.heygen?.legend`, also keyed by question ID.
|
|
292
303
|
|
|
293
304
|
Check for optional distributions before using them. For example, an application
|
|
294
305
|
can route only when a provider supplies a sufficiently high selected-option
|
|
@@ -49,6 +49,41 @@ answers.contacts.value; // string[] | null
|
|
|
49
49
|
`referenceDate` is an optional `YYYY-MM-DD` date that anchors relative dates and
|
|
50
50
|
dates without a year.
|
|
51
51
|
|
|
52
|
+
## File URLs
|
|
53
|
+
|
|
54
|
+
Remote file URLs in `state` require `experimental_download`; otherwise extraction
|
|
55
|
+
throws `DownloadError` before making a network request. Inline bytes and data URLs
|
|
56
|
+
work without a download hook. The model's custom `fetch` does not cover these
|
|
57
|
+
core downloads.
|
|
58
|
+
|
|
59
|
+
For user-supplied URLs on Node.js, configure a DNS-protected transport:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { createGuardedFetch } from 'guarded-fetch';
|
|
63
|
+
import {
|
|
64
|
+
createDownload,
|
|
65
|
+
experimental_extract,
|
|
66
|
+
type Experimental_ExtractionModel,
|
|
67
|
+
} from 'ai';
|
|
68
|
+
|
|
69
|
+
async function readInvoiceFile(model: Experimental_ExtractionModel, url: URL) {
|
|
70
|
+
const fetch = createGuardedFetch();
|
|
71
|
+
try {
|
|
72
|
+
return await experimental_extract({
|
|
73
|
+
model,
|
|
74
|
+
state: [{ type: 'file', mediaType: 'application/pdf', data: url }],
|
|
75
|
+
fields: { invoiceNumber: { type: 'text' } },
|
|
76
|
+
experimental_download: createDownload({ fetch }),
|
|
77
|
+
});
|
|
78
|
+
} finally {
|
|
79
|
+
await fetch.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
See [Secure URL Fetching](/docs/advanced/secure-url-fetching#core-file-downloads)
|
|
85
|
+
for installation and transport requirements on other server runtimes.
|
|
86
|
+
|
|
52
87
|
## Field types
|
|
53
88
|
|
|
54
89
|
Every field has a `type` and optional `instructions`. Instructions accept
|
|
@@ -66,6 +101,29 @@ strings, JSON objects, or JSON arrays.
|
|
|
66
101
|
|
|
67
102
|
Answer value types are inferred from the field definitions.
|
|
68
103
|
|
|
104
|
+
## Provider models
|
|
105
|
+
|
|
106
|
+
Use a provider's `extractionModel` factory:
|
|
107
|
+
|
|
108
|
+
| Provider | Example model |
|
|
109
|
+
| --------- | ------------------------------------------------ |
|
|
110
|
+
| OpenAI | `openai.extractionModel('gpt-6.1-sol')` |
|
|
111
|
+
| Anthropic | `anthropic.extractionModel('claude-sonnet-5-5')` |
|
|
112
|
+
| Google | `google.extractionModel('gemini-4-hydrogen')` |
|
|
113
|
+
|
|
114
|
+
These adapt structured language-model output and extract every field in one
|
|
115
|
+
prompt. Anthropic sends more than 16 fields as parallel calls, see
|
|
116
|
+
[Anthropic extraction models](/providers/ai-sdk-providers/anthropic#extraction-models).
|
|
117
|
+
They return `null` for missing values but no `pNull`, `confidence`,
|
|
118
|
+
`guess`, or `source`. Judge quality against your own labeled examples before
|
|
119
|
+
choosing a model for a task.
|
|
120
|
+
|
|
121
|
+
- Empty strings and empty lists are returned as `null`.
|
|
122
|
+
- Numbers, durations, and number list items are rounded to `decimals`.
|
|
123
|
+
- When the provider refuses a request, the fields in that request are reported
|
|
124
|
+
as refused and `experimental_extract` throws
|
|
125
|
+
`Experimental_ExtractionRefusalError`.
|
|
126
|
+
|
|
69
127
|
## Answers
|
|
70
128
|
|
|
71
129
|
Every answer has the field's `type` and a `value`. `value` is `null` when the
|
|
@@ -201,7 +201,16 @@ A provider's `fetch` option applies to requests made by that provider. Core file
|
|
|
201
201
|
downloads have separate hooks that all accept the function returned by
|
|
202
202
|
`createDownload({ fetch })`: the `download` option of `transcribe` and
|
|
203
203
|
`experimental_generateVideo`, and the `experimental_download` option of
|
|
204
|
-
`generateText` and `
|
|
204
|
+
`generateText`, `streamText`, `experimental_decide`, and `experimental_extract`.
|
|
205
|
+
|
|
206
|
+
`experimental_decide` and `experimental_extract` reject remote file URLs in
|
|
207
|
+
`state` with `DownloadError` unless `experimental_download` is supplied. Inline
|
|
208
|
+
bytes, base64 content, and data URLs do not require a download hook. For untrusted
|
|
209
|
+
URLs, supply `createDownload({ fetch })` with a transport that validates DNS and
|
|
210
|
+
pins the connection to the validated addresses, such as `createGuardedFetch()`
|
|
211
|
+
on Node.js. A model's guarded `fetch` does not protect core state downloads.
|
|
212
|
+
Calling `createDownload()` without a custom `fetch` explicitly opts into the
|
|
213
|
+
runtime's global fetch and does not provide DNS protection.
|
|
205
214
|
|
|
206
215
|
Batch download requests include the call's `abortSignal`. `createDownload`
|
|
207
216
|
forwards it to the transport; custom download functions should do the same so
|
|
@@ -14,25 +14,30 @@ state. See [Decisions](/docs/ai-sdk-core/decisions) for examples and semantics.
|
|
|
14
14
|
|
|
15
15
|
## Parameters
|
|
16
16
|
|
|
17
|
-
| Parameter
|
|
18
|
-
|
|
|
19
|
-
| `model`
|
|
20
|
-
| `state`
|
|
21
|
-
| `questions`
|
|
22
|
-
| `maxOutputTokens`
|
|
23
|
-
| `reasoning`
|
|
24
|
-
| `maxRetries`
|
|
25
|
-
| `abortSignal`
|
|
26
|
-
| `
|
|
27
|
-
| `
|
|
28
|
-
| `
|
|
29
|
-
| `
|
|
30
|
-
| `
|
|
31
|
-
| `
|
|
17
|
+
| Parameter | Type | Description |
|
|
18
|
+
| ----------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
|
19
|
+
| `model` | `Experimental_DecisionModel` | Required experimental v4 model instance or a string ID resolved by Gateway or an explicitly configured decision-capable default provider. |
|
|
20
|
+
| `state` | `Experimental_DecisionState` | Required string, JSON object, or ordered array of text, file, and JSON parts. |
|
|
21
|
+
| `questions` | `Record<string, Experimental_DecisionQuestion>` | Required nonempty question map. |
|
|
22
|
+
| `maxOutputTokens` | `number` | Optional maximum output tokens, an integer >= 1. |
|
|
23
|
+
| `reasoning` | `'provider-default' \| 'none' \| 'minimal' \| 'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | Optional reasoning effort. Language-model adapters default to `'none'`. Native decision providers return an unsupported-setting warning. |
|
|
24
|
+
| `maxRetries` | `number` | Nonnegative integer; defaults to 2. |
|
|
25
|
+
| `abortSignal` | `AbortSignal` | Cancels the decisions request. |
|
|
26
|
+
| `experimental_download` | `Experimental_DownloadFunction` | Required for remote file URLs in state. Use `createDownload({ fetch })` with a DNS-protected transport for untrusted URLs. |
|
|
27
|
+
| `headers` | `Record<string, string>` | Additional HTTP headers. |
|
|
28
|
+
| `providerOptions` | `ProviderOptions` | Provider-specific options. |
|
|
29
|
+
| `telemetry` | `TelemetryOptions` | Telemetry configuration, including per-call integrations, input/output recording, and a function ID. |
|
|
30
|
+
| `runtimeContext` | `Record<string, unknown>` | Context available to lifecycle callbacks and selectively included in telemetry with `telemetry.includeRuntimeContext`. |
|
|
31
|
+
| `onStart` | `(event: Experimental_DecideStartEvent) => void` | Called when the decision operation begins. |
|
|
32
|
+
| `onEnd` | `(event: Experimental_DecideEndEvent) => void` | Called when the decision operation completes successfully. |
|
|
32
33
|
|
|
33
34
|
Set `reasoning: 'provider-default'` to use the underlying language model's default
|
|
34
35
|
reasoning effort instead of the adapter's `'none'` default.
|
|
35
36
|
|
|
37
|
+
Remote file URLs are rejected with `DownloadError` unless `experimental_download`
|
|
38
|
+
is supplied. The model's `fetch` option does not apply to these downloads. See
|
|
39
|
+
[Secure URL Fetching](/docs/advanced/secure-url-fetching#core-file-downloads).
|
|
40
|
+
|
|
36
41
|
See [Lifecycle Callbacks](/docs/ai-sdk-core/lifecycle-callbacks#experimental_decide)
|
|
37
42
|
for the complete `onStart` and `onEnd` event fields.
|
|
38
43
|
|