Skip to content

Migrate from the TypeScript Agents SDK to Python

cf-agents ports the agents package v0.25.0 and the AIChatAgent from @cloudflare/ai-chat. It speaks the same WebSocket protocol, so the same clients connect to it. This page lists what changes when you write the agent in Python.

Side by side

Python

from agents import Agent, callable


class Counter(Agent):
    initial_state = {"count": 0}

    @callable
    async def increment(self, by: int = 1) -> int:
        self.set_state({"count": self.state["count"] + by})
        return self.state["count"]

TypeScript

import { Agent, callable } from "agents";

export class Counter extends Agent<Env, { count: number }> {
  initialState = { count: 0 };

  @callable()
  async increment(by = 1) {
    this.setState({ count: this.state.count + by });
    return this.state.count;
  }
}

Names

Methods and hooks use snake_case. The common ones:

TypeScript Python
initialState, setState initial_state, set_state
validateStateChange, onStateChanged validate_state_change, on_state_changed
onStart, onRequest, onConnect, onMessage, onClose on_start, on_request, on_connect, on_message, on_close
shouldConnectionBeReadonly, getConnectionTags should_connection_be_readonly, get_connection_tags
scheduleEvery, getScheduleById, listSchedules schedule_every, get_schedule_by_id, list_schedules
getSchedule, getSchedules (deprecated) get_schedule_by_id, list_schedules, both async
getQueue, getQueues, dequeueAllByCallback get_queue, queue_items, dequeue_all_by_callback
runFiber, startFiber, onFiberRecovered run_fiber, start_fiber, on_fiber_recovered
keepAlive, keepAliveWhile keep_alive, keep_alive_while
routeAgentRequest, getAgentByName, getCurrentAgent route_agent_request, get_agent_by_name, get_current_agent
@callable() @callable or @callable(...)
this.retry(fn, options) await retry(fn, ...), a module function

URLs don't change. A class still answers at /agents/{kebab-case-name}/..., so existing clients keep working.

Options

Static class options become one frozen dataclass:

from datetime import timedelta

from agents import Agent, AgentOptions, RetryOptions


class Feeds(Agent):
    options = AgentOptions(
        keep_alive_interval=timedelta(seconds=10),
        retry=RetryOptions(max_attempts=5),
    )

Durations are a timedelta or a number of seconds, never milliseconds.

SQL

The this.sql tagged template becomes a call with ? placeholders:

rows = self.sql("SELECT * FROM notes WHERE id = ?", note_id)

Schedules and the queue

Callbacks can be methods as well as names. Both call the method with (payload, schedule) or (payload, item):

await self.schedule(60, self.remind, {"text": "stand up"})
await self.schedule(60, "remind", {"text": "stand up"})

Durable tasks

The taskDefinitions map becomes a @task decorator on a method. Start runs with await self.my_task.run(input). See Run durable tasks.

Chat replies

In TypeScript, onChatMessage returns a Response, usually from the AI SDK's streamText(...).toUIMessageStreamResponse(). In Python, on_chat_message is an async generator that yields text or typed chunks, and you call the model with your own client. There's no onFinish callback, so use on_chat_response. Cancellation replaces the abortSignal, so a stopped turn gets asyncio.CancelledError. See Build a chat agent.

Chat with tools

streamText({ model, tools }) maps to PydanticAIHarness. Pydantic AI runs the tool loop, and @tool methods are the tools.

Python

import pydantic_ai

from agents import Agent, tool
from agents.harness.pydantic_ai import PydanticAIHarness, WorkersAIModel


class Notes(Agent):
    def __init__(self, ctx, env):
        super().__init__(ctx, env)
        model = WorkersAIModel("@cf/qwen/qwen3-30b-a3b-fp8", binding=env.AI)
        agent = pydantic_ai.Agent(model, instructions="You keep the user's notes.")
        self.harness = self.use(PydanticAIHarness("notes", agent, target=self))

    @tool
    async def add_note(self, text: str) -> str:
        """Save a note."""
        return "Saved"

TypeScript

async onChatMessage() {
  return streamText({
    model: workersai("@cf/qwen/qwen3-30b-a3b-fp8"),
    messages: convertToModelMessages(this.messages),
    tools: { addNote },
  }).toUIMessageStreamResponse();
}

The harness stores the conversation itself, so it runs on Agent, not AIChatAgent. Call self.harness.prompt(text) for the reply, or session.stream(text) to stream it. See Run a Pydantic AI agent in a Durable Object.

Errors

The SDK's own exceptions subclass AgentsException, so except AgentsException catches them all. Misuse, such as a wrong argument type, raises TypeError, ValueError or RuntimeError instead.

Not ported

TypeScript Status
McpAgent and MCP's RPC transport Not ported. Use create_mcp_handler.
MCP's legacy SSE transport Not ported. add_mcp_server speaks Streamable HTTP.
Chat client tools and approvals Not ported. Server-side tools and approvals run in the Pydantic AI harness.
Recovery of interrupted chat turns Not ported.
props in routeAgentRequest and getAgentByName Not ported.
Think, voice, email, channels, workflows, browser Not ported.
Agents as tools, RoutedAgents Not ported.
Chat stall watchdog (chatStreamStallTimeoutMs) Not ported.
Cap'n Web transport Not ported.
Tracing spans Not ported. Structured events are.
Deprecated subAgent, abortSubAgent and related Use self.dynamic_agents.