Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Vercel Ai Sdk Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-vercel-ai-sdk-knowledge-patch)
---
name: vercel-ai-sdk-knowledge-patch
description: Vercel AI SDK
version: "7.0.182"
license: MIT
metadata:
author: Nevaberry
---
# Vercel AI SDK Knowledge Patch
Load this skill when migrating Vercel AI SDK code or working with agents,
tools, generation, media, chat streams, MCP, or telemetry. Use the topic
references for complete examples and version-specific behavior.
## Reference index
| Reference | Topics |
| --- | --- |
| [Migration and compatibility](references/migrations.md) | Runtime requirements, codemods, renames, result shapes, validation, deprecated APIs |
| [Agents and tools](references/agents-and-tools.md) | Stop conditions, runtime and tool context, workflows, approvals, repair, discovery, timeouts, steering |
| [Generation and media](references/generation-and-media.md) | Reasoning, structured output, decisions, extraction, batches, files, embeddings, images, video, audio |
| [MCP and runtimes](references/mcp-and-runtimes.md) | MCP transports, schemas, resources, prompts, elicitation, apps, sandboxes, harnesses, realtime sessions |
| [Providers and observability](references/providers-and-observability.md) | Telemetry, durable tracing, content recording, lifecycle callbacks, provider metadata, warnings |
| [UI and streams](references/ui-and-streams.md) | Chat persistence, queues, resumption, validation, tool errors, transforms, retries, cancellation, heartbeats |
## Runtime and migration
v7 requires Node.js 22+ and ESM imports. Set `"type": "module"` or use `.mjs`
for migrated entry points. Run `npx @ai-sdk/codemod v7` for mechanical changes;
review message handling, context, and result shapes separately.
| Existing usage | Guidance |
| --- | --- |
| Generation option `system` | Replace with `instructions`; embedded system messages in `prompt` or `messages` require `allowSystemInMessages: true`. |
| Core generation `onFinish` | Use `onEnd`. |
| Core generation `result.fullStream` | Read the complete event stream from `result.stream`. |
| Deprecated result response methods | Use top-level `createUIMessageStreamResponse` and `createTextStreamResponse`. |
| `experimental_repairToolCall`, `experimental_repairText` | Use `repairToolCall` for text generation and `repairText` with `generateObject` and `streamObject`; the old names remain deprecated aliases. |
| `Experimental_GeneratedImage` | Use `GeneratedFile`. |
| `Experimental_LanguageModelStreamPart`, `experimental_filterActiveTools` | Use `LanguageModelStreamPart` and `filterActiveTools`. |
| Vue `Chat` class | Use the `useChat` composable. |
The unprefixed exports include `customProvider`, `generateImage`,
`generateSpeech`, `transcribe`, `SpeechResult`, and `TranscriptionResult`.
Generation option names are `output`, `prepareStep`, and `telemetry`.
## Results and input validation
Top-level `content`, `toolCalls`, `toolResults`, `files`, `sources`, `warnings`,
and `usage` aggregate across steps. For streamed final-step usage, read
`(await result.finalStep).usage`. Request and response body retention requires
opting in.
Validate untrusted messages before passing them to `generateText`, `streamText`,
`generateObject`, or `streamObject`; these APIs trust the caller's `ModelMessage`
shape. Other inputs such as call settings and decision state rely on declared
types for shape checks; integer ranges and finite decision JSON numbers remain
validated.
Read static tool input errors from `input` following the deprecation of
`rawInput` on `output-error` parts.
## Stream compatibility
Handle `finishReason === 'interrupted'` in incomplete-response checks and
exhaustive finish-reason types. When providers begin emitting it for streams
ending without a completion signal, the SDK returns partial output and stops
tool execution, agent continuation, and automatic UI follow-ups.
From 7.0.144 onward, use `experimental_streamTextLowMemory(options)` in place of
`streamText({ ...options, experimental_lowMemory: true })`. Consume it once;
it retains neither a replay buffer nor final-content results.
Compatible providers emit typed heartbeats with `includePings: true`, which is
off by default. Handle `ping` in exhaustive core stream switches. Pings pass
through retries and are excluded from generated content and UI message streams.
## Approval policies and signed upgrades
Move approval rules from deprecated tool-level `needsApproval` to `toolApproval`
on `generateText`, `streamText`, or `ToolLoopAgent`. For example,
`toolApproval: { publishDraft: 'user-approval' }` gates that tool. Per-tool or
catch-all functions can approve, deny, or ask the user.
`WorkflowAgent` and its `generate()` or `stream()` calls also accept
`toolApproval` to override `needsApproval`. Policy callbacks run in workflow
context; approved calls execute in the same step, and denied calls return
`execution-denied` without pausing the workflow.
Automatic denials no longer receive approval signatures. Rotate
`experimental_toolApprovalSecret` to invalidate signatures issued for denials
by older versions, then request any still-pending approvals again.
Pending approvals can resume from earlier messages until superseded by a user
message. Replay preserves schema-transformed approved inputs and rejects
histories whose reconstructed output differs, including signed histories
missing the original input. Include an approved call's result in later context.
## Agent control and context
`ToolLoopAgent` evaluates `stopWhen` after a step returns tool results and defaults
to `isStepCount(20)`. An array stops when any condition matches; custom predicates
receive `{ steps }`. `stopWhen: isLoopFinished()` removes the step cap while
preserving normal loop exits.
Initialize shared orchestration state with `runtimeContext`; read it in
`prepareStep`, approvals, and lifecycle callbacks. A step can return an updated
`runtimeContext` for subsequent steps. Define a tool's context shape with
`contextSchema`, supply it under that tool's key in `toolsContext`, and read it
from the second argument to `execute`.
`toolChoice: 'none'` gates calls in `generateText`, `streamText`, and
`WorkflowAgent`. Rejected calls skip `repairToolCall` and
`experimental_refineToolInput`; streamed runs withhold those tool parts from clients.
Use a deferred-tool `search` callback to select and rank eligible tools and
`maxResults` to cap the result count. Code-mode can discover and update tools
mid-conversation; `WorkflowAgent` supports deferred tool discovery.
## Durable runs and steering
Construct `WorkflowAgent` from `@ai-sdk/workflow` with
`{ model, tools, runtimeContext }` for runs that need to survive restarts or delayed
approvals. Its durable `generate()` loop returns the core result with typed
output and defaults to a 20-step limit.
In `WorkflowAgent.prepareStep`, returned `instructions` replace current
instructions and carry forward, `providerOptions` merge with the agent's
options, and `headers` override matching call headers.
`generateText`, `streamText`, and `ToolLoopAgent` support experimental steering.
Use `steering.queue()` to defer a message until the current task completes, or
the interrupt option to cancel a model call before it emits output. Steering
messages appear in UI streams and survive message conversion.
Read `stoppedBy` from generation results, the `onEnd` event, or the finish stream
part to determine why the loop ended.
## Timeouts, retries, and cancellation
Configure `timeout: { totalMs: 60_000, stepMs: 10_000, chunkMs: 2_000, toolMs: 5_000 }`
to bound the run, each step, the gap between chunks, and each tool by default.
Use `timeout.tools` for per-tool limits. Abort reasons propagate to stream and
UI consumers as `TimeoutError`.
`timeout.firstChunkMs` caps the wait for the first content of each streaming
step. `firstChunkMs` and `chunkMs` stop at the end of each model response and get
fresh budgets on retry. `stepMs` bounds the complete step, including local tools.
`generateText` warns when given `firstChunkMs` or `chunkMs`.
Set `streamRetries` on `streamText` for provider errors after streaming starts.
The retry-aware `onError` callback can direct one recovery even with
`streamRetries: 0`; recovered results and metadata come from the successful attempt.
`onAbort` receives the call ID and abort reason. Aborting a multi-step run skips `onEnd`.
## Reasoning and structured generation
Use `reasoning: 'high'` on `generateText` or `streamText` for higher reasoning
effort, or `reasoning: 'max'` for the highest portable level. Providers may use
a native effort or budget or coerce `max` with a compatibility warning;
exhaustive `ReasoningLevel` maps and switches must handle `max`.
`Output.array` accepts `minItems` and `maxItems`; pass the specification as
`output` to `generateText` or `streamText`. Array output preserves transforms,
coercions, defaults, pipes, and root-level JSON Schema definitions. `Output.object`
and `Output.array` infer unions when given a value whose type is a union of schemas.
`streamText` emits structured output from the final tool-loop step. Partial JSON
can include `null` and the empty string. Supply an `output` specification to
`startBatch` and read parsed structured output from `getBatchResults`.
Use `experimental_decide` in place of `experimental_evaluate`. Language-model-backed
decisions accept `maxOutputTokens` and `reasoning`, defaulting to disabled reasoning
when omitted; native decision providers warn about unsupported settings.
Account for refusals. A top-level state array represents parts, so wrap a JSON
array in an object or JSON part. Check file-part support before sending images.
## Files and media
Upload with `uploadFile({ api: provider.files(), data, filename })` and reuse
`providerReference` as message-part `data` with a compatible model. `FilesV4`
supports stream uploads and optional metadata, streaming download, and deletion.
Set `experimental_download: createDownload({ fetch })` on `generateText` or
`streamText` to share a cancellable transport for prompt assets and generated
file URLs. On Node.js, a guarded fetch opts into DNS validation.
`experimental_streamSpeech` accepts string input or streamed text deltas and
parts with optional `voice` and `providerOptions`, using a model implementing
`Experimental_StreamingSpeechModelV4`. Choose one of `audioStream` and `fullStream`
to consume. For streaming transcription, read the single-consumer
`fullStream` before awaiting a result promise when both live parts and the final
transcript are needed. See the media reference for model contracts and cancellation.
## Chat and UI validation
React `useChat` accepts `transport: new DirectChatTransport({ agent })`.
`sendAutomaticallyWhen` accepts async conditions. `experimental_queue` queues
messages during an active response and waits for those async decisions.
`useChat({ resume: true })` can resume interrupted streams when the page becomes visible.
Register streamed validators under the bare data-part name, such as `weather`
in `dataPartSchemas` for `data-weather`. Invalid streamed data parts raise
`TypeValidationError`. `validateUIMessages`, `safeValidateUIMessages`, and agent
stream helpers stop at the first invalid message or part. Validation checks
schemas for the part's declared type.
UI streams send the same error text the model received for failed and invalid
tool calls. Set `redactToolErrors: true` to restore masking, or
`redactToolErrors: false` to preserve the model's text even with `onError` set.
## MCP and telemetry
MCP `tools({ schemas })` selects named tools using local input schemas. A local
`outputSchema` validates `structuredContent`, falling back to JSON parsed from
text when absent; missing or invalid content throws. Session management, stream
resumption, and server notifications require a full MCP client.
Register `new OpenTelemetry()` from `@ai-sdk/otel` at startup with
`registerTelemetry` from `ai`. Custom tracers belong in the integration constructor.
For durable tracing, use the same `OpenTelemetryIdGenerator` instance for the
tracer provider's `idGenerator` and `sampler` and the integration's `durable` option.
`recordInputs` and `recordOutputs` govern nested content and raw span results
sent to telemetry integrations and the `ai:telemetry` channel. Use `onWarning`
for per-call generation warnings and `onStepError` to observe step failures.