Skip to main content

Cloudflare Workers AI logoCloudflare Workers AI

Access 7 Cloudflare Workers AI models through Mastra's model router. Authentication is handled automatically using the CLOUDFLARE_API_KEY environment variable. Configure CLOUDFLARE_ACCOUNT_ID as well.

Learn more in the Cloudflare Workers AI documentation.

.env
CLOUDFLARE_ACCOUNT_ID=your-account-id
CLOUDFLARE_API_KEY=your-api-key
src/mastra/agents/my-agent.ts
import { Agent } from "@mastra/core/agent";

const agent = new Agent({
id: "my-agent",
name: "My Agent",
instructions: "You are a helpful assistant",
model: "cloudflare-workers-ai/@cf/google/gemma-4-26b-a4b-it"
});

// 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);
}
info

Mastra uses the OpenAI-compatible /chat/completions endpoint. Some provider-specific features may not be available. Check the Cloudflare Workers AI documentation for details.

Models
Direct link to Models

ModelContextToolsReasoningImageAudioVideoInput $/1MOutput $/1M
cloudflare-workers-ai/@cf/google/gemma-4-26b-a4b-it256K$0.10$0.30
cloudflare-workers-ai/@cf/meta/llama-4-scout-17b-16e-instruct128K$0.27$0.85
cloudflare-workers-ai/@cf/moonshotai/kimi-k2.5256K$0.60$3
cloudflare-workers-ai/@cf/nvidia/nemotron-3-120b-a12b256K$0.50$2
cloudflare-workers-ai/@cf/openai/gpt-oss-120b128K$0.35$0.75
cloudflare-workers-ai/@cf/openai/gpt-oss-20b128K$0.20$0.30
cloudflare-workers-ai/@cf/zai-org/glm-4.7-flash131K$0.06$0.40
7 available models

Advanced configuration
Direct link to Advanced configuration

Custom headers
Direct link to Custom headers

src/mastra/agents/my-agent.ts
const agent = new Agent({
id: "custom-agent",
name: "custom-agent",
model: {
url: "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1",
id: "cloudflare-workers-ai/@cf/google/gemma-4-26b-a4b-it",
apiKey: process.env.CLOUDFLARE_API_KEY,
headers: {
"X-Custom-Header": "value"
}
}
});

Dynamic model selection
Direct link to Dynamic model selection

src/mastra/agents/my-agent.ts
const agent = new Agent({
id: "dynamic-agent",
name: "Dynamic Agent",
model: ({ requestContext }) => {
const useAdvanced = requestContext.task === "complex";
return useAdvanced
? "cloudflare-workers-ai/@cf/zai-org/glm-4.7-flash"
: "cloudflare-workers-ai/@cf/google/gemma-4-26b-a4b-it";
}
});
On this page