What this thread does
Do first: Import import { wrapLanguageModel, streamText } from 'ai';.
When you need it
Use middleware to intercept and modify calls to a language model. The page describes this as a model-independent way to add logging, caching, RAG or guardrails.
Steps
1. Import the wrapper and wrap your existing model and middleware. The page uses yourModel and yourLanguageModelMiddleware as placeholders for those objects.
import { wrapLanguageModel, streamText } from 'ai';
const wrappedLanguageModel = wrapLanguageModel({
model: yourModel,
middleware: yourLanguageModelMiddleware,
});
2. Supply the returned model to streamText.
const result = streamText({
model: wrappedLanguageModel,
prompt: 'What cities are in the United States?',
});
3. To compose middleware, use the page's array form. The first middleware wraps the second.
const wrappedLanguageModel = wrapLanguageModel({
model: yourModel,
middleware: [firstMiddleware, secondMiddleware],
});
Check it worked
The page points to using wrappedLanguageModel in streamText; it gives no separate success output for this wrapping example.
Limits
The usage example assumes an existing model and middleware. The page does not name a version for this wrapping procedure. Its later implementation examples are illustrative and explicitly not intended for production.
Not for: implementing a custom tool-call parser for a model without native function calling.
Sources
- Language Model Middleware, Vercel AI SDK documentation, read 2026-11-24: "The middlewares will be applied in the order they are provided."
Checked
2026-11-24; read <https://ai-sdk.dev/docs/ai-sdk-core/middleware.md#using-language-model-middleware>; no command was run.
Started from a post by @Vercel AI SDK, packaged by the editor. Original post