Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
2062d62
wip
elithrar Feb 23, 2025
36db5d8
Merge branch 'production' into agents-1.0
elithrar Feb 23, 2025
63eaf79
WIP - fixing typos (#20203)
rita3ko Feb 23, 2025
eee0530
onward
elithrar Feb 23, 2025
84eef5f
add tools and human loop images
rita3ko Feb 23, 2025
7416e63
limits, schedules
elithrar Feb 23, 2025
4b6b372
fix config title
elithrar Feb 23, 2025
220e6c0
fix
elithrar Feb 23, 2025
32be3ca
fix config
elithrar Feb 23, 2025
60d0f2f
websockets
elithrar Feb 24, 2025
9635010
fix closing tag
elithrar Feb 24, 2025
b67a3c6
caution
elithrar Feb 24, 2025
3363272
Apply suggestions from code review
Oxyjun Feb 24, 2025
c43f550
state state state
elithrar Feb 24, 2025
7267caf
sql API yo yo yo
elithrar Feb 24, 2025
f9f6c4e
agents: Apply suggestions from code review
elithrar Feb 24, 2025
99cbca4
fix sidebar ordering
elithrar Feb 24, 2025
afc175d
fix sidebar
elithrar Feb 24, 2025
51c6167
state
elithrar Feb 24, 2025
4b9864a
update overview
rita3ko Feb 24, 2025
68928f6
ai models
elithrar Feb 24, 2025
731d6bb
guides, ai models
elithrar Feb 24, 2025
f7c6141
Merge branch 'production' into agents-1.0
elithrar Feb 24, 2025
34667bc
d1
elithrar Feb 24, 2025
2747050
useAgent
elithrar Feb 24, 2025
e8f3978
fix 'er up
elithrar Feb 24, 2025
1036423
browse, fix syntax
elithrar Feb 24, 2025
fbe1d28
testing
elithrar Feb 24, 2025
4c835c9
fix
elithrar Feb 24, 2025
ba11185
fix
elithrar Feb 25, 2025
c90c75c
workflows
elithrar Feb 25, 2025
ae05a2e
@cloudflare/agents -> agents-sdk
elithrar Feb 25, 2025
6aa1260
fix links
elithrar Feb 25, 2025
2001aa1
fix ordering + testing title
elithrar Feb 25, 2025
196a5ba
update index
rita3ko Feb 25, 2025
23c5fee
update index
rita3ko Feb 25, 2025
4fc9c2f
headers
elithrar Feb 25, 2025
71b07d9
remove updated
elithrar Feb 25, 2025
73f6421
index.mdx
elithrar Feb 25, 2025
4b22f32
callback
elithrar Feb 25, 2025
3740f53
rag
elithrar Feb 25, 2025
f09fa7e
fin
elithrar Feb 25, 2025
2d777dd
fix links
elithrar Feb 25, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7,363 changes: 7,363 additions & 0 deletions src/assets/images/agents/agent-workflow.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7,356 changes: 7,356 additions & 0 deletions src/assets/images/agents/co-pilot.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7,367 changes: 7,367 additions & 0 deletions src/assets/images/agents/human-in-the-loop.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7,348 changes: 7,348 additions & 0 deletions src/assets/images/agents/workflow-automation.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ products:
date: 2025-02-14T19:00:00Z
---

We've added an [example prompt](/agents/build/prompts/) to help you get started with building AI agents and applications on Cloudflare [Workers](/workers/), including [Workflows](/workflows/), [Durable Objects](/durable-objects/), and [Workers KV](/kv/).
We've added an [example prompt](/workers/get-started/prompting/) to help you get started with building AI agents and applications on Cloudflare [Workers](/workers/), including [Workflows](/workflows/), [Durable Objects](/durable-objects/), and [Workers KV](/kv/).

You can use this prompt with your favorite AI model, including Claude 3.5 Sonnet, OpenAI's o3-mini, Gemini 2.0 Flash, or Llama 3.3 on Workers AI. Models with large context windows will allow you to paste the prompt directly: provide your own prompt within the `<user_prompt></user_prompt>` tags.

Expand Down
72 changes: 72 additions & 0 deletions src/content/docs/agents/api-reference/configuration.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
title: Configuration
pcx_content_type: concept
sidebar:
order: 3
---

import { MetaInfo, Render, Type, WranglerConfig } from "~/components";

An Agent is configured like any other Cloudflare Workers project, and uses [a wrangler configuration](/workers/wrangler/configuration/) file to define where your code is and what services (bindings) it will use.

The typical file structure for an Agent project created from `npm create cloudflare@latest -- --template cloudflare/agents` follows:

```sh
.
|-- package-lock.json
|-- package.json
|-- public
| `-- index.html
|-- src
| `-- index.ts // your Agent definition
|-- test
| |-- index.spec.ts // your tests
| `-- tsconfig.json
|-- tsconfig.json
|-- vitest.config.mts
|-- worker-configuration.d.ts
`-- wrangler.jsonc // your Workers & Agent configuration
```

Below is a minimal `wrangler.jsonc` file that defines the configuration for an Agent, including the entry point, `durable_object` namespace, and code `migrations`:

<WranglerConfig>

```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "agents-example",
"main": "src/index.ts",
"compatibility_date": "2025-02-23",
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [
{
// Required:
"name": "MyAgent", // How your Agent is called from your Worker
"class_name": "MyAgent", // Must match the class name of the Agent in your code
// Optional: set this if the Agent is defined in another Worker script
"script_name": "the-other-worker"
},
],
},
"migrations": [
{
"tag": "v1",
// Mandatory for the Agent to store state
"new_sqlite_classes": ["MyAgent"],
},
],
"observability": {
"enabled": true,
},
}
```

</WranglerConfig>

The configuration includes:

- A `main` field that points to the entry point of your Agent, which is typically a TypeScript (or JavaScript) file.
- A `durable_objects` field that defines the [Durable Object namespace](/durable-objects/reference/glossary/) that your Agents will run within.
- A `migrations` field that defines the code migrations that your Agent will use. This field is mandatory and must contain at least one migration. The `new_sqlite_classes` field is mandatory for the Agent to store state.
12 changes: 12 additions & 0 deletions src/content/docs/agents/api-reference/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
title: API Reference
pcx_content_type: navigation
sidebar:
order: 5
group:
hideIndex: true
---

import { DirectoryListing } from "~/components"

<DirectoryListing />
162 changes: 162 additions & 0 deletions src/content/docs/agents/api-reference/sdk.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
---
title: Agents SDK
pcx_content_type: concept
sidebar:
order: 2

---

import { MetaInfo, Render, Type, TypeScriptExample, WranglerConfig } from "~/components";

At its most basic, an Agent is a JavaScript class that extends the `Agent` class from the `agents-sdk` package. An Agent encapsulates all of the logic for an Agent, including how clients can connect to it, how it stores state, the methods it exposes, and any error handling.

<TypeScriptExample>

```ts
import { Agent } from "agents-sdk";

class MyAgent extends Agent {
// Define methods on the Agent
}

export default MyAgent;
```

</TypeScriptExample>

An Agent can have many (millions of) instances: each instance is a separate micro-server that runs independently of the others. This allows Agents to scale horizontally: an Agent can be associated with a single user, or many thousands of users, depending on the agent you're building.

Instances of an Agent are addressed by a unique identifier: that identifier (ID) can be the user ID, an email address, GitHub username, a flight ticket number, an invoice ID, or any other identifier that helps to uniquely identify the instance and for whom it is acting on behalf of.

## The Agent class

Writing an Agent requires you to define a class that extends the `Agent` class from the `agents-sdk` package. An Agent encapsulates all of the logic for an Agent, including how clients can connect to it, how it stores state, the methods it exposes, and any error handling.

An Agent has the following class methods:

<TypeScriptExample>

```ts
import { Agent } from "agents-sdk";

interface Env {
// Define environment variables & bindings here
}

// Pass the Env as a TypeScript type argument
// Any services connected to your Agent or Worker as Bindings
// are then available on this.env.<BINDING_NAME>
class MyAgent extends Agent<Env> {
// Called when an Agent is started (or woken up)
async onStart() {
// Can access this.env and this.state
console.log('Agent started');
}

// Called when a HTTP request is received
// Can be connected to routeAgentRequest to automatically route
// requests to an individual Agent.
async onRequest(request: Request) {
console.log("Received request!");
}

// Called when a WebSocket connection is established
async onConnect(connection: Connection, ctx: ConnectionContext) {
console.log("Connected!");
// Check the request at ctx.request
// Authenticate the client
// Give them the OK.
connection.accept();
}

// Called for each message received on the WebSocket connection
async onMessage(connection: Connection, message: WSMessage) {
console.log(`message from client ID: ${connection.id}`)
// Send messages back to the client
connection.send("Hello!");
}

// WebSocket error and disconnection (close) handling.
async onError(connection: Connection, error: unknown): Promise<void> {
console.error(`WS error: ${error}`);
}

async onClose(connection: Connection, code: number, reason: string, wasClean: boolean): Promise<void> {
console.log(`WS closed: ${code} - ${reason} - wasClean: ${wasClean}`);
connection.close();
}

// Called when the Agent's state is updated
// via this.setState or the useAgent hook from the agents-sdk/react package.
async onStateUpdate(state: any) {
// 'state' will be typed if you supply a type parameter to the Agent class.
}
}

export default MyAgent;
```

</TypeScriptExample>

:::note

To learn more about how to manage state within an Agent, refer to the documentation on [managing and syncing state](/agents/examples/manage-and-sync-state/).

:::

You can also define your own methods on an Agent: it's technically valid to publish an Agent only has your own methods exposed, and create/get Agents directly from a Worker.

Your own methods can access the Agent's environment variables and bindings on `this.env`, state on `this.setState`, and call other methods on the Agent via `this.yourMethodName`.

## Calling Agents from Workers

You can create and run an instance of an Agent directly from a Worker in one of three ways:

1. Using the `routeAgentRequest` helper: this will automatically map requests to an individual Agent based on the `/agents/:agent/:name` URL pattern. The value of `:agent` will be the name of your Agent class converted to `kebab-case`, and the value of `:name` will be the name of the Agent instance you want to create or retrieve.
2. Calling `getAgentByName`, which will create a new Agent instance if none exists by that name, or retrieve a handle to an existing instance.
3. The [Durable Objects stub API](/durable-objects/api/id/), which provides a lower level API for creating and retrieving Agents.

These three patterns are shown below: we recommend using either `routeAgentRequest` or `getAgentByName`, which help avoid some boilerplate.

<TypeScriptExample>

```ts
import { Agent, AgentNamespace, getAgentByName, routeAgentRequest } from 'agents-sdk';

interface Env {
// Define your Agent on the environment here
// Passing your Agent class as a TypeScript type parameter allows you to call
// methods defined on your Agent.
MyAgent: AgentNamespace<MyAgent>;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
// Routed addressing
// Automatically routes HTTP requests and/or WebSocket connections to /agents/:agent/:name
// Best for: connecting React apps directly to Agents using useAgent from agents-sdk/react
(await routeAgentRequest(request, env)) || Response.json({ msg: 'no agent here' }, { status: 404 });

// Named addressing
// Best for: convenience method for creating or retrieving an agent by name/ID.
let namedAgent = getAgentByName<Env, MyAgent>(env.MyAgent, 'my-unique-agent-id');
// Pass the incoming request straight to your Agent
let namedResp = (await namedAgent).fetch(request);

// Durable Objects-style addressing
// Best for: controlling ID generation, associating IDs with your existing systems,
// and customizing when/how an Agent is created or invoked
const id = env.MyAgent.newUniqueId();
const agent = env.MyAgent.get(id);
// Pass the incoming request straight to your Agent
let resp = await agent.fetch(request);

return Response.json({ hello: 'visit https://developers.cloudflare.com/agents for more' });
},
} satisfies ExportedHandler<Env>;

export class MyAgent extends Agent<Env> {
// Your Agent implementation goes here
}
```
</TypeScriptExample>
Loading
Loading