Skip to content

Commit 853a41b

Browse files
elithrarrita3koOxyjun
authored
agents: new docset
* wip * WIP - fixing typos (#20203) * add what are agents * update other files * onward * add tools and human loop images * limits, schedules * fix config title * fix * fix config * websockets * fix closing tag * caution * Apply suggestions from code review * state state state * sql API yo yo yo * agents: Apply suggestions from code review Co-authored-by: Jun Lee <[email protected]> * fix sidebar ordering * fix sidebar * state * update overview * ai models * guides, ai models * d1 * useAgent * fix 'er up * browse, fix syntax * testing * fix * fix * workflows * @cloudflare/agents -> agents-sdk * fix links * fix ordering + testing title * update index * update index * headers * remove updated * index.mdx * callback * rag * fin --------- Co-authored-by: Rita Kozlov <[email protected]> Co-authored-by: Rita Kozlov <[email protected]> Co-authored-by: Jun Lee <[email protected]>
1 parent 78e3d9c commit 853a41b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+31236
-1763
lines changed

src/assets/images/agents/agent-workflow.svg

Lines changed: 7363 additions & 0 deletions
Loading

src/assets/images/agents/co-pilot.svg

Lines changed: 7356 additions & 0 deletions
Loading

src/assets/images/agents/human-in-the-loop.svg

Lines changed: 7367 additions & 0 deletions
Loading
13 KB
Loading

src/assets/images/agents/workflow-automation.svg

Lines changed: 7348 additions & 0 deletions
Loading

src/content/changelog/agents/2025-02-14-example-ai-prompts.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ products:
88
date: 2025-02-14T19:00:00Z
99
---
1010

11-
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/).
11+
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/).
1212

1313
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.
1414

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
title: Configuration
3+
pcx_content_type: concept
4+
sidebar:
5+
order: 3
6+
---
7+
8+
import { MetaInfo, Render, Type, WranglerConfig } from "~/components";
9+
10+
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.
11+
12+
The typical file structure for an Agent project created from `npm create cloudflare@latest -- --template cloudflare/agents` follows:
13+
14+
```sh
15+
.
16+
|-- package-lock.json
17+
|-- package.json
18+
|-- public
19+
| `-- index.html
20+
|-- src
21+
| `-- index.ts // your Agent definition
22+
|-- test
23+
| |-- index.spec.ts // your tests
24+
| `-- tsconfig.json
25+
|-- tsconfig.json
26+
|-- vitest.config.mts
27+
|-- worker-configuration.d.ts
28+
`-- wrangler.jsonc // your Workers & Agent configuration
29+
```
30+
31+
Below is a minimal `wrangler.jsonc` file that defines the configuration for an Agent, including the entry point, `durable_object` namespace, and code `migrations`:
32+
33+
<WranglerConfig>
34+
35+
```jsonc
36+
{
37+
"$schema": "node_modules/wrangler/config-schema.json",
38+
"name": "agents-example",
39+
"main": "src/index.ts",
40+
"compatibility_date": "2025-02-23",
41+
"compatibility_flags": ["nodejs_compat"],
42+
"durable_objects": {
43+
"bindings": [
44+
{
45+
// Required:
46+
"name": "MyAgent", // How your Agent is called from your Worker
47+
"class_name": "MyAgent", // Must match the class name of the Agent in your code
48+
// Optional: set this if the Agent is defined in another Worker script
49+
"script_name": "the-other-worker"
50+
},
51+
],
52+
},
53+
"migrations": [
54+
{
55+
"tag": "v1",
56+
// Mandatory for the Agent to store state
57+
"new_sqlite_classes": ["MyAgent"],
58+
},
59+
],
60+
"observability": {
61+
"enabled": true,
62+
},
63+
}
64+
```
65+
66+
</WranglerConfig>
67+
68+
The configuration includes:
69+
70+
- A `main` field that points to the entry point of your Agent, which is typically a TypeScript (or JavaScript) file.
71+
- A `durable_objects` field that defines the [Durable Object namespace](/durable-objects/reference/glossary/) that your Agents will run within.
72+
- 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.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
title: API Reference
3+
pcx_content_type: navigation
4+
sidebar:
5+
order: 5
6+
group:
7+
hideIndex: true
8+
---
9+
10+
import { DirectoryListing } from "~/components"
11+
12+
<DirectoryListing />
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
---
2+
title: Agents SDK
3+
pcx_content_type: concept
4+
sidebar:
5+
order: 2
6+
7+
---
8+
9+
import { MetaInfo, Render, Type, TypeScriptExample, WranglerConfig } from "~/components";
10+
11+
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.
12+
13+
<TypeScriptExample>
14+
15+
```ts
16+
import { Agent } from "agents-sdk";
17+
18+
class MyAgent extends Agent {
19+
// Define methods on the Agent
20+
}
21+
22+
export default MyAgent;
23+
```
24+
25+
</TypeScriptExample>
26+
27+
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.
28+
29+
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.
30+
31+
## The Agent class
32+
33+
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.
34+
35+
An Agent has the following class methods:
36+
37+
<TypeScriptExample>
38+
39+
```ts
40+
import { Agent } from "agents-sdk";
41+
42+
interface Env {
43+
// Define environment variables & bindings here
44+
}
45+
46+
// Pass the Env as a TypeScript type argument
47+
// Any services connected to your Agent or Worker as Bindings
48+
// are then available on this.env.<BINDING_NAME>
49+
class MyAgent extends Agent<Env> {
50+
// Called when an Agent is started (or woken up)
51+
async onStart() {
52+
// Can access this.env and this.state
53+
console.log('Agent started');
54+
}
55+
56+
// Called when a HTTP request is received
57+
// Can be connected to routeAgentRequest to automatically route
58+
// requests to an individual Agent.
59+
async onRequest(request: Request) {
60+
console.log("Received request!");
61+
}
62+
63+
// Called when a WebSocket connection is established
64+
async onConnect(connection: Connection, ctx: ConnectionContext) {
65+
console.log("Connected!");
66+
// Check the request at ctx.request
67+
// Authenticate the client
68+
// Give them the OK.
69+
connection.accept();
70+
}
71+
72+
// Called for each message received on the WebSocket connection
73+
async onMessage(connection: Connection, message: WSMessage) {
74+
console.log(`message from client ID: ${connection.id}`)
75+
// Send messages back to the client
76+
connection.send("Hello!");
77+
}
78+
79+
// WebSocket error and disconnection (close) handling.
80+
async onError(connection: Connection, error: unknown): Promise<void> {
81+
console.error(`WS error: ${error}`);
82+
}
83+
84+
async onClose(connection: Connection, code: number, reason: string, wasClean: boolean): Promise<void> {
85+
console.log(`WS closed: ${code} - ${reason} - wasClean: ${wasClean}`);
86+
connection.close();
87+
}
88+
89+
// Called when the Agent's state is updated
90+
// via this.setState or the useAgent hook from the agents-sdk/react package.
91+
async onStateUpdate(state: any) {
92+
// 'state' will be typed if you supply a type parameter to the Agent class.
93+
}
94+
}
95+
96+
export default MyAgent;
97+
```
98+
99+
</TypeScriptExample>
100+
101+
:::note
102+
103+
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/).
104+
105+
:::
106+
107+
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.
108+
109+
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`.
110+
111+
## Calling Agents from Workers
112+
113+
You can create and run an instance of an Agent directly from a Worker in one of three ways:
114+
115+
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.
116+
2. Calling `getAgentByName`, which will create a new Agent instance if none exists by that name, or retrieve a handle to an existing instance.
117+
3. The [Durable Objects stub API](/durable-objects/api/id/), which provides a lower level API for creating and retrieving Agents.
118+
119+
These three patterns are shown below: we recommend using either `routeAgentRequest` or `getAgentByName`, which help avoid some boilerplate.
120+
121+
<TypeScriptExample>
122+
123+
```ts
124+
import { Agent, AgentNamespace, getAgentByName, routeAgentRequest } from 'agents-sdk';
125+
126+
interface Env {
127+
// Define your Agent on the environment here
128+
// Passing your Agent class as a TypeScript type parameter allows you to call
129+
// methods defined on your Agent.
130+
MyAgent: AgentNamespace<MyAgent>;
131+
}
132+
133+
export default {
134+
async fetch(request, env, ctx): Promise<Response> {
135+
// Routed addressing
136+
// Automatically routes HTTP requests and/or WebSocket connections to /agents/:agent/:name
137+
// Best for: connecting React apps directly to Agents using useAgent from agents-sdk/react
138+
(await routeAgentRequest(request, env)) || Response.json({ msg: 'no agent here' }, { status: 404 });
139+
140+
// Named addressing
141+
// Best for: convenience method for creating or retrieving an agent by name/ID.
142+
let namedAgent = getAgentByName<Env, MyAgent>(env.MyAgent, 'my-unique-agent-id');
143+
// Pass the incoming request straight to your Agent
144+
let namedResp = (await namedAgent).fetch(request);
145+
146+
// Durable Objects-style addressing
147+
// Best for: controlling ID generation, associating IDs with your existing systems,
148+
// and customizing when/how an Agent is created or invoked
149+
const id = env.MyAgent.newUniqueId();
150+
const agent = env.MyAgent.get(id);
151+
// Pass the incoming request straight to your Agent
152+
let resp = await agent.fetch(request);
153+
154+
return Response.json({ hello: 'visit https://developers.cloudflare.com/agents for more' });
155+
},
156+
} satisfies ExportedHandler<Env>;
157+
158+
export class MyAgent extends Agent<Env> {
159+
// Your Agent implementation goes here
160+
}
161+
```
162+
</TypeScriptExample>

0 commit comments

Comments
 (0)