スキル一覧に戻る
cloudflare

agents-sdk

by cloudflare

agents-sdkは、コンテンツ作成と管理を支援するスキルです。高品質なコンテンツ生成と最適化により、SEO対応と利用者満足度の向上を実現します。

4,313🍴 11,683📅 2026年1月23日
GitHubで見るManusで実行

ユースケース

📝

ドキュメント生成

コードからドキュメントを自動生成。

✍️

コンテンツ作成支援

ブログ記事やマーケティングコンテンツの作成を支援。

🎨

UIコンポーネント生成

デザインからUIコンポーネントを生成。

SKILL.md


name: agents-sdk description: Build stateful AI agents using the Cloudflare Agents SDK. Load when creating agents with persistent state, scheduling, RPC, MCP servers, email handling, or streaming chat. Covers Agent class, AIChatAgent, state management, and Code Mode for reduced token usage.

Cloudflare Agents SDK

Build persistent, stateful AI agents on Cloudflare Workers using the agents npm package.

FIRST: Verify Installation

npm install agents

Agents require a binding in wrangler.jsonc:

{
  "durable_objects": {
    // "class_name" must match your Agent class name exactly
    "bindings": [{ "name": "Counter", "class_name": "Counter" }]
  },
  "migrations": [
    // Required: list all Agent classes for SQLite storage
    { "tag": "v1", "new_sqlite_classes": ["Counter"] }
  ]
}

Choosing an Agent Type

Use CaseBase ClassPackage
Custom state + RPC, no chatAgentagents
Chat with message persistenceAIChatAgent@cloudflare/ai-chat
Building an MCP serverMcpAgentagents/mcp

Key Concepts

  • Agent base class provides state, scheduling, RPC, MCP, and email capabilities
  • AIChatAgent adds streaming chat with automatic message persistence and resumable streams
  • Code Mode generates executable code instead of tool calls—reduces token usage significantly
  • this.state / this.setState() - automatic persistence to SQLite, broadcasts to clients
  • this.schedule() - schedule tasks at Date, delay (seconds), or cron expression
  • @callable decorator - expose methods to clients via WebSocket RPC

Quick Reference

TaskAPI
Persist statethis.setState({ count: 1 })
Read statethis.state.count
Schedule taskthis.schedule(60, "taskMethod", payload)
Schedule cronthis.schedule("0 * * * *", "hourlyTask")
Cancel schedulethis.cancelSchedule(id)
Queue taskthis.queue("processItem", payload)
SQL querythis.sql`SELECT * FROM users WHERE id = ${id}`
RPC method@callable() async myMethod() { ... }
Streaming RPC@callable({ streaming: true }) async stream(res) { ... }

Minimal Agent

import { Agent, routeAgentRequest, callable } from "agents";

type State = { count: number };

export class Counter extends Agent<Env, State> {
  initialState = { count: 0 };

  @callable()
  increment() {
    this.setState({ count: this.state.count + 1 });
    return this.state.count;
  }
}

export default {
  fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};

Streaming Chat Agent

Use AIChatAgent for chat with automatic message persistence and resumable streaming.

Install additional dependencies first:

npm install @cloudflare/ai-chat ai @ai-sdk/openai

Add wrangler.jsonc config (same pattern as base Agent):

{
  "durable_objects": {
    "bindings": [{ "name": "Chat", "class_name": "Chat" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Chat"] }]
}
import { AIChatAgent } from "@cloudflare/ai-chat";
import { routeAgentRequest } from "agents";
import { streamText, convertToModelMessages } from "ai";
import { openai } from "@ai-sdk/openai";

export class Chat extends AIChatAgent<Env> {
  async onChatMessage(onFinish) {
    const result = streamText({
      model: openai("gpt-4o"),
      messages: await convertToModelMessages(this.messages),
      onFinish
    });
    return result.toUIMessageStreamResponse();
  }
}

export default {
  fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};

Client (React):

import { useAgent } from "agents/react";
import { useAgentChat } from "@cloudflare/ai-chat/react";

const agent = useAgent({ agent: "Chat", name: "my-chat" });
const { messages, input, handleSubmit } = useAgentChat({ agent });

Detailed References

When to Use Code Mode

Code Mode generates executable JavaScript instead of making individual tool calls. Use it when:

  • Chaining multiple tool calls in sequence
  • Complex conditional logic across tools
  • MCP server orchestration (multiple servers)
  • Token budget is constrained

See references/codemode.md for setup and examples.

Best Practices

  1. Prefer streaming: Use streamText and toUIMessageStreamResponse() for chat
  2. Use AIChatAgent for chat: Handles message persistence and resumable streams automatically
  3. Type your state: Agent<Env, State> ensures type safety for this.state
  4. Use @callable for RPC: Cleaner than manual WebSocket message handling
  5. Code Mode for complex workflows: Reduces round-trips and token usage
  6. Schedule vs Queue: Use schedule() for time-based, queue() for sequential processing

スコア

総合スコア

80/100

リポジトリの品質指標に基づく評価

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

+10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 1000以上

+15
最近の活動

1ヶ月以内に更新

+10
フォーク

10回以上フォークされている

+5
Issue管理

オープンIssueが50未満

0/5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

+5

レビュー

💬

レビュー機能は近日公開予定です