OpenAI
Access 27 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/codex-mini-latest",
});
// 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);
}
Models
| Model | Image | Audio | Video | Tools | Streaming | Context Window |
|---|---|---|---|---|---|---|
openai/gpt-4.1-nano | ✓ | ✗ | ✗ | ✓ | ✗ | 1,047,576 |
openai/gpt-4 | ✗ | ✗ | ✗ | ✓ | ✗ | 8,192 |
openai/o1-pro | ✓ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/gpt-4o-2024-05-13 | ✓ | ✗ | ✗ | ✓ | ✗ | 128,000 |
openai/gpt-4o-2024-08-06 | ✓ | ✗ | ✗ | ✓ | ✗ | 128,000 |
openai/gpt-4.1-mini | ✓ | ✗ | ✗ | ✓ | ✗ | 1,047,576 |
openai/o3-deep-research | ✓ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/gpt-3.5-turbo | ✗ | ✗ | ✗ | ✗ | ✗ | 16,385 |
openai/gpt-4-turbo | ✓ | ✗ | ✗ | ✓ | ✗ | 128,000 |
openai/o1-preview | ✗ | ✗ | ✗ | ✗ | ✗ | 128,000 |
openai/o3-mini | ✗ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/codex-mini-latest | ✗ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/gpt-5-nano | ✓ | ✗ | ✗ | ✓ | ✗ | 400,000 |
openai/gpt-5-codex | ✓ | ✗ | ✗ | ✓ | ✗ | 400,000 |
openai/gpt-4o | ✓ | ✗ | ✗ | ✓ | ✗ | 128,000 |
openai/gpt-4.1 | ✓ | ✗ | ✗ | ✓ | ✗ | 1,047,576 |
openai/o4-mini | ✓ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/o1 | ✓ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/gpt-5-mini | ✓ | ✗ | ✗ | ✓ | ✗ | 400,000 |
openai/o1-mini | ✗ | ✗ | ✗ | ✗ | ✗ | 128,000 |
openai/o3-pro | ✓ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/gpt-4o-2024-11-20 | ✓ | ✗ | ✗ | ✓ | ✗ | 128,000 |
openai/o3 | ✓ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/o4-mini-deep-research | ✓ | ✗ | ✗ | ✓ | ✗ | 200,000 |
openai/gpt-5-chat-latest | ✓ | ✗ | ✗ | ✗ | ✗ | 400,000 |
openai/gpt-4o-mini | ✓ | ✗ | ✗ | ✓ | ✗ | 128,000 |
openai/gpt-5 | ✓ | ✗ | ✗ | ✓ | ✗ | 400,000 |
Advanced Configuration
Custom Headers
const agent = new Agent({
name: "custom-agent",
model: {
modelId: "codex-mini-latest",
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/o4-mini-deep-research"
: "openai/codex-mini-latest";
},
});
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
- yarn
- pnpm
- bun
npm install @ai-sdk/openai
yarn add @ai-sdk/openai
pnpm add @ai-sdk/openai
bun add @ai-sdk/openai