@convex-dev/agent 0.6.4 → 0.7.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 (225) hide show
  1. package/MIGRATION.md +60 -116
  2. package/dist/client/messages.d.ts +1 -398
  3. package/dist/client/messages.d.ts.map +1 -1
  4. package/dist/client/messages.js +3 -47
  5. package/dist/client/messages.js.map +1 -1
  6. package/dist/client/types.d.ts +1 -455
  7. package/dist/client/types.d.ts.map +1 -1
  8. package/dist/component/_generated/component.d.ts +805 -45
  9. package/dist/component/_generated/component.d.ts.map +1 -1
  10. package/dist/component/messages.d.ts +1252 -201
  11. package/dist/component/messages.d.ts.map +1 -1
  12. package/dist/component/messages.js +49 -23
  13. package/dist/component/messages.js.map +1 -1
  14. package/dist/component/schema.d.ts +2593 -332
  15. package/dist/component/schema.d.ts.map +1 -1
  16. package/dist/component/streams.d.ts +7 -1
  17. package/dist/component/streams.d.ts.map +1 -1
  18. package/dist/component/streams.js +24 -30
  19. package/dist/component/streams.js.map +1 -1
  20. package/dist/component/threads.d.ts.map +1 -1
  21. package/dist/component/threads.js +1 -2
  22. package/dist/component/threads.js.map +1 -1
  23. package/dist/react/index.d.ts +5 -5
  24. package/dist/react/index.d.ts.map +1 -1
  25. package/dist/react/index.js +5 -5
  26. package/dist/react/index.js.map +1 -1
  27. package/dist/shared.d.ts +19 -7
  28. package/dist/shared.d.ts.map +1 -1
  29. package/dist/shared.js +4 -4
  30. package/dist/shared.js.map +1 -1
  31. package/dist/streaming/materializePersistedUIMessageChunks.d.ts +16 -0
  32. package/dist/streaming/materializePersistedUIMessageChunks.d.ts.map +1 -0
  33. package/dist/streaming/materializePersistedUIMessageChunks.js +302 -0
  34. package/dist/streaming/materializePersistedUIMessageChunks.js.map +1 -0
  35. package/dist/streaming/persistedUIMessageChunks.d.ts +106 -0
  36. package/dist/streaming/persistedUIMessageChunks.d.ts.map +1 -0
  37. package/dist/streaming/persistedUIMessageChunks.js +475 -0
  38. package/dist/streaming/persistedUIMessageChunks.js.map +1 -0
  39. package/dist/validators.d.ts +10026 -1055
  40. package/dist/validators.d.ts.map +1 -1
  41. package/dist/validators.js +71 -9
  42. package/dist/validators.js.map +1 -1
  43. package/dist/{UIMessages.d.ts → vercel/UIMessages.d.ts} +1 -1
  44. package/dist/vercel/UIMessages.d.ts.map +1 -0
  45. package/dist/{UIMessages.js → vercel/UIMessages.js} +63 -1
  46. package/dist/vercel/UIMessages.js.map +1 -0
  47. package/dist/{client → vercel/client}/createTool.d.ts +23 -16
  48. package/dist/vercel/client/createTool.d.ts.map +1 -0
  49. package/dist/{client → vercel/client}/createTool.js +2 -0
  50. package/dist/vercel/client/createTool.js.map +1 -0
  51. package/dist/{client → vercel/client}/definePlaygroundAPI.d.ts +533 -79
  52. package/dist/{client → vercel/client}/definePlaygroundAPI.d.ts.map +1 -1
  53. package/dist/{client → vercel/client}/definePlaygroundAPI.js +8 -7
  54. package/dist/vercel/client/definePlaygroundAPI.js.map +1 -0
  55. package/dist/{client → vercel/client}/files.d.ts +2 -2
  56. package/dist/vercel/client/files.d.ts.map +1 -0
  57. package/dist/vercel/client/files.js.map +1 -0
  58. package/dist/vercel/client/messages.d.ts +542 -0
  59. package/dist/vercel/client/messages.d.ts.map +1 -0
  60. package/dist/vercel/client/messages.js +66 -0
  61. package/dist/vercel/client/messages.js.map +1 -0
  62. package/dist/{client → vercel/client}/mockModel.d.ts +17 -17
  63. package/dist/vercel/client/mockModel.d.ts.map +1 -0
  64. package/dist/{client → vercel/client}/mockModel.js +12 -13
  65. package/dist/vercel/client/mockModel.js.map +1 -0
  66. package/dist/{client → vercel/client}/saveInputMessages.d.ts +2 -2
  67. package/dist/vercel/client/saveInputMessages.d.ts.map +1 -0
  68. package/dist/vercel/client/saveInputMessages.js.map +1 -0
  69. package/dist/{client → vercel/client}/search.d.ts +119 -22
  70. package/dist/vercel/client/search.d.ts.map +1 -0
  71. package/dist/{client → vercel/client}/search.js +2 -2
  72. package/dist/vercel/client/search.js.map +1 -0
  73. package/dist/{client → vercel/client}/start.d.ts +26 -11
  74. package/dist/vercel/client/start.d.ts.map +1 -0
  75. package/dist/{client → vercel/client}/start.js +64 -22
  76. package/dist/vercel/client/start.js.map +1 -0
  77. package/dist/{client → vercel/client}/streamText.d.ts +13 -12
  78. package/dist/vercel/client/streamText.d.ts.map +1 -0
  79. package/dist/{client → vercel/client}/streamText.js +43 -9
  80. package/dist/vercel/client/streamText.js.map +1 -0
  81. package/dist/{client → vercel/client}/streaming.d.ts +1410 -183
  82. package/dist/vercel/client/streaming.d.ts.map +1 -0
  83. package/dist/{client → vercel/client}/streaming.js +120 -52
  84. package/dist/vercel/client/streaming.js.map +1 -0
  85. package/dist/vercel/client/types.d.ts +456 -0
  86. package/dist/vercel/client/types.d.ts.map +1 -0
  87. package/dist/vercel/client/types.js +3 -0
  88. package/dist/vercel/client/types.js.map +1 -0
  89. package/dist/{client → vercel/client}/utils.d.ts +3 -2
  90. package/dist/vercel/client/utils.d.ts.map +1 -0
  91. package/dist/{client → vercel/client}/utils.js +2 -2
  92. package/dist/vercel/client/utils.js.map +1 -0
  93. package/dist/{deltas.d.ts → vercel/deltas.d.ts} +3 -4
  94. package/dist/vercel/deltas.d.ts.map +1 -0
  95. package/dist/{deltas.js → vercel/deltas.js} +195 -99
  96. package/dist/vercel/deltas.js.map +1 -0
  97. package/dist/{client → vercel}/index.d.ts +482 -106
  98. package/dist/vercel/index.d.ts.map +1 -0
  99. package/dist/{client → vercel}/index.js +64 -46
  100. package/dist/vercel/index.js.map +1 -0
  101. package/dist/{mapping.d.ts → vercel/mapping.d.ts} +5 -19
  102. package/dist/vercel/mapping.d.ts.map +1 -0
  103. package/dist/{mapping.js → vercel/mapping.js} +411 -114
  104. package/dist/vercel/mapping.js.map +1 -0
  105. package/dist/{react → vercel/react}/optimisticallySendMessage.d.ts +2 -2
  106. package/dist/vercel/react/optimisticallySendMessage.d.ts.map +1 -0
  107. package/dist/vercel/react/optimisticallySendMessage.js.map +1 -0
  108. package/dist/{react → vercel/react}/types.d.ts +1 -1
  109. package/dist/vercel/react/types.d.ts.map +1 -0
  110. package/dist/{react → vercel/react}/types.js.map +1 -1
  111. package/dist/{react → vercel/react}/useDeltaStreams.d.ts +1 -1
  112. package/dist/vercel/react/useDeltaStreams.d.ts.map +1 -0
  113. package/dist/{react → vercel/react}/useDeltaStreams.js +1 -1
  114. package/dist/vercel/react/useDeltaStreams.js.map +1 -0
  115. package/dist/{react → vercel/react}/useStreamingUIMessages.d.ts +1 -1
  116. package/dist/vercel/react/useStreamingUIMessages.d.ts.map +1 -0
  117. package/dist/{react → vercel/react}/useStreamingUIMessages.js +7 -3
  118. package/dist/vercel/react/useStreamingUIMessages.js.map +1 -0
  119. package/dist/{react → vercel/react}/useThreadMessages.d.ts +1 -1
  120. package/dist/vercel/react/useThreadMessages.d.ts.map +1 -0
  121. package/dist/{react → vercel/react}/useThreadMessages.js +1 -1
  122. package/dist/vercel/react/useThreadMessages.js.map +1 -0
  123. package/dist/{react → vercel/react}/useUIMessages.d.ts +1 -1
  124. package/dist/vercel/react/useUIMessages.d.ts.map +1 -0
  125. package/dist/{react → vercel/react}/useUIMessages.js +1 -1
  126. package/dist/vercel/react/useUIMessages.js.map +1 -0
  127. package/package.json +31 -24
  128. package/src/client/messages.ts +5 -107
  129. package/src/client/types.ts +0 -608
  130. package/src/component/_generated/component.ts +1089 -48
  131. package/src/component/messages.test.ts +273 -1
  132. package/src/component/messages.ts +62 -32
  133. package/src/component/streams.ts +47 -47
  134. package/src/component/threads.ts +5 -2
  135. package/src/eslintConfig.test.ts +44 -0
  136. package/src/react/index.ts +8 -5
  137. package/src/shared.ts +26 -36
  138. package/src/streaming/materializePersistedUIMessageChunks.test.ts +513 -0
  139. package/src/streaming/materializePersistedUIMessageChunks.ts +398 -0
  140. package/src/streaming/persistedUIMessageChunks.test.ts +205 -0
  141. package/src/streaming/persistedUIMessageChunks.ts +658 -0
  142. package/src/validators.test.ts +4 -1
  143. package/src/validators.ts +89 -8
  144. package/src/{UIMessages.combineUIMessages.test.ts → vercel/UIMessages.combineUIMessages.test.ts} +4 -1
  145. package/src/{UIMessages.ts → vercel/UIMessages.ts} +95 -3
  146. package/src/{client → vercel/client}/approval.test.ts +23 -13
  147. package/src/{client → vercel/client}/createTool.ts +62 -22
  148. package/src/{client → vercel/client}/definePlaygroundAPI.ts +15 -16
  149. package/src/{client → vercel/client}/files.ts +2 -2
  150. package/src/{client → vercel/client}/index.test.ts +99 -31
  151. package/src/vercel/client/messages.ts +182 -0
  152. package/src/{client → vercel/client}/mockModel.ts +38 -39
  153. package/src/{client → vercel/client}/saveInputMessages.test.ts +1 -1
  154. package/src/{client → vercel/client}/saveInputMessages.ts +3 -3
  155. package/src/{client → vercel/client}/search.test.ts +3 -3
  156. package/src/{client → vercel/client}/search.ts +4 -4
  157. package/src/{client → vercel/client}/setup.test.ts +6 -3
  158. package/src/vercel/client/start.test.ts +14 -0
  159. package/src/{client → vercel/client}/start.ts +147 -36
  160. package/src/vercel/client/streamText.test.ts +223 -0
  161. package/src/{client → vercel/client}/streamText.ts +102 -31
  162. package/src/{client → vercel/client}/streaming.integration.test.ts +6 -3
  163. package/src/{client → vercel/client}/streaming.test.ts +178 -4
  164. package/src/{client → vercel/client}/streaming.ts +114 -52
  165. package/src/vercel/client/types.test.ts +13 -0
  166. package/src/vercel/client/types.ts +679 -0
  167. package/src/{client → vercel/client}/utils.ts +13 -7
  168. package/src/{deltas.test.ts → vercel/deltas.test.ts} +384 -93
  169. package/src/{deltas.ts → vercel/deltas.ts} +218 -115
  170. package/src/{fromUIMessages.test.ts → vercel/fromUIMessages.test.ts} +17 -1
  171. package/src/{client → vercel}/index.ts +167 -84
  172. package/src/{mapping.test.ts → vercel/mapping.test.ts} +377 -92
  173. package/src/{mapping.ts → vercel/mapping.ts} +501 -137
  174. package/src/{react → vercel/react}/optimisticallySendMessage.ts +2 -2
  175. package/src/{react → vercel/react}/types.ts +1 -1
  176. package/src/{react → vercel/react}/useDeltaStreams.ts +6 -2
  177. package/src/{react → vercel/react}/useStreamingUIMessages.ts +7 -3
  178. package/src/{react → vercel/react}/useThreadMessages.ts +2 -2
  179. package/src/{react → vercel/react}/useUIMessages.ts +2 -2
  180. package/src/{toUIMessages.test.ts → vercel/toUIMessages.test.ts} +49 -2
  181. package/dist/UIMessages.d.ts.map +0 -1
  182. package/dist/UIMessages.js.map +0 -1
  183. package/dist/client/createTool.d.ts.map +0 -1
  184. package/dist/client/createTool.js.map +0 -1
  185. package/dist/client/definePlaygroundAPI.js.map +0 -1
  186. package/dist/client/files.d.ts.map +0 -1
  187. package/dist/client/files.js.map +0 -1
  188. package/dist/client/index.d.ts.map +0 -1
  189. package/dist/client/index.js.map +0 -1
  190. package/dist/client/mockModel.d.ts.map +0 -1
  191. package/dist/client/mockModel.js.map +0 -1
  192. package/dist/client/saveInputMessages.d.ts.map +0 -1
  193. package/dist/client/saveInputMessages.js.map +0 -1
  194. package/dist/client/search.d.ts.map +0 -1
  195. package/dist/client/search.js.map +0 -1
  196. package/dist/client/start.d.ts.map +0 -1
  197. package/dist/client/start.js.map +0 -1
  198. package/dist/client/streamText.d.ts.map +0 -1
  199. package/dist/client/streamText.js.map +0 -1
  200. package/dist/client/streaming.d.ts.map +0 -1
  201. package/dist/client/streaming.js.map +0 -1
  202. package/dist/client/utils.d.ts.map +0 -1
  203. package/dist/client/utils.js.map +0 -1
  204. package/dist/deltas.d.ts.map +0 -1
  205. package/dist/deltas.js.map +0 -1
  206. package/dist/mapping.d.ts.map +0 -1
  207. package/dist/mapping.js.map +0 -1
  208. package/dist/react/optimisticallySendMessage.d.ts.map +0 -1
  209. package/dist/react/optimisticallySendMessage.js.map +0 -1
  210. package/dist/react/types.d.ts.map +0 -1
  211. package/dist/react/useDeltaStreams.d.ts.map +0 -1
  212. package/dist/react/useDeltaStreams.js.map +0 -1
  213. package/dist/react/useStreamingUIMessages.d.ts.map +0 -1
  214. package/dist/react/useStreamingUIMessages.js.map +0 -1
  215. package/dist/react/useThreadMessages.d.ts.map +0 -1
  216. package/dist/react/useThreadMessages.js.map +0 -1
  217. package/dist/react/useUIMessages.d.ts.map +0 -1
  218. package/dist/react/useUIMessages.js.map +0 -1
  219. package/src/client/streamText.test.ts +0 -102
  220. /package/dist/{client → vercel/client}/files.js +0 -0
  221. /package/dist/{client → vercel/client}/saveInputMessages.js +0 -0
  222. /package/dist/{react → vercel/react}/optimisticallySendMessage.js +0 -0
  223. /package/dist/{react → vercel/react}/types.js +0 -0
  224. /package/src/{UIMessages.test.ts → vercel/UIMessages.test.ts} +0 -0
  225. /package/src/{react → vercel/react}/useUIMessages.test.ts +0 -0
@@ -1,619 +1,11 @@
1
- import type {
2
- FlexibleSchema,
3
- InferSchema,
4
- ModelMessage,
5
- ProviderOptions,
6
- } from "@ai-sdk/provider-utils";
7
- import type { JSONValue } from "@ai-sdk/provider";
8
- import type {
9
- EmbeddingModel,
10
- GenerateObjectResult,
11
- generateText,
12
- GenerateTextResult,
13
- LanguageModelRequestMetadata,
14
- LanguageModelResponseMetadata,
15
- LanguageModelUsage,
16
- LanguageModel,
17
- streamObject,
18
- streamText,
19
- StreamTextResult,
20
- ToolSet,
21
- CallSettings,
22
- generateObject,
23
- } from "ai";
24
-
25
- export interface Output<_T = any, _P = any, _E = any> {
26
- name: string;
27
- responseFormat: any;
28
- parseCompleteOutput: any;
29
- parsePartialOutput: any;
30
- createElementStreamTransform: any;
31
- }
32
1
  import type {
33
2
  GenericActionCtx,
34
3
  GenericDataModel,
35
- WithoutSystemFields,
36
4
  } from "convex/server";
37
- import type {
38
- MessageDoc,
39
- ProviderMetadata,
40
- StreamDelta,
41
- StreamMessage,
42
- ThreadDoc,
43
- } from "../validators.js";
44
- import type { StreamingOptions } from "./streaming.js";
45
5
  import type { ComponentApi } from "../component/_generated/component.js";
46
6
 
47
- /**
48
- * Type-level check that ensures models are from AI SDK v6.
49
- * If a v5 model (LanguageModelV2) is passed, TypeScript will show the error message string.
50
- */
51
- type AssertAISDKv6<T> = T extends { specificationVersion: "v3" }
52
- ? T
53
- : "⚠️ @convex-dev/agent v0.6.0 requires AI SDK v6. Update your dependencies: npm install ai@^6.0.35 @ai-sdk/openai@^3.0.10 (or other provider). See: node_modules/@convex-dev/agent/MIGRATION.md";
54
-
55
- export type AgentPrompt = {
56
- /**
57
- * System message to include in the prompt. Overwrites Agent instructions.
58
- */
59
- system?: string;
60
- /**
61
- * A prompt. It can be either a text prompt or a list of messages.
62
- * If used with `promptMessageId`, it will be used in place of that
63
- * prompt message and no input messages will be saved.
64
- * Otherwise, if used with the storageOptions "promptAndOutput" (default),
65
- * it will be the only message saved.
66
- * If a string is provided, it will be a user message.
67
- */
68
- prompt?: string | Array<ModelMessage> | undefined;
69
- /**
70
- * A list of messages to use as context before the prompt.
71
- * If used with `prompt`, these will precede the prompt.
72
- * If used with the storageOptions "promptAndOutput" (default),
73
- * none of these messages will be saved.
74
- */
75
- messages?: Array<ModelMessage> | undefined;
76
- /**
77
- * If provided, it uses this existing message to anchor the prompt:
78
- * - The specified message will be included, unless `prompt` is also
79
- * provided, in which case that will be inserted in place of this
80
- * specified message.
81
- * - Recent and search messages will not include messages after this
82
- * message's order.
83
- * - If there are already responses on the same order,
84
- * for example, tool calls and responses,
85
- * those will be included automatically.
86
- *
87
- * Note: if this is provided, no input messages will be saved by default.
88
- */
89
- promptMessageId?: string | undefined;
90
- /**
91
- * The model to use for the LLM calls. This will override the languageModel
92
- * specified in the Agent config.
93
- */
94
- model?: LanguageModel;
95
- };
96
-
97
- export type Config = {
98
- /**
99
- * The LLM model to use for generating / streaming text and objects.
100
- * Requires AI SDK v6 (@ai-sdk/* packages v3.x).
101
- *
102
- * @example
103
- * import { openai } from "@ai-sdk/openai"
104
- * const myAgent = new Agent(components.agent, {
105
- * languageModel: openai.chat("gpt-4o-mini"),
106
- * })
107
- */
108
- languageModel?: AssertAISDKv6<LanguageModel>;
109
- /**
110
- * @deprecated Use `embeddingModel` instead.
111
- */
112
- textEmbeddingModel?: EmbeddingModel;
113
- /**
114
- * The model to use for text embeddings. Optional.
115
- * If specified, it will use this for generating vector embeddings
116
- * of chats, and can opt-in to doing vector search for automatic context
117
- * on generateText, etc.
118
- * e.g.
119
- * import { openai } from "@ai-sdk/openai"
120
- * const myAgent = new Agent(components.agent, {
121
- * ...
122
- * embeddingModel: openai.embedding("text-embedding-3-small")
123
- */
124
- embeddingModel?: EmbeddingModel;
125
- /**
126
- * Options to determine what messages are included as context in message
127
- * generation. To disable any messages automatically being added, pass:
128
- * { recentMessages: 0 }
129
- */
130
- contextOptions?: ContextOptions;
131
- /**
132
- * Determines whether messages are automatically stored when passed as
133
- * arguments or generated.
134
- */
135
- storageOptions?: StorageOptions;
136
- /**
137
- * The usage handler to use for this agent.
138
- */
139
- usageHandler?: UsageHandler;
140
- /**
141
- * By default, messages are ordered with context in `fetchContextWithPrompt`,
142
- * but you can override this by providing a context handler. Here you can
143
- * filter, modify, or enrich the context messages. If provided, the default
144
- * ordering will not apply. This excludes the system message / instructions.
145
- */
146
- contextHandler?: ContextHandler;
147
- /**
148
- * Called for each LLM request/response, so you can do things like
149
- * log the raw request body or response headers to a table, or logs.
150
- */
151
- rawRequestResponseHandler?: RawRequestResponseHandler;
152
- /**
153
- * @deprecated Reach out if you use this. Otherwise will be removed soon.
154
- * Default provider options to pass for the LLM calls.
155
- * This can be overridden at each generate/stream callsite on a per-field
156
- * basis. To clear a default setting, you'll need to pass `undefined`.
157
- */
158
- providerOptions?: ProviderOptions;
159
- /**
160
- * The default settings to use for the LLM calls.
161
- * This can be overridden at each generate/stream callsite on a per-field
162
- * basis. To clear a default setting, you'll need to pass `undefined`.
163
- */
164
- callSettings?: CallSettings;
165
- /**
166
- * The maximum number of steps to allow for a single generation.
167
- *
168
- * For example, if an agent wants to call a tool, that call and tool response
169
- * will be one step. Generating a response based on the tool call & response
170
- * will be a second step.
171
- * If it runs out of steps, it will return the last step result, which may
172
- * not be an assistant message.
173
-
174
- * This becomes the default value when `stopWhen` is not specified in the
175
- * Agent or generation callsite.
176
- * AI SDK v5 removed the `maxSteps` argument, but this is kept here for
177
- * convenience and backwards compatibility.
178
- * Defaults to 1.
179
- */
180
- maxSteps?: number;
181
- };
182
-
183
- /**
184
- * Options to configure what messages are fetched as context,
185
- * automatically with thread.generateText, or directly via search.
186
- */
187
- export type ContextOptions = {
188
- /**
189
- * Whether to include tool messages in the context.
190
- * By default, tool calls and results are not included.
191
- */
192
- excludeToolMessages?: boolean;
193
- /**
194
- * How many recent messages to include. These are added after the search
195
- * messages, and do not count against the search limit.
196
- * Default: 100
197
- */
198
- recentMessages?: number;
199
- /**
200
- * Options for searching messages.
201
- */
202
- searchOptions?: {
203
- /**
204
- * The maximum number of messages to fetch. Default is 10.
205
- */
206
- limit: number;
207
- /**
208
- * Whether to use text search to find messages. Default is false.
209
- */
210
- textSearch?: boolean;
211
- /**
212
- * Whether to use vector search to find messages. Default is false.
213
- * At least one of textSearch or vectorSearch must be true.
214
- */
215
- vectorSearch?: boolean;
216
- /**
217
- * The score threshold for vector search. Default is 0.0.
218
- */
219
- vectorScoreThreshold?: number;
220
- /**
221
- * What messages around the search results to include.
222
- * Default: { before: 2, after: 1 }
223
- * (two before, and one after each message found in the search)
224
- * Note, this is after the limit is applied.
225
- * By default this will quadruple the number of messages fetched.
226
- */
227
- messageRange?: { before: number; after: number };
228
- };
229
- /**
230
- * Whether to search across other threads for relevant messages.
231
- * By default, only the current thread is searched.
232
- */
233
- searchOtherThreads?: boolean;
234
- };
235
-
236
- /**
237
- * Options to configure the automatic saving of messages
238
- * when generating text / objects in a thread.
239
- */
240
- export type StorageOptions = {
241
- /**
242
- * Whether to save messages to the thread history.
243
- * Pass "all" to save all input and output messages.
244
- * Pass "none" to not save any input or output messages.
245
- * Pass "promptAndOutput" to save the prompt and all output messages.
246
- * If you pass {messages} but no {prompt}, it will assume messages.at(-1) is
247
- * the prompt.
248
- * Defaults to "promptAndOutput".
249
- */
250
- saveMessages?: "all" | "none" | "promptAndOutput";
251
- };
252
-
253
- export type GenerationOutputMetadata = {
254
- /**
255
- * The ID of the prompt message for the generation.
256
- */
257
- promptMessageId?: string;
258
- /**
259
- * The order of the prompt message and responses for the generation.
260
- * Each order starts with a user message, then followed by agent responses.
261
- * If a promptMessageId is provided, that dictates the order.
262
- */
263
- order?: number;
264
- /**
265
- * The messages saved for the generation - both saved input and output.
266
- * If you passed promptMessageId, it will not include that message.
267
- */
268
- savedMessages?: MessageDoc[];
269
- /**
270
- * @deprecated Use promptMessageId instead.
271
- * The ID of the prompt message for the generation.
272
- */
273
- messageId?: string;
274
- };
275
-
276
- export type UsageHandler = (
277
- ctx: ActionCtx,
278
- args: {
279
- userId: string | undefined;
280
- threadId: string | undefined;
281
- agentName: string | undefined;
282
- usage: LanguageModelUsage;
283
- // Often has more information, like cached token usage in the case of openai.
284
- providerMetadata: ProviderMetadata | undefined;
285
- model: string;
286
- provider: string;
287
- },
288
- ) => void | Promise<void>;
289
-
290
- /**
291
- * By default, messages are ordered with context in `fetchContextWithPrompt`,
292
- * but you can override this by providing a context handler. Here you can filter
293
- * out, add in, or reorder messages.
294
- */
295
- export type ContextHandler = (
296
- ctx: ActionCtx,
297
- args: {
298
- /**
299
- * All messages in the default order.
300
- */
301
- allMessages: ModelMessage[];
302
- /**
303
- * The messages fetched from search.
304
- */
305
- search: ModelMessage[];
306
- /**
307
- * The recent messages already in the thread history,
308
- * excluding any messages that came after promptMessageId.
309
- */
310
- recent: ModelMessage[];
311
- /**
312
- * The messages passed as the `messages` argument to e.g. generateText.
313
- */
314
- inputMessages: ModelMessage[];
315
- /**
316
- * The message(s) passed as the `prompt` argument to e.g. generateText.
317
- * Otherwise, if `promptMessageId` was provided, the message at that id.
318
- * `prompt` will override the message at `promptMessageId`.
319
- */
320
- inputPrompt: ModelMessage[];
321
- /**
322
- * Any messages on the same `order` as the promptMessageId message after the
323
- * prompt message. These are presumably existing responses to the prompt
324
- * message.
325
- */
326
- existingResponses: ModelMessage[];
327
- /**
328
- * The user associated with the generation, if any.
329
- */
330
- userId: string | undefined;
331
- /**
332
- * The thread associated with the generation, if any.
333
- */
334
- threadId: string | undefined;
335
- },
336
- ) => ModelMessage[] | Promise<ModelMessage[]>;
337
-
338
- export type RawRequestResponseHandler = (
339
- ctx: ActionCtx,
340
- args: {
341
- userId: string | undefined;
342
- threadId: string | undefined;
343
- agentName: string | undefined;
344
- request: LanguageModelRequestMetadata;
345
- response: LanguageModelResponseMetadata;
346
- },
347
- ) => void | Promise<void>;
348
-
349
7
  export type AgentComponent = ComponentApi;
350
8
 
351
- export type TextArgs<
352
- AgentTools extends ToolSet,
353
- TOOLS extends ToolSet | undefined = undefined,
354
- OUTPUT extends Output<any, any, any> = never,
355
- > = Omit<
356
- Parameters<
357
- typeof generateText<TOOLS extends undefined ? AgentTools : TOOLS, OUTPUT>
358
- >[0],
359
- "model" | "prompt" | "messages"
360
- > & {
361
- /**
362
- * The tools to use for the tool calls. This will override tools specified
363
- * in the Agent constructor or createThread / continueThread.
364
- */
365
- tools?: TOOLS;
366
- } & AgentPrompt;
367
-
368
- export type StreamingTextArgs<
369
- AgentTools extends ToolSet,
370
- TOOLS extends ToolSet | undefined = undefined,
371
- OUTPUT extends Output<any, any, any> = never,
372
- > = Omit<
373
- Parameters<
374
- typeof streamText<TOOLS extends undefined ? AgentTools : TOOLS, OUTPUT>
375
- >[0],
376
- "model" | "prompt" | "messages"
377
- > & {
378
- /**
379
- * The tools to use for the tool calls. This will override tools specified
380
- * in the Agent constructor or createThread / continueThread.
381
- */
382
- tools?: TOOLS;
383
- } & AgentPrompt;
384
-
385
- export type ObjectMode = "object" | "array" | "enum" | "no-schema";
386
-
387
- export type GenerateObjectArgs<
388
- SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,
389
- OUTPUT extends ObjectMode = InferSchema<SCHEMA> extends string
390
- ? "enum"
391
- : "object",
392
- RESULT = OUTPUT extends "array"
393
- ? Array<InferSchema<SCHEMA>>
394
- : InferSchema<SCHEMA>,
395
- > = AgentPrompt &
396
- Omit<
397
- Parameters<typeof generateObject<SCHEMA, OUTPUT, RESULT>>[0],
398
- "model" | "prompt" | "messages"
399
- > & {
400
- schema?: SCHEMA;
401
- enum?: Array<RESULT>;
402
- };
403
-
404
- export type StreamObjectArgs<
405
- SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,
406
- OUTPUT extends ObjectMode = InferSchema<SCHEMA> extends string
407
- ? "enum"
408
- : "object",
409
- RESULT = OUTPUT extends "array"
410
- ? Array<InferSchema<SCHEMA>>
411
- : InferSchema<SCHEMA>,
412
- > = AgentPrompt &
413
- Omit<
414
- Parameters<typeof streamObject<SCHEMA, OUTPUT, RESULT>>[0],
415
- "model" | "prompt" | "messages"
416
- > & {
417
- schema?: SCHEMA;
418
- enum?: Array<RESULT>;
419
- };
420
-
421
- export type MaybeCustomCtx<
422
- CustomCtx,
423
- DataModel extends GenericDataModel,
424
- AgentTools extends ToolSet,
425
- > =
426
- CustomCtx extends Record<string, unknown>
427
- ? {
428
- /**
429
- * If you have a custom ctx that you use with the Agent
430
- * (e.g. new Agent<{ orgId: string }>(...))
431
- * you need to provide this function to add any extra fields.
432
- * e.g.
433
- * ```ts
434
- * const myAgent = new Agent<{ orgId: string }>(...);
435
- * const myAction = myAgent.asTextAction({
436
- * customCtx: (ctx: ActionCtx, target, llmArgs) => {
437
- * const orgId = await lookupOrgId(ctx, target.threadId);
438
- * return { orgId };
439
- * },
440
- * });
441
- * ```
442
- * Then, in your tools, you can
443
- */
444
- customCtx: (
445
- ctx: GenericActionCtx<DataModel>,
446
- target: {
447
- userId?: string | undefined;
448
- threadId?: string | undefined;
449
- },
450
- llmArgs: TextArgs<AgentTools>,
451
- ) => CustomCtx;
452
- }
453
- : { customCtx?: never };
454
-
455
- type ThreadOutputMetadata = Required<GenerationOutputMetadata>;
456
-
457
- /**
458
- * The interface for a thread returned from {@link createThread} or {@link continueThread}.
459
- * This is contextual to a thread and/or user.
460
- */
461
- export interface Thread<DefaultTools extends ToolSet> {
462
- /**
463
- * The target threadId, from the startThread or continueThread initializers.
464
- */
465
- threadId: string;
466
- /**
467
- * Get the metadata for the thread.
468
- */
469
- getMetadata: () => Promise<ThreadDoc>;
470
- /**
471
- * Update the metadata for the thread.
472
- */
473
- updateMetadata: (
474
- patch: Partial<WithoutSystemFields<ThreadDoc>>,
475
- ) => Promise<ThreadDoc>;
476
- /**
477
- * This behaves like {@link generateText} from the "ai" package except that
478
- * it add context based on the userId and threadId and saves the input and
479
- * resulting messages to the thread, if specified.
480
- * Use {@link continueThread} to get a version of this function already scoped
481
- * to a thread (and optionally userId).
482
- * @param args The arguments to the generateText function, along with extra controls
483
- * for the {@link ContextOptions} and {@link StorageOptions}.
484
- * @returns The result of the generateText function.
485
- */
486
- generateText<
487
- TOOLS extends ToolSet | undefined = undefined,
488
- OUTPUT extends Output<any, any, any> = never,
489
- >(
490
- generateTextArgs: AgentPrompt &
491
- TextArgs<TOOLS extends undefined ? DefaultTools : TOOLS, TOOLS, OUTPUT>,
492
- options?: Options,
493
- ): Promise<
494
- GenerateTextResult<TOOLS extends undefined ? DefaultTools : TOOLS, OUTPUT> &
495
- ThreadOutputMetadata
496
- >;
497
-
498
- /**
499
- * This behaves like {@link streamText} from the "ai" package except that
500
- * it add context based on the userId and threadId and saves the input and
501
- * resulting messages to the thread, if specified.
502
- * Use {@link continueThread} to get a version of this function already scoped
503
- * to a thread (and optionally userId).
504
- * @param args The arguments to the streamText function, along with extra controls
505
- * for the {@link ContextOptions} and {@link StorageOptions}.
506
- * @returns The result of the streamText function.
507
- */
508
- streamText<
509
- TOOLS extends ToolSet | undefined = undefined,
510
- OUTPUT extends Output<any, any, any> = never,
511
- >(
512
- streamTextArgs: AgentPrompt &
513
- StreamingTextArgs<
514
- TOOLS extends undefined ? DefaultTools : TOOLS,
515
- TOOLS,
516
- OUTPUT
517
- >,
518
- options?: Options & {
519
- /**
520
- * Whether to save incremental data (deltas) from streaming responses.
521
- * Defaults to false.
522
- * If false, it will not save any deltas to the database.
523
- * If true, it will save deltas with {@link DEFAULT_STREAMING_OPTIONS}.
524
- *
525
- * Regardless of this option, when streaming you are able to use this
526
- * `streamText` function as you would with the "ai" package's version:
527
- * iterating over the text, streaming it over HTTP, etc.
528
- */
529
- saveStreamDeltas?: boolean | StreamingOptions;
530
- },
531
- ): Promise<
532
- StreamTextResult<TOOLS extends undefined ? DefaultTools : TOOLS, OUTPUT> &
533
- ThreadOutputMetadata
534
- >;
535
- /**
536
- * This behaves like {@link generateObject} from the "ai" package except that
537
- * it add context based on the userId and threadId and saves the input and
538
- * resulting messages to the thread, if specified. This overload is for objects, arrays, and enums.
539
- * Use {@link continueThread} to get a version of this function already scoped
540
- * to a thread (and optionally userId).
541
- * @param args The arguments to the generateObject function, along with extra controls
542
- * for the {@link ContextOptions} and {@link StorageOptions}.
543
- * @returns The result of the generateObject function.
544
- */
545
- generateObject<
546
- SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,
547
- OUTPUT extends ObjectMode = InferSchema<SCHEMA> extends string
548
- ? "enum"
549
- : "object",
550
- RESULT = OUTPUT extends "array"
551
- ? Array<InferSchema<SCHEMA>>
552
- : InferSchema<SCHEMA>,
553
- >(
554
- generateObjectArgs: AgentPrompt &
555
- GenerateObjectArgs<SCHEMA, OUTPUT, RESULT>,
556
- options?: Options,
557
- ): Promise<GenerateObjectResult<RESULT> & ThreadOutputMetadata>;
558
- /**
559
- * This behaves like {@link streamObject} from the "ai" package except that
560
- * it add context based on the userId and threadId and saves the input and
561
- * resulting messages to the thread, if specified.
562
- * Use {@link continueThread} to get a version of this function already scoped
563
- * to a thread (and optionally userId).
564
- * @param args The arguments to the streamObject function, along with extra controls
565
- * for the {@link ContextOptions} and {@link StorageOptions}.
566
- * @returns The result of the streamObject function.
567
- */
568
- streamObject<
569
- SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,
570
- OUTPUT extends ObjectMode = InferSchema<SCHEMA> extends string
571
- ? "enum"
572
- : "object",
573
- RESULT = OUTPUT extends "array"
574
- ? Array<InferSchema<SCHEMA>>
575
- : InferSchema<SCHEMA>,
576
- >(
577
- /**
578
- * The same arguments you'd pass to "ai" sdk {@link streamObject}.
579
- */
580
- streamObjectArgs: AgentPrompt & StreamObjectArgs<SCHEMA, OUTPUT, RESULT>,
581
- options?: Options,
582
- ): Promise<
583
- ReturnType<typeof streamObject<SCHEMA, OUTPUT, RESULT>> &
584
- ThreadOutputMetadata
585
- >;
586
- }
587
-
588
- export type Options = {
589
- /**
590
- * The context options to use for passing in message history to the LLM.
591
- */
592
- contextOptions?: ContextOptions;
593
- /**
594
- * The storage options to use for saving the input and output messages to the thread.
595
- */
596
- storageOptions?: StorageOptions;
597
- /**
598
- * The usage handler to use for this thread. Overrides any handler
599
- * set in the agent constructor.
600
- */
601
- usageHandler?: UsageHandler;
602
- /**
603
- * By default, messages are ordered with context in `fetchContextWithPrompt`,
604
- * but you can override this by providing a context handler. Here you can
605
- * filter, modify, or enrich the context messages. If provided, the default
606
- * ordering will not apply. This excludes the system message / instructions.
607
- */
608
- contextHandler?: ContextHandler;
609
- };
610
-
611
- export type SyncStreamsReturnValue =
612
- | { kind: "list"; messages: StreamMessage[] }
613
- | { kind: "deltas"; deltas: StreamDelta[] }
614
- | undefined;
615
-
616
- /* Type utils follow */
617
9
  export type QueryCtx = Pick<GenericActionCtx<GenericDataModel>, "runQuery">;
618
10
  export type MutationCtx = Pick<
619
11
  GenericActionCtx<GenericDataModel>,