General Introduction
Cloudflare Agents is an open source development framework from Cloudflare designed to help developers build intelligent AI agents on the global edge network. It gives agents the ability to persist state, communicate in real-time, and run autonomously, and the project is currently in active development. Core features include state management and WebSocket real-time interaction, which can already be used to create chatbots or automated task tools.Cloudflare Agents aims to build a distributed intelligent agent system where agents can run globally with support for sleep and wake-up mechanisms. Developers can join this open source project with a simple installation step and work together to advance AI technology.
Function List
- Core Agent Framework: Provides state management functionality where agents can memorize historical interaction data.
- real time communication: Supports instant dialog between the agent and the client via WebSocket.
- HTTP Routing: Handles web requests and facilitates interfacing with external services.
- React Integration: Built-in React hooks for front-end developers.
- Basic AI Chat: Support for building simple intelligent dialog systems.
- Functions under development: Includes an advanced memory system, WebRTC audio and video support, and e-mail capabilities.
Using Help
Cloudflare Agents is a developer-oriented tool that requires basic programming knowledge before use. Below is a detailed installation and operation guide to help you get started quickly and take full advantage of its features.
Installation process
Cloudflare Agents is installed via npm and supports new projects or adding to existing projects. Here are the steps.
New construction projects
- Checking the environment
Ensure that your computer has Node.js (recommended version 16 or higher) and npm installed. open a terminal and enternode -v
cap (a poem)npm -v
View the version number. - Create a project
Run the following command in the terminal:
npm create cloudflare@latest -- ---template cloudflare/agents-starter
You will be prompted to enter a project name and select a directory, and a base project will be generated upon completion.
3. Go to the project directory
importation cd the name of your project
Go to the newly created project folder.
4. Starting local development
Running:
npm run dev
This will start the local server, and you can access the local address via your browser (usually the http://localhost:8787
) to see the effect.
Add to existing project
- Go to the project directory
end-usecd
command to switch to your existing project folder. - Installing the SDK
Input:
npm install agents-sdk
This will add the Cloudflare Agents core library to the project.
3. Configuration Code
Introduced in the code agents-sdk
, refer to the official documentation for specific usage.
Main Functions
Creating a simple AI chat agent
- Writing proxy code
Create a file in the project (e.g.worker.ts
), enter the following code:
import { Agent } from "agents-sdk";
export class ChatAgent extends Agent {
async onRequest(request) {
const message = await request.text();
return new Response(`You Said: ${message}`);
}
}
This agent will simply reply to what the user enters.
2. Deploying to Cloudflare
Runs in the terminal:
npx wrangler@latest deploy
Follow the prompts to log in to your Cloudflare account, and an online URL will be returned when the deployment is complete.
3. test function
Visit the deployed URL with a browser, or send a message with a tool such as Postman to check that the response is working.
Real-time communication using WebSocket
- Configuring WebSocket Support
Modify the agent code to include real-time communication:import { Agent } from "agents-sdk"; export class RealTimeAgent extends Agent { async onConnect(connection) { connection.send("Connected!") ; } async onMessage(connection, message) { connection.send(`Received message: ${message}`); } } }
- front-end connection broker
Add it in the front-end code:const ws = new WebSocket("wss://Your proxy URL"); ws.onmessage = (event) => console.log(event.data); ws.send("hello");
This creates a real-time communication channel, where messages are sent and replies are received immediately.
- operational test
After deployment, run the front-end code using the console of the browser developer tool to see how the message interaction works.
Managing Agent Status
- Save and update status
Add state management to the agent:export class StateAgent extends Agent { async onRequest(request) { this.state.count = (this.state.count || 0) + 1; return new Response(`Visits: ${this.state.count || 0) return new Response(`Visits: ${this.state.count}`); } } }
- Validation State Persistence
Visit the proxy URL several times after deployment and observe if the count continues to increase, proving that the state is preserved. - application scenario
Status management is suitable for scenarios where history needs to be recorded, such as the number of user interactions or task progress.
Operation process details
- local debugging: Run
npm run dev
Activate development mode and automatically update the code after modification for easy testing. - Deployment goes live: Use of
npx wrangler@latest deploy
Publish agents to the Cloudflare global network. - Access to documents: Access official document Get more code samples and API details.
- Community involvement: If you have suggestions for improvements, you can submit issues or code on GitHub and participate in project development.
caveat
- environment variable: If you need to call an external AI model (e.g., OpenAI), do it in the
wrangler.toml
file to configure the API key. - network requirement: Deployment requires a stable network connection to ensure that there are no interruptions when logging into Cloudflare.
- Learning Resources: Officially provided Playground Example (located in the GitHub repository of the
examples/playground
), you can run the reference directly.
With the above steps, you can easily build an AI agent. the advantage of Cloudflare Agents is its globally distributed deployment and state persistence features, which are suitable for application scenarios that require low latency and high availability.