@cloudflare/ai-chat 0.0.7 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +105 -0
- package/README.md +225 -459
- package/dist/ai-chat-v5-migration.d.ts +9 -9
- package/dist/ai-chat-v5-migration.js +25 -4
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/experimental/forever.d.ts +29 -0
- package/dist/experimental/forever.js +55 -0
- package/dist/experimental/forever.js.map +1 -0
- package/dist/index.d.ts +126 -74
- package/dist/index.js +753 -632
- package/dist/index.js.map +1 -1
- package/dist/message-builder-Bwc_Umye.js +231 -0
- package/dist/message-builder-Bwc_Umye.js.map +1 -0
- package/dist/react.d.ts +27 -9
- package/dist/react.js +248 -259
- package/dist/react.js.map +1 -1
- package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
- package/dist/types.d.ts +16 -4
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -1
- package/e2e/chat.spec.ts +1703 -0
- package/e2e/client-tools.spec.ts +504 -0
- package/e2e/llm.spec.ts +637 -0
- package/e2e/playwright.config.ts +24 -0
- package/e2e/worker.ts +176 -0
- package/e2e/wrangler.jsonc +23 -0
- package/package.json +12 -5
- package/scripts/build.ts +2 -1
- package/src/ai-chat-v5-migration.ts +32 -5
- package/src/experimental/forever.ts +66 -0
- package/src/index.ts +850 -1132
- package/src/message-builder.ts +384 -0
- package/src/react-tests/use-agent-chat.test.tsx +738 -2
- package/src/react.tsx +396 -462
- package/src/resumable-stream.ts +441 -0
- package/src/tests/chat-context.test.ts +1 -1
- package/src/tests/chat-persistence.test.ts +5 -5
- package/src/tests/clear-history.test.ts +132 -0
- package/src/tests/client-tool-duplicate-message.test.ts +457 -14
- package/src/tests/client-tools-broadcast.test.ts +2 -2
- package/src/tests/client-tools-continuation.test.ts +314 -0
- package/src/tests/client-tools-reconnect.test.ts +143 -0
- package/src/tests/custom-body-continuation.test.ts +309 -0
- package/src/tests/custom-body.test.ts +186 -0
- package/src/tests/destroy.test.ts +57 -0
- package/src/tests/get-messages-endpoint.test.ts +79 -0
- package/src/tests/max-persisted-messages.test.ts +201 -0
- package/src/tests/merge-server-state.test.ts +106 -0
- package/src/tests/message-builder.test.ts +808 -0
- package/src/tests/migration.test.ts +282 -0
- package/src/tests/non-sse-response.test.ts +2 -2
- package/src/tests/onfinish-cleanup.test.ts +362 -0
- package/src/tests/plaintext-response.test.ts +87 -0
- package/src/tests/resumable-streaming.test.ts +220 -14
- package/src/tests/row-size-guard.test.ts +374 -0
- package/src/tests/sanitize-messages.test.ts +215 -0
- package/src/tests/validate-messages.test.ts +269 -0
- package/src/tests/worker.ts +85 -23
- package/src/types.ts +17 -1
- package/src/ws-chat-transport.ts +203 -0
package/README.md
CHANGED
|
@@ -1,93 +1,89 @@
|
|
|
1
|
-
|
|
1
|
+
# @cloudflare/ai-chat
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AI chat agents with automatic message persistence, resumable streaming, and tool support. Built on Cloudflare Durable Objects and the [AI SDK](https://ai-sdk.dev).
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
#### The Nature of AI Chat
|
|
8
|
-
|
|
9
|
-
AI chat transcends simple request-response patterns. It's a continuous dialogue where:
|
|
10
|
-
|
|
11
|
-
- **Persistence**: Conversations are automatically saved and restored across sessions
|
|
12
|
-
- **Streaming**: Real-time responses that flow naturally to users
|
|
13
|
-
- **Resumability**: Automatic recovery from disconnections without losing context
|
|
14
|
-
- **Tools**: Seamless integration of client and server-side capabilities
|
|
15
|
-
- **State**: Each conversation maintains its own memory and understanding
|
|
16
|
-
|
|
17
|
-
Built on Cloudflare's global network with Durable Objects, your chat agents persist across time, maintaining context and relationships with users.
|
|
18
|
-
|
|
19
|
-
#### 💫 Core Principles
|
|
20
|
-
|
|
21
|
-
1. **Automatic Persistence**: Messages are saved automatically - no manual storage needed
|
|
22
|
-
2. **Resumable Streaming**: Disconnections don't break the flow - streams resume automatically
|
|
23
|
-
3. **Tool Harmony**: Mix server and client-side tools seamlessly
|
|
24
|
-
4. **AI SDK Integration**: Built on the latest AI SDK v6 for maximum compatibility
|
|
25
|
-
5. **React First**: Designed for modern React applications with hooks
|
|
26
|
-
|
|
27
|
-
---
|
|
28
|
-
|
|
29
|
-
### 🌱 Beginning the Journey
|
|
30
|
-
|
|
31
|
-
Install the package in your project:
|
|
5
|
+
## Install
|
|
32
6
|
|
|
33
7
|
```sh
|
|
34
|
-
npm install @cloudflare/ai-chat agents ai
|
|
8
|
+
npm install @cloudflare/ai-chat agents ai workers-ai-provider
|
|
35
9
|
```
|
|
36
10
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
### 📝 Your First Chat Agent
|
|
11
|
+
## Quick Start
|
|
40
12
|
|
|
41
|
-
|
|
13
|
+
### Server
|
|
42
14
|
|
|
43
|
-
```
|
|
15
|
+
```typescript
|
|
44
16
|
import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
45
|
-
import {
|
|
46
|
-
import {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
createUIMessageStream,
|
|
50
|
-
createUIMessageStreamResponse
|
|
51
|
-
} from "ai";
|
|
52
|
-
|
|
53
|
-
export class ChatAgent extends AIChatAgent<Env> {
|
|
17
|
+
import { createWorkersAI } from "workers-ai-provider";
|
|
18
|
+
import { streamText, convertToModelMessages } from "ai";
|
|
19
|
+
|
|
20
|
+
export class ChatAgent extends AIChatAgent {
|
|
54
21
|
async onChatMessage() {
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
writer.merge(result.toUIMessageStream());
|
|
63
|
-
}
|
|
22
|
+
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
23
|
+
|
|
24
|
+
const result = streamText({
|
|
25
|
+
model: workersai("@cf/zai-org/glm-4.7-flash"),
|
|
26
|
+
messages: await convertToModelMessages(this.messages)
|
|
64
27
|
});
|
|
65
28
|
|
|
66
|
-
return
|
|
29
|
+
return result.toUIMessageStreamResponse();
|
|
67
30
|
}
|
|
68
31
|
}
|
|
69
32
|
```
|
|
70
33
|
|
|
71
|
-
That
|
|
34
|
+
That gives you: automatic message persistence in SQLite, resumable streaming on disconnect/reconnect, and real-time WebSocket delivery to all connected clients.
|
|
72
35
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
36
|
+
### Client
|
|
37
|
+
|
|
38
|
+
```tsx
|
|
39
|
+
import { useAgent } from "agents/react";
|
|
40
|
+
import { useAgentChat } from "@cloudflare/ai-chat/react";
|
|
41
|
+
|
|
42
|
+
function Chat() {
|
|
43
|
+
const agent = useAgent({ agent: "ChatAgent" });
|
|
44
|
+
const { messages, sendMessage, clearHistory, status } = useAgentChat({
|
|
45
|
+
agent
|
|
46
|
+
});
|
|
77
47
|
|
|
78
|
-
|
|
48
|
+
return (
|
|
49
|
+
<div>
|
|
50
|
+
{messages.map((msg) => (
|
|
51
|
+
<div key={msg.id}>
|
|
52
|
+
<strong>{msg.role}:</strong>
|
|
53
|
+
{msg.parts.map((part, i) =>
|
|
54
|
+
part.type === "text" ? <span key={i}>{part.text}</span> : null
|
|
55
|
+
)}
|
|
56
|
+
</div>
|
|
57
|
+
))}
|
|
58
|
+
|
|
59
|
+
<form
|
|
60
|
+
onSubmit={(e) => {
|
|
61
|
+
e.preventDefault();
|
|
62
|
+
const input = e.currentTarget.elements.namedItem(
|
|
63
|
+
"input"
|
|
64
|
+
) as HTMLInputElement;
|
|
65
|
+
sendMessage({
|
|
66
|
+
role: "user",
|
|
67
|
+
parts: [{ type: "text", text: input.value }]
|
|
68
|
+
});
|
|
69
|
+
input.value = "";
|
|
70
|
+
}}
|
|
71
|
+
>
|
|
72
|
+
<input name="input" placeholder="Type a message..." />
|
|
73
|
+
</form>
|
|
74
|
+
</div>
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
```
|
|
79
78
|
|
|
80
|
-
|
|
79
|
+
### Wrangler Config
|
|
81
80
|
|
|
82
81
|
```jsonc
|
|
82
|
+
// wrangler.jsonc
|
|
83
83
|
{
|
|
84
|
+
"ai": { "binding": "AI" },
|
|
84
85
|
"durable_objects": {
|
|
85
|
-
"bindings": [
|
|
86
|
-
{
|
|
87
|
-
"name": "ChatAgent",
|
|
88
|
-
"class_name": "ChatAgent"
|
|
89
|
-
}
|
|
90
|
-
]
|
|
86
|
+
"bindings": [{ "name": "ChatAgent", "class_name": "ChatAgent" }]
|
|
91
87
|
},
|
|
92
88
|
"migrations": [
|
|
93
89
|
{
|
|
@@ -98,473 +94,243 @@ Define your chat agent in your `wrangler.toml`:
|
|
|
98
94
|
}
|
|
99
95
|
```
|
|
100
96
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
#### Streaming Responses (Recommended)
|
|
104
|
-
|
|
105
|
-
For real-time interaction, use streaming:
|
|
106
|
-
|
|
107
|
-
```ts
|
|
108
|
-
import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
109
|
-
import { openai } from "@ai-sdk/openai";
|
|
110
|
-
import {
|
|
111
|
-
streamText,
|
|
112
|
-
convertToModelMessages,
|
|
113
|
-
createUIMessageStream,
|
|
114
|
-
createUIMessageStreamResponse
|
|
115
|
-
} from "ai";
|
|
116
|
-
|
|
117
|
-
export class StreamingChat extends AIChatAgent<Env> {
|
|
118
|
-
async onChatMessage(onFinish) {
|
|
119
|
-
const stream = createUIMessageStream({
|
|
120
|
-
execute: async ({ writer }) => {
|
|
121
|
-
const result = streamText({
|
|
122
|
-
model: openai("gpt-4o"),
|
|
123
|
-
messages: await convertToModelMessages(this.messages),
|
|
124
|
-
onFinish
|
|
125
|
-
});
|
|
126
|
-
|
|
127
|
-
writer.merge(result.toUIMessageStream());
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
return createUIMessageStreamResponse({ stream });
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
```
|
|
97
|
+
## Tools
|
|
135
98
|
|
|
136
|
-
|
|
99
|
+
### Server-side tools
|
|
137
100
|
|
|
138
|
-
|
|
101
|
+
Tools with an `execute` function run on the server automatically:
|
|
139
102
|
|
|
140
|
-
```
|
|
141
|
-
import {
|
|
142
|
-
import {
|
|
143
|
-
import {
|
|
103
|
+
```typescript
|
|
104
|
+
import { createWorkersAI } from "workers-ai-provider";
|
|
105
|
+
import { streamText, convertToModelMessages, tool } from "ai";
|
|
106
|
+
import { z } from "zod";
|
|
144
107
|
|
|
145
|
-
export class
|
|
108
|
+
export class ChatAgent extends AIChatAgent {
|
|
146
109
|
async onChatMessage() {
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
110
|
+
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
111
|
+
|
|
112
|
+
const result = streamText({
|
|
113
|
+
model: workersai("@cf/zai-org/glm-4.7-flash"),
|
|
114
|
+
messages: await convertToModelMessages(this.messages),
|
|
115
|
+
tools: {
|
|
116
|
+
getWeather: tool({
|
|
117
|
+
description: "Get weather for a city",
|
|
118
|
+
inputSchema: z.object({ city: z.string() }),
|
|
119
|
+
execute: async ({ city }) => {
|
|
120
|
+
const data = await fetchWeather(city);
|
|
121
|
+
return { temperature: data.temp, condition: data.condition };
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
},
|
|
125
|
+
maxSteps: 5
|
|
157
126
|
});
|
|
158
127
|
|
|
159
|
-
return
|
|
160
|
-
headers: { "Content-Type": "application/json" }
|
|
161
|
-
});
|
|
128
|
+
return result.toUIMessageStreamResponse();
|
|
162
129
|
}
|
|
163
130
|
}
|
|
164
131
|
```
|
|
165
132
|
|
|
166
|
-
###
|
|
133
|
+
### Client-side tools
|
|
167
134
|
|
|
168
|
-
|
|
135
|
+
Tools without `execute` are handled on the client via `onToolCall`. Use this for tools that need browser APIs (geolocation, clipboard, camera):
|
|
169
136
|
|
|
170
|
-
```
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
name: "my-chat"
|
|
179
|
-
});
|
|
180
|
-
|
|
181
|
-
// Set up the chat interaction
|
|
182
|
-
const { messages, sendMessage, clearHistory, status } = useAgentChat({
|
|
183
|
-
agent
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
const [input, setInput] = useState("");
|
|
137
|
+
```typescript
|
|
138
|
+
// Server: define tool without execute
|
|
139
|
+
getLocation: tool({
|
|
140
|
+
description: "Get the user's location from their browser",
|
|
141
|
+
inputSchema: z.object({})
|
|
142
|
+
// No execute -- client handles it
|
|
143
|
+
});
|
|
144
|
+
```
|
|
187
145
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
146
|
+
```tsx
|
|
147
|
+
// Client: handle via onToolCall
|
|
148
|
+
const { messages, sendMessage } = useAgentChat({
|
|
149
|
+
agent,
|
|
150
|
+
onToolCall: async ({ toolCall, addToolOutput }) => {
|
|
151
|
+
if (toolCall.toolName === "getLocation") {
|
|
152
|
+
const pos = await new Promise((resolve, reject) =>
|
|
153
|
+
navigator.geolocation.getCurrentPosition(resolve, reject)
|
|
154
|
+
);
|
|
155
|
+
addToolOutput({
|
|
156
|
+
toolCallId: toolCall.toolCallId,
|
|
157
|
+
output: { lat: pos.coords.latitude, lng: pos.coords.longitude }
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
```
|
|
191
163
|
|
|
192
|
-
|
|
193
|
-
role: "user",
|
|
194
|
-
parts: [{ type: "text", text: input }]
|
|
195
|
-
});
|
|
196
|
-
setInput("");
|
|
197
|
-
};
|
|
164
|
+
### Tool approval (human-in-the-loop)
|
|
198
165
|
|
|
199
|
-
|
|
200
|
-
<div className="chat-interface">
|
|
201
|
-
<div className="messages">
|
|
202
|
-
{messages.map((message) => (
|
|
203
|
-
<div key={message.id} className="message">
|
|
204
|
-
<div className="role">{message.role}</div>
|
|
205
|
-
<div className="content">
|
|
206
|
-
{message.parts.map((part, i) => {
|
|
207
|
-
if (part.type === "text")
|
|
208
|
-
return <span key={i}>{part.text}</span>;
|
|
209
|
-
return null;
|
|
210
|
-
})}
|
|
211
|
-
</div>
|
|
212
|
-
</div>
|
|
213
|
-
))}
|
|
214
|
-
</div>
|
|
215
|
-
|
|
216
|
-
<form onSubmit={handleSubmit}>
|
|
217
|
-
<input
|
|
218
|
-
value={input}
|
|
219
|
-
onChange={(e) => setInput(e.target.value)}
|
|
220
|
-
placeholder="Type your message..."
|
|
221
|
-
/>
|
|
222
|
-
</form>
|
|
166
|
+
Use `needsApproval` for tools that require user confirmation before executing:
|
|
223
167
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
168
|
+
```typescript
|
|
169
|
+
// Server
|
|
170
|
+
processPayment: tool({
|
|
171
|
+
description: "Process a payment",
|
|
172
|
+
inputSchema: z.object({ amount: z.number(), recipient: z.string() }),
|
|
173
|
+
needsApproval: async ({ amount }) => amount > 100, // Only require approval for large amounts
|
|
174
|
+
execute: async ({ amount, recipient }) => charge(amount, recipient)
|
|
175
|
+
});
|
|
228
176
|
```
|
|
229
177
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
178
|
+
```tsx
|
|
179
|
+
// Client
|
|
180
|
+
const { messages, addToolApprovalResponse } = useAgentChat({ agent });
|
|
181
|
+
|
|
182
|
+
// When rendering tool parts with state === "approval-requested":
|
|
183
|
+
<button onClick={() => addToolApprovalResponse({ id: approvalId, approved: true })}>
|
|
184
|
+
Approve
|
|
185
|
+
</button>
|
|
186
|
+
<button onClick={() => addToolApprovalResponse({ id: approvalId, approved: false })}>
|
|
187
|
+
Reject
|
|
188
|
+
</button>
|
|
189
|
+
```
|
|
233
190
|
|
|
234
|
-
|
|
191
|
+
## Resumable Streaming
|
|
235
192
|
|
|
236
|
-
|
|
237
|
-
2. **On disconnect**: The stream continues server-side, buffering chunks
|
|
238
|
-
3. **On reconnect**: Client receives all buffered chunks and continues streaming
|
|
193
|
+
Streams automatically resume on disconnect/reconnect. No configuration needed.
|
|
239
194
|
|
|
240
|
-
|
|
195
|
+
When a client disconnects mid-stream, chunks are buffered in SQLite. On reconnect, the client receives all buffered chunks and continues receiving the live stream.
|
|
241
196
|
|
|
242
|
-
|
|
197
|
+
Disable with `resume: false`:
|
|
243
198
|
|
|
244
199
|
```tsx
|
|
245
|
-
|
|
246
|
-
import { useAgentChat } from "@cloudflare/ai-chat/react";
|
|
247
|
-
|
|
248
|
-
function ResumableChat() {
|
|
249
|
-
const agent = useAgent({
|
|
250
|
-
agent: "ResumableStreamingChat",
|
|
251
|
-
name: "demo"
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
// resume: true is the default - streams automatically resume on reconnect
|
|
255
|
-
const { messages, sendMessage, status } = useAgentChat({
|
|
256
|
-
agent
|
|
257
|
-
// resume: true is the default
|
|
258
|
-
});
|
|
259
|
-
|
|
260
|
-
// Try it: Start a long response, refresh the page, and watch it resume!
|
|
261
|
-
return (
|
|
262
|
-
<div>
|
|
263
|
-
{status === "streaming" && <div>Streaming...</div>}
|
|
264
|
-
{/* Your chat UI */}
|
|
265
|
-
</div>
|
|
266
|
-
);
|
|
267
|
-
}
|
|
200
|
+
const { messages } = useAgentChat({ agent, resume: false });
|
|
268
201
|
```
|
|
269
202
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
### 🔧 Tool Support
|
|
203
|
+
## Storage Management
|
|
273
204
|
|
|
274
|
-
|
|
205
|
+
### Limiting stored messages
|
|
275
206
|
|
|
276
|
-
|
|
207
|
+
Cap the number of messages kept in SQLite:
|
|
277
208
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
282
|
-
import { openai } from "@ai-sdk/openai";
|
|
283
|
-
import { streamText, convertToModelMessages, tool } from "ai";
|
|
284
|
-
import { z } from "zod";
|
|
285
|
-
import { createUIMessageStream, createUIMessageStreamResponse } from "ai";
|
|
209
|
+
```typescript
|
|
210
|
+
export class ChatAgent extends AIChatAgent {
|
|
211
|
+
maxPersistedMessages = 200; // Keep last 200 messages
|
|
286
212
|
|
|
287
|
-
export class ToolChat extends AIChatAgent<Env> {
|
|
288
213
|
async onChatMessage() {
|
|
289
|
-
|
|
290
|
-
execute: async ({ writer }) => {
|
|
291
|
-
const result = streamText({
|
|
292
|
-
model: openai("gpt-4o"),
|
|
293
|
-
messages: await convertToModelMessages(this.messages),
|
|
294
|
-
tools: {
|
|
295
|
-
getWeather: tool({
|
|
296
|
-
description: "Get weather for a city",
|
|
297
|
-
parameters: z.object({ city: z.string() }),
|
|
298
|
-
execute: async ({ city }) => {
|
|
299
|
-
// Fetch weather from your API
|
|
300
|
-
const weather = await fetch(`https://api.weather.com/${city}`);
|
|
301
|
-
return { temperature: 72, condition: "sunny" };
|
|
302
|
-
}
|
|
303
|
-
})
|
|
304
|
-
}
|
|
305
|
-
});
|
|
306
|
-
|
|
307
|
-
writer.merge(result.toUIMessageStream());
|
|
308
|
-
}
|
|
309
|
-
});
|
|
310
|
-
|
|
311
|
-
return createUIMessageStreamResponse({ stream });
|
|
214
|
+
// ...
|
|
312
215
|
}
|
|
313
216
|
}
|
|
314
217
|
```
|
|
315
218
|
|
|
316
|
-
|
|
219
|
+
Oldest messages are deleted when the count exceeds the limit. This controls storage only -- it does not affect what is sent to the LLM.
|
|
317
220
|
|
|
318
|
-
|
|
221
|
+
### Controlling LLM context
|
|
319
222
|
|
|
320
|
-
|
|
321
|
-
import { useAgent } from "agents/react";
|
|
322
|
-
import { useAgentChat } from "@cloudflare/ai-chat/react";
|
|
323
|
-
import { tool } from "ai";
|
|
324
|
-
import { z } from "zod";
|
|
223
|
+
Use the AI SDK's `pruneMessages()` to control what is sent to the model, independently of what is stored:
|
|
325
224
|
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
const { messages, sendMessage, addToolResult } = useAgentChat({
|
|
330
|
-
agent,
|
|
331
|
-
onToolCall: async ({ toolCall, addToolOutput }) => {
|
|
332
|
-
if (toolCall.toolName === "showAlert") {
|
|
333
|
-
alert(toolCall.input.message);
|
|
334
|
-
addToolOutput({
|
|
335
|
-
toolCallId: toolCall.toolCallId,
|
|
336
|
-
output: { success: true }
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
});
|
|
225
|
+
```typescript
|
|
226
|
+
import { createWorkersAI } from "workers-ai-provider";
|
|
227
|
+
import { streamText, convertToModelMessages, pruneMessages } from "ai";
|
|
341
228
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
// description: "Shows an alert to the user",
|
|
345
|
-
// parameters: z.object({ message: z.string() })
|
|
346
|
-
// // No execute = client handles it
|
|
347
|
-
// })
|
|
348
|
-
}
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
#### Human-in-the-Loop Tools
|
|
229
|
+
export class ChatAgent extends AIChatAgent {
|
|
230
|
+
maxPersistedMessages = 200;
|
|
352
231
|
|
|
353
|
-
For tools requiring user approval before execution:
|
|
354
|
-
|
|
355
|
-
```tsx
|
|
356
|
-
import { useAgentChat } from "@cloudflare/ai-chat/react";
|
|
357
|
-
|
|
358
|
-
function HumanInTheLoopChat() {
|
|
359
|
-
const agent = useAgent({ agent: "ApprovalChat" });
|
|
360
|
-
|
|
361
|
-
const { messages, sendMessage, addToolResult } = useAgentChat({
|
|
362
|
-
agent,
|
|
363
|
-
toolsRequiringConfirmation: ["sendEmail", "deleteFile"],
|
|
364
|
-
onToolCall: async ({ toolCall, addToolOutput }) => {
|
|
365
|
-
if (toolCall.toolName === "sendEmail") {
|
|
366
|
-
const approved = confirm(`Send email to ${toolCall.input.recipient}?`);
|
|
367
|
-
if (approved) {
|
|
368
|
-
// Execute the tool
|
|
369
|
-
const result = await sendEmail(toolCall.input);
|
|
370
|
-
addToolOutput({
|
|
371
|
-
toolCallId: toolCall.toolCallId,
|
|
372
|
-
output: result,
|
|
373
|
-
autoContinue: true // Automatically continue after tool result
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
});
|
|
379
|
-
}
|
|
380
|
-
```
|
|
381
|
-
|
|
382
|
-
### 📊 Message Metadata
|
|
383
|
-
|
|
384
|
-
Attach custom metadata to messages for tracking, analytics, or display purposes:
|
|
385
|
-
|
|
386
|
-
```ts
|
|
387
|
-
import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
388
|
-
import { openai } from "@ai-sdk/openai";
|
|
389
|
-
import {
|
|
390
|
-
streamText,
|
|
391
|
-
convertToModelMessages,
|
|
392
|
-
createUIMessageStream,
|
|
393
|
-
createUIMessageStreamResponse
|
|
394
|
-
} from "ai";
|
|
395
|
-
|
|
396
|
-
export class MetadataChat extends AIChatAgent<Env> {
|
|
397
232
|
async onChatMessage() {
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
writer.merge(
|
|
408
|
-
result.toUIMessageStream({
|
|
409
|
-
messageMetadata: ({ part }) => {
|
|
410
|
-
if (part.type === "start") {
|
|
411
|
-
return {
|
|
412
|
-
model: "gpt-4o",
|
|
413
|
-
createdAt: Date.now(),
|
|
414
|
-
messageCount: this.messages.length
|
|
415
|
-
};
|
|
416
|
-
}
|
|
417
|
-
if (part.type === "finish") {
|
|
418
|
-
return {
|
|
419
|
-
responseTime: Date.now() - startTime,
|
|
420
|
-
totalTokens: part.totalUsage?.totalTokens
|
|
421
|
-
};
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
})
|
|
425
|
-
);
|
|
426
|
-
}
|
|
233
|
+
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
234
|
+
|
|
235
|
+
const result = streamText({
|
|
236
|
+
model: workersai("@cf/zai-org/glm-4.7-flash"),
|
|
237
|
+
messages: pruneMessages({
|
|
238
|
+
messages: await convertToModelMessages(this.messages),
|
|
239
|
+
reasoning: "before-last-message",
|
|
240
|
+
toolCalls: "before-last-2-messages"
|
|
241
|
+
})
|
|
427
242
|
});
|
|
428
243
|
|
|
429
|
-
return
|
|
244
|
+
return result.toUIMessageStreamResponse();
|
|
430
245
|
}
|
|
431
246
|
}
|
|
432
247
|
```
|
|
433
248
|
|
|
434
|
-
|
|
249
|
+
### Row size protection
|
|
435
250
|
|
|
436
|
-
|
|
437
|
-
{
|
|
438
|
-
messages.map((message) => (
|
|
439
|
-
<div key={message.id}>
|
|
440
|
-
{message.metadata?.createdAt && (
|
|
441
|
-
<span>{new Date(message.metadata.createdAt).toLocaleTimeString()}</span>
|
|
442
|
-
)}
|
|
443
|
-
{message.metadata?.totalTokens && (
|
|
444
|
-
<span>{message.metadata.totalTokens} tokens</span>
|
|
445
|
-
)}
|
|
446
|
-
</div>
|
|
447
|
-
));
|
|
448
|
-
}
|
|
449
|
-
```
|
|
450
|
-
|
|
451
|
-
For more details, see the [AI SDK Message Metadata documentation](https://ai-sdk.dev/docs/ai-sdk-ui/message-metadata).
|
|
251
|
+
Messages approaching SQLite's 2MB row limit are automatically compacted. Large tool outputs are replaced with an LLM-friendly summary that instructs the model to suggest re-running the tool. Compacted messages include `metadata.compactedToolOutputs` so clients can detect and display this gracefully.
|
|
452
252
|
|
|
453
|
-
|
|
253
|
+
## Custom Request Data
|
|
454
254
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
Add custom headers or context to requests:
|
|
255
|
+
Include custom data with every chat request using the `body` option:
|
|
458
256
|
|
|
459
257
|
```tsx
|
|
460
258
|
const { messages, sendMessage } = useAgentChat({
|
|
461
259
|
agent,
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
userTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone
|
|
466
|
-
},
|
|
467
|
-
headers: {
|
|
468
|
-
"X-Widget-Version": "1.0.0",
|
|
469
|
-
"X-Request-ID": crypto.randomUUID()
|
|
470
|
-
}
|
|
471
|
-
})
|
|
472
|
-
});
|
|
473
|
-
```
|
|
474
|
-
|
|
475
|
-
#### Automatic Tool Continuation
|
|
476
|
-
|
|
477
|
-
Enable automatic continuation after tool results for seamless UX:
|
|
478
|
-
|
|
479
|
-
```tsx
|
|
480
|
-
const { messages, addToolResult } = useAgentChat({
|
|
481
|
-
agent,
|
|
482
|
-
autoContinueAfterToolResult: true, // Automatically continue after tool execution
|
|
483
|
-
onToolCall: async ({ toolCall, addToolOutput }) => {
|
|
484
|
-
const result = await executeTool(toolCall);
|
|
485
|
-
addToolOutput({
|
|
486
|
-
toolCallId: toolCall.toolCallId,
|
|
487
|
-
output: result,
|
|
488
|
-
autoContinue: true // Server will automatically continue the conversation
|
|
489
|
-
});
|
|
260
|
+
body: {
|
|
261
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
262
|
+
userId: "abc"
|
|
490
263
|
}
|
|
491
264
|
});
|
|
492
|
-
```
|
|
493
|
-
|
|
494
|
-
### 🎯 Real-World Examples
|
|
495
|
-
|
|
496
|
-
Explore these examples to see `@cloudflare/ai-chat` in action:
|
|
497
|
-
|
|
498
|
-
- **Basic Chat**: [`examples/playground/src/agents/chat.ts`](../../examples/playground/src/agents/chat.ts) - Simple streaming chat
|
|
499
|
-
- **Resumable Streaming**: [`examples/resumable-stream-chat/`](../../examples/resumable-stream-chat/) - Automatic stream resumption
|
|
500
|
-
- **Human-in-the-Loop**: [`guides/human-in-the-loop/`](../../guides/human-in-the-loop/) - Tools requiring user approval
|
|
501
265
|
|
|
502
|
-
|
|
266
|
+
// Or use a function for dynamic values:
|
|
267
|
+
body: () => ({ token: getAuthToken(), timestamp: Date.now() });
|
|
268
|
+
```
|
|
503
269
|
|
|
504
|
-
|
|
270
|
+
Access these fields on the server via `options.body`:
|
|
505
271
|
|
|
506
|
-
|
|
272
|
+
```typescript
|
|
273
|
+
async onChatMessage(onFinish, options) {
|
|
274
|
+
const { timezone, userId } = options?.body ?? {};
|
|
275
|
+
}
|
|
276
|
+
```
|
|
507
277
|
|
|
508
|
-
|
|
278
|
+
## API Reference
|
|
509
279
|
|
|
510
|
-
|
|
511
|
-
- `persistMessages(messages, excludeBroadcastIds?)`: Manually persist messages (usually automatic)
|
|
512
|
-
- `messages`: Array of current chat messages
|
|
280
|
+
### `AIChatAgent<Env, State>`
|
|
513
281
|
|
|
514
|
-
|
|
282
|
+
Extends `Agent` from the `agents` package.
|
|
515
283
|
|
|
516
|
-
|
|
284
|
+
| Property / Method | Type | Description |
|
|
285
|
+
| ------------------------------------ | --------------------- | --------------------------------------------------------------------------- |
|
|
286
|
+
| `messages` | `UIMessage[]` | Current conversation messages (loaded from SQLite) |
|
|
287
|
+
| `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
|
|
288
|
+
| `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
|
|
289
|
+
| `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
|
|
290
|
+
| `saveMessages(messages)` | `Promise<void>` | Persist messages and trigger `onChatMessage` |
|
|
517
291
|
|
|
518
|
-
|
|
292
|
+
### `useAgentChat(options)`
|
|
519
293
|
|
|
520
|
-
React hook for chat interactions.
|
|
294
|
+
React hook for chat interactions. Wraps the AI SDK's `useChat` with WebSocket transport.
|
|
521
295
|
|
|
522
296
|
**Options:**
|
|
523
297
|
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
298
|
+
| Option | Type | Description |
|
|
299
|
+
| ----------------------------- | --------------------------------------- | -------------------------------------------------------- |
|
|
300
|
+
| `agent` | `ReturnType<typeof useAgent>` | Agent connection (required) |
|
|
301
|
+
| `onToolCall` | `({ toolCall, addToolOutput }) => void` | Handle client-side tool execution |
|
|
302
|
+
| `autoContinueAfterToolResult` | `boolean` | Auto-continue after client tool results. Default: `true` |
|
|
303
|
+
| `resume` | `boolean` | Enable stream resumption. Default: `true` |
|
|
304
|
+
| `body` | `object \| () => object` | Custom data sent with every request (see below) |
|
|
305
|
+
| `prepareSendMessagesRequest` | `(options) => { body?, headers? }` | Advanced per-request customization |
|
|
306
|
+
| `getInitialMessages` | `(options) => Promise<UIMessage[]>` | Custom initial message loader |
|
|
530
307
|
|
|
531
308
|
**Returns:**
|
|
532
309
|
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
- Automatic message persistence in SQLite
|
|
544
|
-
- WebSocket-based real-time communication
|
|
545
|
-
- Resumable streaming infrastructure
|
|
546
|
-
- Tool execution coordination
|
|
547
|
-
|
|
548
|
-
For more information about the underlying agent framework, see the [`agents` README](../agents/README.md).
|
|
549
|
-
|
|
550
|
-
### 💬 The Path Forward
|
|
551
|
-
|
|
552
|
-
We're continuously improving `@cloudflare/ai-chat`:
|
|
310
|
+
| Property | Type | Description |
|
|
311
|
+
| ------------------------- | ---------------------------------- | ------------------------------------------------------- |
|
|
312
|
+
| `messages` | `UIMessage[]` | Chat messages |
|
|
313
|
+
| `sendMessage` | `(message) => void` | Send a message |
|
|
314
|
+
| `clearHistory` | `() => void` | Clear conversation |
|
|
315
|
+
| `addToolOutput` | `({ toolCallId, output }) => void` | Provide tool output |
|
|
316
|
+
| `addToolApprovalResponse` | `({ id, approved }) => void` | Approve/reject a tool |
|
|
317
|
+
| `setMessages` | `(messages \| updater) => void` | Set messages (syncs to server) |
|
|
318
|
+
| `status` | `string` | `"idle"` \| `"submitted"` \| `"streaming"` \| `"error"` |
|
|
553
319
|
|
|
554
|
-
|
|
555
|
-
- **Better Error Handling**: Graceful degradation and recovery
|
|
556
|
-
- **Performance Optimizations**: Faster streaming and lower latency
|
|
557
|
-
- **Developer Experience**: Better TypeScript types and debugging tools
|
|
320
|
+
### Exports
|
|
558
321
|
|
|
559
|
-
|
|
322
|
+
| Import path | What it provides |
|
|
323
|
+
| --------------------------- | --------------------------------------------------- |
|
|
324
|
+
| `@cloudflare/ai-chat` | `AIChatAgent`, `createToolsFromClientSchemas` |
|
|
325
|
+
| `@cloudflare/ai-chat/react` | `useAgentChat` |
|
|
326
|
+
| `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage` |
|
|
560
327
|
|
|
561
|
-
|
|
328
|
+
## Examples
|
|
562
329
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
4. Update documentation as needed
|
|
330
|
+
- [Resumable streaming chat](../../examples/resumable-stream-chat/) -- automatic stream resumption
|
|
331
|
+
- [Human-in-the-loop guide](../../guides/human-in-the-loop/) -- tool approval with `needsApproval` + `onToolCall`
|
|
332
|
+
- [Playground](../../examples/playground/) -- kitchen-sink demo of all SDK features
|
|
567
333
|
|
|
568
|
-
|
|
334
|
+
## License
|
|
569
335
|
|
|
570
|
-
MIT
|
|
336
|
+
MIT
|