Language Model Middleware
Language model middleware is a way to enhance the behavior of language models by intercepting and modifying the calls to the language model. It can be used to add features like guardrails, RAG, caching, and logging in a language model agnostic way. Such middleware can be developed and distributed independently from the language models that they are applied to.Using Language Model Middleware
You can use language model middleware with thewrapLanguageModel function.
It takes a language model and a language model middleware and returns a new
language model that incorporates the middleware.
streamText:
Multiple Middlewares
You can provide multiple middlewares to thewrapLanguageModel function.
The middlewares will be applied in the order they are provided.
Built-in Middleware
The AI SDK comes with several built-in middlewares that you can use to configure language models:extractReasoningMiddleware: Extracts reasoning information from the generated text and exposes it as areasoningproperty on the result.extractJsonMiddleware: Extracts JSON from text content by stripping markdown code fences. Useful when usingOutput.object()with models that wrap JSON responses in code blocks.simulateStreamingMiddleware: Simulates streaming behavior with responses from non-streaming language models.defaultSettingsMiddleware: Applies default settings to a language model.addToolInputExamplesMiddleware: Adds tool input examples to tool descriptions for providers that don’t natively support theinputExamplesproperty.
Extract Reasoning
Some providers and models expose reasoning information in the generated text using special tags, e.g. <think> and </think>. TheextractReasoningMiddleware function can be used to extract this reasoning information and expose it as a reasoning property on the result.
generateText and streamText.
The extractReasoningMiddleware function also includes a startWithReasoning option.
When set to true, the reasoning tag will be prepended to the generated text.
This is useful for models that do not include the reasoning tag at the beginning of the response.
Extract JSON
Some models wrap JSON responses in markdown code fences (e.g.,```json ... ```) even when you request structured output.
The extractJsonMiddleware function strips these code fences from the response, making it compatible with Output.object().
Simulate Streaming
ThesimulateStreamingMiddleware function can be used to simulate streaming behavior with responses from non-streaming language models.
This is useful when you want to maintain a consistent streaming interface even when using models that only provide complete responses.
Default Settings
ThedefaultSettingsMiddleware function can be used to apply default settings to a language model.
Add Tool Input Examples
TheaddToolInputExamplesMiddleware function adds tool input examples to tool descriptions.
This is useful for providers that don’t natively support the inputExamples property on tools.
The middleware serializes the examples into the tool’s description text so models can still benefit from seeing example inputs.
inputExamples, the middleware will append them to the tool’s description:
Options
prefix(optional): A prefix text to prepend before the examples. Default:'Input Examples:'.format(optional): A custom formatter function for each example. Receives the example object and its index. Default:JSON.stringify(example.input).remove(optional): Whether to remove theinputExamplesproperty from the tool after adding them to the description. Default:true.
Implementing Language Model Middleware
Implementing language model middleware is advanced functionality and requires
a solid understanding of the language model specification.
transformParams: Transforms the parameters before they are passed to the language model, for bothdoGenerateanddoStream.wrapGenerate: Wraps thedoGeneratemethod of the language model. You can modify the parameters, call the language model, and modify the result.wrapStream: Wraps thedoStreammethod of the language model. You can modify the parameters, call the language model, and modify the result.
Examples
These examples are not meant to be used in production. They are just to show
how you can use middleware to enhance the behavior of language models.
Logging
This example shows how to log the parameters and generated text of a language model call.Caching
This example shows how to build a simple cache for the generated text of a language model call.Retrieval Augmented Generation (RAG)
This example shows how to use RAG as middleware.Helper functions like
getLastUserMessageText and findSources are not part
of the AI SDK. They are just used in this example to illustrate the concept of
RAG.Guardrails
Guard rails are a way to ensure that the generated text of a language model call is safe and appropriate. This example shows how to use guardrails as middleware.Configuring Per Request Custom Metadata
To send and access custom metadata in Middleware, you can useproviderOptions. This is useful when building logging middleware where you want to pass additional context like user IDs, timestamps, or other contextual data that can help with tracking and debugging.