You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
At its most basic, an Agent is a JavaScript class that extends the `Agent` class from the `@cloudflare/agents` 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
12
@@ -28,7 +28,135 @@ An Agent can have many (millions of) instances: each instance is a separate micr
28
28
29
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
30
31
-
## Agent
31
+
## The Agent class
32
32
33
-
TODO - agent class
33
+
Writing an Agent requires you to define a class that extends the `Agent` class from the `@cloudflare/agents` 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
34
35
+
An Agent has the following class methods:
36
+
37
+
<TypeScriptExample>
38
+
39
+
```ts
40
+
import { Agent } from"@cloudflare/agents";
41
+
42
+
interfaceEnv {
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
+
classMyAgentextendsAgent<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
// via this.setState or the useAgent hook from the @cloudflare/agents/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
+
exportdefaultMyAgent;
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.
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.
Copy file name to clipboardExpand all lines: src/content/docs/agents/examples/manage-and-sync-state.mdx
+54-3Lines changed: 54 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -14,9 +14,11 @@ Every Agent has built-in state management capabilities, including built-in stora
14
14
* Immediately consistent within the Agent: read your own writes.
15
15
* Thread-safe for concurrent updates
16
16
17
-
### State management
17
+
Agent state is stored in SQL database that associate with each indidivual Agent instance: you can interact with it using the higher-level `this.setState` API (recommended) or by directly querying the database with `this.sql`.
18
18
19
-
Every agent has built-in state management capabilities. You can set and update the agent's state directly using `this.state`:
19
+
### State API
20
+
21
+
Every agent has built-in state management capabilities. You can set and update the agent's state directly using `this.setState`:
20
22
21
23
<TypeScriptExample>
22
24
@@ -51,6 +53,32 @@ export class MyAgent extends Agent {
51
53
52
54
</TypeScriptExample>
53
55
56
+
If you're using TypeScript, you can also provide a type for your Agent's state by passing in a type as a [type parameter](https://www.typescriptlang.org/docs/handbook/2/generics.html#using-type-parameters-in-generic-constraints) as the _second_ type parameter to the `Agent` class definition.
Clients can connect to an Agent and stay synchronized with its state using the React hooks provided as part of `@cloudflare/agents/react`:
@@ -78,4 +106,27 @@ Common use cases:
78
106
* Multi-window/tab synchronization
79
107
* Live updates across multiple devices
80
108
* Maintaining consistent UI state across clients
81
-
* When new clients connect, they automatically receive the current state from the agent, ensuring all clients start with the latest data.
109
+
* When new clients connect, they automatically receive the current state from the agent, ensuring all clients start with the latest data.
110
+
111
+
### SQL API
112
+
113
+
Every individual Agent instance has its own SQL (SQLite) database that runs _within the same context_ as the Agent itself. This means that inserting or querying data within your Agent is effectively zero-latency: the Agent doesn't have to round-trip across a continent or the world to access its own data.
114
+
115
+
TODO
116
+
117
+
<TypeScriptExample>
118
+
119
+
```ts
120
+
121
+
122
+
```
123
+
124
+
</TypeScriptExample>
125
+
126
+
:::note
127
+
128
+
Learn more about the zero-latency SQL storage that powers both Agents and Durable Objects [on our blog](https://blog.cloudflare.com/sqlite-in-durable-objects/).
129
+
130
+
:::
131
+
132
+
The SQL API exposed to an Agent is identical to the one [within by Durable Objects](/durable-objects/api/sql-storage/). This means that you can use the same SQL queries and commands to interact with the Agent's database.
0 commit comments