CloudflareでAIエージェントを作るのに便利なやつ

Yusuke Wada
Workers Tech Talks in Kyoto #2


Yusuke Wada

::right::

me


アジェンダ


AIエージェントとは?

AIエージェントは、AIを活用したコンピュータプログラムで、明示的な指示がなくても自律的にタスクを実行して人間のユーザーを支援することができます。

https://www.cloudflare.com/ja-jp/learning/ai/what-is-agentic-ai/


AIの変遷

AIの変遷


AIエージェントの例


CloudflareはAIエージェント構築に向いている


"Cloudflare Agents"は既存の機能の合わせ技

Cloudflare Agents



中でも最近使って便利なやつ


1. Agents SDK


サーバーサイドでステート管理をしたい


Agents SDKでできること


コード例: Agentsクラス

import { Agent, callable } from 'agents'

export class CounterAgent extends Agent {
  initialState = { count: 0 }

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

コード例: useAgent

import { useState } from 'react'
import { useAgent } from 'agents/react'

export function CounterWidget() {
  const [count, setCount] = useState(0)

  const agent = useAgent({
    agent: 'CounterAgent',
    onStateUpdate: (state) => setCount(state.count)
  })

  return (
    <>
      {count}
      <button onClick={() => agent.stub.increment()}>+</button>
    </>
  )
}

デモ: カウンター


counter


2. Workers AI

::right::

ss


コード例

app.get('/', async (c) => {
  const prompt = c.req.query('q') ?? 'Explain Cloudflare Workers in one sentence.'

  const result = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct-fast', {
    messages: [{ role: 'user', content: prompt }]
  })

  return c.json(result)
})

3. Schedule tasks


コード例

import { Agent } from 'agents'

export class Reminder extends Agent<Env, { message?: string }> {
  async remind(seconds: number, text: string) {
    await this.schedule(seconds, 'notify', { text })
  }

  // 時間が来たら呼ばれる
  async notify({ text }: { text: string }) {
    this.setState({ message: text }) // クライアントに自動同期
  }
}

タイミングの指定方法

await this.schedule(60, 'notify', { text }) // 60秒後
await this.schedule('0 9 * * *', 'notify', { text }) // 毎朝9時(cron)
await this.schedule(new Date('2026-07-08 19:00'), 'notify', { text }) // 特定日時

デモ: memo2task


memo2task


4. Workflows


コード例 (Cloudflare Workflows)


5. Browser Run


Quick Actions


コード例

app.get('/', (c) => {
  const url = c.req.query('url') ?? 'https://example.com'
  return c.env.BROWSER.quickAction('screenshot', { url })
})


デモ: screenshot-workflow

screenshot-workflow


より実践的なデモ: Meshi Agent


使った技術


まとめ

← → / space ・ f: fullscreen