Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Agent AI SDK Model Provider, Tool Pattern, and Migration

How Cloudflare Agents SDK wires Workers AI and AI Gateway into the AI SDK via createAI, tools, streaming, and v5-to-v6 migration.

This page summarizes Cloudflare documentation on connecting the Agents SDK to the Vercel AI SDK: choosing models with createAI, calling them from agents and chat handlers, handling tools and streaming, and moving off deprecated workers-ai-provider / ai-gateway-provider packages as AI SDK versions advance.

createAI: one factory for Workers AI, AI Gateway, and vendor models

Section titled “createAI: one factory for Workers AI, AI Gateway, and vendor models”

createAI from agents/models/ai-sdk is the current entry point for text generation, tools, structured output, embeddings, images, speech, transcription, and reranking in agent code that uses the AI SDK.

The Agents SDK has a new createAI function for the AI SDK and Pi AI. It unifies what workers-ai-provider and ai-gateway-provider did: Workers AI models, AI Gateway catalog models, dynamic routes, and vendor models, through the AI binding or an account id and API token.

— Cloudflare, createAI replaces workers-ai-provider and ai-gateway-provider

workers-ai-provider and ai-gateway-provider are feature-frozen and deprecated; Workers AI AI SDK configuration directs new work to createAI. For AI Search, the cluster points to ai-search-provider and createAISearchNamespace instead of createAISearch from the old Workers AI provider package.

With createAI you can:

  • Pass Workers AI ids (@cf/...), AI Gateway catalog ids, or dynamic routes (dynamic/<route>).
  • Pass vendor model objects from official AI SDK packages; they are sent to AI Gateway’s provider-native endpoint unchanged.
  • Authenticate with the Worker AI binding, or accountId + apiToken for cross-account gateway use or calls from outside a Worker.
  • Set gateway options: caching, logging, metadata, retries, fallback, BYOK (byokAlias, vendorKey), and zero data retention (zdr).
  • Resume dropped streams for catalog or dynamic routes when using the binding.
Before (deprecated) After (createAI)
createWorkersAI({ binding }) createAI({ binding })
createWorkersAI({ accountId, apiKey }) createAI({ accountId, apiToken })
createAiGateway(...) createAI(...), with fallback for model lists
createAISearch from workers-ai-provider createAISearchNamespace from ai-search-provider

Minimal pattern from the createAI changelog and Using AI Models:

import { createAI } from "agents/models/ai-sdk";
import { streamText } from "ai";
const ai = createAI({ binding: env.AI, id: "my-gateway" });
const result = streamText({
model: ai("anthropic/claude-opus-5.5", {
fallback: ["@cf/zai-org/glm-4.7-flash"],
}),
prompt: "Write a haiku about Durable Objects",
});

In a Think class, return the model from getModel() as shown in AI SDK models:

import { createAI } from "agents/models/ai-sdk";
getModel() {
return createAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.7-code");
}

createAI implements a ProviderV4-style registry: it works with createProviderRegistry and can be set as globalThis.AI_SDK_DEFAULT_PROVIDER so bare model strings resolve through Cloudflare routing.

AI binding: configure Workers AI on the agent runtime

Section titled “AI binding: configure Workers AI on the agent runtime”

Agents that call env.AI.run directly (without the AI SDK) need an ai binding in Wrangler, as described in Configuration and Using AI Models:

{
"ai": {
"binding": "AI"
}
}

The same binding is passed into createAI({ binding: this.env.AI }) for AI SDK calls. Workers AI supports stream: true on AI.run when you want native binding streaming instead of streamText.

Chat agents: streamText, async messages, and UI streams

Section titled “Chat agents: streamText, async messages, and UI streams”

Chat agents use AIChatAgent, createAI, and AI SDK streaming APIs. With AI SDK v6, convertToModelMessages() is async—every call must be awaited:

The convertToModelMessages() function is now asynchronous. Update all calls to await the result:

— Cloudflare, Agents SDK v0.3.0 with AI SDK v6 support

const result = streamText({
model: ai("@cf/zai-org/glm-4.7-flash"),
messages: await convertToModelMessages(this.messages),
});
return result.toUIMessageStreamResponse();

You can merge LLM output with custom data parts via createUIMessageStream and writer.write() (same doc). For guardrails, RAG, or logging without changing chat logic, wrap the language model with wrapLanguageModel and middleware from the AI SDK (examples on the chat agents page).

You may still use OpenAI, Anthropic, or other AI SDK adapters with the same convertToModelMessages pattern; the Agents docs treat createAI as one provider among many.

Cloudflare shipped Agents SDK v0.1.0 with AI SDK v5 (changelog) and Agents SDK v0.3.0 with AI SDK v6 (changelog). Pair package versions accordingly when upgrading.

Message parts and legacy format migration (v5)

Section titled “Message parts and legacy format migration (v5)”

AI SDK v5 UI messages use a parts array instead of a single content string. The v0.1.0 Agents release adds automatic message migration so v4-style content and toolInvocations convert to v5 parts without manual rewrites (same v5 changelog).

Typical sendMessage shapes:

sendMessage({
role: "user",
parts: [{ type: "text", text: "Hello, assistant!" }],
});

Import updates for React hooks: UIMessage replaces Message; useChat comes from @ai-sdk/react instead of ai/react (v5 changelog).

Unified server tools and breaking changes (v6)

Section titled “Unified server tools and breaking changes (v6)”

AI SDK v6 introduces a unified tool pattern where all tools are defined on the server using the tool() function. This replaces the previous client-side AITool pattern.

— Cloudflare, Agents SDK v0.3.0 with AI SDK v6 support

Summary of v6-related changes called out in that release:

Area Change
Tools Define with tool() on the server; use needsApproval instead of toolsRequiringConfirmation
UI messages → model await convertToModelMessages(...)
Types CoreMessage removed; use ModelMessage
Structured JSON generateObject mode removed; prefer generateText / streamText with Output.object() and stopWhen (structured output is its own step)
Tool UI helpers isToolUIPart / getToolName include dynamic tools; use isStaticToolUIPart / getStaticToolName for v5-style static-only checks
Submitting tool results addToolResult() → addToolOutput()

Agents SDK v0.3.0 adds dynamic tool approval and an onToolCall callback on React hooks for human-in-the-loop flows (v6 changelog).

Tool confirmation: detect pending approval in the UI

Section titled “Tool confirmation: detect pending approval in the UI”

For human-in-the-loop flows, detect tool parts waiting for user confirmation by scanning messages for tool UI parts in state input-available:

const pendingToolCallConfirmation = messages.some((m) =>
m.parts?.some(
(part) => isToolUIPart(part) && part.state === "input-available",
),
);

On approval, submit output with addToolOutput (v6) or addToolResult (v5-era examples in Agents SDK v0.1.0 changelog). MCP-backed agents can expose remote tools via this.mcp.getAITools() (MCP Client API), namespaced by server id for streamText tool sets.

Later workers-ai-provider releases (e.g. v3.1.1, changelog) fixed token-by-token streaming, tool-call id handling, and reporting finishReason: "error" when a stream ends unexpectedly instead of silently returning "stop". The same capabilities are described as part of the unified createAI provider going forward.

Use streamText with onChunk when you need chunk-level logging or warning handling (v5/v6 changelogs).

Send multimodal input with parts that include file (or image in v5 examples); the Workers AI / createAI stack converts to the model’s expected format (v6 changelog).

Before full migration to createAI, workers-ai-provider v3.1.1 added provider.transcription(), provider.speech(), and provider.reranking() for Whisper, Aura TTS, and reranker models (GLM-4.7-Flash changelog). The Models overview states the AI SDK-facing factory supports these modalities through the same gateway path.

The same createAI options apply to agents/models/pi-ai (Pi harness streaming) and a separate agents/models/opencode path for OpenCode (Models, Pi AI). Pick agents/models/ai-sdk when you use generateText, streamText, or Think.

Common mistakes when wiring Agents to the AI SDK

Section titled “Common mistakes when wiring Agents to the AI SDK”
  • Calling convertToModelMessages without await after moving to AI SDK v6 (v6 changelog).
  • Defining tools only on the client after v6; server tool() definitions are required for the unified pattern.
  • Still installing workers-ai-provider for new apps; Vercel AI SDK on Workers AI says to use createAI instead.
  • Using addToolResult after upgrading hooks to v6 semantics; rename to addToolOutput (chat agents deprecations).
  • Forgetting the ai binding in Wrangler when mixing raw env.AI.run and createAI in one project (Configuration).
  • Structured output with generateText + Output.object() without stopWhen / multi-step config when the model needs an extra step (v6 changelog).

Model reference

Catalog, gateway routing, and provider comparison: Models.

Calling LLMs concepts

Provider overview for agent authors: Calling LLMs.

  1. Confirm Wrangler defines an ai binding and that createAI({ binding: env.AI }) resolves a known model id in a minimal generateText or streamText call per Using AI Models.

  2. If you use AI Gateway, verify gateway id, fallbacks, and logging in a test Worker using the pattern from createAI replaces workers-ai-provider and ai-gateway-provider.

  3. For chat UIs, exercise tool approval: confirm pending state with input-available parts and that approval submits via addToolOutput following Chat agents.

  4. After any AI SDK major upgrade, cross-check Agents SDK release notes (v5 / v6) for deprecated APIs still present in your codebase.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match your project or the linked Cloudflare docs, email yimasynthetic@gmail.com with the page URL and the exact sentence you believe is wrong so it can be corrected.