|
| 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