@convex-dev/agent 0.2.0-alpha.2 → 0.2.1

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 (100) hide show
  1. package/dist/client/createTool.d.ts +4 -6
  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 +9 -2
  7. package/dist/client/files.d.ts.map +1 -1
  8. package/dist/client/files.js +61 -6
  9. package/dist/client/files.js.map +1 -1
  10. package/dist/client/index.d.ts +232 -242
  11. package/dist/client/index.d.ts.map +1 -1
  12. package/dist/client/index.js +375 -383
  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 +30 -22
  23. package/dist/client/streaming.d.ts.map +1 -1
  24. package/dist/client/streaming.js +36 -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/shared.d.ts +3 -3
  71. package/dist/shared.d.ts.map +1 -1
  72. package/dist/shared.js.map +1 -1
  73. package/dist/validators.d.ts +109 -1590
  74. package/dist/validators.d.ts.map +1 -1
  75. package/dist/validators.js +4 -81
  76. package/dist/validators.js.map +1 -1
  77. package/package.json +3 -3
  78. package/src/client/createTool.ts +5 -10
  79. package/src/client/files.ts +89 -11
  80. package/src/client/index.test.ts +25 -35
  81. package/src/client/index.ts +686 -652
  82. package/src/client/messages.ts +16 -2
  83. package/src/client/search.ts +10 -7
  84. package/src/client/streaming.ts +62 -57
  85. package/src/client/types.ts +227 -97
  86. package/src/component/_generated/api.d.ts +47 -357
  87. package/src/component/messages.ts +157 -96
  88. package/src/component/schema.ts +4 -4
  89. package/src/component/streams.ts +180 -69
  90. package/src/mapping.ts +23 -2
  91. package/src/parts.ts +39 -0
  92. package/src/react/SmoothText.tsx +9 -0
  93. package/src/react/deltas.test.ts +38 -42
  94. package/src/react/deltas.ts +24 -86
  95. package/src/react/index.ts +35 -13
  96. package/src/react/optimisticallySendMessage.ts +2 -8
  97. package/src/react/useSmoothText.ts +14 -15
  98. package/src/shared.ts +3 -3
  99. package/src/validators.test.ts +0 -17
  100. 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, ProviderOptions } 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,75 @@ 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 { createThread, getThreadMetadata } from "./threads.js";
23
+ export { fetchContextMessages, filterOutOrphanedToolMessages, } from "./search.js";
24
+ export { abortStream, listStreams, syncStreams } from "./streaming.js";
25
+ export { createThread, getThreadMetadata, updateThreadMetadata, searchThreadTitles, } 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 usage handler to use for this agent.
62
+ */
63
+ usageHandler?: UsageHandler;
64
+ /**
65
+ * Called for each LLM request/response, so you can do things like
66
+ * log the raw request body or response headers to a table, or logs.
67
+ */
68
+ rawRequestResponseHandler?: RawRequestResponseHandler;
69
+ /**
70
+ * Default provider options to pass for the LLM calls.
71
+ * This can be overridden at each generate/stream callsite on a per-field
72
+ * basis. To clear a default setting, you'll need to pass `undefined`.
73
+ */
74
+ providerOptions?: ProviderOptions;
75
+ /**
76
+ * The default settings to use for the LLM calls.
77
+ * This can be overridden at each generate/stream callsite on a per-field
78
+ * basis. To clear a default setting, you'll need to pass `undefined`.
79
+ */
80
+ callSettings?: CallSettings;
81
+ };
27
82
  export declare class Agent<
28
83
  /**
29
84
  * You can require that all `ctx` args to generateText & streamText
@@ -46,31 +101,20 @@ export declare class Agent<
46
101
  */
47
102
  CustomCtx extends object = object, AgentTools extends ToolSet = any> {
48
103
  component: AgentComponent;
49
- options: {
104
+ options: Config & {
50
105
  /**
51
106
  * The name for the agent. This will be attributed on each message
52
107
  * created by this agent.
53
108
  */
54
- name?: string;
109
+ name: string;
55
110
  /**
56
111
  * The LLM model to use for generating / streaming text and objects.
57
112
  * e.g.
58
113
  * import { openai } from "@ai-sdk/openai"
59
114
  * const myAgent = new Agent(components.agent, {
60
- * chat: openai.chat("gpt-4o-mini"),
115
+ * languageModel: openai.chat("gpt-4o-mini"),
61
116
  */
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>;
117
+ languageModel: LanguageModel;
74
118
  /**
75
119
  * The default system prompt to put in each request.
76
120
  * Override per-prompt by passing the "system" parameter.
@@ -83,63 +127,30 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
83
127
  * (import { createTool } from "@convex-dev/agent")
84
128
  */
85
129
  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
130
  /**
98
131
  * When generating or streaming text with tools available, this
99
132
  * determines when to stop. Defaults to stepCountIs(1).
100
133
  */
101
134
  stopWhen?: StopCondition<AgentTools> | Array<StopCondition<AgentTools>>;
102
135
  /**
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.
136
+ * @deprecated Use `languageEmbeddingModel` instead.
110
137
  */
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.
115
- */
116
- rawRequestResponseHandler?: RawRequestResponseHandler;
138
+ chat?: LanguageModel;
117
139
  };
118
- constructor(component: AgentComponent, options: {
140
+ constructor(component: AgentComponent, options: Config & {
119
141
  /**
120
142
  * The name for the agent. This will be attributed on each message
121
143
  * created by this agent.
122
144
  */
123
- name?: string;
145
+ name: string;
124
146
  /**
125
147
  * The LLM model to use for generating / streaming text and objects.
126
148
  * e.g.
127
149
  * import { openai } from "@ai-sdk/openai"
128
150
  * const myAgent = new Agent(components.agent, {
129
- * chat: openai.chat("gpt-4o-mini"),
130
- */
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")
151
+ * languageModel: openai.chat("gpt-4o-mini"),
141
152
  */
142
- textEmbedding?: EmbeddingModel<string>;
153
+ languageModel: LanguageModel;
143
154
  /**
144
155
  * The default system prompt to put in each request.
145
156
  * Override per-prompt by passing the "system" parameter.
@@ -152,37 +163,15 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
152
163
  * (import { createTool } from "@convex-dev/agent")
153
164
  */
154
165
  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
166
  /**
167
167
  * When generating or streaming text with tools available, this
168
168
  * determines when to stop. Defaults to stepCountIs(1).
169
169
  */
170
170
  stopWhen?: StopCondition<AgentTools> | Array<StopCondition<AgentTools>>;
171
171
  /**
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`.
175
- */
176
- callSettings?: CallSettings;
177
- /**
178
- * The usage handler to use for this agent.
172
+ * @deprecated Use `languageEmbeddingModel` instead.
179
173
  */
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;
174
+ chat?: LanguageModel;
186
175
  });
187
176
  /**
188
177
  * Start a new thread with the agent. This will have a fresh history, though if
@@ -194,7 +183,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
194
183
  * @param args The thread metadata.
195
184
  * @returns The threadId of the new thread and the thread object.
196
185
  */
197
- createThread<ThreadTools extends ToolSet | undefined = undefined>(ctx: RunActionCtx & CustomCtx, args?: {
186
+ createThread(ctx: RunActionCtx & CustomCtx, args?: {
198
187
  /**
199
188
  * The userId to associate with the thread. If not provided, the thread will be
200
189
  * anonymous.
@@ -208,19 +197,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
208
197
  * The summary of the thread. Not currently used for anything.
209
198
  */
210
199
  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
200
  }): Promise<{
222
201
  threadId: string;
223
- thread: Thread<ThreadTools extends undefined ? AgentTools : ThreadTools>;
202
+ thread: Thread<AgentTools>;
224
203
  }>;
225
204
  /**
226
205
  * Start a new thread with the agent. This will have a fresh history, though if
@@ -231,7 +210,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
231
210
  * @param args The thread metadata.
232
211
  * @returns The threadId of the new thread.
233
212
  */
234
- createThread<ThreadTools extends ToolSet | undefined = undefined>(ctx: RunMutationCtx, args?: {
213
+ createThread(ctx: RunMutationCtx, args?: {
235
214
  /**
236
215
  * The userId to associate with the thread. If not provided, the thread will be
237
216
  * anonymous.
@@ -245,16 +224,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
245
224
  * The summary of the thread. Not currently used for anything.
246
225
  */
247
226
  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
227
  }): Promise<{
259
228
  threadId: string;
260
229
  }>;
@@ -266,7 +235,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
266
235
  * @param { threadId, userId }: the thread and user to associate the messages with.
267
236
  * @returns Functions bound to the userId and threadId on a `{thread}` object.
268
237
  */
269
- continueThread<ThreadTools extends ToolSet | undefined = undefined>(ctx: ActionCtx & CustomCtx, args: {
238
+ continueThread(ctx: ActionCtx & CustomCtx, args: {
270
239
  /**
271
240
  * The associated thread created by {@link createThread}
272
241
  */
@@ -276,18 +245,86 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
276
245
  * relevant messages from the same user as context for the LLM calls.
277
246
  */
278
247
  userId?: string | null;
248
+ }): Promise<{
249
+ thread: Thread<AgentTools>;
250
+ }>;
251
+ start<TOOLS extends ToolSet | undefined, T>(ctx: ActionCtx & CustomCtx,
252
+ /**
253
+ * These are the arguments you'll pass to the LLM call such as
254
+ * `generateText` or `streamText`. This function will look up the context
255
+ * and provide functions to save the steps, abort the generation, and more.
256
+ * The type of the arguments returned infers from the type of the arguments
257
+ * you pass here.
258
+ */
259
+ args: T & {
279
260
  /**
280
- * The usage handler to use for this thread. Overrides any handler
281
- * set in the agent constructor.
261
+ * If provided, this message will be used as the "prompt" for the LLM call,
262
+ * instead of the prompt or messages.
263
+ * This is useful if you want to first save a user message, then use it as
264
+ * the prompt for the LLM call in another call.
282
265
  */
283
- usageHandler?: UsageHandler;
266
+ promptMessageId?: string;
284
267
  /**
285
- * The tools to use for this thread.
286
- * Overrides any tools passed in the agent constructor.
268
+ * The model to use for the LLM calls. This will override the model specified
269
+ * in the Agent constructor.
287
270
  */
288
- tools?: ThreadTools;
271
+ model?: LanguageModel;
272
+ /**
273
+ * The tools to use for the tool calls. This will override tools specified
274
+ * in the Agent constructor or createThread / continueThread.
275
+ */
276
+ tools?: TOOLS;
277
+ /**
278
+ * The single prompt message to use for the LLM call. This will be the
279
+ * last message in the context. If it's a string, it will be a user role.
280
+ */
281
+ prompt?: string | (ModelMessage | Message)[];
282
+ /**
283
+ * If provided alongside prompt, the ordering will be:
284
+ * 1. system prompt
285
+ * 2. search context
286
+ * 3. recent messages
287
+ * 4. these messages
288
+ * 5. prompt messages, including those already on the same `order` as
289
+ * the promptMessageId message, if provided.
290
+ */
291
+ messages?: (ModelMessage | Message)[];
292
+ /**
293
+ * This will be the first message in the context, and overrides the
294
+ * agent's instructions.
295
+ */
296
+ system?: string;
297
+ /**
298
+ * The abort signal to be passed to the LLM call. If triggered, it will
299
+ * mark the pending message as failed. If the generation is asynchronously
300
+ * aborted, it will trigger this signal when detected.
301
+ */
302
+ abortSignal?: AbortSignal;
303
+ _internal?: {
304
+ generateId?: IdGenerator;
305
+ };
306
+ }, options?: Options & {
307
+ userId?: string | null;
308
+ threadId?: string;
289
309
  }): Promise<{
290
- thread: Thread<ThreadTools extends undefined ? AgentTools : ThreadTools>;
310
+ args: T & {
311
+ system?: string;
312
+ model: LanguageModel;
313
+ messages: ModelMessage[];
314
+ tools?: TOOLS extends undefined ? AgentTools : TOOLS;
315
+ } & CallSettings;
316
+ order: number;
317
+ stepOrder: number;
318
+ userId: string | undefined;
319
+ promptMessageId: string | undefined;
320
+ updateModel: (model: LanguageModel | undefined) => void;
321
+ save: <TOOLS extends ToolSet>(toSave: {
322
+ step: StepResult<TOOLS>;
323
+ } | {
324
+ object: GenerateObjectResult<unknown>;
325
+ }, createPendingMessage?: boolean) => Promise<void>;
326
+ fail: (reason: string) => Promise<void>;
327
+ getSavedMessages: () => MessageDoc[];
291
328
  }>;
292
329
  /**
293
330
  * This behaves like {@link generateText} from the "ai" package except that
@@ -297,21 +334,14 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
297
334
  * to a thread (and optionally userId).
298
335
  * @param ctx The context passed from the action function calling this.
299
336
  * @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
337
+ * @param generateTextArgs The arguments to the generateText function, along with extra controls
301
338
  * for the {@link ContextOptions} and {@link StorageOptions}.
302
339
  * @returns The result of the generateText function.
303
340
  */
304
- generateText<TOOLS extends ToolSet | undefined = undefined, OUTPUT = never, OUTPUT_PARTIAL = never>(ctx: ActionCtx & CustomCtx, { userId: argsUserId, threadId, tools: threadTools, ...usageHandler }: {
341
+ generateText<TOOLS extends ToolSet | undefined = undefined, OUTPUT = never, OUTPUT_PARTIAL = never>(ctx: ActionCtx & CustomCtx, threadOpts: {
305
342
  userId?: string | null;
306
343
  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>;
344
+ }, generateTextArgs: TextArgs<AgentTools, TOOLS, OUTPUT, OUTPUT_PARTIAL>, options?: Options): Promise<GenerateTextResult<TOOLS extends undefined ? AgentTools : TOOLS, OUTPUT> & GenerationOutputMetadata>;
315
345
  /**
316
346
  * This behaves like {@link streamText} from the "ai" package except that
317
347
  * it add context based on the userId and threadId and saves the input and
@@ -319,18 +349,14 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
319
349
  * Use {@link continueThread} to get a version of this function already scoped
320
350
  * to a thread (and optionally userId).
321
351
  */
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 }: {
352
+ streamText<TOOLS extends ToolSet | undefined = undefined, OUTPUT = never, PARTIAL_OUTPUT = never>(ctx: ActionCtx & CustomCtx, threadOpts: {
325
353
  userId?: string | null;
326
354
  threadId?: string;
327
- usageHandler?: UsageHandler;
328
- tools?: ToolSet;
329
355
  },
330
356
  /**
331
357
  * The arguments to the streamText function, similar to the ai `streamText` function.
332
358
  */
333
- args: StreamingTextArgs<AgentTools, TOOLS, OUTPUT, PARTIAL_OUTPUT>,
359
+ streamTextArgs: StreamingTextArgs<AgentTools, TOOLS, OUTPUT, PARTIAL_OUTPUT>,
334
360
  /**
335
361
  * The {@link ContextOptions} and {@link StorageOptions}
336
362
  * options to use for fetching contextual messages and saving input/output messages.
@@ -355,20 +381,19 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
355
381
  * Use {@link continueThread} to get a version of this function already scoped
356
382
  * to a thread (and optionally userId).
357
383
  */
358
- generateObject<T>(ctx: ActionCtx, { userId: argsUserId, threadId, ...usageHandler }: {
384
+ 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
385
  userId?: string | null;
360
386
  threadId?: string;
361
- usageHandler?: UsageHandler;
362
387
  },
363
388
  /**
364
389
  * The arguments to the generateObject function, similar to the ai.generateObject function.
365
390
  */
366
- args: OurObjectArgs<T>,
391
+ generateObjectArgs: GenerateObjectArgs<SCHEMA, OUTPUT, RESULT>,
367
392
  /**
368
393
  * The {@link ContextOptions} and {@link StorageOptions}
369
394
  * options to use for fetching contextual messages and saving input/output messages.
370
395
  */
371
- options?: Options): Promise<GenerateObjectResult<T> & GenerationOutputMetadata>;
396
+ options?: Options): Promise<GenerateObjectResult<RESULT> & GenerationOutputMetadata>;
372
397
  /**
373
398
  * This behaves like `streamObject` from the "ai" package except that
374
399
  * it add context based on the userId and threadId and saves the input and
@@ -376,20 +401,32 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
376
401
  * Use {@link continueThread} to get a version of this function already scoped
377
402
  * to a thread (and optionally userId).
378
403
  */
379
- streamObject<T extends z.Schema | Schema>(ctx: ActionCtx, { userId: argsUserId, threadId, ...usageHandler }: {
404
+ 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
405
  userId?: string | null;
381
406
  threadId?: string;
382
- usageHandler?: UsageHandler;
383
407
  },
384
408
  /**
385
409
  * The arguments to the streamObject function, similar to the ai `streamObject` function.
386
410
  */
387
- args: OurStreamObjectArgs<T>,
411
+ streamObjectArgs: StreamObjectArgs<SCHEMA, OUTPUT, RESULT> & {
412
+ /**
413
+ * If provided, this message will be used as the "prompt" for the LLM call,
414
+ * instead of the prompt or messages.
415
+ * This is useful if you want to first save a user message, then use it as
416
+ * the prompt for the LLM call in another call.
417
+ */
418
+ promptMessageId?: string;
419
+ /**
420
+ * The model to use for the LLM calls. This will override the model specified
421
+ * in the Agent constructor.
422
+ */
423
+ model?: LanguageModel;
424
+ },
388
425
  /**
389
426
  * The {@link ContextOptions} and {@link StorageOptions}
390
427
  * options to use for fetching contextual messages and saving input/output messages.
391
428
  */
392
- options?: Options): Promise<StreamObjectResult<DeepPartial<T>, T, never> & GenerationOutputMetadata>;
429
+ options?: Options): Promise<ReturnType<typeof streamObject<SCHEMA, OUTPUT, RESULT>> & GenerationOutputMetadata>;
393
430
  /**
394
431
  * Save a message to the thread.
395
432
  * @param ctx A ctx object from a mutation or action.
@@ -507,9 +544,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
507
544
  title?: string | undefined;
508
545
  type?: "source" | undefined;
509
546
  providerOptions?: Record<string, Record<string, any>> | undefined;
510
- url?: string | undefined;
511
547
  id: string;
512
548
  sourceType: "url";
549
+ url: string;
513
550
  } | {
514
551
  filename?: string | undefined;
515
552
  providerMetadata?: Record<string, Record<string, any>> | undefined;
@@ -519,6 +556,19 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
519
556
  sourceType: "document";
520
557
  mediaType: string;
521
558
  })[] | undefined;
559
+ warnings?: ({
560
+ details?: string | undefined;
561
+ type: "unsupported-setting";
562
+ setting: string;
563
+ } | {
564
+ details?: string | undefined;
565
+ type: "unsupported-tool";
566
+ tool: any;
567
+ } | {
568
+ type: "other";
569
+ message: string;
570
+ })[] | undefined;
571
+ finishReason?: "length" | "error" | "other" | "stop" | "content-filter" | "tool-calls" | "unknown" | undefined;
522
572
  reasoningDetails?: ({
523
573
  providerOptions?: Record<string, Record<string, any>> | undefined;
524
574
  signature?: string | undefined;
@@ -533,19 +583,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
533
583
  type: "redacted";
534
584
  data: string;
535
585
  })[] | 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
586
  _id: string;
550
587
  _creationTime: number;
551
588
  status: "pending" | "success" | "failed";
@@ -722,14 +759,13 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
722
759
  * @param args What message to save. Generally the parent message sent into
723
760
  * the generateText call.
724
761
  */
725
- completeMessage(ctx: RunMutationCtx, args: {
726
- threadId: string;
762
+ finalizeMessage(ctx: RunMutationCtx, args: {
727
763
  messageId: string;
728
764
  result: {
729
- kind: "error";
765
+ status: "failed";
730
766
  error: string;
731
767
  } | {
732
- kind: "success";
768
+ status: "success";
733
769
  };
734
770
  }): Promise<void>;
735
771
  /**
@@ -849,21 +885,23 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
849
885
  pageSize?: number;
850
886
  }): Promise<void>;
851
887
  _saveMessagesAndFetchContext<T extends {
852
- id?: string;
853
888
  prompt?: string | (ModelMessage | Message)[];
854
889
  messages?: (ModelMessage | Message)[];
855
890
  system?: string;
856
891
  promptMessageId?: string;
857
- model?: LanguageModelV2;
892
+ pendingMessageId?: string;
893
+ model?: LanguageModel;
858
894
  }>(ctx: RunActionCtx, args: T, { userId: argsUserId, threadId, contextOptions, storageOptions, }: {
859
- userId: string | undefined;
895
+ userId: string | null | undefined;
860
896
  threadId: string | undefined;
861
897
  } & Options): Promise<{
862
- args: T & {
863
- model: LanguageModelV2;
864
- };
898
+ args: Extract<T, {
899
+ model: LanguageModel;
900
+ messages: ModelMessage[];
901
+ }> & CallSettings;
865
902
  userId: string | undefined;
866
- messageId: string | undefined;
903
+ promptMessageId: string | undefined;
904
+ pendingMessageId: string | undefined;
867
905
  order: number | undefined;
868
906
  stepOrder: number | undefined;
869
907
  savedMessages: MessageDoc[] | undefined;
@@ -877,20 +915,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
877
915
  }): Promise<{
878
916
  embeddings: number[][];
879
917
  }>;
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
918
  /**
895
919
  * WORKFLOW UTILITIES
896
920
  */
@@ -925,23 +949,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
925
949
  * @param spec Configuration for the agent acting as an action, including
926
950
  * {@link ContextOptions}, {@link StorageOptions}, and {@link stopWhen}.
927
951
  */
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;
952
+ asTextAction<DataModel extends GenericDataModel>(spec: MaybeCustomCtx<CustomCtx, DataModel, AgentTools> & {
945
953
  /**
946
954
  * Whether to stream the text.
947
955
  * If false, it will generate the text in a single call. (default)
@@ -950,30 +958,12 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
950
958
  * defaults if you pass true.
951
959
  */
952
960
  stream?: boolean | StreamingOptions;
953
- } & (CustomCtx extends Record<string, unknown> ? {
954
961
  /**
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
962
+ * When to stop generating text.
963
+ * Defaults to the {@link Agent["options"].stopWhen} option.
969
964
  */
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", {
965
+ stopWhen?: StopCondition<AgentTools> | Array<StopCondition<AgentTools>>;
966
+ } & Options, overrides?: CallSettings): import("convex/server").RegisteredAction<"internal", {
977
967
  userId?: string | undefined;
978
968
  threadId?: string | undefined;
979
969
  providerOptions?: Record<string, Record<string, any>> | undefined;
@@ -1095,16 +1085,18 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1095
1085
  } | undefined;
1096
1086
  }, Promise<{
1097
1087
  text: string;
1098
- messageId: string | undefined;
1088
+ promptMessageId: string | undefined;
1099
1089
  order: number | undefined;
1100
1090
  finishReason: import("@ai-sdk/provider").LanguageModelV2FinishReason;
1101
1091
  warnings: Promise<import("@ai-sdk/provider").LanguageModelV2CallWarning[] | undefined>;
1092
+ savedMessageIds: string[];
1102
1093
  } | {
1103
1094
  text: string;
1104
- messageId: string | undefined;
1095
+ promptMessageId: string | undefined;
1105
1096
  order: number | undefined;
1106
1097
  finishReason: import("@ai-sdk/provider").LanguageModelV2FinishReason;
1107
1098
  warnings: import("@ai-sdk/provider").LanguageModelV2CallWarning[] | undefined;
1099
+ savedMessageIds: string[];
1108
1100
  }>>;
1109
1101
  /**
1110
1102
  * Create an action that generates an object out of this agent so you can call
@@ -1113,10 +1105,7 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1113
1105
  * the normal parameters to {@link generateObject}, plus {@link ContextOptions}
1114
1106
  * and stopWhen.
1115
1107
  */
1116
- asObjectAction<T>(spec: OurObjectArgs<T>, options?: {
1117
- contextOptions?: ContextOptions;
1118
- storageOptions?: StorageOptions;
1119
- }): import("convex/server").RegisteredAction<"internal", {
1108
+ asObjectAction<T>(objectArgs: Omit<Parameters<typeof generateObject<FlexibleSchema<T>>>[0], "model">, options?: Options & MaybeCustomCtx<CustomCtx, DataModel, AgentTools>): import("convex/server").RegisteredAction<"internal", {
1120
1109
  userId?: string | undefined;
1121
1110
  threadId?: string | undefined;
1122
1111
  providerOptions?: Record<string, Record<string, any>> | undefined;
@@ -1231,10 +1220,11 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1231
1220
  } | undefined;
1232
1221
  }, Promise<{
1233
1222
  object: T;
1234
- messageId: string | undefined;
1223
+ promptMessageId: string | undefined;
1235
1224
  order: number | undefined;
1236
1225
  finishReason: import("@ai-sdk/provider").LanguageModelV2FinishReason;
1237
1226
  warnings: import("@ai-sdk/provider").LanguageModelV2CallWarning[] | undefined;
1227
+ savedMessageIds: string[];
1238
1228
  }>>;
1239
1229
  /**
1240
1230
  * Save messages to the thread.
@@ -1285,9 +1275,9 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1285
1275
  title?: string | undefined;
1286
1276
  type?: "source" | undefined;
1287
1277
  providerOptions?: Record<string, Record<string, any>> | undefined;
1288
- url?: string | undefined;
1289
1278
  id: string;
1290
1279
  sourceType: "url";
1280
+ url: string;
1291
1281
  } | {
1292
1282
  filename?: string | undefined;
1293
1283
  providerMetadata?: Record<string, Record<string, any>> | undefined;
@@ -1297,6 +1287,19 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1297
1287
  sourceType: "document";
1298
1288
  mediaType: string;
1299
1289
  })[] | undefined;
1290
+ warnings?: ({
1291
+ details?: string | undefined;
1292
+ type: "unsupported-setting";
1293
+ setting: string;
1294
+ } | {
1295
+ details?: string | undefined;
1296
+ type: "unsupported-tool";
1297
+ tool: any;
1298
+ } | {
1299
+ type: "other";
1300
+ message: string;
1301
+ })[] | undefined;
1302
+ finishReason?: "length" | "error" | "other" | "stop" | "content-filter" | "tool-calls" | "unknown" | undefined;
1300
1303
  reasoningDetails?: ({
1301
1304
  providerOptions?: Record<string, Record<string, any>> | undefined;
1302
1305
  signature?: string | undefined;
@@ -1311,19 +1314,6 @@ CustomCtx extends object = object, AgentTools extends ToolSet = any> {
1311
1314
  type: "redacted";
1312
1315
  data: string;
1313
1316
  })[] | 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
1317
  message: {
1328
1318
  providerOptions?: Record<string, Record<string, any>> | undefined;
1329
1319
  role: "user";