Build your first Python agent on Cloudflare Workers
This guide builds a counter agent. Each counter has a name, keeps its count between requests, and pushes every change to connected clients. It takes about ten minutes.
Prerequisites
uvand Node.js 22 or later.- Python 3.12 or later.
cf-agentsdoesn't install on older versions. - A Cloudflare account. The free plan works.
1. Create a Python Worker
uvx --from workers-py pywrangler init
cd hello-agents # the directory you chose during init
uv add cf-agents
Check that pyproject.toml now lists cf-agents under dependencies.
2. Write the agent
Replace src/entry.py:
from workers import Request, Response, WorkerEntrypoint
from agents import Agent, callable, route_agent_request
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"]
async def on_request(self, request: Request) -> Response:
if request.method == "POST":
await self.increment()
return Response.json(self.state)
class Default(WorkerEntrypoint):
async def fetch(self, request: Request) -> Response:
response = await route_agent_request(request, self.env)
if response is None:
return Response("Not found", status=404)
return response
initial_stateis the state a new counter starts with.set_state()saves the new state and sends it to every connected client.@callablelets a client callincrementover its WebSocket.on_requestanswers plain HTTP requests to the agent.route_agent_requestsends/agents/counter/{name}to the counter called{name}, and returnsNonefor any other path.
3. Configure Wrangler
Replace the Wrangler config with one of these:
{
"name": "hello-agents",
"main": "src/entry.py",
"compatibility_date": "2026-07-20",
"compatibility_flags": ["python_workers"],
"durable_objects": {
"bindings": [{ "class_name": "Counter", "name": "Counter" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }]
}
name = "hello-agents"
main = "src/entry.py"
compatibility_date = "2026-07-20"
compatibility_flags = ["python_workers"]
[[durable_objects.bindings]]
class_name = "Counter"
name = "Counter"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["Counter"]
# cloudflare.config.py needs Wynd: run `uvx wynd dev` in place of `pywrangler dev`.
from wynd.config import Config, Worker, bindings, exports
config = Config(
worker=Worker(
name="hello-agents",
entrypoint="src/entry.py",
compatibility_date="2026-07-20",
env={"Counter": bindings.DurableObject("Counter")},
exports={"Counter": exports.DurableObject()},
),
)
Each agent class needs a Durable Object
binding
and a migration
that creates it as a SQLite-backed class. route_agent_request finds the agent by the
binding's name, converted to kebab case, so the binding Counter answers at
/agents/counter/.... In cloudflare.config.py, the env and exports
entries take the place of both, as
Write config in Python explains.
4. Run it locally
uv run pywrangler dev
In another terminal, increment a counter called my-counter twice:
curl -X POST http://localhost:8787/agents/counter/my-counter
curl -X POST http://localhost:8787/agents/counter/my-counter
{"count": 1}
{"count": 2}
A different name is a different counter, with its own state:
curl http://localhost:8787/agents/counter/other
{"count": 0}
If you get something else, check these in order:
Not found(404) comes from yourDefault.fetch. The path doesn't start with/agents/.Invalid request(400) meanscountermatches no binding. Check the binding'snameinwrangler.jsonc.Not implemented(404) means the request reached the agent, but the class has noon_request.
Troubleshooting lists more errors.
5. Call it from a client
Browsers and Node.js connect with the agents npm package. Create a separate
folder for the client and install it:
mkdir client && cd client
npm init -y
npm install agents
import { AgentClient } from "agents/client";
const client = new AgentClient({
agent: "Counter",
name: "my-counter",
host: "localhost:8787",
onStateUpdate: (state) => console.log("state:", state),
});
const count = await client.call("increment", [10]);
console.log("increment returned", count);
client.close();
node client.mjs
state: { count: 2 }
state: { count: 12 }
increment returned 12
The client receives the current state when it connects, then the new state
after increment runs. In React, the
useAgent hook does the same.
6. Deploy
From the Worker folder:
uv run pywrangler deploy
Wrangler prints the Worker's URL. Send the same curl request to it, and set
host in the client to that hostname.
Next steps
- Store and sync state to type the state, validate changes and store rows in SQLite.
- Connect clients to call methods from React and stream results.
- Build a chat agent to stream replies from a model.