@convex-dev/agent 0.2.0-alpha.2 → 0.2.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.
Files changed (96) hide show
  1. package/dist/client/createTool.d.ts +3 -5
  2. package/dist/client/createTool.d.ts.map +1 -1
  3. package/dist/client/createTool.js +0 -1
  4. package/dist/client/createTool.js.map +1 -1
  5. package/dist/client/definePlaygroundAPI.d.ts +28 -28
  6. package/dist/client/files.d.ts +8 -1
  7. package/dist/client/files.d.ts.map +1 -1
  8. package/dist/client/files.js +60 -5
  9. package/dist/client/files.js.map +1 -1
  10. package/dist/client/index.d.ts +223 -239
  11. package/dist/client/index.d.ts.map +1 -1
  12. package/dist/client/index.js +368 -382
  13. package/dist/client/index.js.map +1 -1
  14. package/dist/client/messages.d.ts +91 -373
  15. package/dist/client/messages.d.ts.map +1 -1
  16. package/dist/client/messages.js +7 -1
  17. package/dist/client/messages.js.map +1 -1
  18. package/dist/client/search.d.ts +15 -15
  19. package/dist/client/search.d.ts.map +1 -1
  20. package/dist/client/search.js +3 -3
  21. package/dist/client/search.js.map +1 -1
  22. package/dist/client/streaming.d.ts +21 -22
  23. package/dist/client/streaming.d.ts.map +1 -1
  24. package/dist/client/streaming.js +35 -40
  25. package/dist/client/streaming.js.map +1 -1
  26. package/dist/client/types.d.ts +148 -61
  27. package/dist/client/types.d.ts.map +1 -1
  28. package/dist/component/_generated/api.d.ts +47 -357
  29. package/dist/component/messages.d.ts +157 -150
  30. package/dist/component/messages.d.ts.map +1 -1
  31. package/dist/component/messages.js +124 -70
  32. package/dist/component/messages.js.map +1 -1
  33. package/dist/component/schema.d.ts +1147 -2687
  34. package/dist/component/schema.d.ts.map +1 -1
  35. package/dist/component/schema.js +5 -4
  36. package/dist/component/schema.js.map +1 -1
  37. package/dist/component/streams.d.ts +29 -323
  38. package/dist/component/streams.d.ts.map +1 -1
  39. package/dist/component/streams.js +104 -60
  40. package/dist/component/streams.js.map +1 -1
  41. package/dist/component/threads.d.ts +4 -4
  42. package/dist/component/users.d.ts +3 -3
  43. package/dist/mapping.d.ts +4 -1
  44. package/dist/mapping.d.ts.map +1 -1
  45. package/dist/mapping.js +17 -1
  46. package/dist/mapping.js.map +1 -1
  47. package/dist/parts.d.ts +3 -0
  48. package/dist/parts.d.ts.map +1 -0
  49. package/dist/parts.js +34 -0
  50. package/dist/parts.js.map +1 -0
  51. package/dist/react/SmoothText.d.ts +5 -0
  52. package/dist/react/SmoothText.d.ts.map +1 -0
  53. package/dist/react/SmoothText.js +6 -0
  54. package/dist/react/SmoothText.js.map +1 -0
  55. package/dist/react/deltas.d.ts +3 -2
  56. package/dist/react/deltas.d.ts.map +1 -1
  57. package/dist/react/deltas.js +19 -79
  58. package/dist/react/deltas.js.map +1 -1
  59. package/dist/react/index.d.ts +1 -0
  60. package/dist/react/index.d.ts.map +1 -1
  61. package/dist/react/index.js +31 -11
  62. package/dist/react/index.js.map +1 -1
  63. package/dist/react/optimisticallySendMessage.d.ts.map +1 -1
  64. package/dist/react/optimisticallySendMessage.js +2 -8
  65. package/dist/react/optimisticallySendMessage.js.map +1 -1
  66. package/dist/react/useSmoothText.d.ts +13 -12
  67. package/dist/react/useSmoothText.d.ts.map +1 -1
  68. package/dist/react/useSmoothText.js +1 -1
  69. package/dist/react/useSmoothText.js.map +1 -1
  70. package/dist/validators.d.ts +109 -1590
  71. package/dist/validators.d.ts.map +1 -1
  72. package/dist/validators.js +4 -81
  73. package/dist/validators.js.map +1 -1
  74. package/package.json +3 -3
  75. package/src/client/createTool.ts +4 -9
  76. package/src/client/files.ts +88 -10
  77. package/src/client/index.test.ts +9 -21
  78. package/src/client/index.ts +664 -650
  79. package/src/client/messages.ts +16 -2
  80. package/src/client/search.ts +10 -7
  81. package/src/client/streaming.ts +53 -57
  82. package/src/client/types.ts +227 -97
  83. package/src/component/_generated/api.d.ts +47 -357
  84. package/src/component/messages.ts +157 -96
  85. package/src/component/schema.ts +4 -4
  86. package/src/component/streams.ts +180 -69
  87. package/src/mapping.ts +23 -2
  88. package/src/parts.ts +39 -0
  89. package/src/react/SmoothText.tsx +9 -0
  90. package/src/react/deltas.test.ts +38 -42
  91. package/src/react/deltas.ts +24 -86
  92. package/src/react/index.ts +35 -13
  93. package/src/react/optimisticallySendMessage.ts +2 -8
  94. package/src/react/useSmoothText.ts +14 -15
  95. package/src/validators.test.ts +0 -17
  96. package/src/validators.ts +8 -101
@@ -1,6 +1,7 @@
1
- import type { LanguageModelV2 } from "@ai-sdk/provider";
2
- import type { ModelMessage, DeepPartial, GenerateObjectResult, GenerateTextResult, StepResult, StreamObjectResult, StreamTextResult, ToolSet, StopCondition, Schema, LanguageModel, EmbeddingModel, CallSettings } from "ai";
3
- import { type GenericActionCtx, type GenericDataModel, type PaginationOptions, type PaginationResult } from "convex/server";
1
+ import type { FlexibleSchema, IdGenerator, InferSchema } from "@ai-sdk/provider-utils";
2
+ import type { CallSettings, EmbeddingModel, GenerateObjectResult, GenerateTextResult, LanguageModel, ModelMessage, StepResult, StopCondition, StreamTextResult, ToolSet } from "ai";
3
+ import { generateObject, streamObject } from "ai";
4
+ import { type GenericDataModel, type PaginationOptions, type PaginationResult } from "convex/server";
4
5
  import type { MessageDoc, ThreadDoc } from "../component/schema.js";
5
6
  import type { threadFieldsSupportingPatch } from "../component/threads.js";
6
7
  import { type VectorDimension } from "../component/vector/tables.js";
@@ -9,21 +10,69 @@ import { type Message, type MessageStatus, type MessageWithMetadata, type Provid
9
10
  import { createTool } from "./createTool.js";
10
11
  import { type SaveMessageArgs, type SaveMessagesArgs } from "./messages.js";
11
12
  import { type StreamingOptions } from "./streaming.js";
12
- import type { ActionCtx, AgentComponent, ContextOptions, GenerationOutputMetadata, Options, OurObjectArgs, OurStreamObjectArgs, RawRequestResponseHandler, RunActionCtx, RunMutationCtx, RunQueryCtx, StorageOptions, StreamingTextArgs, SyncStreamsReturnValue, TextArgs, Thread, UsageHandler } from "./types.js";
13
- import type z from "zod/v3";
13
+ import type { ActionCtx, AgentComponent, ContextOptions, DefaultObjectSchema, GenerationOutputMetadata, MaybeCustomCtx, GenerateObjectArgs, ObjectMode, ObjectSchema, Options, RawRequestResponseHandler, RunActionCtx, RunMutationCtx, RunQueryCtx, StorageOptions, StreamingTextArgs, StreamObjectArgs, SyncStreamsReturnValue, TextArgs, Thread, UsageHandler } from "./types.js";
14
+ import type { DataModel } from "../component/_generated/dataModel.js";
14
15
  export { stepCountIs } from "ai";
15
16
  export { vMessageDoc, vThreadDoc } from "../component/schema.js";
16
- export { serializeDataOrUrl, deserializeMessage, serializeMessage, } from "../mapping.js";
17
+ export { deserializeMessage, serializeDataOrUrl, serializeMessage, } from "../mapping.js";
17
18
  export { vAssistantMessage, vContextOptions, vMessage, vPaginationResult, vProviderMetadata, vStorageOptions, vStreamArgs, vSystemMessage, vToolMessage, vUsage, vUserMessage, } from "../validators.js";
18
19
  export type { ToolCtx } from "./createTool.js";
20
+ export { definePlaygroundAPI, type AgentsFn, type PlaygroundAPI, } from "./definePlaygroundAPI.js";
19
21
  export { getFile, storeFile } from "./files.js";
20
- export { filterOutOrphanedToolMessages, fetchContextMessages, } from "./search.js";
21
- export { abortStream, listStreams, syncStreams } from "./streaming.js";
22
22
  export { listMessages, saveMessage, saveMessages, type SaveMessageArgs, type SaveMessagesArgs, } from "./messages.js";
23
+ export { fetchContextMessages, filterOutOrphanedToolMessages, } from "./search.js";
24
+ export { abortStream, listStreams, syncStreams } from "./streaming.js";
23
25
  export { createThread, getThreadMetadata } from "./threads.js";
24
26
  export { createTool, extractText, isTool };
25
- export { definePlaygroundAPI, type PlaygroundAPI, type AgentsFn, } from "./definePlaygroundAPI.js";
26
27
  export type { AgentComponent, ContextOptions, MessageDoc, ProviderMetadata, RawRequestResponseHandler, StorageOptions, StreamArgs, SyncStreamsReturnValue, Thread, ThreadDoc, Usage, UsageHandler, };
28
+ export type Config = {
29
+ /**
30
+ * The LLM model to use for generating / streaming text and objects.
31
+ * e.g.
32
+ * import { openai } from "@ai-sdk/openai"
33
+ * const myAgent = new Agent(components.agent, {
34
+ * languageModel: openai.chat("gpt-4o-mini"),
35
+ */
36
+ languageModel?: LanguageModel;
37
+ /**
38
+ * The model to use for text embeddings. Optional.
39
+ * If specified, it will use this for generating vector embeddings
40
+ * of chats, and can opt-in to doing vector search for automatic context
41
+ * on generateText, etc.
42
+ * e.g.
43
+ * import { openai } from "@ai-sdk/openai"
44
+ * const myAgent = new Agent(components.agent, {
45
+ * ...
46
+ * textEmbeddingModel: openai.embedding("text-embedding-3-small")
47
+ */
48
+ textEmbeddingModel?: EmbeddingModel<string>;
49
+ /**
50
+ * Options to determine what messages are included as context in message
51
+ * generation. To disable any messages automatically being added, pass:
52
+ * { recentMessages: 0 }
53
+ */
54
+ contextOptions?: ContextOptions;
55
+ /**
56
+ * Determines whether messages are automatically stored when passed as
57
+ * arguments or generated.
58
+ */
59
+ storageOptions?: StorageOptions;
60
+ /**
61
+ * The default settings to use for the LLM calls.
62
+ * This can be overridden at each generate/stream callsite on a per-field
63
+ * basis. To clear a default setting, you'll need to pass `undefined`.
64
+ */
65
+ callSettings?: CallSettings;
66
+ /**
67
+ * The usage handler to use for this agent.
68
+ */
69
+ usageHandler?: UsageHandler;
70
+ /**
71
+ * Called for each LLM request/response, so you can do things like
72
+ * log the raw request body or response headers to a table, or logs.
73
+ */
74
+ rawRequestResponseHandler?: RawRequestResponseHandler;
75
+ };
27
76
  export declare class Agent<
28
77
  /**
29
78
  * You can require that all `ctx` args to generateText & streamText
@@ -46,7 +95,7 @@ export declare class Agent<
46
95
  */
47
96
  CustomCtx extends object = object, AgentTools extends ToolSet = any> {
48
97
  component: AgentComponent;
49
- options: {
98
+ options: Config & {
50
99
  /**
51
100
  * The name for the agent. This will be attributed on each message
52
101
  * created by this agent.
@@ -57,20 +106,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
57
106
  * e.g.
58
107
  * import { openai } from "@ai-sdk/openai"
59
108
  * const myAgent = new Agent(components.agent, {
60
- * chat: openai.chat("gpt-4o-mini"),
109
+ * languageModel: openai.chat("gpt-4o-mini"),
61
110
  */
62
- chat: LanguageModel;
63
- /**
64
- * The model to use for text embeddings. Optional.
65
- * If specified, it will use this for generating vector embeddings
66
- * of chats, and can opt-in to doing vector search for automatic context
67
- * on generateText, etc.
68
- * e.g.
69
- * import { openai } from "@ai-sdk/openai"
70
- * const myAgent = new Agent(components.agent, {
71
- * textEmbedding: openai.embedding("text-embedding-3-small")
72
- */
73
- textEmbedding?: EmbeddingModel<string>;
111
+ languageModel: LanguageModel;
74
112
  /**
75
113
  * The default system prompt to put in each request.
76
114
  * Override per-prompt by passing the "system" parameter.
@@ -83,39 +121,17 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
83
121
  * (import { createTool } from "@convex-dev/agent")
84
122
  */
85
123
  tools?: AgentTools;
86
- /**
87
- * Options to determine what messages are included as context in message
88
- * generation. To disable any messages automatically being added, pass:
89
- * { recentMessages: 0 }
90
- */
91
- contextOptions?: ContextOptions;
92
- /**
93
- * Determines whether messages are automatically stored when passed as
94
- * arguments or generated.
95
- */
96
- storageOptions?: StorageOptions;
97
124
  /**
98
125
  * When generating or streaming text with tools available, this
99
126
  * determines when to stop. Defaults to stepCountIs(1).
100
127
  */
101
128
  stopWhen?: StopCondition<AgentTools> | Array<StopCondition<AgentTools>>;
102
129
  /**
103
- * The default settings to use for the LLM calls.
104
- * This can be overridden at each generate/stream callsite on a per-field
105
- * basis. To clear a default setting, you'll need to pass `undefined`.
106
- */
107
- callSettings?: CallSettings;
108
- /**
109
- * The usage handler to use for this agent.
110
- */
111
- usageHandler?: UsageHandler;
112
- /**
113
- * Called for each LLM request/response, so you can do things like
114
- * log the raw request body or response headers to a table, or logs.
130
+ * @deprecated Use `languageEmbeddingModel` instead.
115
131
  */
116
- rawRequestResponseHandler?: RawRequestResponseHandler;
132
+ chat?: LanguageModel;
117
133
  };
118
- constructor(component: AgentComponent, options: {
134
+ constructor(component: AgentComponent, options: Config & {
119
135
  /**
120
136
  * The name for the agent. This will be attributed on each message
121
137
  * created by this agent.
@@ -126,20 +142,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
126
142
  * e.g.
127
143
  * import { openai } from "@ai-sdk/openai"
128
144
  * const myAgent = new Agent(components.agent, {
129
- * chat: openai.chat("gpt-4o-mini"),
145
+ * languageModel: openai.chat("gpt-4o-mini"),
130
146
  */
131
- chat: LanguageModel;
132
- /**
133
- * The model to use for text embeddings. Optional.
134
- * If specified, it will use this for generating vector embeddings
135
- * of chats, and can opt-in to doing vector search for automatic context
136
- * on generateText, etc.
137
- * e.g.
138
- * import { openai } from "@ai-sdk/openai"
139
- * const myAgent = new Agent(components.agent, {
140
- * textEmbedding: openai.embedding("text-embedding-3-small")
141
- */
142
- textEmbedding?: EmbeddingModel<string>;
147
+ languageModel: LanguageModel;
143
148
  /**
144
149
  * The default system prompt to put in each request.
145
150
  * Override per-prompt by passing the "system" parameter.
@@ -152,37 +157,15 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
152
157
  * (import { createTool } from "@convex-dev/agent")
153
158
  */
154
159
  tools?: AgentTools;
155
- /**
156
- * Options to determine what messages are included as context in message
157
- * generation. To disable any messages automatically being added, pass:
158
- * { recentMessages: 0 }
159
- */
160
- contextOptions?: ContextOptions;
161
- /**
162
- * Determines whether messages are automatically stored when passed as
163
- * arguments or generated.
164
- */
165
- storageOptions?: StorageOptions;
166
160
  /**
167
161
  * When generating or streaming text with tools available, this
168
162
  * determines when to stop. Defaults to stepCountIs(1).
169
163
  */
170
164
  stopWhen?: StopCondition<AgentTools> | Array<StopCondition<AgentTools>>;
171
165
  /**
172
- * The default settings to use for the LLM calls.
173
- * This can be overridden at each generate/stream callsite on a per-field
174
- * basis. To clear a default setting, you'll need to pass `undefined`.
166
+ * @deprecated Use `languageEmbeddingModel` instead.
175
167
  */
176
- callSettings?: CallSettings;
177
- /**
178
- * The usage handler to use for this agent.
179
- */
180
- usageHandler?: UsageHandler;
181
- /**
182
- * Called for each LLM request/response, so you can do things like
183
- * log the raw request body or response headers to a table, or logs.
184
- */
185
- rawRequestResponseHandler?: RawRequestResponseHandler;
168
+ chat?: LanguageModel;
186
169
  });
187
170
  /**
188
171
  * Start a new thread with the agent. This will have a fresh history, though if
@@ -194,7 +177,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
194
177
  * @param args The thread metadata.
195
178
  * @returns The threadId of the new thread and the thread object.
196
179
  */
197
- createThread<ThreadTools extends ToolSet | undefined = undefined>(ctx: RunActionCtx & CustomCtx, args?: {
180
+ createThread(ctx: RunActionCtx & CustomCtx, args?: {
198
181
  /**
199
182
  * The userId to associate with the thread. If not provided, the thread will be
200
183
  * anonymous.
@@ -208,19 +191,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
208
191
  * The summary of the thread. Not currently used for anything.
209
192
  */
210
193
  summary?: string;
211
- /**
212
- * The usage handler to use for this thread. Overrides any handler
213
- * set in the agent constructor.
214
- */
215
- usageHandler?: UsageHandler;
216
- /**
217
- * The tools to use for this thread.
218
- * Overrides any tools passed in the agent constructor.
219
- */
220
- tools?: ThreadTools;
221
194
  }): Promise<{
222
195
  threadId: string;
223
- thread: Thread<ThreadTools extends undefined ? AgentTools : ThreadTools>;
196
+ thread: Thread<AgentTools>;
224
197
  }>;
225
198
  /**
226
199
  * Start a new thread with the agent. This will have a fresh history, though if
@@ -231,7 +204,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
231
204
  * @param args The thread metadata.
232
205
  * @returns The threadId of the new thread.
233
206
  */
234
- createThread<ThreadTools extends ToolSet | undefined = undefined>(ctx: RunMutationCtx, args?: {
207
+ createThread(ctx: RunMutationCtx, args?: {
235
208
  /**
236
209
  * The userId to associate with the thread. If not provided, the thread will be
237
210
  * anonymous.
@@ -245,16 +218,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
245
218
  * The summary of the thread. Not currently used for anything.
246
219
  */
247
220
  summary?: string;
248
- /**
249
- * The usage handler to use for this thread. Overrides any handler
250
- * set in the agent constructor.
251
- */
252
- usageHandler?: UsageHandler;
253
- /**
254
- * The tools to use for this thread.
255
- * Overrides any tools passed in the agent constructor.
256
- */
257
- tools?: ThreadTools;
258
221
  }): Promise<{
259
222
  threadId: string;
260
223
  }>;
@@ -266,7 +229,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
266
229
  * @param { threadId, userId }: the thread and user to associate the messages with.
267
230
  * @returns Functions bound to the userId and threadId on a `{thread}` object.
268
231
  */
269
- continueThread<ThreadTools extends ToolSet | undefined = undefined>(ctx: ActionCtx & CustomCtx, args: {
232
+ continueThread(ctx: ActionCtx & CustomCtx, args: {
270
233
  /**
271
234
  * The associated thread created by {@link createThread}
272
235
  */
@@ -276,18 +239,86 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
276
239
  * relevant messages from the same user as context for the LLM calls.
277
240
  */
278
241
  userId?: string | null;
242
+ }): Promise<{
243
+ thread: Thread<AgentTools>;
244
+ }>;
245
+ start<TOOLS extends ToolSet | undefined, T>(ctx: ActionCtx & CustomCtx,
246
+ /**
247
+ * These are the arguments you'll pass to the LLM call such as
248
+ * `generateText` or `streamText`. This function will look up the context
249
+ * and provide functions to save the steps, abort the generation, and more.
250
+ * The type of the arguments returned infers from the type of the arguments
251
+ * you pass here.
252
+ */
253
+ args: T & {
254
+ /**
255
+ * If provided, this message will be used as the "prompt" for the LLM call,
256
+ * instead of the prompt or messages.
257
+ * This is useful if you want to first save a user message, then use it as
258
+ * the prompt for the LLM call in another call.
259
+ */
260
+ promptMessageId?: string;
261
+ /**
262
+ * The model to use for the LLM calls. This will override the model specified
263
+ * in the Agent constructor.
264
+ */
265
+ model?: LanguageModel;
279
266
  /**
280
- * The usage handler to use for this thread. Overrides any handler
281
- * set in the agent constructor.
267
+ * The tools to use for the tool calls. This will override tools specified
268
+ * in the Agent constructor or createThread / continueThread.
282
269
  */
283
- usageHandler?: UsageHandler;
270
+ tools?: TOOLS;
284
271
  /**
285
- * The tools to use for this thread.
286
- * Overrides any tools passed in the agent constructor.
272
+ * The single prompt message to use for the LLM call. This will be the
273
+ * last message in the context. If it's a string, it will be a user role.
287
274
  */
288
- tools?: ThreadTools;
275
+ prompt?: string | (ModelMessage | Message)[];
276
+ /**
277
+ * If provided alongside prompt, the ordering will be:
278
+ * 1. system prompt
279
+ * 2. search context
280
+ * 3. recent messages
281
+ * 4. these messages
282
+ * 5. prompt messages, including those already on the same `order` as
283
+ * the promptMessageId message, if provided.
284
+ */
285
+ messages?: (ModelMessage | Message)[];
286
+ /**
287
+ * This will be the first message in the context, and overrides the
288
+ * agent's instructions.
289
+ */
290
+ system?: string;
291
+ /**
292
+ * The abort signal to be passed to the LLM call. If triggered, it will
293
+ * mark the pending message as failed. If the generation is asynchronously
294
+ * aborted, it will trigger this signal when detected.
295
+ */
296
+ abortSignal?: AbortSignal;
297
+ _internal?: {
298
+ generateId?: IdGenerator;
299
+ };
300
+ }, options?: Options & {
301
+ userId?: string | null;
302
+ threadId?: string;
289
303
  }): Promise<{
290
- thread: Thread<ThreadTools extends undefined ? AgentTools : ThreadTools>;
304
+ args: T & {
305
+ system?: string;
306
+ model: LanguageModel;
307
+ messages: ModelMessage[];
308
+ tools?: TOOLS extends undefined ? AgentTools : TOOLS;
309
+ } & CallSettings;
310
+ order: number;
311
+ stepOrder: number;
312
+ userId: string | undefined;
313
+ promptMessageId: string | undefined;
314
+ updateModel: (model: LanguageModel | undefined) => void;
315
+ save: <TOOLS extends ToolSet>(toSave: {
316
+ step: StepResult<TOOLS>;
317
+ } | {
318
+ object: GenerateObjectResult<unknown>;
319
+ }, createPendingMessage?: boolean) => Promise<void>;
320
+ fail: (reason: string) => Promise<void>;
321
+ getSavedMessages: () => MessageDoc[];
291
322
  }>;
292
323
  /**
293
324
  * This behaves like {@link generateText} from the "ai" package except that
@@ -297,21 +328,14 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
297
328
  * to a thread (and optionally userId).
298
329
  * @param ctx The context passed from the action function calling this.
299
330
  * @param { userId, threadId }: The user and thread to associate the message with
300
- * @param args The arguments to the generateText function, along with extra controls
331
+ * @param generateTextArgs The arguments to the generateText function, along with extra controls
301
332
  * for the {@link ContextOptions} and {@link StorageOptions}.
302
333
  * @returns The result of the generateText function.
303
334
  */
304
- generateText<TOOLS extends ToolSet | undefined = undefined, OUTPUT = never, OUTPUT_PARTIAL = never>(ctx: ActionCtx & CustomCtx, { userId: argsUserId, threadId, tools: threadTools, ...usageHandler }: {
335
+ generateText<TOOLS extends ToolSet | undefined = undefined, OUTPUT = never, OUTPUT_PARTIAL = never>(ctx: ActionCtx & CustomCtx, threadOpts: {
305
336
  userId?: string | null;
306
337
  threadId?: string;
307
- /**
308
- * The usage handler to use for this thread. Overrides any handler
309
- * set in the agent constructor.
310
- */
311
- usageHandler?: UsageHandler;
312
- /** Note: to get better type inference, pass tools in the next arg */
313
- tools?: ToolSet;
314
- }, args: TextArgs<AgentTools, TOOLS, OUTPUT, OUTPUT_PARTIAL>, options?: Options): Promise<GenerateTextResult<TOOLS extends undefined ? AgentTools : TOOLS, OUTPUT> & GenerationOutputMetadata>;
338
+ }, generateTextArgs: TextArgs<AgentTools, TOOLS, OUTPUT, OUTPUT_PARTIAL>, options?: Options): Promise<GenerateTextResult<TOOLS extends undefined ? AgentTools : TOOLS, OUTPUT> & GenerationOutputMetadata>;
315
339
  /**
316
340
  * This behaves like {@link streamText} from the "ai" package except that
317
341
  * it add context based on the userId and threadId and saves the input and
@@ -319,18 +343,14 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
319
343
  * Use {@link continueThread} to get a version of this function already scoped
320
344
  * to a thread (and optionally userId).
321
345
  */
322
- streamText<TOOLS extends ToolSet | undefined = undefined, OUTPUT = never, PARTIAL_OUTPUT = never>(ctx: ActionCtx & CustomCtx, { userId: argsUserId, threadId,
323
- /** Note: to get better type inference, pass tools in the next arg */
324
- tools: threadTools, ...usageHandler }: {
346
+ streamText<TOOLS extends ToolSet | undefined = undefined, OUTPUT = never, PARTIAL_OUTPUT = never>(ctx: ActionCtx & CustomCtx, threadOpts: {
325
347
  userId?: string | null;
326
348
  threadId?: string;
327
- usageHandler?: UsageHandler;
328
- tools?: ToolSet;
329
349
  },
330
350
  /**
331
351
  * The arguments to the streamText function, similar to the ai `streamText` function.
332
352
  */
333
- args: StreamingTextArgs<AgentTools, TOOLS, OUTPUT, PARTIAL_OUTPUT>,
353
+ streamTextArgs: StreamingTextArgs<AgentTools, TOOLS, OUTPUT, PARTIAL_OUTPUT>,
334
354
  /**
335
355
  * The {@link ContextOptions} and {@link StorageOptions}
336
356
  * options to use for fetching contextual messages and saving input/output messages.
@@ -355,20 +375,19 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
355
375
  * Use {@link continueThread} to get a version of this function already scoped
356
376
  * to a thread (and optionally userId).
357
377
  */
358
- generateObject<T>(ctx: ActionCtx, { userId: argsUserId, threadId, ...usageHandler }: {
378
+ generateObject<SCHEMA extends ObjectSchema = DefaultObjectSchema, OUTPUT extends ObjectMode = InferSchema<SCHEMA> extends string ? "enum" : "object", RESULT = OUTPUT extends "array" ? Array<InferSchema<SCHEMA>> : InferSchema<SCHEMA>>(ctx: ActionCtx & CustomCtx, threadOpts: {
359
379
  userId?: string | null;
360
380
  threadId?: string;
361
- usageHandler?: UsageHandler;
362
381
  },
363
382
  /**
364
383
  * The arguments to the generateObject function, similar to the ai.generateObject function.
365
384
  */
366
- args: OurObjectArgs<T>,
385
+ generateObjectArgs: GenerateObjectArgs<SCHEMA, OUTPUT, RESULT>,
367
386
  /**
368
387
  * The {@link ContextOptions} and {@link StorageOptions}
369
388
  * options to use for fetching contextual messages and saving input/output messages.
370
389
  */
371
- options?: Options): Promise<GenerateObjectResult<T> & GenerationOutputMetadata>;
390
+ options?: Options): Promise<GenerateObjectResult<RESULT> & GenerationOutputMetadata>;
372
391
  /**
373
392
  * This behaves like `streamObject` from the "ai" package except that
374
393
  * it add context based on the userId and threadId and saves the input and
@@ -376,20 +395,32 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
376
395
  * Use {@link continueThread} to get a version of this function already scoped
377
396
  * to a thread (and optionally userId).
378
397
  */
379
- streamObject<T extends z.Schema | Schema>(ctx: ActionCtx, { userId: argsUserId, threadId, ...usageHandler }: {
398
+ streamObject<SCHEMA extends ObjectSchema = DefaultObjectSchema, OUTPUT extends ObjectMode = InferSchema<SCHEMA> extends string ? "enum" : "object", RESULT = OUTPUT extends "array" ? Array<InferSchema<SCHEMA>> : InferSchema<SCHEMA>>(ctx: ActionCtx & CustomCtx, threadOpts: {
380
399
  userId?: string | null;
381
400
  threadId?: string;
382
- usageHandler?: UsageHandler;
383
401
  },
384
402
  /**
385
403
  * The arguments to the streamObject function, similar to the ai `streamObject` function.
386
404
  */
387
- args: OurStreamObjectArgs<T>,
405
+ streamObjectArgs: StreamObjectArgs<SCHEMA, OUTPUT, RESULT> & {
406
+ /**
407
+ * If provided, this message will be used as the "prompt" for the LLM call,
408
+ * instead of the prompt or messages.
409
+ * This is useful if you want to first save a user message, then use it as
410
+ * the prompt for the LLM call in another call.
411
+ */
412
+ promptMessageId?: string;
413
+ /**
414
+ * The model to use for the LLM calls. This will override the model specified
415
+ * in the Agent constructor.
416
+ */
417
+ model?: LanguageModel;
418
+ },
388
419
  /**
389
420
  * The {@link ContextOptions} and {@link StorageOptions}
390
421
  * options to use for fetching contextual messages and saving input/output messages.
391
422
  */
392
- options?: Options): Promise<StreamObjectResult<DeepPartial<T>, T, never> & GenerationOutputMetadata>;
423
+ options?: Options): Promise<ReturnType<typeof streamObject<SCHEMA, OUTPUT, RESULT>> & GenerationOutputMetadata>;
393
424
  /**
394
425
  * Save a message to the thread.
395
426
  * @param ctx A ctx object from a mutation or action.
@@ -507,9 +538,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
507
538
  title?: string | undefined;
508
539
  type?: "source" | undefined;
509
540
  providerOptions?: Record<string, Record<string, any>> | undefined;
510
- url?: string | undefined;
511
541
  id: string;
512
542
  sourceType: "url";
543
+ url: string;
513
544
  } | {
514
545
  filename?: string | undefined;
515
546
  providerMetadata?: Record<string, Record<string, any>> | undefined;
@@ -519,6 +550,19 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
519
550
  sourceType: "document";
520
551
  mediaType: string;
521
552
  })[] | undefined;
553
+ warnings?: ({
554
+ details?: string | undefined;
555
+ type: "unsupported-setting";
556
+ setting: string;
557
+ } | {
558
+ details?: string | undefined;
559
+ type: "unsupported-tool";
560
+ tool: any;
561
+ } | {
562
+ type: "other";
563
+ message: string;
564
+ })[] | undefined;
565
+ finishReason?: "length" | "error" | "other" | "stop" | "content-filter" | "tool-calls" | "unknown" | undefined;
522
566
  reasoningDetails?: ({
523
567
  providerOptions?: Record<string, Record<string, any>> | undefined;
524
568
  signature?: string | undefined;
@@ -533,19 +577,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
533
577
  type: "redacted";
534
578
  data: string;
535
579
  })[] | undefined;
536
- warnings?: ({
537
- details?: string | undefined;
538
- type: "unsupported-setting";
539
- setting: string;
540
- } | {
541
- details?: string | undefined;
542
- type: "unsupported-tool";
543
- tool: any;
544
- } | {
545
- type: "other";
546
- message: string;
547
- })[] | undefined;
548
- finishReason?: "length" | "error" | "other" | "stop" | "content-filter" | "tool-calls" | "unknown" | undefined;
549
580
  _id: string;
550
581
  _creationTime: number;
551
582
  status: "pending" | "success" | "failed";
@@ -722,14 +753,13 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
722
753
  * @param args What message to save. Generally the parent message sent into
723
754
  * the generateText call.
724
755
  */
725
- completeMessage(ctx: RunMutationCtx, args: {
726
- threadId: string;
756
+ finalizeMessage(ctx: RunMutationCtx, args: {
727
757
  messageId: string;
728
758
  result: {
729
- kind: "error";
759
+ status: "failed";
730
760
  error: string;
731
761
  } | {
732
- kind: "success";
762
+ status: "success";
733
763
  };
734
764
  }): Promise<void>;
735
765
  /**
@@ -849,21 +879,23 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
849
879
  pageSize?: number;
850
880
  }): Promise<void>;
851
881
  _saveMessagesAndFetchContext<T extends {
852
- id?: string;
853
882
  prompt?: string | (ModelMessage | Message)[];
854
883
  messages?: (ModelMessage | Message)[];
855
884
  system?: string;
856
885
  promptMessageId?: string;
857
- model?: LanguageModelV2;
886
+ pendingMessageId?: string;
887
+ model?: LanguageModel;
858
888
  }>(ctx: RunActionCtx, args: T, { userId: argsUserId, threadId, contextOptions, storageOptions, }: {
859
- userId: string | undefined;
889
+ userId: string | null | undefined;
860
890
  threadId: string | undefined;
861
891
  } & Options): Promise<{
862
- args: T & {
863
- model: LanguageModelV2;
864
- };
892
+ args: Extract<T, {
893
+ model: LanguageModel;
894
+ messages: ModelMessage[];
895
+ }> & CallSettings;
865
896
  userId: string | undefined;
866
- messageId: string | undefined;
897
+ promptMessageId: string | undefined;
898
+ pendingMessageId: string | undefined;
867
899
  order: number | undefined;
868
900
  stepOrder: number | undefined;
869
901
  savedMessages: MessageDoc[] | undefined;
@@ -877,20 +909,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
877
909
  }): Promise<{
878
910
  embeddings: number[][];
879
911
  }>;
880
- /**
881
- * Process messages to inline file and image URLs that point to localhost
882
- * by converting them to base64. This solves the problem of LLMs not being
883
- * able to access localhost URLs.
884
- */
885
- private _inlineMessagesFiles;
886
- /**
887
- * Check if a URL points to localhost
888
- */
889
- private _isLocalhostUrl;
890
- /**
891
- * Download a file from a URL
892
- */
893
- private _downloadFile;
894
912
  /**
895
913
  * WORKFLOW UTILITIES
896
914
  */
@@ -925,23 +943,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
925
943
  * @param spec Configuration for the agent acting as an action, including
926
944
  * {@link ContextOptions}, {@link StorageOptions}, and {@link stopWhen}.
927
945
  */
928
- asTextAction<DataModel extends GenericDataModel>(spec?: {
929
- /**
930
- * When to stop generating text.
931
- * Defaults to the {@link Agent["options"].stopWhen} option.
932
- */
933
- stopWhen?: StopCondition<AgentTools> | Array<StopCondition<AgentTools>>;
934
- /**
935
- * The {@link ContextOptions} to use for fetching contextual messages and
936
- * saving input/output messages.
937
- * Defaults to the {@link Agent.contextOptions} option.
938
- */
939
- contextOptions?: ContextOptions;
940
- /**
941
- * The {@link StorageOptions} to use for saving input/output messages.
942
- * Defaults to the {@link Agent.storageOptions} option.
943
- */
944
- storageOptions?: StorageOptions;
946
+ asTextAction<DataModel extends GenericDataModel>(spec: MaybeCustomCtx<CustomCtx, DataModel, AgentTools> & {
945
947
  /**
946
948
  * Whether to stream the text.
947
949
  * If false, it will generate the text in a single call. (default)
@@ -950,30 +952,12 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
950
952
  * defaults if you pass true.
951
953
  */
952
954
  stream?: boolean | StreamingOptions;
953
- } & (CustomCtx extends Record<string, unknown> ? {
954
955
  /**
955
- * If you have a custom ctx that you use with the Agent
956
- * (e.g. new Agent<{ orgId: string }>(...))
957
- * you need to provide this function to add any extra fields.
958
- * e.g.
959
- * ```ts
960
- * const myAgent = new Agent<{ orgId: string }>(...);
961
- * const myAction = myAgent.asTextAction({
962
- * customCtx: (ctx: ActionCtx, target, llmArgs) => {
963
- * const orgId = await lookupOrgId(ctx, target.threadId);
964
- * return { orgId };
965
- * },
966
- * });
967
- * ```
968
- * Then, in your tools, you can
956
+ * When to stop generating text.
957
+ * Defaults to the {@link Agent["options"].stopWhen} option.
969
958
  */
970
- customCtx: (ctx: GenericActionCtx<DataModel>, target: {
971
- userId?: string | undefined;
972
- threadId?: string | undefined;
973
- }, llmArgs: TextArgs<AgentTools>) => CustomCtx;
974
- } : {
975
- customCtx?: never;
976
- })): import("convex/server").RegisteredAction<"internal", {
959
+ stopWhen?: StopCondition<AgentTools> | Array<StopCondition<AgentTools>>;
960
+ } & Options, overrides?: CallSettings): import("convex/server").RegisteredAction<"internal", {
977
961
  userId?: string | undefined;
978
962
  threadId?: string | undefined;
979
963
  providerOptions?: Record<string, Record<string, any>> | undefined;
@@ -1095,16 +1079,18 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1095
1079
  } | undefined;
1096
1080
  }, Promise<{
1097
1081
  text: string;
1098
- messageId: string | undefined;
1082
+ promptMessageId: string | undefined;
1099
1083
  order: number | undefined;
1100
1084
  finishReason: import("@ai-sdk/provider").LanguageModelV2FinishReason;
1101
1085
  warnings: Promise<import("@ai-sdk/provider").LanguageModelV2CallWarning[] | undefined>;
1086
+ savedMessageIds: string[];
1102
1087
  } | {
1103
1088
  text: string;
1104
- messageId: string | undefined;
1089
+ promptMessageId: string | undefined;
1105
1090
  order: number | undefined;
1106
1091
  finishReason: import("@ai-sdk/provider").LanguageModelV2FinishReason;
1107
1092
  warnings: import("@ai-sdk/provider").LanguageModelV2CallWarning[] | undefined;
1093
+ savedMessageIds: string[];
1108
1094
  }>>;
1109
1095
  /**
1110
1096
  * Create an action that generates an object out of this agent so you can call
@@ -1113,10 +1099,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1113
1099
  * the normal parameters to {@link generateObject}, plus {@link ContextOptions}
1114
1100
  * and stopWhen.
1115
1101
  */
1116
- asObjectAction<T>(spec: OurObjectArgs<T>, options?: {
1117
- contextOptions?: ContextOptions;
1118
- storageOptions?: StorageOptions;
1119
- }): import("convex/server").RegisteredAction<"internal", {
1102
+ asObjectAction<T>(objectArgs: Omit<Parameters<typeof generateObject<FlexibleSchema<T>>>[0], "model">, options?: Options & MaybeCustomCtx<CustomCtx, DataModel, AgentTools>): import("convex/server").RegisteredAction<"internal", {
1120
1103
  userId?: string | undefined;
1121
1104
  threadId?: string | undefined;
1122
1105
  providerOptions?: Record<string, Record<string, any>> | undefined;
@@ -1231,10 +1214,11 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1231
1214
  } | undefined;
1232
1215
  }, Promise<{
1233
1216
  object: T;
1234
- messageId: string | undefined;
1217
+ promptMessageId: string | undefined;
1235
1218
  order: number | undefined;
1236
1219
  finishReason: import("@ai-sdk/provider").LanguageModelV2FinishReason;
1237
1220
  warnings: import("@ai-sdk/provider").LanguageModelV2CallWarning[] | undefined;
1221
+ savedMessageIds: string[];
1238
1222
  }>>;
1239
1223
  /**
1240
1224
  * Save messages to the thread.
@@ -1285,9 +1269,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1285
1269
  title?: string | undefined;
1286
1270
  type?: "source" | undefined;
1287
1271
  providerOptions?: Record<string, Record<string, any>> | undefined;
1288
- url?: string | undefined;
1289
1272
  id: string;
1290
1273
  sourceType: "url";
1274
+ url: string;
1291
1275
  } | {
1292
1276
  filename?: string | undefined;
1293
1277
  providerMetadata?: Record<string, Record<string, any>> | undefined;
@@ -1297,6 +1281,19 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1297
1281
  sourceType: "document";
1298
1282
  mediaType: string;
1299
1283
  })[] | undefined;
1284
+ warnings?: ({
1285
+ details?: string | undefined;
1286
+ type: "unsupported-setting";
1287
+ setting: string;
1288
+ } | {
1289
+ details?: string | undefined;
1290
+ type: "unsupported-tool";
1291
+ tool: any;
1292
+ } | {
1293
+ type: "other";
1294
+ message: string;
1295
+ })[] | undefined;
1296
+ finishReason?: "length" | "error" | "other" | "stop" | "content-filter" | "tool-calls" | "unknown" | undefined;
1300
1297
  reasoningDetails?: ({
1301
1298
  providerOptions?: Record<string, Record<string, any>> | undefined;
1302
1299
  signature?: string | undefined;
@@ -1311,19 +1308,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1311
1308
  type: "redacted";
1312
1309
  data: string;
1313
1310
  })[] | undefined;
1314
- warnings?: ({
1315
- details?: string | undefined;
1316
- type: "unsupported-setting";
1317
- setting: string;
1318
- } | {
1319
- details?: string | undefined;
1320
- type: "unsupported-tool";
1321
- tool: any;
1322
- } | {
1323
- type: "other";
1324
- message: string;
1325
- })[] | undefined;
1326
- finishReason?: "length" | "error" | "other" | "stop" | "content-filter" | "tool-calls" | "unknown" | undefined;
1327
1311
  message: {
1328
1312
  providerOptions?: Record<string, Record<string, any>> | undefined;
1329
1313
  role: "user";