Model Providers and Routing
Relevant source files
The following files were used as context for generating this wiki page:The Model Providers and Routing system in Mastra provides a unified, flexible interface for interacting with a wide range of Large Language Models (LLMs) from various providers. It abstracts away the complexity of handling different APIs, authentication methods, and configurations, allowing developers to switch between models and providers with minimal code changes. The core of this system is the model router, which uses a simple string format, "provider/model-name", to dynamically select and configure the appropriate LLM for a given task.
This system is designed for extensibility and resilience, supporting features like model fallbacks, dynamic model selection based on runtime context, and provider-specific configurations. It also includes a concept of "gateways," which are services that aggregate multiple underlying model providers. The entire ecosystem is managed through a central provider registry and supported by tooling for automatic documentation generation.
Sources: packages/core/scripts/generate-model-docs.ts:602-606, templates/template-docs-chatbot/README.md:38-40
Core Architecture
The system is built around a few key components: the Model Router, the Provider Registry, and Gateways. These work together to resolve a model identifier into a fully configured client ready to make API calls.
This diagram shows the high-level relationship between an Agent, the Model Router, the Provider Registry, and the final LLM Provider.
Model Router String
The primary way to specify a model is through a string with the format "provider/model-name". The Mastra framework parses this string to identify the provider and the specific model to use. This simple convention allows for easy configuration and dynamic switching between dozens of models across numerous providers.
Example usage in an Agent configuration:
import { Agent } from "@mastra/core/agent";
const agent = new Agent({
id: "my-agent",
model: "openai/gpt-4o-mini"
});
Sources: packages/core/scripts/generate-model-docs.ts:634-646, templates/template-pdf-questions/README.md:41-47
Provider Registry
The Provider Registry is a central JSON file (provider-registry.json) that contains configuration details for each supported provider. This includes the provider's name, API endpoint URL, the environment variable for the API key, and a list of available models. This registry is the single source of truth for the model router.
The system includes a script to automatically generate documentation from this registry, indicating its central role.
Sources: packages/core/scripts/generate-model-docs.ts:133-136, packages/core/scripts/generate-model-docs.ts:840-843
Gateways
Gateways are a special type of provider that aggregate models from multiple other providers. They offer features like unified access, caching, rate limiting, and failover. The system identifies certain providers as gateways, such as openrouter, netlify, and vercel.
These are treated similarly to direct providers but may have their own authentication and endpoint logic.
Sources: packages/core/scripts/generate-model-docs.ts:88-89, packages/core/scripts/generate-model-docs.ts:400-408
Model Resolution Flow
When a model is specified, the resolveModel function is responsible for parsing the configuration and returning a usable model object. This function can handle a simple model string, a complex model object, or a function that dynamically returns a model configuration.
The following diagram illustrates the logic within the resolveModel function.
This flow allows for great flexibility, from simple static configuration to complex, request-dependent dynamic model selection.
Sources: packages/agent-builder/src/utils.ts:100-103, packages/core/scripts/generate-model-docs.ts:723-736
Advanced Configuration
The system supports several advanced configuration patterns to provide more control and resilience.
Model Fallbacks
To build more resilient applications, you can provide an array of model configurations. If the primary model fails (e.g., due to a provider outage, rate limit, or timeout), Mastra will automatically retry the request with the next model in the fallback chain. Each model in the chain can have its own maxRetries count.
import { Agent } from '@mastra/core/agent';
const agent = new Agent({
id: 'resilient-assistant',
model: [
{
model: "openai/gpt-5",
maxRetries: 3,
},
{
model: "anthropic/claude-4-5-sonnet",
maxRetries: 2,
},
{
model: "google/gemini-2.5-pro",
maxRetries: 2,
},
],
});
Sources: packages/core/scripts/generate-model-docs.ts:792-814
Dynamic Model Selection
The model property can be a function that receives the requestContext. This allows for dynamic model selection based on runtime information, such as user identity, tenant configuration, or task complexity. This pattern is powerful for A/B testing, multi-tenant applications, or optimizing cost-performance trade-offs.
const agent = new Agent({
id: "dynamic-assistant",
name: "Dynamic Assistant",
model: ({ requestContext }) => {
const provider = requestContext.get("provider-id");
const model = requestContext.get("model-id");
return `${provider}/${model}`;
},
});
Sources: packages/core/scripts/generate-model-docs.ts:739-750, packages/core/scripts/generate-model-docs.ts:352-363
Provider-Specific Options
While Mastra provides a unified interface, it also allows you to pass provider-specific options using the providerOptions field. This can be done at the agent level (for all messages) or at the message level (for a single request). This enables access to unique features of each model provider, like reasoningEffort for OpenAI or cacheControl for Anthropic.
The system includes a script, generate-provider-options-docs.ts, which uses ts-morph to inspect the AI SDK's type definitions and automatically generate documentation for these options.
// Agent-level provider options
const planner = new Agent({
id: "planner",
instructions: {
role: "system",
content: "You are a helpful assistant.",
providerOptions: {
openai: { reasoningEffort: "low" }
}
},
model: "openai/o3-pro",
});
// Message-level provider options
const highEffort = await planner.generate([
{
role: "user",
content: "Plan a complex dinner menu.",
providerOptions: {
openai: { reasoningEffort: "high" }
}
}
]);
Sources: packages/core/scripts/generate-model-docs.ts:757-783, packages/core/scripts/generate-provider-options-docs.ts:13-19, packages/core/scripts/generate-provider-options-docs.ts:143-150
Custom Headers
You can specify custom HTTP headers for requests to a model provider. This is useful for passing organization IDs or other provider-specific metadata.
const agent = new Agent({
id: "custom-agent",
model: {
id: "openai/gpt-4-turbo",
apiKey: process.env.OPENAI_API_KEY,
headers: {
"OpenAI-Organization": "org-abc123"
}
}
});
Sources: packages/core/scripts/generate-model-docs.ts:339-350, packages/core/scripts/generate-model-docs.ts:786-790
Provider and Gateway Ecosystem
The framework is designed to support a wide variety of providers and gateways. The documentation generation scripts maintain lists of popular and gateway providers.
Popular Providers
These are direct integrations with major LLM providers.
| Provider Name | ID |
|---|---|
| OpenAI | openai |
| Anthropic | anthropic |
google | |
| DeepSeek | deepseek |
| Groq | groq |
| Mistral | mistral |
| xAI | xai |
Sources: packages/core/scripts/generate-model-docs.ts:85-85
Gateway Providers
These providers aggregate models from other sources.
| Gateway Name | ID |
|---|---|
| Netlify | netlify |
| OpenRouter | openrouter |
| Vercel | vercel |
| Azure OpenAI | azure-openai |
Sources: packages/core/scripts/generate-model-docs.ts:88-88
System Internals & Tooling
The provider system is supported by a set of scripts and conventions that automate maintenance and documentation.
Documentation Generation
The repository contains scripts like generate-model-docs.ts and generate-provider-options-docs.ts. These scripts parse the provider-registry.json and TypeScript type definitions from the AI SDK to automatically generate Markdown documentation for each provider, their models, and their specific configuration options. This ensures that the documentation stays in sync with the codebase.
The generate-model-docs.ts script fetches additional model metadata from https://models.dev/api.json, such as context window size, cost, and modalities (image, audio, etc.), to enrich the generated documentation.
Sources: packages/core/scripts/generate-model-docs.ts:1-5, packages/core/scripts/generate-provider-options-docs.ts:1-6, packages/core/scripts/generate-model-docs.ts:208-212
Conclusion
Mastra's Model Providers and Routing system is a powerful abstraction layer that simplifies the use of diverse LLMs. By standardizing the interface through the "provider/model-name" convention and a central registry, it allows developers to build flexible, resilient, and provider-agnostic AI applications. Advanced features like fallbacks, dynamic selection, and provider-specific options offer fine-grained control, while the underlying tooling ensures the system is maintainable and well-documented.