Skip to main content

  cf-agents

Cloudflare Agents for Python Workers

PyPI - Version pypi

Use cf-agents to keep state, schedule work and serve WebSocket clients from a Python Worker.

What it does

  • The SDK provides a typed, async API for Python 3.12 or later.
  • The SDK makes the JavaScript runtime calls from your Python code.
  • The API and behaviour match the TypeScript Agents SDK, so TypeScript clients such as useAgent connect unchanged.

Install

Create a project with uv and pywrangler, then add the package. Wynd also works.

$ uvx --from workers-py pywrangler init
$ uv add cf-agents

Quickstart

This example runs a team's daily lunch vote. Its Agent keeps state, runs schedules and exposes @callable methods to WebSocket clients. Replace search_menus_by_agent and choose_winners with your own code.

from typing import TypedDict

from agents import Agent, Schedule, callable, route_agent_request
from workers import WorkerEntrypoint, Request, Response

from utils import search_menus_by_agent, choose_winners

MODEL = "@cf/zai-org/glm-4.7-flash"
SYSTEM_PROMPT = """
You help deliver results to a bunch of co-workers who are choosing lunch together.
The user is going to provide you with the options.
Your task is to make the choice sound exciting so people who voted for something
else feel validated.
"""


class Restaurant(TypedDict):
    cuisine: str
    name: str
    address: str


class Vote(TypedDict):
    username: str
    restaurant_name: str


class LunchState(TypedDict):
    office_address: str
    todays_votes: list[Vote]
    todays_ruling: str | None
    restaurants: list[Restaurant]


class LunchAgent(Agent[LunchState]):
    initial_state = LunchState(
        office_address="County Hall, London",
        todays_votes=[],
        todays_ruling=None,
        restaurants=[],
    )

    async def on_start(self) -> None:
        # Cron expressions, evaluated in UTC
        await self.schedule("30 23 * * 1-5", self.choose_lunch)
        await self.schedule("0 17 * * *", self.reset_lunch)

    @callable
    async def nominate_restaurant(self, restaurant_name: str) -> None:
        # A Workflow researches the restaurant, stores its menu in
        # Vectorize, then updates this agent's list of restaurants
        await self.env.RESTAURANT_RESEARCHER_WORKFLOW.create(
            {
                "params": {
                    "restaurantName": restaurant_name,
                    "agent": self.name,
                    "near": self.state["office_address"],
                }
            }
        )

    @callable
    async def search_restaurants(self, query: str) -> list[str]:
        # Vector search, filtered by metadata to this agent's menus
        results = await search_menus_by_agent(query, self.name)
        return [result["metadata"]["restaurantName"] for result in results]

    @callable
    async def vote(self, username: str, restaurant_name: str) -> None:
        state = self.state
        vote = Vote(username=username, restaurant_name=restaurant_name)
        votes = [*state["todays_votes"], vote]
        # Broadcasts the new state to every connected eater
        self.set_state({**state, "todays_votes": votes})

    async def reset_lunch(self, payload: None, schedule: Schedule) -> None:
        self.set_state({**self.state, "todays_votes": [], "todays_ruling": None})

    async def choose_lunch(self, payload: None, schedule: Schedule) -> None:
        winners = choose_winners(self.state["todays_votes"])
        result = await self.env.AI.run(
            MODEL,
            {
                "messages": [
                    {"role": "system", "content": SYSTEM_PROMPT},
                    {"role": "user", "content": ", ".join(winners)},
                ]
            },
        )
        self.set_state({**self.state, "todays_ruling": result.response})


class Default(WorkerEntrypoint):
    async def fetch(self, request: Request) -> Response:
        response = await route_agent_request(request, self.env)
        return response or Response("Not Found", status=404)

For a chat agent that stores messages and streams model replies, use AIChatAgent.

Goals

cf-agents has one maintainer, so the scope is limited. Planned:

  • MCP
  • Channels
  • Integration with Agent Traces
  • A harness/opinionated framework, similar to Think
  • Integrations with popular Agent libraries in the Python eco-system (such as LangChain or CrewAI)

Some of these need changes to the Python Workers runtime first. A Python Worker also exceeds the free plan's limits easily today.

Links

Metadata

Release files for cf-agents 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cf-agents 0.3.0
File Size Uploaded Provenance Actions
cf_agents-0.3.0.tar.gz 284.3 kB Without provenance Details for cf_agents-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cf-agents 0.3.0
File Interpreter ABI Platform Actions
cf_agents-0.3.0-py3-none-any.whl Python 3 none any Details for cf_agents-0.3.0-py3-none-any.whl

Total release size: 627.0 kB

Release files / cf_agents-0.3.0.tar.gz

Download URL cf_agents-0.3.0.tar.gz
Size 284.3 kB
Tags Source
SHA-256 checksum
How to use checksums
2a9489e86555984c36e7d68842104bee627791b9bac0b3e2fdb0bb6bc1541224
BLAKE2b-256 checksum
How to use checksums
fe1117f34afe2d614bcc24051a64bb6f1bb3c5c8125bb0175eddc96c125c366d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / cf_agents-0.3.0-py3-none-any.whl

Download URL cf_agents-0.3.0-py3-none-any.whl
Size 342.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
773e425a187075f167f67b30536c6bfd50913e91f5bacf50689c2f06698f1d62
BLAKE2b-256 checksum
How to use checksums
8a2b68df190ccce587ebde5e826c81bb46d3db1f05dfc2ad348ce78c4874a505
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for cf-agents 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page