@convex-dev/agent 0.6.3 → 0.7.0-alpha.0

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