页面简介
Learn how to use middleware to enhance the behavior of language models
正文摘录
AI SDK CoreMenuLanguage Model MiddlewareCopy for LLMView MarkdownAsk AI about this pageLanguage 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 the wrapLanguageModel function. It takes a language model and a language model middleware and returns a new language model that incorporates the middleware. import { wrapLanguageModel, streamText } from 'ai'; const wrappedLanguageModel = wrapLanguageModel({ model: yourModel, middleware: yourLanguageModelMiddleware, }); The wrapped language model can be used just like any other language model, e.g. in streamText: const result = streamText({ model: wrappedLanguageModel, prompt: 'What cities are in the United States?', }); Multiple middlewares You can provide multiple middlewares to the wrapLanguageModel function. The middlewares will be applied in the order they are provided. const wrappedLanguageModel = wrapLanguageModel({ model: yourModel, middleware: [firstMiddleware, secondMiddleware], }); // applied as: firstMiddleware(secondMiddleware(yourModel)) 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 a reasoning property on the result. extractJsonMiddleware: Extracts JSON from text content by stripping markdown code fences. Useful when using Output.object() with models that wrap JSON responses in code blocks. simulateStreamingMiddleware: Simulates streaming behavior with responses from non-streaming language models. defaultInstructionsMiddleware: Applies default instructions when a call does not provide its own instructions. defaultSettingsMiddleware: Applies default settings to a language model. addToolInputExamplesMiddleware: Adds tool input examples to tool descriptions for providers that don't natively support the inputExamples property. Extract Reasoning Some providers and models expose reasoning information in the generated text using special tags, e.g. <think> and </think>. The extractReasoningMiddleware function can be used to extract this reasoning information and expose it as a reasoning property on the result. import { wrapLanguageModel, extractReasoningMiddleware } from 'ai'; const model = wrapLanguageModel({ model: yourModel, middleware: extractReasoningMiddleware({ tagName: 'think' }), }); You can then use that enhanced model in functions like 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. For more details, see the DeepSeek R1 guide. 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(). import { wrapLanguageModel, extractJsonMiddleware, Output, generateText, } from 'ai'; import { z } from 'zod'; const model = wrapLanguageModel({ model: yourModel, middleware: extractJsonMiddleware(), }); const result = await generateText({ model, output: Output.object({ schema: z.object({ name: z.string(), ingredients: z.array(z.string()), }), }), prompt: 'Generate a recipe.', }); You can also provide a custom transform function for models that use different formatting: const model = wrapLanguageModel({ model: yourModel, middleware: extractJsonMiddleware({ transform: text => text.replace(/^PREFIX/, '').replace(/SUFFIX$/, ''), }), }); Simulate Streaming The simulateStreamingMiddleware 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. import { wrapLanguageModel, simulateStreamingMiddleware } from 'ai'; const model = wrapLanguageModel({ model: yourModel, middleware: simulateStreamingMiddleware(), }); Default Settings The defaultSettingsMiddleware function can be used to apply default settings to a language model. import { wrapLanguageModel, defaultSettingsMiddleware } from 'ai'; const model = wrapLanguageModel({ model: yourModel, middleware: defaultSettingsMiddleware({ settings: { temperature: 0.5, maxOutputTokens: 800, providerOptions: { openai: { store: false } }, }, }), }); Default Instructions The defaultInstructionsMiddleware function applies instructions to calls that do not already contain a system message. Instructions provided directly on a call take precedence over the defaults. import { wrapLanguageModel, defaultInstructionsMiddleware } from 'ai'; const model = wrapLanguageModel({ model: yourModel, middleware: defaultInstructionsMiddleware({ instructions: 'You are a concise technical assistant.', }), }); The instructions option also accepts a SystemModelMessage or an array of SystemModelMessage objects when you need provider options on an instruction. The middleware treats any system message in the normalized prompt as call-level instructions and does not add the defaults. Only enable allowSystemInMessages for trusted message histories, because a system message in that history can override these defaults. Add Tool Input Examples The addToolInputExamplesMiddleware 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. import { wrapLanguageModel, addToolInputExamplesMiddleware } from 'ai'; const model = wrapLanguageModel({ model: yourModel, middleware: addToolInputExamplesMiddleware({ prefix: 'Input Examples:', }), }); When you define a tool with inputExamples, the middleware will append them to the tool's description: import { generateText, tool } from 'ai'; import { z } from 'zod'; const result = await generateText({ model, // wrapped model from above tools: { weather: tool({ description: 'Get the weather in a location', inputSchema: z.object({ location: z.string(), }), inputExamples: [ { input: { location: 'San Francisco' } }, { input: { location: 'London' } }, ], }), }, prompt: 'What is the weather in Tokyo?', }); The tool description will be transformed to: Get the weather in a location Input Examples: {"location":"San Francisco"} {"location":"London"} 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 the inputExamples property from the tool after adding them to the description. Default: true. const model = wrapLanguageModel({ model: yourModel, middleware: addToolInputExamplesMiddleware({ prefix: 'Input Examples:', format: (example, index) => `${index + 1}. ${JSON.stringify(example.input)}`, remove: true, }), }); Community Middleware The AI SDK provides a Language Model Middleware specification. Community members can develop middleware that adheres to this specification, making it compatible with the AI SDK ecosystem. Here are some community middlewares that you can explore: Custom tool call parser The Custom tool call parser middleware extends tool call capabilities to models that don't natively support the OpenAI-style tools parameter. This includes many self-hosted and third-party models that lack native function calling features. Using this middleware on models that support native function calls may result in unintended performance degradation, so check whether your model supports native function calls before deciding to use it. This middleware enables function calling capabilities by converting function schemas into prompt instructions and parsing the model's responses into structured function calls. It works by transforming the JSON function definitions into natural language instructions the model can understand, then analyzing the generated text to extract function call attempts. This approach allows developers to use the same function calling API across different model providers, even with models that don't natively support the OpenAI-style function calling format, providing a consistent function calling experience regardless of the underlying model implementation. The @ai-sdk-tool/parser package offers three middleware variants: createToolMiddleware: A flexible function for creating custom tool call middleware tailored to specific models hermesToolMiddleware: Ready-to-use middleware for Hermes & Qwen format function calls gemmaToolMiddleware: Pre-configured middleware for Gemma 3 model series function call format Here's how you can enable function calls with Gemma models that don't support them natively: import { wrapLanguageModel } from 'ai'; import { gemmaToolMiddleware } from '@ai-sdk-tool/parser'; const model = wrapLanguageModel({ model: openrouter('google/gemma-3-27b-it'), middleware: gemmaToolMiddleware, }); Find more examples at this link. Implementing Language Model Middleware Implementing language model middleware is advanced functionality and requires a solid understanding of the language model specification. You can implement any of the following three function to modify the behavior of the language model: transformParams: Transforms the parameters before they are passed to the language model, for both doGenerate and doStream. wrapGene