|
| 1 | +# Agent Tools |
| 2 | + |
| 3 | +Agent tools let one chat agent dispatch another chat-capable sub-agent as part |
| 4 | +of its work. The child is a real sub-agent with its own Durable Object storage, |
| 5 | +messages, tools, resumable stream, and drill-in URL. The parent keeps a small |
| 6 | +run registry so clients can render the child timeline, replay it after refresh, |
| 7 | +and clean it up later. |
| 8 | + |
| 9 | +Agent tools support `@cloudflare/think` agents and `AIChatAgent` subclasses. |
| 10 | +`AIChatAgent` children run headlessly through `saveMessages()`, so they should |
| 11 | +use server-side tools. Browser-provided client tools are not available during an |
| 12 | +agent-tool turn unless you model that interaction as server-side state or a |
| 13 | +separate parent-mediated workflow. |
| 14 | + |
| 15 | +## Use an Agent as an AI SDK tool |
| 16 | + |
| 17 | +Use `agentTool()` when the parent model should decide when to call the helper. |
| 18 | + |
| 19 | +```ts |
| 20 | +import { Think } from "@cloudflare/think"; |
| 21 | +import { agentTool } from "agents/agent-tools"; |
| 22 | +import { z } from "zod"; |
| 23 | + |
| 24 | +export class Researcher extends Think<Env> { |
| 25 | + getSystemPrompt() { |
| 26 | + return "Research the user's topic and end with a concise summary."; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +export class Assistant extends Think<Env> { |
| 31 | + getTools() { |
| 32 | + return { |
| 33 | + research: agentTool(Researcher, { |
| 34 | + description: "Research one topic in depth.", |
| 35 | + displayName: "Researcher", |
| 36 | + inputSchema: z.object({ |
| 37 | + query: z.string().min(3) |
| 38 | + }) |
| 39 | + }) |
| 40 | + }; |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +The child can also be an `AIChatAgent`: |
| 46 | + |
| 47 | +```ts |
| 48 | +import { AIChatAgent } from "@cloudflare/ai-chat"; |
| 49 | +import { agentTool } from "agents/agent-tools"; |
| 50 | +import { convertToModelMessages, stepCountIs, streamText } from "ai"; |
| 51 | +import { z } from "zod"; |
| 52 | + |
| 53 | +export class Summarizer extends AIChatAgent<Env> { |
| 54 | + protected override formatAgentToolInput(input: { text: string }, request) { |
| 55 | + return { |
| 56 | + id: `agent-tool-${request.runId}-input`, |
| 57 | + role: "user", |
| 58 | + parts: [{ type: "text", text: `Summarize:\n\n${input.text}` }] |
| 59 | + }; |
| 60 | + } |
| 61 | + |
| 62 | + async onChatMessage() { |
| 63 | + const result = streamText({ |
| 64 | + model: this.env.MODEL, |
| 65 | + messages: await convertToModelMessages(this.messages) |
| 66 | + }); |
| 67 | + return result.toUIMessageStreamResponse(); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +export class Assistant extends AIChatAgent<Env> { |
| 72 | + async onChatMessage() { |
| 73 | + const result = streamText({ |
| 74 | + model: this.env.MODEL, |
| 75 | + messages: await convertToModelMessages(this.messages), |
| 76 | + tools: { |
| 77 | + summarize: agentTool(Summarizer, { |
| 78 | + description: "Summarize long text in a separate retained agent.", |
| 79 | + inputSchema: z.object({ text: z.string() }) |
| 80 | + }) |
| 81 | + }, |
| 82 | + stopWhen: stepCountIs(5) |
| 83 | + }); |
| 84 | + return result.toUIMessageStreamResponse(); |
| 85 | + } |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +The generated tool calls `this.runAgentTool(ChildAgent, ...)`, streams |
| 90 | +`agent-tool-event` frames on the parent WebSocket, and returns the child |
| 91 | +summary to the parent model. If the run fails, aborts, or is interrupted, the |
| 92 | +tool returns a structured failure instead of an empty success value. |
| 93 | + |
| 94 | +## Run an Agent tool imperatively |
| 95 | + |
| 96 | +Use `runAgentTool()` for deterministic workflows, scheduled work, HTTP |
| 97 | +handlers, or fan-out code. |
| 98 | + |
| 99 | +```ts |
| 100 | +const [a, b] = await Promise.allSettled([ |
| 101 | + this.runAgentTool(Researcher, { |
| 102 | + input: { query: "HTTP/3" }, |
| 103 | + parentToolCallId: toolCallId, |
| 104 | + displayOrder: 0 |
| 105 | + }), |
| 106 | + this.runAgentTool(Researcher, { |
| 107 | + input: { query: "gRPC" }, |
| 108 | + parentToolCallId: toolCallId, |
| 109 | + displayOrder: 1 |
| 110 | + }) |
| 111 | +]); |
| 112 | +``` |
| 113 | + |
| 114 | +`runAgentTool()` is idempotent by `runId`. Passing the same `runId` never starts |
| 115 | +a duplicate child turn. Completed, failed, aborted, and interrupted runs are |
| 116 | +retained until you explicitly clear them. |
| 117 | + |
| 118 | +## Render child timelines in React |
| 119 | + |
| 120 | +`useAgentToolEvents()` is a headless hook. It subscribes to the existing parent |
| 121 | +connection, deduplicates replay/live races, applies child `UIMessageChunk` |
| 122 | +bodies to message parts, and groups sibling runs by parent tool call id. |
| 123 | + |
| 124 | +```tsx |
| 125 | +import { useAgent, useAgentToolEvents } from "agents/react"; |
| 126 | +import { useAgentChat } from "@cloudflare/ai-chat/react"; |
| 127 | + |
| 128 | +const agent = useAgent({ agent: "Assistant", name: userId }); |
| 129 | +const { messages } = useAgentChat({ agent }); |
| 130 | +const agentTools = useAgentToolEvents({ agent }); |
| 131 | + |
| 132 | +for (const message of messages) { |
| 133 | + for (const part of message.parts) { |
| 134 | + if (part.type === "tool-call") { |
| 135 | + const runs = agentTools.getRunsForToolCall(part.toolCallId); |
| 136 | + // Render the child runs beside this tool call. |
| 137 | + } |
| 138 | + } |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | +Imperative runs without a parent tool call are available as |
| 143 | +`agentTools.unboundRuns`. |
| 144 | + |
| 145 | +## Drill in and gate access |
| 146 | + |
| 147 | +Agent tools are normal sub-agents. Connect to a retained child through the |
| 148 | +parent route: |
| 149 | + |
| 150 | +```ts |
| 151 | +useAgent({ |
| 152 | + agent: "Assistant", |
| 153 | + name: userId, |
| 154 | + sub: [{ agent: "Researcher", name: runId }] |
| 155 | +}); |
| 156 | +``` |
| 157 | + |
| 158 | +Gate external access with the parent registry so guessed run ids cannot spawn |
| 159 | +fresh child facets: |
| 160 | + |
| 161 | +```ts |
| 162 | +override async onBeforeSubAgent(_request, child) { |
| 163 | + if (!this.hasAgentToolRun(child.className, child.name)) { |
| 164 | + return new Response("Not found", { status: 404 }); |
| 165 | + } |
| 166 | +} |
| 167 | +``` |
| 168 | + |
| 169 | +## Clear retained runs |
| 170 | + |
| 171 | +Runs and child facets are retained by default for refresh, drill-in, and later |
| 172 | +inspection. Delete them explicitly when clearing chat history or applying your |
| 173 | +own retention policy: |
| 174 | + |
| 175 | +```ts |
| 176 | +await this.clearAgentToolRuns(); |
| 177 | +await this.clearAgentToolRuns({ |
| 178 | + status: ["completed", "error", "aborted", "interrupted"] |
| 179 | +}); |
| 180 | +await this.clearAgentToolRuns({ olderThan: Date.now() - 7 * 24 * 60 * 60_000 }); |
| 181 | +``` |
| 182 | + |
| 183 | +If a retained run is still `starting` or `running`, cleanup cancels the child |
| 184 | +before deleting its facet. |
0 commit comments