AI (Workers AI / AI Gateway)
Cloudflare’s AI endpoints — Workers AI and AI Gateway — are OpenAI-compatible, and so is Ollama. The integration uses that to give you one Microsoft.Extensions.AI IChatClient/IEmbeddingGenerator that runs against local Ollama during development and Cloudflare in production — the connection string just changes the endpoint and model.
Add an AI resource (hosting)
Section titled “Add an AI resource (hosting)”builder.AddCloudflareEnvironment();
var ai = builder.AddCloudflareAI("ai", o =>{ o.ChatModel = "@cf/meta/llama-3.1-8b-instruct"; // Cloudflare model (prod) o.EmbeddingModel = "@cf/baai/bge-base-en-v1.5"; o.LocalChatModel = "llama3.2"; // Ollama model (dev) o.LocalEmbeddingModel = "all-minilm";}).RunAsEmulator();await builder.addCloudflareEnvironment();const ai = await builder.addCloudflareAI('ai', { configure: async options => { await options.chatModel.set('@cf/meta/llama-3.1-8b-instruct'); await options.embeddingModel.set('@cf/baai/bge-base-en-v1.5'); await options.localChatModel.set('llama3.2'); await options.localEmbeddingModel.set('all-minilm'); }}).runAsEmulator();aspire run→ with.RunAsEmulator(), a local Ollama server starts (shared across AI resources in the environment, with a persistent data volume) and pulls the configured local models. No Cloudflare credentials needed.aspire deploy→ the same code talks to Workers AI (or an AI Gateway, see below)..RunAsEmulator()only affects run mode.
Container vs. host-installed Ollama
Section titled “Container vs. host-installed Ollama”.RunAsEmulator() runs Ollama as a container (Docker required) — self-contained and consistent with the other emulators. If you’d rather use an Ollama installed on your machine (for example to use a native GPU without container passthrough, or to avoid Docker), call .RunOnHost() instead:
var ai = builder.AddCloudflareAI("ai", o => { /* models */ }) .RunOnHost(); // attach to a host-installed Ollama instead of a containerconst ai = await builder.addCloudflareAI('ai', { configure: async options => { /* configure models */ }}).runOnHost();Both give the same credential-free local dev loop and the same IChatClient/IEmbeddingGenerator; only the source of the Ollama server differs.
Routing through an AI Gateway
Section titled “Routing through an AI Gateway”Set a GatewayId to route through AI Gateway — caching, logging, rate limiting, and multi-provider models (anthropic/claude-*, openai/*, workers-ai/@cf/*). The gateway is provisioned at deploy.
var ai = builder.AddCloudflareAI("ai", o =>{ o.GatewayId = "my-gateway"; o.ChatModel = "anthropic/claude-3-5-sonnet"; // a Claude model, via the gateway}).RunAsEmulator();const ai = await builder.addCloudflareAI('ai', { configure: async options => { await options.gatewayId.set('my-gateway'); await options.chatModel.set('anthropic/claude-3-5-sonnet'); }}).runAsEmulator();Reference it from a service
Section titled “Reference it from a service”builder.AddProject<Projects.Api>("api").WithReference(ai);await builder.addProject('api', '../Api/Api.csproj').withReference(ai);Use it (client)
Section titled “Use it (client)”In the consuming project, register an IChatClient and/or IEmbeddingGenerator:
builder.AddCloudflareAIChatClient("ai");builder.AddCloudflareAIEmbeddingGenerator("ai");Then inject the standard Microsoft.Extensions.AI abstractions — identical code locally and in production:
app.MapPost("/chat", async (IChatClient chat, string prompt, CancellationToken ct) =>{ var response = await chat.GetResponseAsync(prompt, cancellationToken: ct); return Results.Ok(response.Text);});
app.MapPost("/embed", async (IEmbeddingGenerator<string, Embedding<float>> embedder, string text, CancellationToken ct) =>{ var embedding = await embedder.GenerateVectorAsync(text, cancellationToken: ct); return Results.Ok(embedding.ToArray());});How the endpoint is chosen
Section titled “How the endpoint is chosen”The client reads the connection string the AppHost injects:
Provider |
Endpoint | When |
|---|---|---|
Ollama |
http://…/v1 (local) |
aspire run with .RunAsEmulator() |
WorkersAI |
…/accounts/{id}/ai/v1 |
Deployed, no gateway |
AIGateway |
gateway.ai.cloudflare.com/v1/{id}/{gateway}/compat |
Deployed, with a gateway |
All three are OpenAI-compatible, so the OpenAI-backed IChatClient/IEmbeddingGenerator works against each unchanged.
Credentials
Section titled “Credentials”- API token (runtime + gateway provisioning): needs Workers AI: Read (and AI Gateway: Edit if you use a gateway) — see API Tokens. By default the client reuses the environment’s Cloudflare API token; scope it with
.WithAccessToken(parameter)if you prefer. - Local dev with
.RunAsEmulator(): none — Ollama runs locally with no key.
