@convex-dev/agent 0.1.1-alpha.0 → 0.1.2-alpha.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 +9 -3
- package/dist/commonjs/client/createTool.d.ts +49 -0
- package/dist/commonjs/client/createTool.d.ts.map +1 -0
- package/dist/commonjs/client/createTool.js +45 -0
- package/dist/commonjs/client/createTool.js.map +1 -0
- package/dist/commonjs/client/index.d.ts +101 -322
- package/dist/commonjs/client/index.d.ts.map +1 -1
- package/dist/commonjs/client/index.js +142 -194
- package/dist/commonjs/client/index.js.map +1 -1
- package/dist/commonjs/client/streaming.d.ts +54 -0
- package/dist/commonjs/client/streaming.d.ts.map +1 -0
- package/dist/commonjs/client/streaming.js +121 -0
- package/dist/commonjs/client/streaming.js.map +1 -0
- package/dist/commonjs/client/types.d.ts +290 -2
- package/dist/commonjs/client/types.d.ts.map +1 -1
- package/dist/commonjs/component/messages.d.ts +109 -143
- package/dist/commonjs/component/messages.d.ts.map +1 -1
- package/dist/commonjs/component/messages.js +15 -14
- package/dist/commonjs/component/messages.js.map +1 -1
- package/dist/commonjs/component/schema.d.ts +1026 -52
- package/dist/commonjs/component/schema.d.ts.map +1 -1
- package/dist/commonjs/component/schema.js +39 -1
- package/dist/commonjs/component/schema.js.map +1 -1
- package/dist/commonjs/component/streams.d.ts +191 -0
- package/dist/commonjs/component/streams.d.ts.map +1 -0
- package/dist/commonjs/component/streams.js +169 -0
- package/dist/commonjs/component/streams.js.map +1 -0
- package/dist/commonjs/component/threads.d.ts +1 -1
- package/dist/commonjs/component/threads.js +3 -3
- package/dist/commonjs/component/threads.js.map +1 -1
- package/dist/commonjs/component/users.js +2 -2
- package/dist/commonjs/component/users.js.map +1 -1
- package/dist/commonjs/component/vector/index.d.ts +8 -8
- package/dist/commonjs/component/vector/index.d.ts.map +1 -1
- package/dist/commonjs/component/vector/tables.d.ts +5 -5
- package/dist/commonjs/component/vector/tables.d.ts.map +1 -1
- package/dist/commonjs/component/vector/tables.js +1 -1
- package/dist/commonjs/component/vector/tables.js.map +1 -1
- package/dist/commonjs/mapping.d.ts.map +1 -1
- package/dist/commonjs/mapping.js +3 -1
- package/dist/commonjs/mapping.js.map +1 -1
- package/dist/commonjs/react/index.d.ts +99 -0
- package/dist/commonjs/react/index.d.ts.map +1 -1
- package/dist/commonjs/react/index.js +505 -1
- package/dist/commonjs/react/index.js.map +1 -1
- package/dist/commonjs/react/toUIMessages.d.ts +8 -0
- package/dist/commonjs/react/toUIMessages.d.ts.map +1 -0
- package/dist/commonjs/react/toUIMessages.js +134 -0
- package/dist/commonjs/react/toUIMessages.js.map +1 -0
- package/dist/commonjs/validators.d.ts +513 -11
- package/dist/commonjs/validators.d.ts.map +1 -1
- package/dist/commonjs/validators.js +49 -2
- package/dist/commonjs/validators.js.map +1 -1
- package/dist/esm/client/createTool.d.ts +49 -0
- package/dist/esm/client/createTool.d.ts.map +1 -0
- package/dist/esm/client/createTool.js +45 -0
- package/dist/esm/client/createTool.js.map +1 -0
- package/dist/esm/client/index.d.ts +101 -322
- package/dist/esm/client/index.d.ts.map +1 -1
- package/dist/esm/client/index.js +142 -194
- package/dist/esm/client/index.js.map +1 -1
- package/dist/esm/client/streaming.d.ts +54 -0
- package/dist/esm/client/streaming.d.ts.map +1 -0
- package/dist/esm/client/streaming.js +121 -0
- package/dist/esm/client/streaming.js.map +1 -0
- package/dist/esm/client/types.d.ts +290 -2
- package/dist/esm/client/types.d.ts.map +1 -1
- package/dist/esm/component/messages.d.ts +109 -143
- package/dist/esm/component/messages.d.ts.map +1 -1
- package/dist/esm/component/messages.js +15 -14
- package/dist/esm/component/messages.js.map +1 -1
- package/dist/esm/component/schema.d.ts +1026 -52
- package/dist/esm/component/schema.d.ts.map +1 -1
- package/dist/esm/component/schema.js +39 -1
- package/dist/esm/component/schema.js.map +1 -1
- package/dist/esm/component/streams.d.ts +191 -0
- package/dist/esm/component/streams.d.ts.map +1 -0
- package/dist/esm/component/streams.js +169 -0
- package/dist/esm/component/streams.js.map +1 -0
- package/dist/esm/component/threads.d.ts +1 -1
- package/dist/esm/component/threads.js +3 -3
- package/dist/esm/component/threads.js.map +1 -1
- package/dist/esm/component/users.js +2 -2
- package/dist/esm/component/users.js.map +1 -1
- package/dist/esm/component/vector/index.d.ts +8 -8
- package/dist/esm/component/vector/index.d.ts.map +1 -1
- package/dist/esm/component/vector/tables.d.ts +5 -5
- package/dist/esm/component/vector/tables.d.ts.map +1 -1
- package/dist/esm/component/vector/tables.js +1 -1
- package/dist/esm/component/vector/tables.js.map +1 -1
- package/dist/esm/mapping.d.ts.map +1 -1
- package/dist/esm/mapping.js +3 -1
- package/dist/esm/mapping.js.map +1 -1
- package/dist/esm/react/index.d.ts +99 -0
- package/dist/esm/react/index.d.ts.map +1 -1
- package/dist/esm/react/index.js +505 -1
- package/dist/esm/react/index.js.map +1 -1
- package/dist/esm/react/toUIMessages.d.ts +8 -0
- package/dist/esm/react/toUIMessages.d.ts.map +1 -0
- package/dist/esm/react/toUIMessages.js +134 -0
- package/dist/esm/react/toUIMessages.js.map +1 -0
- package/dist/esm/validators.d.ts +513 -11
- package/dist/esm/validators.d.ts.map +1 -1
- package/dist/esm/validators.js +49 -2
- package/dist/esm/validators.js.map +1 -1
- package/package.json +6 -2
- package/src/client/createTool.ts +108 -0
- package/src/client/index.ts +270 -689
- package/src/client/streaming.ts +166 -0
- package/src/client/types.ts +430 -5
- package/src/component/_generated/api.d.ts +367 -190
- package/src/component/messages.ts +15 -14
- package/src/component/schema.ts +46 -0
- package/src/component/streams.ts +206 -0
- package/src/component/threads.ts +3 -3
- package/src/component/users.ts +2 -2
- package/src/component/vector/tables.ts +1 -1
- package/src/mapping.ts +3 -1
- package/src/react/index.ts +687 -1
- package/src/react/toUIMessages.ts +153 -0
- package/src/validators.test.ts +18 -0
- package/src/validators.ts +72 -2
- package/dist/commonjs/deltaStreaming.d.ts +0 -2
- package/dist/commonjs/deltaStreaming.d.ts.map +0 -1
- package/dist/commonjs/deltaStreaming.js +0 -2
- package/dist/commonjs/deltaStreaming.js.map +0 -1
- package/dist/esm/deltaStreaming.d.ts +0 -2
- package/dist/esm/deltaStreaming.d.ts.map +0 -1
- package/dist/esm/deltaStreaming.js +0 -2
- package/dist/esm/deltaStreaming.js.map +0 -1
- package/src/deltaStreaming.ts +0 -1
package/src/react/index.ts
CHANGED
|
@@ -1,10 +1,696 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TextPart, ToolCallPart, ToolResultPart } from "ai";
|
|
2
|
+
import type { BetterOmit, ErrorMessage, Expand } from "convex-helpers";
|
|
3
|
+
import {
|
|
4
|
+
type PaginatedQueryArgs,
|
|
5
|
+
usePaginatedQuery,
|
|
6
|
+
type UsePaginatedQueryResult,
|
|
7
|
+
useQuery,
|
|
8
|
+
} from "convex/react";
|
|
9
|
+
import type {
|
|
10
|
+
FunctionArgs,
|
|
11
|
+
FunctionReference,
|
|
12
|
+
PaginationOptions,
|
|
13
|
+
PaginationResult,
|
|
14
|
+
} from "convex/server";
|
|
15
|
+
import { useMemo, useState } from "react";
|
|
16
|
+
import type { MessageDoc } from "../client";
|
|
17
|
+
import type { SyncStreamsReturnValue } from "../client/types";
|
|
18
|
+
import type {
|
|
19
|
+
StreamArgs,
|
|
20
|
+
StreamDelta,
|
|
21
|
+
StreamMessage,
|
|
22
|
+
TextStreamPart,
|
|
23
|
+
} from "../validators";
|
|
24
|
+
import type { UIMessageOrdered } from "./toUIMessages";
|
|
25
|
+
import { toUIMessages } from "./toUIMessages";
|
|
26
|
+
|
|
27
|
+
export { toUIMessages, type UIMessageOrdered };
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A hook that fetches messages from a thread.
|
|
31
|
+
*
|
|
32
|
+
* This hook is a wrapper around `usePaginatedQuery` and `useStreamingThreadMessages`.
|
|
33
|
+
* It will fetch both full messages and streaming messages, and merge them together.
|
|
34
|
+
*
|
|
35
|
+
* The query must take as arguments `{ threadId, paginationOpts }` and return a
|
|
36
|
+
* pagination result of objects that extend `MessageDoc`.
|
|
37
|
+
*
|
|
38
|
+
* For streaming, it should look like this:
|
|
39
|
+
* ```ts
|
|
40
|
+
* export const listThreadMessages = query({
|
|
41
|
+
* args: {
|
|
42
|
+
* threadId: v.string(),
|
|
43
|
+
* paginationOpts: paginationOptsValidator,
|
|
44
|
+
* streamArgs: vStreamArgs,
|
|
45
|
+
* ... other arguments you want
|
|
46
|
+
* },
|
|
47
|
+
* handler: async (ctx, { threadId, paginationOpts, streamArgs }) => {
|
|
48
|
+
* // await authorizeThreadAccess(ctx, threadId);
|
|
49
|
+
* const paginated = await agent.listMessages(ctx, { threadId, paginationOpts });
|
|
50
|
+
* const streams = await agent.syncStreams(ctx, { threadId, streamArgs });
|
|
51
|
+
* // Here you could filter out / modify the documents & stream deltas.
|
|
52
|
+
* return { ...paginated, streams };
|
|
53
|
+
* },
|
|
54
|
+
* });
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* Then the hook can be used like this:
|
|
58
|
+
* ```ts
|
|
59
|
+
* const messages = useThreadMessages(
|
|
60
|
+
* api.myModule.listThreadMessages,
|
|
61
|
+
* { threadId },
|
|
62
|
+
* { initialNumItems: 10, stream: true }
|
|
63
|
+
* );
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
* @param query The query to use to fetch messages.
|
|
67
|
+
* It must take as arguments `{ threadId, paginationOpts }` and return a
|
|
68
|
+
* pagination result of objects that extend `MessageDoc`.
|
|
69
|
+
* To support streaming, it must also take in `streamArgs: vStreamArgs` and
|
|
70
|
+
* return a `streams` object returned from `agent.syncStreams`.
|
|
71
|
+
* @param args The arguments to pass to the query other than `paginationOpts`
|
|
72
|
+
* and `streamArgs`. So `{ threadId }` at minimum, plus any other arguments that
|
|
73
|
+
* you want to pass to the query.
|
|
74
|
+
* @param options The options for the query. Similar to usePaginatedQuery.
|
|
75
|
+
* To enable streaming, pass `stream: true`.
|
|
76
|
+
* @returns The messages. If stream is true, it will return a list of messages
|
|
77
|
+
* that includes both full messages and streaming messages.
|
|
78
|
+
*/
|
|
79
|
+
export function useThreadMessages<
|
|
80
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
81
|
+
Query extends ThreadQuery<any, any>,
|
|
82
|
+
>(
|
|
83
|
+
query: Query,
|
|
84
|
+
args: ThreadMessagesArgs<Query> | "skip",
|
|
85
|
+
options: {
|
|
86
|
+
initialNumItems: number;
|
|
87
|
+
stream?: Query extends ThreadStreamQuery
|
|
88
|
+
? boolean
|
|
89
|
+
: ErrorMessage<"To enable streaming, your query must take in streamArgs: vStreamArgs and return a streams object returned from agent.syncStreams. See docs.">;
|
|
90
|
+
}
|
|
91
|
+
): UsePaginatedQueryResult<
|
|
92
|
+
ThreadMessagesResult<Query> & { streaming?: boolean }
|
|
93
|
+
> {
|
|
94
|
+
// These are full messages
|
|
95
|
+
const paginated = usePaginatedQuery(
|
|
96
|
+
query,
|
|
97
|
+
args as PaginatedQueryArgs<Query> | "skip",
|
|
98
|
+
{ initialNumItems: options.initialNumItems }
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
// These are streaming messages that will not include full messages.
|
|
102
|
+
const streamMessages = useStreamingThreadMessages(
|
|
103
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
104
|
+
query as ThreadStreamQuery<any, any>,
|
|
105
|
+
!options.stream ? "skip" : args
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
const merged = useMemo(() => {
|
|
109
|
+
const streamListMessages =
|
|
110
|
+
streamMessages?.map((m) => ({
|
|
111
|
+
...m,
|
|
112
|
+
streaming: true,
|
|
113
|
+
})) ?? [];
|
|
114
|
+
return {
|
|
115
|
+
...paginated,
|
|
116
|
+
results: paginated.results
|
|
117
|
+
.map((m) => ({ ...m, streaming: false }))
|
|
118
|
+
.concat(streamListMessages)
|
|
119
|
+
.sort((a, b) =>
|
|
120
|
+
a.order === b.order ? a.stepOrder - b.stepOrder : a.order - b.order
|
|
121
|
+
)
|
|
122
|
+
// They shouldn't overlap, but check for duplicates just in case.
|
|
123
|
+
.filter(
|
|
124
|
+
(m, i, arr) =>
|
|
125
|
+
!arr[i - 1] ||
|
|
126
|
+
m.order !== arr[i - 1].order ||
|
|
127
|
+
m.stepOrder !== arr[i - 1].stepOrder
|
|
128
|
+
),
|
|
129
|
+
};
|
|
130
|
+
}, [paginated, streamMessages]);
|
|
131
|
+
|
|
132
|
+
return merged as ThreadMessagesResult<Query>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A hook that fetches streaming messages from a thread.
|
|
137
|
+
* This ONLY returns streaming messages. To get both, use `useThreadMessages`.
|
|
138
|
+
*
|
|
139
|
+
* @param query The query to use to fetch messages.
|
|
140
|
+
* It must take as arguments `{ threadId, paginationOpts, streamArgs }` and
|
|
141
|
+
* return a `streams` object returned from `agent.syncStreams`.
|
|
142
|
+
* @param args The arguments to pass to the query other than `paginationOpts`
|
|
143
|
+
* and `streamArgs`. So `{ threadId }` at minimum, plus any other arguments that
|
|
144
|
+
* you want to pass to the query.
|
|
145
|
+
* @returns The streaming messages.
|
|
146
|
+
*/
|
|
147
|
+
export function useStreamingThreadMessages<
|
|
148
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
149
|
+
Query extends ThreadStreamQuery<any, any>,
|
|
150
|
+
>(
|
|
151
|
+
query: Query,
|
|
152
|
+
args: ThreadMessagesArgs<Query> | "skip"
|
|
153
|
+
): Array<ThreadMessagesResult<Query>> | undefined {
|
|
154
|
+
// Invariant: streamMessages[streamId] is comprised of all deltas up to the
|
|
155
|
+
// cursor. There can be multiple messages in the same stream, e.g. for tool
|
|
156
|
+
// calls.
|
|
157
|
+
const [streams, setStreams] = useState<
|
|
158
|
+
Array<{ stream: StreamMessage; cursor: number; messages: MessageDoc[] }>
|
|
159
|
+
>([]);
|
|
160
|
+
// Get all the active streams
|
|
161
|
+
const streamList = useQuery(
|
|
162
|
+
query,
|
|
163
|
+
args === "skip"
|
|
164
|
+
? args
|
|
165
|
+
: ({
|
|
166
|
+
...args,
|
|
167
|
+
paginationOpts: { cursor: null, numItems: 0 },
|
|
168
|
+
streamArgs: { kind: "list" } as StreamArgs,
|
|
169
|
+
} as FunctionArgs<Query>)
|
|
170
|
+
) as
|
|
171
|
+
| { streams: Extract<SyncStreamsReturnValue, { kind: "list" }> }
|
|
172
|
+
| undefined;
|
|
173
|
+
// Get the cursors for all the active streams
|
|
174
|
+
const cursors = useMemo(() => {
|
|
175
|
+
if (!streamList?.streams) return [];
|
|
176
|
+
if (streamList.streams.kind !== "list") {
|
|
177
|
+
throw new Error("Expected list streams");
|
|
178
|
+
}
|
|
179
|
+
return streamList.streams.messages.map(({ streamId }) => {
|
|
180
|
+
const stream = streams.find((s) => s.stream.streamId === streamId);
|
|
181
|
+
// Because of the invariant, we can just take the last chunk's end.
|
|
182
|
+
const cursor = stream?.cursor ?? 0;
|
|
183
|
+
return { streamId, cursor };
|
|
184
|
+
});
|
|
185
|
+
}, [streamList, streams]);
|
|
186
|
+
// Get the deltas for all the active streams, if any.
|
|
187
|
+
const cursorQuery = useQuery(
|
|
188
|
+
query,
|
|
189
|
+
args === "skip" || !streamList
|
|
190
|
+
? ("skip" as const)
|
|
191
|
+
: ({
|
|
192
|
+
...args,
|
|
193
|
+
paginationOpts: { cursor: null, numItems: 0 },
|
|
194
|
+
streamArgs: { kind: "deltas", cursors } as StreamArgs,
|
|
195
|
+
} as FunctionArgs<Query>)
|
|
196
|
+
) as
|
|
197
|
+
| { streams: Extract<SyncStreamsReturnValue, { kind: "deltas" }> }
|
|
198
|
+
| undefined;
|
|
199
|
+
// Merge any deltas into the streamChunks, keeping it unmodified if unchanged.
|
|
200
|
+
const [messages, newStreams, changed] = useMemo(() => {
|
|
201
|
+
if (args === "skip") return [undefined, streams, false];
|
|
202
|
+
if (!streamList) return [undefined, streams, false];
|
|
203
|
+
if (cursorQuery && cursorQuery.streams?.kind !== "deltas") {
|
|
204
|
+
throw new Error("Expected deltas streams");
|
|
205
|
+
}
|
|
206
|
+
return mergeDeltas(
|
|
207
|
+
args.threadId,
|
|
208
|
+
streamList.streams.messages,
|
|
209
|
+
streams,
|
|
210
|
+
cursorQuery?.streams?.deltas ?? []
|
|
211
|
+
);
|
|
212
|
+
}, [cursorQuery, streams, streamList]);
|
|
213
|
+
// Now assemble the chunks into messages
|
|
214
|
+
if (args === "skip") {
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
217
|
+
if (changed) {
|
|
218
|
+
setStreams(newStreams);
|
|
219
|
+
}
|
|
220
|
+
return messages as ThreadMessagesResult<Query>[] | undefined;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function mergeDeltas(
|
|
224
|
+
threadId: string,
|
|
225
|
+
streamMessages: StreamMessage[],
|
|
226
|
+
existingStreams: Array<{
|
|
227
|
+
stream: StreamMessage;
|
|
228
|
+
cursor: number;
|
|
229
|
+
messages: MessageDoc[];
|
|
230
|
+
}>,
|
|
231
|
+
allDeltas: StreamDelta[]
|
|
232
|
+
): [
|
|
233
|
+
MessageDoc[],
|
|
234
|
+
Array<{ stream: StreamMessage; cursor: number; messages: MessageDoc[] }>,
|
|
235
|
+
boolean,
|
|
236
|
+
] {
|
|
237
|
+
const newStreams: Array<{
|
|
238
|
+
stream: StreamMessage;
|
|
239
|
+
cursor: number;
|
|
240
|
+
messages: MessageDoc[];
|
|
241
|
+
}> = [];
|
|
242
|
+
// Seed the existing chunks
|
|
243
|
+
let changed = false;
|
|
244
|
+
for (const streamMessage of streamMessages) {
|
|
245
|
+
const deltas = allDeltas
|
|
246
|
+
.filter((d) => d.streamId === streamMessage.streamId)
|
|
247
|
+
.sort((a, b) => a.start - b.start);
|
|
248
|
+
const existing = existingStreams.find(
|
|
249
|
+
(s) => s.stream.streamId === streamMessage.streamId
|
|
250
|
+
);
|
|
251
|
+
const [newStream, messageChanged] = applyDeltasToStreamMessages(
|
|
252
|
+
threadId,
|
|
253
|
+
streamMessage,
|
|
254
|
+
existing,
|
|
255
|
+
deltas
|
|
256
|
+
);
|
|
257
|
+
newStreams.push(newStream);
|
|
258
|
+
if (messageChanged) changed = true;
|
|
259
|
+
}
|
|
260
|
+
for (const { stream } of existingStreams) {
|
|
261
|
+
if (!newStreams.find((s) => s.stream.streamId === stream.streamId)) {
|
|
262
|
+
// There's a stream that's no longer active.
|
|
263
|
+
changed = true;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const messages = newStreams
|
|
267
|
+
.sort(
|
|
268
|
+
(a, b) =>
|
|
269
|
+
a.stream.order - b.stream.order ||
|
|
270
|
+
a.stream.stepOrder - b.stream.stepOrder
|
|
271
|
+
)
|
|
272
|
+
.map((s) => s.messages)
|
|
273
|
+
.flat();
|
|
274
|
+
return [messages, newStreams, changed];
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function applyDeltasToStreamMessages(
|
|
278
|
+
threadId: string,
|
|
279
|
+
streamMessage: StreamMessage,
|
|
280
|
+
existing:
|
|
281
|
+
| { stream: StreamMessage; cursor: number; messages: MessageDoc[] }
|
|
282
|
+
| undefined,
|
|
283
|
+
deltas: StreamDelta[]
|
|
284
|
+
): [
|
|
285
|
+
{ stream: StreamMessage; cursor: number; messages: MessageDoc[] },
|
|
286
|
+
boolean,
|
|
287
|
+
] {
|
|
288
|
+
let changed = false;
|
|
289
|
+
const newStream = {
|
|
290
|
+
stream: streamMessage,
|
|
291
|
+
cursor: existing?.cursor ?? 0,
|
|
292
|
+
messages: existing?.messages ?? [],
|
|
293
|
+
};
|
|
294
|
+
let parts: TextStreamPart[] = [];
|
|
295
|
+
for (const delta of deltas) {
|
|
296
|
+
if (delta.parts.length === 0) {
|
|
297
|
+
console.warn(`Got delta for stream ${delta.streamId} with no parts`);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (newStream.cursor !== delta.start) {
|
|
301
|
+
if (newStream.cursor >= delta.end) {
|
|
302
|
+
console.debug(
|
|
303
|
+
`Got duplicate delta for stream ${delta.streamId} at ${delta.start}`
|
|
304
|
+
);
|
|
305
|
+
continue;
|
|
306
|
+
} else if (newStream.cursor < delta.start) {
|
|
307
|
+
console.warn(
|
|
308
|
+
`Got delta for stream ${delta.streamId} that has a gap ${newStream.cursor} -> ${delta.start}`
|
|
309
|
+
);
|
|
310
|
+
continue;
|
|
311
|
+
} else {
|
|
312
|
+
throw new Error(
|
|
313
|
+
`Got unexpected delta for stream ${delta.streamId}: delta: ${delta.start} -> ${delta.end} existing cursor: ${newStream.cursor}`
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
changed = true;
|
|
318
|
+
newStream.cursor = delta.end;
|
|
319
|
+
parts.push(...delta.parts);
|
|
320
|
+
}
|
|
321
|
+
if (!changed) {
|
|
322
|
+
return [existing ?? newStream, false];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (!newStream.messages.at(-1)) {
|
|
326
|
+
newStream.messages.push(
|
|
327
|
+
createStreamingMessage(
|
|
328
|
+
threadId,
|
|
329
|
+
streamMessage,
|
|
330
|
+
parts[0]!,
|
|
331
|
+
newStream.messages.length
|
|
332
|
+
)
|
|
333
|
+
);
|
|
334
|
+
parts = parts.slice(1);
|
|
335
|
+
}
|
|
336
|
+
let currentMessage = newStream.messages.at(-1)!;
|
|
337
|
+
let lastContent = getLastContent(currentMessage);
|
|
338
|
+
for (const part of parts) {
|
|
339
|
+
let contentToAdd:
|
|
340
|
+
| TextPart
|
|
341
|
+
| ToolCallPart
|
|
342
|
+
| { type: "reasoning"; text: string }
|
|
343
|
+
| ToolResultPart
|
|
344
|
+
| undefined;
|
|
345
|
+
const isToolRole = part.type === "source" || part.type === "tool-result";
|
|
346
|
+
if (isToolRole !== (currentMessage.message!.role === "tool")) {
|
|
347
|
+
currentMessage = createStreamingMessage(
|
|
348
|
+
threadId,
|
|
349
|
+
streamMessage,
|
|
350
|
+
part,
|
|
351
|
+
newStream.messages.length
|
|
352
|
+
);
|
|
353
|
+
lastContent = getLastContent(currentMessage);
|
|
354
|
+
newStream.messages.push(currentMessage);
|
|
355
|
+
}
|
|
356
|
+
switch (part.type) {
|
|
357
|
+
case "text-delta":
|
|
358
|
+
currentMessage.text += part.textDelta;
|
|
359
|
+
if (lastContent?.type === "text") {
|
|
360
|
+
lastContent.text += part.textDelta;
|
|
361
|
+
} else {
|
|
362
|
+
contentToAdd = {
|
|
363
|
+
type: "text",
|
|
364
|
+
text: part.textDelta,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
break;
|
|
368
|
+
case "tool-call-streaming-start":
|
|
369
|
+
currentMessage.tool = true;
|
|
370
|
+
contentToAdd = {
|
|
371
|
+
type: "tool-call",
|
|
372
|
+
toolCallId: part.toolCallId,
|
|
373
|
+
toolName: part.toolName,
|
|
374
|
+
args: "",
|
|
375
|
+
};
|
|
376
|
+
break;
|
|
377
|
+
case "tool-call-delta":
|
|
378
|
+
{
|
|
379
|
+
currentMessage.tool = true;
|
|
380
|
+
if (lastContent?.type !== "tool-call") {
|
|
381
|
+
throw new Error("Expected last content to be a tool call");
|
|
382
|
+
}
|
|
383
|
+
if (typeof lastContent.args !== "string") {
|
|
384
|
+
throw new Error("Expected args to be a string");
|
|
385
|
+
}
|
|
386
|
+
lastContent.args += part.argsTextDelta;
|
|
387
|
+
}
|
|
388
|
+
break;
|
|
389
|
+
case "tool-call":
|
|
390
|
+
currentMessage.tool = true;
|
|
391
|
+
contentToAdd = part;
|
|
392
|
+
break;
|
|
393
|
+
case "reasoning":
|
|
394
|
+
if (lastContent?.type === "reasoning") {
|
|
395
|
+
lastContent.text += part.textDelta;
|
|
396
|
+
} else {
|
|
397
|
+
contentToAdd = {
|
|
398
|
+
type: "reasoning",
|
|
399
|
+
text: part.textDelta,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
break;
|
|
403
|
+
case "source":
|
|
404
|
+
if (!currentMessage.sources) {
|
|
405
|
+
currentMessage.sources = [];
|
|
406
|
+
}
|
|
407
|
+
currentMessage.sources.push(part.source);
|
|
408
|
+
break;
|
|
409
|
+
case "tool-result":
|
|
410
|
+
contentToAdd = part;
|
|
411
|
+
break;
|
|
412
|
+
default:
|
|
413
|
+
console.warn(`Received unexpected part: ${JSON.stringify(part)}`);
|
|
414
|
+
break;
|
|
415
|
+
}
|
|
416
|
+
if (contentToAdd) {
|
|
417
|
+
if (!currentMessage.message!.content) {
|
|
418
|
+
currentMessage.message!.content = [];
|
|
419
|
+
}
|
|
420
|
+
if (!Array.isArray(currentMessage.message?.content)) {
|
|
421
|
+
throw new Error("Expected message content to be an array");
|
|
422
|
+
}
|
|
423
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
424
|
+
currentMessage.message.content.push(contentToAdd as any);
|
|
425
|
+
lastContent = contentToAdd;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return [newStream, true];
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function getLastContent(message: MessageDoc) {
|
|
432
|
+
if (Array.isArray(message.message?.content)) {
|
|
433
|
+
return message.message.content.at(-1);
|
|
434
|
+
}
|
|
435
|
+
return undefined;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function createStreamingMessage(
|
|
439
|
+
threadId: string,
|
|
440
|
+
message: StreamMessage,
|
|
441
|
+
part: TextStreamPart,
|
|
442
|
+
index: number
|
|
443
|
+
): MessageDoc {
|
|
444
|
+
const { streamId, ...rest } = message;
|
|
445
|
+
const metadata: MessageDoc = {
|
|
446
|
+
_id: `${streamId}-${index}`,
|
|
447
|
+
_creationTime: Date.now(),
|
|
448
|
+
status: "pending",
|
|
449
|
+
threadId,
|
|
450
|
+
tool: false,
|
|
451
|
+
...rest,
|
|
452
|
+
};
|
|
453
|
+
switch (part.type) {
|
|
454
|
+
case "text-delta":
|
|
455
|
+
return {
|
|
456
|
+
...metadata,
|
|
457
|
+
message: {
|
|
458
|
+
role: "assistant",
|
|
459
|
+
content: [{ type: "text", text: part.textDelta }],
|
|
460
|
+
},
|
|
461
|
+
text: part.textDelta,
|
|
462
|
+
};
|
|
463
|
+
case "tool-call-streaming-start":
|
|
464
|
+
return {
|
|
465
|
+
...metadata,
|
|
466
|
+
tool: true,
|
|
467
|
+
message: {
|
|
468
|
+
role: "assistant",
|
|
469
|
+
content: [
|
|
470
|
+
{
|
|
471
|
+
type: "tool-call",
|
|
472
|
+
toolName: part.toolName,
|
|
473
|
+
toolCallId: part.toolCallId,
|
|
474
|
+
args: "", // when it's a string, it's a partial call
|
|
475
|
+
},
|
|
476
|
+
],
|
|
477
|
+
},
|
|
478
|
+
};
|
|
479
|
+
case "reasoning":
|
|
480
|
+
return {
|
|
481
|
+
...metadata,
|
|
482
|
+
message: {
|
|
483
|
+
role: "assistant",
|
|
484
|
+
content: [{ type: "reasoning", text: part.textDelta }],
|
|
485
|
+
},
|
|
486
|
+
reasoning: part.textDelta,
|
|
487
|
+
};
|
|
488
|
+
case "source":
|
|
489
|
+
console.warn("Received source part first??");
|
|
490
|
+
return {
|
|
491
|
+
...metadata,
|
|
492
|
+
tool: true,
|
|
493
|
+
message: { role: "tool", content: [] },
|
|
494
|
+
sources: [part.source],
|
|
495
|
+
};
|
|
496
|
+
case "tool-call":
|
|
497
|
+
return {
|
|
498
|
+
...metadata,
|
|
499
|
+
tool: true,
|
|
500
|
+
message: { role: "assistant", content: [part] },
|
|
501
|
+
};
|
|
502
|
+
case "tool-call-delta":
|
|
503
|
+
console.warn("Received tool call delta part first??");
|
|
504
|
+
return {
|
|
505
|
+
...metadata,
|
|
506
|
+
tool: true,
|
|
507
|
+
message: {
|
|
508
|
+
role: "assistant",
|
|
509
|
+
content: [
|
|
510
|
+
{
|
|
511
|
+
type: "tool-call",
|
|
512
|
+
toolCallId: part.toolCallId,
|
|
513
|
+
toolName: part.toolName,
|
|
514
|
+
args: part.argsTextDelta,
|
|
515
|
+
},
|
|
516
|
+
],
|
|
517
|
+
},
|
|
518
|
+
};
|
|
519
|
+
case "tool-result":
|
|
520
|
+
return {
|
|
521
|
+
...metadata,
|
|
522
|
+
tool: true,
|
|
523
|
+
message: { role: "tool", content: [part] },
|
|
524
|
+
};
|
|
525
|
+
default:
|
|
526
|
+
throw new Error(`Unexpected part type: ${JSON.stringify(part)}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
type ThreadQuery<
|
|
531
|
+
Args = unknown,
|
|
532
|
+
M extends MessageDoc = MessageDoc,
|
|
533
|
+
> = FunctionReference<
|
|
534
|
+
"query",
|
|
535
|
+
"public",
|
|
536
|
+
{
|
|
537
|
+
threadId: string;
|
|
538
|
+
paginationOpts: PaginationOptions;
|
|
539
|
+
// TODO: will this allow passing a function that doesn't have this param?
|
|
540
|
+
/**
|
|
541
|
+
* If { stream: true } is passed, it will also query for stream deltas.
|
|
542
|
+
* In order for this to work, the query must take as an argument streamArgs.
|
|
543
|
+
*/
|
|
544
|
+
streamArgs?: StreamArgs;
|
|
545
|
+
} & Args,
|
|
546
|
+
PaginationResult<M> & { streams?: SyncStreamsReturnValue }
|
|
547
|
+
>;
|
|
548
|
+
|
|
549
|
+
type ThreadStreamQuery<
|
|
550
|
+
Args = Record<string, unknown>,
|
|
551
|
+
M extends MessageDoc = MessageDoc,
|
|
552
|
+
> = FunctionReference<
|
|
553
|
+
"query",
|
|
554
|
+
"public",
|
|
555
|
+
{
|
|
556
|
+
threadId: string;
|
|
557
|
+
paginationOpts: PaginationOptions;
|
|
558
|
+
streamArgs?: StreamArgs; // required for stream query
|
|
559
|
+
} & Args,
|
|
560
|
+
PaginationResult<M> & { streams: SyncStreamsReturnValue }
|
|
561
|
+
>;
|
|
562
|
+
|
|
563
|
+
type ThreadMessagesArgs<Query extends ThreadQuery<unknown, MessageDoc>> =
|
|
564
|
+
Query extends ThreadQuery<unknown, MessageDoc>
|
|
565
|
+
? Expand<BetterOmit<FunctionArgs<Query>, "paginationOpts" | "streamArgs">>
|
|
566
|
+
: never;
|
|
567
|
+
|
|
568
|
+
type ThreadMessagesResult<Query extends ThreadQuery<unknown, MessageDoc>> =
|
|
569
|
+
Query extends ThreadQuery<unknown, infer M> ? M : never;
|
|
570
|
+
|
|
571
|
+
// TODO: pass in the messages we need to watch? that way it can be consistent..
|
|
572
|
+
|
|
573
|
+
// export function streamMessagesToUIMessages(
|
|
574
|
+
// messages: StreamsChunk[],
|
|
575
|
+
// keyOrder: string[]
|
|
576
|
+
// ): UIMessageOrdered[] {
|
|
577
|
+
// const uiMessagesByMessageId: Record<string, UIMessageOrdered[]> = {};
|
|
578
|
+
// for (const message of messages) {
|
|
579
|
+
// if (message.deltas.length === 0) {
|
|
580
|
+
// continue;
|
|
581
|
+
// }
|
|
582
|
+
// if (!uiMessagesByMessageId[message.key]) {
|
|
583
|
+
// uiMessagesByMessageId[message.key] = [];
|
|
584
|
+
// }
|
|
585
|
+
// if (uiMessagesByMessageId[message.key].length === 0) {
|
|
586
|
+
// uiMessagesByMessageId[message.key] = [
|
|
587
|
+
// createUIMessageFromPart(message.deltas[0], {
|
|
588
|
+
// id: message.key,
|
|
589
|
+
// createdAt: new Date(),
|
|
590
|
+
// }),
|
|
591
|
+
// ];
|
|
592
|
+
// }
|
|
593
|
+
// const currentMessage = uiMessagesByMessageId[message.key].at(-1)!;
|
|
594
|
+
// const lastPart = currentMessage.parts.at(-1);
|
|
595
|
+
// for (const delta of message.deltas) {
|
|
596
|
+
// switch (delta.type) {
|
|
597
|
+
// case "text-delta":
|
|
598
|
+
// currentMessage.content += delta.textDelta;
|
|
599
|
+
// if (lastPart?.type === "text") {
|
|
600
|
+
// lastPart.text += delta.textDelta;
|
|
601
|
+
// } else {
|
|
602
|
+
// currentMessage.parts.push({
|
|
603
|
+
// type: "text",
|
|
604
|
+
// text: delta.textDelta,
|
|
605
|
+
// });
|
|
606
|
+
// }
|
|
607
|
+
// break;
|
|
608
|
+
// case "tool-call-delta": {
|
|
609
|
+
// let lastToolInvocation: ToolInvocationUIPart | undefined;
|
|
610
|
+
// for (let i = currentMessage.parts.length - 1; i >= 0; i--) {
|
|
611
|
+
// const part = currentMessage.parts[i];
|
|
612
|
+
// if (
|
|
613
|
+
// part.type === "tool-invocation" &&
|
|
614
|
+
// part.toolInvocation.state === "partial-call"
|
|
615
|
+
// ) {
|
|
616
|
+
// lastToolInvocation = part;
|
|
617
|
+
// break;
|
|
618
|
+
// }
|
|
619
|
+
// }
|
|
620
|
+
// if (lastToolInvocation) {
|
|
621
|
+
// lastToolInvocation.toolInvocation = {
|
|
622
|
+
// ...lastToolInvocation.toolInvocation,
|
|
623
|
+
// state: "call",
|
|
624
|
+
// };
|
|
625
|
+
// break;
|
|
626
|
+
// }
|
|
627
|
+
// console.error(
|
|
628
|
+
// `Received a tool call delta without a previous tool invocation: ${JSON.stringify(currentMessage.parts)}, creating one anyways...`
|
|
629
|
+
// );
|
|
630
|
+
// }
|
|
631
|
+
// // fallthrough
|
|
632
|
+
// case "tool-call-streaming-start":
|
|
633
|
+
// currentMessage.parts.push({
|
|
634
|
+
// type: "tool-invocation",
|
|
635
|
+
// toolInvocation: {
|
|
636
|
+
// toolCallId: delta.toolCallId,
|
|
637
|
+
// toolName: delta.toolName,
|
|
638
|
+
// args: {},
|
|
639
|
+
// state: "partial-call",
|
|
640
|
+
// step:
|
|
641
|
+
// currentMessage.parts.filter(
|
|
642
|
+
// (part) => part.type === "tool-invocation"
|
|
643
|
+
// ).length + 1,
|
|
644
|
+
// },
|
|
645
|
+
// });
|
|
646
|
+
// break;
|
|
647
|
+
// case "tool-call":
|
|
648
|
+
// currentMessage.parts.push({
|
|
649
|
+
// type: "tool-invocation",
|
|
650
|
+
// toolInvocation: {
|
|
651
|
+
// toolCallId: delta.toolCallId,
|
|
652
|
+
// toolName: delta.toolName,
|
|
653
|
+
// args: delta.args,
|
|
654
|
+
// state: "call",
|
|
655
|
+
// step:
|
|
656
|
+
// currentMessage.parts.filter(
|
|
657
|
+
// (part) => part.type === "tool-invocation"
|
|
658
|
+
// ).length + 1,
|
|
659
|
+
// },
|
|
660
|
+
// });
|
|
661
|
+
// break;
|
|
662
|
+
// case "reasoning":
|
|
663
|
+
// if (lastPart?.type === "reasoning") {
|
|
664
|
+
// lastPart.reasoning += delta.textDelta;
|
|
665
|
+
// } else {
|
|
666
|
+
// currentMessage.parts.push({
|
|
667
|
+
// type: "reasoning",
|
|
668
|
+
// reasoning: delta.textDelta,
|
|
669
|
+
// details: [],
|
|
670
|
+
// });
|
|
671
|
+
// }
|
|
672
|
+
// break;
|
|
673
|
+
// case "source":
|
|
674
|
+
// currentMessage.parts.push({
|
|
675
|
+
// type: "source",
|
|
676
|
+
// source: delta.source,
|
|
677
|
+
// });
|
|
678
|
+
// break;
|
|
679
|
+
// default:
|
|
680
|
+
// console.warn(`Received unexpected part: ${JSON.stringify(delta)}`);
|
|
681
|
+
// break;
|
|
682
|
+
// }
|
|
683
|
+
// }
|
|
684
|
+
// }
|
|
685
|
+
// return keyOrder.map((key) => uiMessagesByMessageId[key]).flat();
|
|
686
|
+
// }
|
|
2
687
|
|
|
3
688
|
if (typeof window === "undefined") {
|
|
4
689
|
throw new Error("this is frontend code, but it's running somewhere else!");
|
|
5
690
|
}
|
|
6
691
|
|
|
7
692
|
/**
|
|
693
|
+
* @deprecated use useThreadMessages or useStreamingThreadMessages instead
|
|
8
694
|
* Use this hook to stream text from a server action, using the
|
|
9
695
|
* toTextStreamResponse or equivalent HTTP streaming endpoint returning text.
|
|
10
696
|
* @param url The URL of the server action to stream text from.
|