Integrate OpenRouter with Mastra to access a variety of AI models through a unified interface. This guide provides complete examples from basic setup to advanced configurations.
The simplest way to start is using the automatic project creation:
You’ll be guided through prompts to set up your project. For this example, select:
For detailed instructions on setting up a Mastra project manually or adding Mastra to an existing project, refer to the official Mastra documentation.
After creating your project with create-mastra, you’ll find a .env.development file in your project root. Since we selected OpenAI during setup but will be using OpenRouter instead:
.env.development fileOPENAI_API_KEY lineYou can also remove the @ai-sdk/openai package since we’ll be using OpenRouter instead:
After setting up your Mastra project, you’ll need to modify the agent files to use OpenRouter instead of the default OpenAI provider.
If you used create-mastra, you’ll likely have a file at src/mastra/agents/agent.ts or similar. Replace its contents with:
Also make sure to update your Mastra entry point at src/mastra/index.ts to use your renamed agent:
Once you’ve configured your agent to use OpenRouter, you can run the Mastra development server:
This will start the Mastra development server and make your agent available at:
http://localhost:4111/api/agents/assistant/generatehttp://localhost:4111The Mastra playground provides a user-friendly interface where you can interact with your agent and test its capabilities without writing any additional code.
You can also test the API endpoint using curl if needed:
The simplest way to integrate OpenRouter with Mastra is by using the OpenRouter AI provider with Mastra’s Agent system:
For more control over your OpenRouter requests, you can pass additional configuration options:
You can also pass provider-specific options in your requests:
OpenRouter gives you access to various models from different providers. Here’s how to use multiple models:
For more information and detailed documentation, check out these resources: