Skip to main content

Middleware Implementation

Middleware allows you to enhance the behavior of language models by intercepting and modifying calls. You can implement custom middleware for logging, caching, guardrails, RAG, and more.
Implementing middleware requires understanding of the language model specification.

Middleware Specification

Middleware implements the LanguageModelV3Middleware interface:

Middleware Methods

transformParams

Transforms parameters before they’re passed to the model:

wrapGenerate

Wraps the doGenerate method for non-streaming calls:

wrapStream

Wraps the doStream method for streaming calls:

Real-World Middleware Examples

Logging Middleware

Log all model interactions:

Caching Middleware

Cache model responses:

RAG Middleware

Add context from a vector database:

Guardrail Middleware

Filter sensitive information:

Retry Middleware

Add custom retry logic:

Composing Middleware

Combine multiple middleware:

Accessing Provider Metadata

Pass custom metadata to middleware:

Testing Middleware

Best Practices

  1. Always handle both generate and stream: Implement both wrapGenerate and wrapStream for consistent behavior
  2. Preserve stream characteristics: Don’t buffer entire streams in memory
  3. Handle errors gracefully: Wrap operations in try-catch blocks
  4. Document side effects: Clearly document any caching, logging, or external calls
  5. Make middleware configurable: Accept options for customization
  6. Test thoroughly: Test both success and error paths

Next Steps