OpenAI
Access 25 OpenAI models through Mastra’s model router. Authentication is handled automatically using the OPENAI_API_KEY
environment variable.
Learn more in the OpenAI documentation .
OPENAI_API_KEY=your-api-key
import { Agent } from "@mastra/core";
const agent = new Agent({
name: "my-agent",
instructions: "You are a helpful assistant",
model: "openai/gpt-3.5-turbo"
});
// Generate a response
const response = await agent.generate("Hello!");
// Stream a response
const stream = await agent.stream("Tell me a story");
for await (const chunk of stream) {
console.log(chunk);
}
Mastra uses the OpenAI-compatible /chat/completions
endpoint. Some provider-specific features may not be available. Check the OpenAI documentation for details.
Models
Model | Context | Tools | Reasoning | Image | Audio | Video | Input $/1M | Output $/1M |
---|---|---|---|---|---|---|---|---|
openai/gpt-4.1-nano | 1.0M | $0.10 | $0.40 | |||||
openai/gpt-4 | 8K | $30 | $60 | |||||
openai/o1-pro | 200K | $150 | $600 | |||||
openai/gpt-4o-2024-05-13 | 128K | $5 | $15 | |||||
openai/gpt-4o-2024-08-06 | 128K | $3 | $10 | |||||
openai/gpt-4.1-mini | 1.0M | $0.40 | $2 | |||||
openai/o3-deep-research | 200K | $10 | $40 | |||||
openai/gpt-3.5-turbo | 16K | $0.50 | $2 | |||||
openai/gpt-4-turbo | 128K | $10 | $30 | |||||
openai/o1-preview | 128K | $15 | $60 | |||||
openai/o3-mini | 200K | $1 | $4 | |||||
openai/codex-mini-latest | 200K | $2 | $6 | |||||
openai/gpt-5-nano | 400K | $0.05 | $0.40 | |||||
openai/gpt-5-codex | 400K | — | — | |||||
openai/gpt-4o | 128K | $3 | $10 | |||||
openai/gpt-4.1 | 1.0M | $2 | $8 | |||||
openai/o4-mini | 200K | $1 | $4 | |||||
openai/o1 | 200K | $15 | $60 | |||||
openai/gpt-5-mini | 400K | $0.25 | $2 | |||||
openai/o1-mini | 128K | $1 | $4 | |||||
openai/o3-pro | 200K | $20 | $80 | |||||
openai/gpt-4o-2024-11-20 | 128K | $3 | $10 | |||||
openai/o3 | 200K | $2 | $8 | |||||
openai/o4-mini-deep-research | 200K | $2 | $8 | |||||
openai/gpt-5-chat-latest | 400K | $1 | $10 | |||||
openai/gpt-4o-mini | 128K | $0.15 | $0.60 | |||||
openai/gpt-5 | 400K | $1 | $10 |
Advanced Configuration
Custom Headers
const agent = new Agent({
name: "custom-agent",
model: {
url: "https://api.openai.com/v1/chat/completions",
modelId: "gpt-3.5-turbo",
apiKey: process.env.OPENAI_API_KEY,
headers: {
"X-Custom-Header": "value"
}
}
});
Dynamic Model Selection
const agent = new Agent({
name: "dynamic-agent",
model: ({ runtimeContext }) => {
const useAdvanced = runtimeContext.task === "complex";
return useAdvanced
? "openai/gpt-3.5-turbo"
: "openai/gpt-4";
}
});
Direct Provider Installation
This provider can also be installed directly as a standalone package, which can be used instead of the Mastra model router string. View the package documentation for more details.
npm install @ai-sdk/openai