@cloudflare/ai-chat 0.5.3 → 0.6.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/README.md +59 -3
- package/dist/index.d.ts +104 -2
- package/dist/index.js +442 -29
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -102,7 +102,7 @@ Tools with an `execute` function run on the server automatically:
|
|
|
102
102
|
|
|
103
103
|
```typescript
|
|
104
104
|
import { createWorkersAI } from "workers-ai-provider";
|
|
105
|
-
import { streamText, convertToModelMessages, tool } from "ai";
|
|
105
|
+
import { streamText, convertToModelMessages, stepCountIs, tool } from "ai";
|
|
106
106
|
import { z } from "zod";
|
|
107
107
|
|
|
108
108
|
export class ChatAgent extends AIChatAgent {
|
|
@@ -122,7 +122,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
122
122
|
}
|
|
123
123
|
})
|
|
124
124
|
},
|
|
125
|
-
|
|
125
|
+
stopWhen: stepCountIs(5)
|
|
126
126
|
});
|
|
127
127
|
|
|
128
128
|
return result.toUIMessageStreamResponse();
|
|
@@ -188,6 +188,60 @@ const { messages, addToolApprovalResponse } = useAgentChat({ agent });
|
|
|
188
188
|
</button>
|
|
189
189
|
```
|
|
190
190
|
|
|
191
|
+
### Agent tools
|
|
192
|
+
|
|
193
|
+
`AIChatAgent` subclasses can be used as retained, streaming agent tools from a
|
|
194
|
+
parent agent through `runAgentTool()` or `agentTool()`:
|
|
195
|
+
|
|
196
|
+
```typescript
|
|
197
|
+
import { AIChatAgent } from "@cloudflare/ai-chat";
|
|
198
|
+
import { agentTool } from "agents/agent-tools";
|
|
199
|
+
import { convertToModelMessages, streamText } from "ai";
|
|
200
|
+
import { z } from "zod";
|
|
201
|
+
|
|
202
|
+
export class Summarizer extends AIChatAgent<Env> {
|
|
203
|
+
protected override formatAgentToolInput(input: { text: string }, request) {
|
|
204
|
+
return {
|
|
205
|
+
id: `agent-tool-${request.runId}-input`,
|
|
206
|
+
role: "user",
|
|
207
|
+
parts: [{ type: "text", text: `Summarize:\n\n${input.text}` }]
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async onChatMessage() {
|
|
212
|
+
const result = streamText({
|
|
213
|
+
model: this.env.MODEL,
|
|
214
|
+
messages: await convertToModelMessages(this.messages)
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
return result.toUIMessageStreamResponse();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export class ChatAgent extends AIChatAgent<Env> {
|
|
222
|
+
async onChatMessage() {
|
|
223
|
+
const result = streamText({
|
|
224
|
+
model: this.env.MODEL,
|
|
225
|
+
messages: await convertToModelMessages(this.messages),
|
|
226
|
+
tools: {
|
|
227
|
+
summarize: agentTool(Summarizer, {
|
|
228
|
+
description: "Summarize long text in a separate retained agent.",
|
|
229
|
+
inputSchema: z.object({ text: z.string() })
|
|
230
|
+
})
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
return result.toUIMessageStreamResponse();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Agent-tool turns are headless. Server-side tools work normally, but
|
|
240
|
+
browser-provided client tools are not available unless you design a separate
|
|
241
|
+
server-side or parent-mediated handoff. Override `formatAgentToolInput()`,
|
|
242
|
+
`getAgentToolOutput()`, and `getAgentToolSummary()` when you need structured
|
|
243
|
+
inputs or outputs.
|
|
244
|
+
|
|
191
245
|
## Resumable Streaming
|
|
192
246
|
|
|
193
247
|
Streams automatically resume on disconnect/reconnect. No configuration needed.
|
|
@@ -271,7 +325,9 @@ if (result.status === "aborted") {
|
|
|
271
325
|
|
|
272
326
|
This is the same shape `Think.saveMessages` uses — see
|
|
273
327
|
[`cloudflare/agents#1406`](https://github.com/cloudflare/agents/issues/1406)
|
|
274
|
-
for the
|
|
328
|
+
for the agent-tool orchestration pattern that motivated the API. The shipped
|
|
329
|
+
agent-tool API is documented in
|
|
330
|
+
[`docs/agent-tools.md`](../../docs/agent-tools.md).
|
|
275
331
|
|
|
276
332
|
## Storage Management
|
|
277
333
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
Agent,
|
|
3
|
+
AgentContext,
|
|
4
|
+
AgentToolRunInspection,
|
|
5
|
+
AgentToolStoredChunk,
|
|
6
|
+
FiberRecoveryContext
|
|
7
|
+
} from "agents";
|
|
2
8
|
import {
|
|
3
9
|
ChatRecoveryContext,
|
|
4
10
|
ChatRecoveryContext as ChatRecoveryContext$1,
|
|
@@ -148,6 +154,13 @@ declare class AIChatAgent<
|
|
|
148
154
|
* connections awaiting a continuation stream to start.
|
|
149
155
|
*/
|
|
150
156
|
private _continuation;
|
|
157
|
+
private _agentToolForwarders;
|
|
158
|
+
private _agentToolClosers;
|
|
159
|
+
private _agentToolAbortControllers;
|
|
160
|
+
private _agentToolLastErrors;
|
|
161
|
+
private _agentToolPreTurnAssistantIds;
|
|
162
|
+
private _agentToolLiveSequences;
|
|
163
|
+
private _agentToolActiveRunId;
|
|
151
164
|
/**
|
|
152
165
|
* Client tool schemas from the most recent chat request.
|
|
153
166
|
* Stored so they can be passed to onChatMessage during tool continuations.
|
|
@@ -250,7 +263,12 @@ declare class AIChatAgent<
|
|
|
250
263
|
* mutate the array directly.
|
|
251
264
|
*/
|
|
252
265
|
messages: UIMessage[];
|
|
266
|
+
broadcast(
|
|
267
|
+
msg: string | ArrayBuffer | ArrayBufferView,
|
|
268
|
+
without?: string[]
|
|
269
|
+
): void;
|
|
253
270
|
constructor(ctx: AgentContext, env: Env);
|
|
271
|
+
private _ensureAgentToolTables;
|
|
254
272
|
private _flushAwaitingStreamStartConnections;
|
|
255
273
|
private _mergeAutoContinuationPrerequisite;
|
|
256
274
|
private _storeDeferredAutoContinuation;
|
|
@@ -470,6 +488,68 @@ declare class AIChatAgent<
|
|
|
470
488
|
* ```
|
|
471
489
|
*/
|
|
472
490
|
protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
|
|
491
|
+
/**
|
|
492
|
+
* Convert an agent-tool input payload into the synthetic user message that
|
|
493
|
+
* starts a headless `AIChatAgent` turn.
|
|
494
|
+
*/
|
|
495
|
+
protected formatAgentToolInput(
|
|
496
|
+
input: unknown,
|
|
497
|
+
request: {
|
|
498
|
+
runId: string;
|
|
499
|
+
}
|
|
500
|
+
): UIMessage;
|
|
501
|
+
/**
|
|
502
|
+
* Override to return structured agent-tool output instead of the default
|
|
503
|
+
* final assistant text.
|
|
504
|
+
*/
|
|
505
|
+
protected getAgentToolOutput(
|
|
506
|
+
_request: {
|
|
507
|
+
runId: string;
|
|
508
|
+
input: unknown;
|
|
509
|
+
},
|
|
510
|
+
messagesAfterStart: readonly UIMessage[]
|
|
511
|
+
): unknown;
|
|
512
|
+
/**
|
|
513
|
+
* Override to customize the concise summary stored on the parent run.
|
|
514
|
+
*/
|
|
515
|
+
protected getAgentToolSummary(
|
|
516
|
+
_request: {
|
|
517
|
+
runId: string;
|
|
518
|
+
input: unknown;
|
|
519
|
+
},
|
|
520
|
+
output: unknown,
|
|
521
|
+
messagesAfterStart: readonly UIMessage[]
|
|
522
|
+
): string;
|
|
523
|
+
startAgentToolRun(
|
|
524
|
+
input: unknown,
|
|
525
|
+
options: {
|
|
526
|
+
runId: string;
|
|
527
|
+
signal?: AbortSignal;
|
|
528
|
+
}
|
|
529
|
+
): Promise<AgentToolRunInspection>;
|
|
530
|
+
cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
|
|
531
|
+
inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
|
|
532
|
+
getAgentToolChunks(
|
|
533
|
+
runId: string,
|
|
534
|
+
options?: {
|
|
535
|
+
afterSequence?: number;
|
|
536
|
+
}
|
|
537
|
+
): Promise<AgentToolStoredChunk[]>;
|
|
538
|
+
tailAgentToolRun(
|
|
539
|
+
runId: string,
|
|
540
|
+
options?: {
|
|
541
|
+
afterSequence?: number;
|
|
542
|
+
signal?: AbortSignal;
|
|
543
|
+
}
|
|
544
|
+
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
545
|
+
private _getAgentToolRunRow;
|
|
546
|
+
private _getAgentToolStreamId;
|
|
547
|
+
private _getAgentToolStoredChunks;
|
|
548
|
+
private _getAgentToolMessagesAfterStart;
|
|
549
|
+
private _closeAgentToolTailers;
|
|
550
|
+
private static _stringifyAgentToolValue;
|
|
551
|
+
private static _parseAgentToolValue;
|
|
552
|
+
private static _extractLatestAssistantText;
|
|
473
553
|
/**
|
|
474
554
|
* Persist messages and trigger `onChatMessage()` for a new response.
|
|
475
555
|
*
|
|
@@ -659,19 +739,41 @@ declare class AIChatAgent<
|
|
|
659
739
|
* the AI is still streaming), then retries persisted messages with backoff
|
|
660
740
|
* in case streaming completes between attempts.
|
|
661
741
|
*
|
|
742
|
+
* `applyUpdate` may return its argument by reference (or `{ ...part }`
|
|
743
|
+
* with no semantic changes) to signal an idempotent no-op — this is
|
|
744
|
+
* detected via `_isToolPartUnchanged` and short-circuits the SQLite
|
|
745
|
+
* write and `MESSAGE_UPDATED` broadcast.
|
|
746
|
+
*
|
|
662
747
|
* @param toolCallId - The tool call ID to find
|
|
663
748
|
* @param callerName - Name for log messages (e.g. "_applyToolResult")
|
|
664
749
|
* @param matchStates - Which tool part states to match
|
|
665
750
|
* @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
|
|
666
|
-
* @returns true if the update was applied
|
|
751
|
+
* @returns true if the update was applied (or matched as an idempotent
|
|
752
|
+
* no-op), false if no matching part was found
|
|
667
753
|
*/
|
|
668
754
|
private _findAndUpdateToolPart;
|
|
755
|
+
/**
|
|
756
|
+
* Returns true if `applied` is the same reference as `original`, or if
|
|
757
|
+
* the two have identical state-relevant fields. Used by
|
|
758
|
+
* `_findAndUpdateToolPart` to detect idempotent re-applies and skip
|
|
759
|
+
* SQLite writes plus `MESSAGE_UPDATED` broadcasts.
|
|
760
|
+
*/
|
|
761
|
+
private static _isToolPartUnchanged;
|
|
669
762
|
/**
|
|
670
763
|
* Applies a tool result to an existing assistant message.
|
|
671
764
|
* This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
|
|
672
765
|
* The server is the source of truth, so we update the message here and broadcast
|
|
673
766
|
* the update to all clients.
|
|
674
767
|
*
|
|
768
|
+
* `output-available` and `output-error` are accepted as valid starting
|
|
769
|
+
* states for *idempotent* re-application — duplicate WS frames, second
|
|
770
|
+
* tabs re-running the same tool, and provider-replay round-trips all
|
|
771
|
+
* become silent no-ops rather than a warn + skipped update. The first
|
|
772
|
+
* applied terminal result wins; subsequent results carrying *different*
|
|
773
|
+
* data are also dropped (preserving the existing "first write wins"
|
|
774
|
+
* contract — see `client-tool-duplicate-message.test.ts`). See issue
|
|
775
|
+
* #1404.
|
|
776
|
+
*
|
|
675
777
|
* @param toolCallId - The tool call ID this result is for
|
|
676
778
|
* @param _toolName - The name of the tool (unused, kept for API compat)
|
|
677
779
|
* @param output - The output from the tool execution
|