@langchain/langgraph-sdk 0.1.10 → 1.0.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 (235) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +11 -0
  3. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  4. package/dist/auth/error.cjs +76 -86
  5. package/dist/auth/error.cjs.map +1 -0
  6. package/dist/auth/error.d.cts +13 -0
  7. package/dist/auth/error.d.cts.map +1 -0
  8. package/dist/auth/error.d.ts +12 -8
  9. package/dist/auth/error.d.ts.map +1 -0
  10. package/dist/auth/error.js +76 -83
  11. package/dist/auth/error.js.map +1 -0
  12. package/dist/auth/index.cjs +36 -44
  13. package/dist/auth/index.cjs.map +1 -0
  14. package/dist/auth/index.d.cts +31 -0
  15. package/dist/auth/index.d.cts.map +1 -0
  16. package/dist/auth/index.d.ts +20 -15
  17. package/dist/auth/index.d.ts.map +1 -0
  18. package/dist/auth/index.js +35 -39
  19. package/dist/auth/index.js.map +1 -0
  20. package/dist/auth/types.d.cts +294 -0
  21. package/dist/auth/types.d.cts.map +1 -0
  22. package/dist/auth/types.d.ts +162 -165
  23. package/dist/auth/types.d.ts.map +1 -0
  24. package/dist/client.cjs +1110 -1294
  25. package/dist/client.cjs.map +1 -0
  26. package/dist/client.d.cts +697 -0
  27. package/dist/client.d.cts.map +1 -0
  28. package/dist/client.d.ts +656 -639
  29. package/dist/client.d.ts.map +1 -0
  30. package/dist/client.js +1101 -1281
  31. package/dist/client.js.map +1 -0
  32. package/dist/index.cjs +6 -8
  33. package/dist/index.d.cts +7 -0
  34. package/dist/index.d.ts +7 -7
  35. package/dist/index.js +4 -2
  36. package/dist/logging/index.cjs +30 -31
  37. package/dist/logging/index.cjs.map +1 -0
  38. package/dist/logging/index.d.cts +47 -0
  39. package/dist/logging/index.d.cts.map +1 -0
  40. package/dist/logging/index.d.ts +20 -16
  41. package/dist/logging/index.d.ts.map +1 -0
  42. package/dist/logging/index.js +31 -29
  43. package/dist/logging/index.js.map +1 -0
  44. package/dist/react/index.cjs +5 -7
  45. package/dist/react/index.d.cts +4 -0
  46. package/dist/react/index.d.ts +4 -3
  47. package/dist/react/index.js +4 -2
  48. package/dist/react/stream.cjs +14 -15
  49. package/dist/react/stream.cjs.map +1 -0
  50. package/dist/react/stream.custom.cjs +126 -145
  51. package/dist/react/stream.custom.cjs.map +1 -0
  52. package/dist/react/stream.custom.d.cts +39 -0
  53. package/dist/react/stream.custom.d.cts.map +1 -0
  54. package/dist/react/stream.custom.d.ts +35 -37
  55. package/dist/react/stream.custom.d.ts.map +1 -0
  56. package/dist/react/stream.custom.js +122 -137
  57. package/dist/react/stream.custom.js.map +1 -0
  58. package/dist/react/stream.d.cts +73 -0
  59. package/dist/react/stream.d.cts.map +1 -0
  60. package/dist/react/stream.d.ts +21 -15
  61. package/dist/react/stream.d.ts.map +1 -0
  62. package/dist/react/stream.js +12 -11
  63. package/dist/react/stream.js.map +1 -0
  64. package/dist/react/stream.lgp.cjs +438 -498
  65. package/dist/react/stream.lgp.cjs.map +1 -0
  66. package/dist/react/stream.lgp.js +433 -490
  67. package/dist/react/stream.lgp.js.map +1 -0
  68. package/dist/react/thread.cjs +18 -15
  69. package/dist/react/thread.cjs.map +1 -0
  70. package/dist/react/thread.js +19 -13
  71. package/dist/react/thread.js.map +1 -0
  72. package/dist/react/types.d.cts +356 -0
  73. package/dist/react/types.d.cts.map +1 -0
  74. package/dist/react/types.d.ts +334 -329
  75. package/dist/react/types.d.ts.map +1 -0
  76. package/dist/react-ui/client.cjs +123 -184
  77. package/dist/react-ui/client.cjs.map +1 -0
  78. package/dist/react-ui/client.d.cts +90 -0
  79. package/dist/react-ui/client.d.cts.map +1 -0
  80. package/dist/react-ui/client.d.ts +67 -51
  81. package/dist/react-ui/client.d.ts.map +1 -0
  82. package/dist/react-ui/client.js +118 -143
  83. package/dist/react-ui/client.js.map +1 -0
  84. package/dist/react-ui/index.cjs +14 -13
  85. package/dist/react-ui/index.cjs.map +1 -0
  86. package/dist/react-ui/index.d.cts +3 -0
  87. package/dist/react-ui/index.d.ts +3 -2
  88. package/dist/react-ui/index.js +8 -3
  89. package/dist/react-ui/index.js.map +1 -0
  90. package/dist/react-ui/server/index.cjs +5 -7
  91. package/dist/react-ui/server/index.d.cts +3 -0
  92. package/dist/react-ui/server/index.d.ts +3 -2
  93. package/dist/react-ui/server/index.js +4 -2
  94. package/dist/react-ui/server/server.cjs +53 -44
  95. package/dist/react-ui/server/server.cjs.map +1 -0
  96. package/dist/react-ui/server/server.d.cts +55 -0
  97. package/dist/react-ui/server/server.d.cts.map +1 -0
  98. package/dist/react-ui/server/server.d.ts +43 -39
  99. package/dist/react-ui/server/server.d.ts.map +1 -0
  100. package/dist/react-ui/server/server.js +54 -42
  101. package/dist/react-ui/server/server.js.map +1 -0
  102. package/dist/react-ui/types.cjs +32 -36
  103. package/dist/react-ui/types.cjs.map +1 -0
  104. package/dist/react-ui/types.d.cts +25 -0
  105. package/dist/react-ui/types.d.cts.map +1 -0
  106. package/dist/react-ui/types.d.ts +23 -19
  107. package/dist/react-ui/types.d.ts.map +1 -0
  108. package/dist/react-ui/types.js +32 -34
  109. package/dist/react-ui/types.js.map +1 -0
  110. package/dist/schema.d.cts +278 -0
  111. package/dist/schema.d.cts.map +1 -0
  112. package/dist/schema.d.ts +250 -242
  113. package/dist/schema.d.ts.map +1 -0
  114. package/dist/singletons/fetch.cjs +16 -20
  115. package/dist/singletons/fetch.cjs.map +1 -0
  116. package/dist/singletons/fetch.d.cts +14 -0
  117. package/dist/singletons/fetch.d.cts.map +1 -0
  118. package/dist/singletons/fetch.d.ts +5 -2
  119. package/dist/singletons/fetch.d.ts.map +1 -0
  120. package/dist/singletons/fetch.js +16 -17
  121. package/dist/singletons/fetch.js.map +1 -0
  122. package/dist/types.d.cts +187 -0
  123. package/dist/types.d.cts.map +1 -0
  124. package/dist/types.d.ts +178 -173
  125. package/dist/types.d.ts.map +1 -0
  126. package/dist/types.messages.d.cts +91 -0
  127. package/dist/types.messages.d.cts.map +1 -0
  128. package/dist/types.messages.d.ts +71 -66
  129. package/dist/types.messages.d.ts.map +1 -0
  130. package/dist/types.stream.d.cts +235 -0
  131. package/dist/types.stream.d.cts.map +1 -0
  132. package/dist/types.stream.d.ts +149 -142
  133. package/dist/types.stream.d.ts.map +1 -0
  134. package/dist/ui/branching.cjs +145 -141
  135. package/dist/ui/branching.cjs.map +1 -0
  136. package/dist/ui/branching.d.cts +22 -0
  137. package/dist/ui/branching.d.cts.map +1 -0
  138. package/dist/ui/branching.d.ts +17 -30
  139. package/dist/ui/branching.d.ts.map +1 -0
  140. package/dist/ui/branching.js +147 -139
  141. package/dist/ui/branching.js.map +1 -0
  142. package/dist/ui/errors.cjs +14 -12
  143. package/dist/ui/errors.cjs.map +1 -0
  144. package/dist/ui/errors.js +14 -9
  145. package/dist/ui/errors.js.map +1 -0
  146. package/dist/ui/manager.cjs +156 -232
  147. package/dist/ui/manager.cjs.map +1 -0
  148. package/dist/ui/manager.js +156 -228
  149. package/dist/ui/manager.js.map +1 -0
  150. package/dist/ui/messages.cjs +55 -69
  151. package/dist/ui/messages.cjs.map +1 -0
  152. package/dist/ui/messages.js +55 -66
  153. package/dist/ui/messages.js.map +1 -0
  154. package/dist/ui/utils.cjs +10 -10
  155. package/dist/ui/utils.cjs.map +1 -0
  156. package/dist/ui/utils.js +10 -8
  157. package/dist/ui/utils.js.map +1 -0
  158. package/dist/utils/async_caller.cjs +103 -185
  159. package/dist/utils/async_caller.cjs.map +1 -0
  160. package/dist/utils/async_caller.d.cts +53 -0
  161. package/dist/utils/async_caller.d.cts.map +1 -0
  162. package/dist/utils/async_caller.d.ts +36 -31
  163. package/dist/utils/async_caller.d.ts.map +1 -0
  164. package/dist/utils/async_caller.js +101 -177
  165. package/dist/utils/async_caller.js.map +1 -0
  166. package/dist/utils/env.cjs +11 -13
  167. package/dist/utils/env.cjs.map +1 -0
  168. package/dist/utils/env.js +11 -11
  169. package/dist/utils/env.js.map +1 -0
  170. package/dist/utils/signals.cjs +18 -19
  171. package/dist/utils/signals.cjs.map +1 -0
  172. package/dist/utils/signals.js +18 -17
  173. package/dist/utils/signals.js.map +1 -0
  174. package/dist/utils/sse.cjs +110 -140
  175. package/dist/utils/sse.cjs.map +1 -0
  176. package/dist/utils/sse.js +110 -138
  177. package/dist/utils/sse.js.map +1 -0
  178. package/dist/utils/stream.cjs +90 -114
  179. package/dist/utils/stream.cjs.map +1 -0
  180. package/dist/utils/stream.js +90 -111
  181. package/dist/utils/stream.js.map +1 -0
  182. package/package.json +73 -81
  183. package/auth.cjs +0 -1
  184. package/auth.d.cts +0 -1
  185. package/auth.d.ts +0 -1
  186. package/auth.js +0 -1
  187. package/client.cjs +0 -1
  188. package/client.d.cts +0 -1
  189. package/client.d.ts +0 -1
  190. package/client.js +0 -1
  191. package/dist/auth/types.cjs +0 -2
  192. package/dist/auth/types.js +0 -1
  193. package/dist/react/stream.lgp.d.ts +0 -7
  194. package/dist/react/thread.d.ts +0 -4
  195. package/dist/react/types.cjs +0 -2
  196. package/dist/react/types.js +0 -1
  197. package/dist/schema.cjs +0 -2
  198. package/dist/schema.js +0 -1
  199. package/dist/types.cjs +0 -2
  200. package/dist/types.js +0 -1
  201. package/dist/types.messages.cjs +0 -2
  202. package/dist/types.messages.js +0 -1
  203. package/dist/types.stream.cjs +0 -2
  204. package/dist/types.stream.js +0 -1
  205. package/dist/ui/branching.test.cjs +0 -370
  206. package/dist/ui/branching.test.d.ts +0 -1
  207. package/dist/ui/branching.test.js +0 -368
  208. package/dist/ui/errors.d.ts +0 -12
  209. package/dist/ui/manager.d.ts +0 -87
  210. package/dist/ui/messages.d.ts +0 -18
  211. package/dist/ui/utils.d.ts +0 -2
  212. package/dist/utils/env.d.ts +0 -1
  213. package/dist/utils/signals.d.ts +0 -1
  214. package/dist/utils/sse.d.ts +0 -8
  215. package/dist/utils/stream.d.ts +0 -13
  216. package/index.cjs +0 -1
  217. package/index.d.cts +0 -1
  218. package/index.d.ts +0 -1
  219. package/index.js +0 -1
  220. package/logging.cjs +0 -1
  221. package/logging.d.cts +0 -1
  222. package/logging.d.ts +0 -1
  223. package/logging.js +0 -1
  224. package/react-ui/server.cjs +0 -1
  225. package/react-ui/server.d.cts +0 -1
  226. package/react-ui/server.d.ts +0 -1
  227. package/react-ui/server.js +0 -1
  228. package/react-ui.cjs +0 -1
  229. package/react-ui.d.cts +0 -1
  230. package/react-ui.d.ts +0 -1
  231. package/react-ui.js +0 -1
  232. package/react.cjs +0 -1
  233. package/react.d.cts +0 -1
  234. package/react.d.ts +0 -1
  235. package/react.js +0 -1
package/dist/client.js CHANGED
@@ -3,1295 +3,1115 @@ import { getEnvironmentVariable } from "./utils/env.js";
3
3
  import { mergeSignals } from "./utils/signals.js";
4
4
  import { BytesLineDecoder, SSEDecoder } from "./utils/sse.js";
5
5
  import { IterableReadableStream } from "./utils/stream.js";
6
+
7
+ //#region src/client.ts
6
8
  function* iterateHeaders(headers) {
7
- let iter;
8
- let shouldClear = false;
9
- // eslint-disable-next-line no-instanceof/no-instanceof
10
- if (headers instanceof Headers) {
11
- const entries = [];
12
- headers.forEach((value, name) => {
13
- entries.push([name, value]);
14
- });
15
- iter = entries;
16
- }
17
- else if (Array.isArray(headers)) {
18
- iter = headers;
19
- }
20
- else {
21
- shouldClear = true;
22
- iter = Object.entries(headers ?? {});
23
- }
24
- for (const item of iter) {
25
- const name = item[0];
26
- if (typeof name !== "string")
27
- throw new TypeError(`Expected header name to be a string, got ${typeof name}`);
28
- const values = Array.isArray(item[1]) ? item[1] : [item[1]];
29
- let didClear = false;
30
- for (const value of values) {
31
- if (value === undefined)
32
- continue;
33
- // New object keys should always overwrite older headers
34
- // Yield a null to clear the header in the headers object
35
- // before adding the new value
36
- if (shouldClear && !didClear) {
37
- didClear = true;
38
- yield [name, null];
39
- }
40
- yield [name, value];
41
- }
42
- }
9
+ let iter;
10
+ let shouldClear = false;
11
+ if (headers instanceof Headers) {
12
+ const entries = [];
13
+ headers.forEach((value, name) => {
14
+ entries.push([name, value]);
15
+ });
16
+ iter = entries;
17
+ } else if (Array.isArray(headers)) iter = headers;
18
+ else {
19
+ shouldClear = true;
20
+ iter = Object.entries(headers ?? {});
21
+ }
22
+ for (const item of iter) {
23
+ const name = item[0];
24
+ if (typeof name !== "string") throw new TypeError(`Expected header name to be a string, got ${typeof name}`);
25
+ const values = Array.isArray(item[1]) ? item[1] : [item[1]];
26
+ let didClear = false;
27
+ for (const value of values) {
28
+ if (value === void 0) continue;
29
+ if (shouldClear && !didClear) {
30
+ didClear = true;
31
+ yield [name, null];
32
+ }
33
+ yield [name, value];
34
+ }
35
+ }
43
36
  }
44
37
  function mergeHeaders(...headerObjects) {
45
- const outputHeaders = new Headers();
46
- for (const headers of headerObjects) {
47
- if (!headers)
48
- continue;
49
- for (const [name, value] of iterateHeaders(headers)) {
50
- if (value === null)
51
- outputHeaders.delete(name);
52
- else
53
- outputHeaders.append(name, value);
54
- }
55
- }
56
- const headerEntries = [];
57
- outputHeaders.forEach((value, name) => {
58
- headerEntries.push([name, value]);
59
- });
60
- return Object.fromEntries(headerEntries);
38
+ const outputHeaders = new Headers();
39
+ for (const headers of headerObjects) {
40
+ if (!headers) continue;
41
+ for (const [name, value] of iterateHeaders(headers)) if (value === null) outputHeaders.delete(name);
42
+ else outputHeaders.append(name, value);
43
+ }
44
+ const headerEntries = [];
45
+ outputHeaders.forEach((value, name) => {
46
+ headerEntries.push([name, value]);
47
+ });
48
+ return Object.fromEntries(headerEntries);
61
49
  }
62
50
  /**
63
- * Get the API key from the environment.
64
- * Precedence:
65
- * 1. explicit argument
66
- * 2. LANGGRAPH_API_KEY
67
- * 3. LANGSMITH_API_KEY
68
- * 4. LANGCHAIN_API_KEY
69
- *
70
- * @param apiKey - Optional API key provided as an argument
71
- * @returns The API key if found, otherwise undefined
72
- */
73
- export function getApiKey(apiKey) {
74
- if (apiKey) {
75
- return apiKey;
76
- }
77
- const prefixes = ["LANGGRAPH", "LANGSMITH", "LANGCHAIN"];
78
- for (const prefix of prefixes) {
79
- const envKey = getEnvironmentVariable(`${prefix}_API_KEY`);
80
- if (envKey) {
81
- // Remove surrounding quotes
82
- return envKey.trim().replace(/^["']|["']$/g, "");
83
- }
84
- }
85
- return undefined;
51
+ * Get the API key from the environment.
52
+ * Precedence:
53
+ * 1. explicit argument
54
+ * 2. LANGGRAPH_API_KEY
55
+ * 3. LANGSMITH_API_KEY
56
+ * 4. LANGCHAIN_API_KEY
57
+ *
58
+ * @param apiKey - Optional API key provided as an argument
59
+ * @returns The API key if found, otherwise undefined
60
+ */
61
+ function getApiKey(apiKey) {
62
+ if (apiKey) return apiKey;
63
+ const prefixes = [
64
+ "LANGGRAPH",
65
+ "LANGSMITH",
66
+ "LANGCHAIN"
67
+ ];
68
+ for (const prefix of prefixes) {
69
+ const envKey = getEnvironmentVariable(`${prefix}_API_KEY`);
70
+ if (envKey) return envKey.trim().replace(/^["']|["']$/g, "");
71
+ }
72
+ return void 0;
86
73
  }
87
74
  const REGEX_RUN_METADATA = /(\/threads\/(?<thread_id>.+))?\/runs\/(?<run_id>.+)/;
88
75
  function getRunMetadataFromResponse(response) {
89
- const contentLocation = response.headers.get("Content-Location");
90
- if (!contentLocation)
91
- return undefined;
92
- const match = REGEX_RUN_METADATA.exec(contentLocation);
93
- if (!match?.groups?.run_id)
94
- return undefined;
95
- return {
96
- run_id: match.groups.run_id,
97
- thread_id: match.groups.thread_id || undefined,
98
- };
99
- }
100
- class BaseClient {
101
- constructor(config) {
102
- Object.defineProperty(this, "asyncCaller", {
103
- enumerable: true,
104
- configurable: true,
105
- writable: true,
106
- value: void 0
107
- });
108
- Object.defineProperty(this, "timeoutMs", {
109
- enumerable: true,
110
- configurable: true,
111
- writable: true,
112
- value: void 0
113
- });
114
- Object.defineProperty(this, "apiUrl", {
115
- enumerable: true,
116
- configurable: true,
117
- writable: true,
118
- value: void 0
119
- });
120
- Object.defineProperty(this, "defaultHeaders", {
121
- enumerable: true,
122
- configurable: true,
123
- writable: true,
124
- value: void 0
125
- });
126
- Object.defineProperty(this, "onRequest", {
127
- enumerable: true,
128
- configurable: true,
129
- writable: true,
130
- value: void 0
131
- });
132
- const callerOptions = {
133
- maxRetries: 4,
134
- maxConcurrency: 4,
135
- ...config?.callerOptions,
136
- };
137
- let defaultApiUrl = "http://localhost:8123";
138
- if (!config?.apiUrl &&
139
- typeof globalThis === "object" &&
140
- globalThis != null) {
141
- const fetchSmb = Symbol.for("langgraph_api:fetch");
142
- const urlSmb = Symbol.for("langgraph_api:url");
143
- const global = globalThis;
144
- if (global[fetchSmb])
145
- callerOptions.fetch ??= global[fetchSmb];
146
- if (global[urlSmb])
147
- defaultApiUrl = global[urlSmb];
148
- }
149
- this.asyncCaller = new AsyncCaller(callerOptions);
150
- this.timeoutMs = config?.timeoutMs;
151
- // default limit being capped by Chrome
152
- // https://github.com/nodejs/undici/issues/1373
153
- // Regex to remove trailing slash, if present
154
- this.apiUrl = config?.apiUrl?.replace(/\/$/, "") || defaultApiUrl;
155
- this.defaultHeaders = config?.defaultHeaders || {};
156
- this.onRequest = config?.onRequest;
157
- const apiKey = getApiKey(config?.apiKey);
158
- if (apiKey) {
159
- this.defaultHeaders["x-api-key"] = apiKey;
160
- }
161
- }
162
- prepareFetchOptions(path, options) {
163
- const mutatedOptions = {
164
- ...options,
165
- headers: mergeHeaders(this.defaultHeaders, options?.headers),
166
- };
167
- if (mutatedOptions.json) {
168
- mutatedOptions.body = JSON.stringify(mutatedOptions.json);
169
- mutatedOptions.headers = mergeHeaders(mutatedOptions.headers, {
170
- "content-type": "application/json",
171
- });
172
- delete mutatedOptions.json;
173
- }
174
- if (mutatedOptions.withResponse) {
175
- delete mutatedOptions.withResponse;
176
- }
177
- let timeoutSignal = null;
178
- if (typeof options?.timeoutMs !== "undefined") {
179
- if (options.timeoutMs != null) {
180
- timeoutSignal = AbortSignal.timeout(options.timeoutMs);
181
- }
182
- }
183
- else if (this.timeoutMs != null) {
184
- timeoutSignal = AbortSignal.timeout(this.timeoutMs);
185
- }
186
- mutatedOptions.signal = mergeSignals(timeoutSignal, mutatedOptions.signal);
187
- const targetUrl = new URL(`${this.apiUrl}${path}`);
188
- if (mutatedOptions.params) {
189
- for (const [key, value] of Object.entries(mutatedOptions.params)) {
190
- if (value == null)
191
- continue;
192
- const strValue = typeof value === "string" || typeof value === "number"
193
- ? value.toString()
194
- : JSON.stringify(value);
195
- targetUrl.searchParams.append(key, strValue);
196
- }
197
- delete mutatedOptions.params;
198
- }
199
- return [targetUrl, mutatedOptions];
200
- }
201
- async fetch(path, options) {
202
- const [url, init] = this.prepareFetchOptions(path, options);
203
- let finalInit = init;
204
- if (this.onRequest) {
205
- finalInit = await this.onRequest(url, init);
206
- }
207
- const response = await this.asyncCaller.fetch(url, finalInit);
208
- const body = (() => {
209
- if (response.status === 202 || response.status === 204) {
210
- return undefined;
211
- }
212
- return response.json();
213
- })();
214
- if (options?.withResponse) {
215
- return [await body, response];
216
- }
217
- return body;
218
- }
219
- }
220
- export class CronsClient extends BaseClient {
221
- /**
222
- *
223
- * @param threadId The ID of the thread.
224
- * @param assistantId Assistant ID to use for this cron job.
225
- * @param payload Payload for creating a cron job.
226
- * @returns The created background run.
227
- */
228
- async createForThread(threadId, assistantId, payload) {
229
- const json = {
230
- schedule: payload?.schedule,
231
- input: payload?.input,
232
- config: payload?.config,
233
- context: payload?.context,
234
- metadata: payload?.metadata,
235
- assistant_id: assistantId,
236
- interrupt_before: payload?.interruptBefore,
237
- interrupt_after: payload?.interruptAfter,
238
- webhook: payload?.webhook,
239
- multitask_strategy: payload?.multitaskStrategy,
240
- if_not_exists: payload?.ifNotExists,
241
- checkpoint_during: payload?.checkpointDuring,
242
- durability: payload?.durability,
243
- };
244
- return this.fetch(`/threads/${threadId}/runs/crons`, {
245
- method: "POST",
246
- json,
247
- });
248
- }
249
- /**
250
- *
251
- * @param assistantId Assistant ID to use for this cron job.
252
- * @param payload Payload for creating a cron job.
253
- * @returns
254
- */
255
- async create(assistantId, payload) {
256
- const json = {
257
- schedule: payload?.schedule,
258
- input: payload?.input,
259
- config: payload?.config,
260
- context: payload?.context,
261
- metadata: payload?.metadata,
262
- assistant_id: assistantId,
263
- interrupt_before: payload?.interruptBefore,
264
- interrupt_after: payload?.interruptAfter,
265
- webhook: payload?.webhook,
266
- multitask_strategy: payload?.multitaskStrategy,
267
- if_not_exists: payload?.ifNotExists,
268
- checkpoint_during: payload?.checkpointDuring,
269
- durability: payload?.durability,
270
- };
271
- return this.fetch(`/runs/crons`, {
272
- method: "POST",
273
- json,
274
- });
275
- }
276
- /**
277
- *
278
- * @param cronId Cron ID of Cron job to delete.
279
- */
280
- async delete(cronId) {
281
- await this.fetch(`/runs/crons/${cronId}`, {
282
- method: "DELETE",
283
- });
284
- }
285
- /**
286
- *
287
- * @param query Query options.
288
- * @returns List of crons.
289
- */
290
- async search(query) {
291
- return this.fetch("/runs/crons/search", {
292
- method: "POST",
293
- json: {
294
- assistant_id: query?.assistantId ?? undefined,
295
- thread_id: query?.threadId ?? undefined,
296
- limit: query?.limit ?? 10,
297
- offset: query?.offset ?? 0,
298
- sort_by: query?.sortBy ?? undefined,
299
- sort_order: query?.sortOrder ?? undefined,
300
- select: query?.select ?? undefined,
301
- },
302
- });
303
- }
304
- /**
305
- * Count cron jobs matching filters.
306
- *
307
- * @param query.assistantId Assistant ID to filter by.
308
- * @param query.threadId Thread ID to filter by.
309
- * @returns Number of cron jobs matching the criteria.
310
- */
311
- async count(query) {
312
- return this.fetch(`/runs/crons/count`, {
313
- method: "POST",
314
- json: {
315
- assistant_id: query?.assistantId ?? undefined,
316
- thread_id: query?.threadId ?? undefined,
317
- },
318
- });
319
- }
320
- }
321
- export class AssistantsClient extends BaseClient {
322
- /**
323
- * Get an assistant by ID.
324
- *
325
- * @param assistantId The ID of the assistant.
326
- * @returns Assistant
327
- */
328
- async get(assistantId) {
329
- return this.fetch(`/assistants/${assistantId}`);
330
- }
331
- /**
332
- * Get the JSON representation of the graph assigned to a runnable
333
- * @param assistantId The ID of the assistant.
334
- * @param options.xray Whether to include subgraphs in the serialized graph representation. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
335
- * @returns Serialized graph
336
- */
337
- async getGraph(assistantId, options) {
338
- return this.fetch(`/assistants/${assistantId}/graph`, {
339
- params: { xray: options?.xray },
340
- });
341
- }
342
- /**
343
- * Get the state and config schema of the graph assigned to a runnable
344
- * @param assistantId The ID of the assistant.
345
- * @returns Graph schema
346
- */
347
- async getSchemas(assistantId) {
348
- return this.fetch(`/assistants/${assistantId}/schemas`);
349
- }
350
- /**
351
- * Get the schemas of an assistant by ID.
352
- *
353
- * @param assistantId The ID of the assistant to get the schema of.
354
- * @param options Additional options for getting subgraphs, such as namespace or recursion extraction.
355
- * @returns The subgraphs of the assistant.
356
- */
357
- async getSubgraphs(assistantId, options) {
358
- if (options?.namespace) {
359
- return this.fetch(`/assistants/${assistantId}/subgraphs/${options.namespace}`, { params: { recurse: options?.recurse } });
360
- }
361
- return this.fetch(`/assistants/${assistantId}/subgraphs`, {
362
- params: { recurse: options?.recurse },
363
- });
364
- }
365
- /**
366
- * Create a new assistant.
367
- * @param payload Payload for creating an assistant.
368
- * @returns The created assistant.
369
- */
370
- async create(payload) {
371
- return this.fetch("/assistants", {
372
- method: "POST",
373
- json: {
374
- graph_id: payload.graphId,
375
- config: payload.config,
376
- context: payload.context,
377
- metadata: payload.metadata,
378
- assistant_id: payload.assistantId,
379
- if_exists: payload.ifExists,
380
- name: payload.name,
381
- description: payload.description,
382
- },
383
- });
384
- }
385
- /**
386
- * Update an assistant.
387
- * @param assistantId ID of the assistant.
388
- * @param payload Payload for updating the assistant.
389
- * @returns The updated assistant.
390
- */
391
- async update(assistantId, payload) {
392
- return this.fetch(`/assistants/${assistantId}`, {
393
- method: "PATCH",
394
- json: {
395
- graph_id: payload.graphId,
396
- config: payload.config,
397
- context: payload.context,
398
- metadata: payload.metadata,
399
- name: payload.name,
400
- description: payload.description,
401
- },
402
- });
403
- }
404
- /**
405
- * Delete an assistant.
406
- *
407
- * @param assistantId ID of the assistant.
408
- */
409
- async delete(assistantId) {
410
- return this.fetch(`/assistants/${assistantId}`, {
411
- method: "DELETE",
412
- });
413
- }
414
- /**
415
- * List assistants.
416
- * @param query Query options.
417
- * @returns List of assistants.
418
- */
419
- async search(query) {
420
- return this.fetch("/assistants/search", {
421
- method: "POST",
422
- json: {
423
- graph_id: query?.graphId ?? undefined,
424
- metadata: query?.metadata ?? undefined,
425
- limit: query?.limit ?? 10,
426
- offset: query?.offset ?? 0,
427
- sort_by: query?.sortBy ?? undefined,
428
- sort_order: query?.sortOrder ?? undefined,
429
- select: query?.select ?? undefined,
430
- },
431
- });
432
- }
433
- /**
434
- * Count assistants matching filters.
435
- *
436
- * @param query.metadata Metadata to filter by. Exact match for each key/value.
437
- * @param query.graphId Optional graph id to filter by.
438
- * @returns Number of assistants matching the criteria.
439
- */
440
- async count(query) {
441
- return this.fetch(`/assistants/count`, {
442
- method: "POST",
443
- json: {
444
- metadata: query?.metadata ?? undefined,
445
- graph_id: query?.graphId ?? undefined,
446
- },
447
- });
448
- }
449
- /**
450
- * List all versions of an assistant.
451
- *
452
- * @param assistantId ID of the assistant.
453
- * @returns List of assistant versions.
454
- */
455
- async getVersions(assistantId, payload) {
456
- return this.fetch(`/assistants/${assistantId}/versions`, {
457
- method: "POST",
458
- json: {
459
- metadata: payload?.metadata ?? undefined,
460
- limit: payload?.limit ?? 10,
461
- offset: payload?.offset ?? 0,
462
- },
463
- });
464
- }
465
- /**
466
- * Change the version of an assistant.
467
- *
468
- * @param assistantId ID of the assistant.
469
- * @param version The version to change to.
470
- * @returns The updated assistant.
471
- */
472
- async setLatest(assistantId, version) {
473
- return this.fetch(`/assistants/${assistantId}/latest`, {
474
- method: "POST",
475
- json: { version },
476
- });
477
- }
478
- }
479
- export class ThreadsClient extends BaseClient {
480
- /**
481
- * Get a thread by ID.
482
- *
483
- * @param threadId ID of the thread.
484
- * @returns The thread.
485
- */
486
- async get(threadId) {
487
- return this.fetch(`/threads/${threadId}`);
488
- }
489
- /**
490
- * Create a new thread.
491
- *
492
- * @param payload Payload for creating a thread.
493
- * @returns The created thread.
494
- */
495
- async create(payload) {
496
- // Normalize ttl to an object if a number is provided
497
- const ttlPayload = typeof payload?.ttl === "number"
498
- ? { ttl: payload.ttl, strategy: "delete" }
499
- : payload?.ttl;
500
- return this.fetch(`/threads`, {
501
- method: "POST",
502
- json: {
503
- metadata: {
504
- ...payload?.metadata,
505
- graph_id: payload?.graphId,
506
- },
507
- thread_id: payload?.threadId,
508
- if_exists: payload?.ifExists,
509
- supersteps: payload?.supersteps?.map((s) => ({
510
- updates: s.updates.map((u) => ({
511
- values: u.values,
512
- command: u.command,
513
- as_node: u.asNode,
514
- })),
515
- })),
516
- ttl: ttlPayload,
517
- },
518
- });
519
- }
520
- /**
521
- * Copy an existing thread
522
- * @param threadId ID of the thread to be copied
523
- * @returns Newly copied thread
524
- */
525
- async copy(threadId) {
526
- return this.fetch(`/threads/${threadId}/copy`, {
527
- method: "POST",
528
- });
529
- }
530
- /**
531
- * Update a thread.
532
- *
533
- * @param threadId ID of the thread.
534
- * @param payload Payload for updating the thread.
535
- * @returns The updated thread.
536
- */
537
- async update(threadId, payload) {
538
- const ttlPayload = typeof payload?.ttl === "number"
539
- ? { ttl: payload.ttl, strategy: "delete" }
540
- : payload?.ttl;
541
- return this.fetch(`/threads/${threadId}`, {
542
- method: "PATCH",
543
- json: { metadata: payload?.metadata, ttl: ttlPayload },
544
- });
545
- }
546
- /**
547
- * Delete a thread.
548
- *
549
- * @param threadId ID of the thread.
550
- */
551
- async delete(threadId) {
552
- return this.fetch(`/threads/${threadId}`, {
553
- method: "DELETE",
554
- });
555
- }
556
- /**
557
- * List threads
558
- *
559
- * @param query Query options
560
- * @returns List of threads
561
- */
562
- async search(query) {
563
- return this.fetch("/threads/search", {
564
- method: "POST",
565
- json: {
566
- metadata: query?.metadata ?? undefined,
567
- ids: query?.ids ?? undefined,
568
- limit: query?.limit ?? 10,
569
- offset: query?.offset ?? 0,
570
- status: query?.status,
571
- sort_by: query?.sortBy,
572
- sort_order: query?.sortOrder,
573
- select: query?.select ?? undefined,
574
- },
575
- });
576
- }
577
- /**
578
- * Count threads matching filters.
579
- *
580
- * @param query.metadata Thread metadata to filter on.
581
- * @param query.values State values to filter on.
582
- * @param query.status Thread status to filter on.
583
- * @returns Number of threads matching the criteria.
584
- */
585
- async count(query) {
586
- return this.fetch(`/threads/count`, {
587
- method: "POST",
588
- json: {
589
- metadata: query?.metadata ?? undefined,
590
- values: query?.values ?? undefined,
591
- status: query?.status ?? undefined,
592
- },
593
- });
594
- }
595
- /**
596
- * Get state for a thread.
597
- *
598
- * @param threadId ID of the thread.
599
- * @returns Thread state.
600
- */
601
- async getState(threadId, checkpoint, options) {
602
- if (checkpoint != null) {
603
- if (typeof checkpoint !== "string") {
604
- return this.fetch(`/threads/${threadId}/state/checkpoint`, {
605
- method: "POST",
606
- json: { checkpoint, subgraphs: options?.subgraphs },
607
- });
608
- }
609
- // deprecated
610
- return this.fetch(`/threads/${threadId}/state/${checkpoint}`, { params: { subgraphs: options?.subgraphs } });
611
- }
612
- return this.fetch(`/threads/${threadId}/state`, {
613
- params: { subgraphs: options?.subgraphs },
614
- });
615
- }
616
- /**
617
- * Add state to a thread.
618
- *
619
- * @param threadId The ID of the thread.
620
- * @returns
621
- */
622
- async updateState(threadId, options) {
623
- return this.fetch(`/threads/${threadId}/state`, {
624
- method: "POST",
625
- json: {
626
- values: options.values,
627
- checkpoint_id: options.checkpointId,
628
- checkpoint: options.checkpoint,
629
- as_node: options?.asNode,
630
- },
631
- });
632
- }
633
- /**
634
- * Patch the metadata of a thread.
635
- *
636
- * @param threadIdOrConfig Thread ID or config to patch the state of.
637
- * @param metadata Metadata to patch the state with.
638
- */
639
- async patchState(threadIdOrConfig, metadata) {
640
- let threadId;
641
- if (typeof threadIdOrConfig !== "string") {
642
- if (typeof threadIdOrConfig.configurable?.thread_id !== "string") {
643
- throw new Error("Thread ID is required when updating state with a config.");
644
- }
645
- threadId = threadIdOrConfig.configurable.thread_id;
646
- }
647
- else {
648
- threadId = threadIdOrConfig;
649
- }
650
- return this.fetch(`/threads/${threadId}/state`, {
651
- method: "PATCH",
652
- json: { metadata },
653
- });
654
- }
655
- /**
656
- * Get all past states for a thread.
657
- *
658
- * @param threadId ID of the thread.
659
- * @param options Additional options.
660
- * @returns List of thread states.
661
- */
662
- async getHistory(threadId, options) {
663
- return this.fetch(`/threads/${threadId}/history`, {
664
- method: "POST",
665
- json: {
666
- limit: options?.limit ?? 10,
667
- before: options?.before,
668
- metadata: options?.metadata,
669
- checkpoint: options?.checkpoint,
670
- },
671
- });
672
- }
673
- async *joinStream(threadId, options
674
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
675
- ) {
676
- let [url, init] = this.prepareFetchOptions(`/threads/${threadId}/stream`, {
677
- method: "GET",
678
- headers: options?.lastEventId
679
- ? { "Last-Event-ID": options.lastEventId }
680
- : undefined,
681
- params: options?.streamMode
682
- ? { stream_mode: options.streamMode }
683
- : undefined,
684
- });
685
- if (this.onRequest != null)
686
- init = await this.onRequest(url, init);
687
- const response = await this.asyncCaller.fetch(url, init);
688
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
689
- const stream = (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() }))
690
- .pipeThrough(BytesLineDecoder())
691
- .pipeThrough(SSEDecoder());
692
- yield* IterableReadableStream.fromReadableStream(stream);
693
- }
694
- }
695
- export class RunsClient extends BaseClient {
696
- /**
697
- * Create a run and stream the results.
698
- *
699
- * @param threadId The ID of the thread.
700
- * @param assistantId Assistant ID to use for this run.
701
- * @param payload Payload for creating a run.
702
- */
703
- async *stream(threadId, assistantId, payload) {
704
- const json = {
705
- input: payload?.input,
706
- command: payload?.command,
707
- config: payload?.config,
708
- context: payload?.context,
709
- metadata: payload?.metadata,
710
- stream_mode: payload?.streamMode,
711
- stream_subgraphs: payload?.streamSubgraphs,
712
- stream_resumable: payload?.streamResumable,
713
- feedback_keys: payload?.feedbackKeys,
714
- assistant_id: assistantId,
715
- interrupt_before: payload?.interruptBefore,
716
- interrupt_after: payload?.interruptAfter,
717
- checkpoint: payload?.checkpoint,
718
- checkpoint_id: payload?.checkpointId,
719
- webhook: payload?.webhook,
720
- multitask_strategy: payload?.multitaskStrategy,
721
- on_completion: payload?.onCompletion,
722
- on_disconnect: payload?.onDisconnect,
723
- after_seconds: payload?.afterSeconds,
724
- if_not_exists: payload?.ifNotExists,
725
- checkpoint_during: payload?.checkpointDuring,
726
- durability: payload?.durability,
727
- };
728
- const endpoint = threadId == null ? `/runs/stream` : `/threads/${threadId}/runs/stream`;
729
- let [url, init] = this.prepareFetchOptions(endpoint, {
730
- method: "POST",
731
- json,
732
- timeoutMs: null,
733
- signal: payload?.signal,
734
- });
735
- if (this.onRequest != null)
736
- init = await this.onRequest(url, init);
737
- const response = await this.asyncCaller.fetch(url, init);
738
- const runMetadata = getRunMetadataFromResponse(response);
739
- if (runMetadata)
740
- payload?.onRunCreated?.(runMetadata);
741
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
742
- const stream = (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() }))
743
- .pipeThrough(BytesLineDecoder())
744
- .pipeThrough(SSEDecoder());
745
- yield* IterableReadableStream.fromReadableStream(stream);
746
- }
747
- /**
748
- * Create a run.
749
- *
750
- * @param threadId The ID of the thread.
751
- * @param assistantId Assistant ID to use for this run.
752
- * @param payload Payload for creating a run.
753
- * @returns The created run.
754
- */
755
- async create(threadId, assistantId, payload) {
756
- const json = {
757
- input: payload?.input,
758
- command: payload?.command,
759
- config: payload?.config,
760
- context: payload?.context,
761
- metadata: payload?.metadata,
762
- stream_mode: payload?.streamMode,
763
- stream_subgraphs: payload?.streamSubgraphs,
764
- stream_resumable: payload?.streamResumable,
765
- assistant_id: assistantId,
766
- interrupt_before: payload?.interruptBefore,
767
- interrupt_after: payload?.interruptAfter,
768
- webhook: payload?.webhook,
769
- checkpoint: payload?.checkpoint,
770
- checkpoint_id: payload?.checkpointId,
771
- multitask_strategy: payload?.multitaskStrategy,
772
- after_seconds: payload?.afterSeconds,
773
- if_not_exists: payload?.ifNotExists,
774
- checkpoint_during: payload?.checkpointDuring,
775
- durability: payload?.durability,
776
- langsmith_tracer: payload?._langsmithTracer
777
- ? {
778
- project_name: payload?._langsmithTracer?.projectName,
779
- example_id: payload?._langsmithTracer?.exampleId,
780
- }
781
- : undefined,
782
- };
783
- const endpoint = threadId === null ? "/runs" : `/threads/${threadId}/runs`;
784
- const [run, response] = await this.fetch(endpoint, {
785
- method: "POST",
786
- json,
787
- signal: payload?.signal,
788
- withResponse: true,
789
- });
790
- const runMetadata = getRunMetadataFromResponse(response);
791
- if (runMetadata)
792
- payload?.onRunCreated?.(runMetadata);
793
- return run;
794
- }
795
- /**
796
- * Create a batch of stateless background runs.
797
- *
798
- * @param payloads An array of payloads for creating runs.
799
- * @returns An array of created runs.
800
- */
801
- async createBatch(payloads) {
802
- const filteredPayloads = payloads
803
- .map((payload) => ({ ...payload, assistant_id: payload.assistantId }))
804
- .map((payload) => {
805
- return Object.fromEntries(Object.entries(payload).filter(([_, v]) => v !== undefined));
806
- });
807
- return this.fetch("/runs/batch", {
808
- method: "POST",
809
- json: filteredPayloads,
810
- });
811
- }
812
- /**
813
- * Create a run and wait for it to complete.
814
- *
815
- * @param threadId The ID of the thread.
816
- * @param assistantId Assistant ID to use for this run.
817
- * @param payload Payload for creating a run.
818
- * @returns The last values chunk of the thread.
819
- */
820
- async wait(threadId, assistantId, payload) {
821
- const json = {
822
- input: payload?.input,
823
- command: payload?.command,
824
- config: payload?.config,
825
- context: payload?.context,
826
- metadata: payload?.metadata,
827
- assistant_id: assistantId,
828
- interrupt_before: payload?.interruptBefore,
829
- interrupt_after: payload?.interruptAfter,
830
- checkpoint: payload?.checkpoint,
831
- checkpoint_id: payload?.checkpointId,
832
- webhook: payload?.webhook,
833
- multitask_strategy: payload?.multitaskStrategy,
834
- on_completion: payload?.onCompletion,
835
- on_disconnect: payload?.onDisconnect,
836
- after_seconds: payload?.afterSeconds,
837
- if_not_exists: payload?.ifNotExists,
838
- checkpoint_during: payload?.checkpointDuring,
839
- durability: payload?.durability,
840
- langsmith_tracer: payload?._langsmithTracer
841
- ? {
842
- project_name: payload?._langsmithTracer?.projectName,
843
- example_id: payload?._langsmithTracer?.exampleId,
844
- }
845
- : undefined,
846
- };
847
- const endpoint = threadId == null ? `/runs/wait` : `/threads/${threadId}/runs/wait`;
848
- const [run, response] = await this.fetch(endpoint, {
849
- method: "POST",
850
- json,
851
- timeoutMs: null,
852
- signal: payload?.signal,
853
- withResponse: true,
854
- });
855
- const runMetadata = getRunMetadataFromResponse(response);
856
- if (runMetadata)
857
- payload?.onRunCreated?.(runMetadata);
858
- const raiseError = payload?.raiseError !== undefined ? payload.raiseError : true;
859
- if (raiseError &&
860
- "__error__" in run &&
861
- typeof run.__error__ === "object" &&
862
- run.__error__ &&
863
- "error" in run.__error__ &&
864
- "message" in run.__error__) {
865
- throw new Error(`${run.__error__?.error}: ${run.__error__?.message}`);
866
- }
867
- return run;
868
- }
869
- /**
870
- * List all runs for a thread.
871
- *
872
- * @param threadId The ID of the thread.
873
- * @param options Filtering and pagination options.
874
- * @returns List of runs.
875
- */
876
- async list(threadId, options) {
877
- return this.fetch(`/threads/${threadId}/runs`, {
878
- params: {
879
- limit: options?.limit ?? 10,
880
- offset: options?.offset ?? 0,
881
- status: options?.status ?? undefined,
882
- select: options?.select ?? undefined,
883
- },
884
- });
885
- }
886
- /**
887
- * Get a run by ID.
888
- *
889
- * @param threadId The ID of the thread.
890
- * @param runId The ID of the run.
891
- * @returns The run.
892
- */
893
- async get(threadId, runId) {
894
- return this.fetch(`/threads/${threadId}/runs/${runId}`);
895
- }
896
- /**
897
- * Cancel a run.
898
- *
899
- * @param threadId The ID of the thread.
900
- * @param runId The ID of the run.
901
- * @param wait Whether to block when canceling
902
- * @param action Action to take when cancelling the run. Possible values are `interrupt` or `rollback`. Default is `interrupt`.
903
- * @returns
904
- */
905
- async cancel(threadId, runId, wait = false, action = "interrupt") {
906
- return this.fetch(`/threads/${threadId}/runs/${runId}/cancel`, {
907
- method: "POST",
908
- params: {
909
- wait: wait ? "1" : "0",
910
- action,
911
- },
912
- });
913
- }
914
- /**
915
- * Block until a run is done.
916
- *
917
- * @param threadId The ID of the thread.
918
- * @param runId The ID of the run.
919
- * @returns
920
- */
921
- async join(threadId, runId, options) {
922
- return this.fetch(`/threads/${threadId}/runs/${runId}/join`, {
923
- timeoutMs: null,
924
- signal: options?.signal,
925
- });
926
- }
927
- /**
928
- * Stream output from a run in real-time, until the run is done.
929
- *
930
- * @param threadId The ID of the thread. Can be set to `null` | `undefined` for stateless runs.
931
- * @param runId The ID of the run.
932
- * @param options Additional options for controlling the stream behavior:
933
- * - signal: An AbortSignal that can be used to cancel the stream request
934
- * - lastEventId: The ID of the last event received. Can be used to reconnect to a stream without losing events.
935
- * - cancelOnDisconnect: When true, automatically cancels the run if the client disconnects from the stream
936
- * - streamMode: Controls what types of events to receive from the stream (can be a single mode or array of modes)
937
- * Must be a subset of the stream modes passed when creating the run. Background runs default to having the union of all
938
- * stream modes enabled.
939
- * @returns An async generator yielding stream parts.
940
- */
941
- async *joinStream(threadId, runId, options
942
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
943
- ) {
944
- const opts = typeof options === "object" &&
945
- options != null &&
946
- // eslint-disable-next-line no-instanceof/no-instanceof
947
- options instanceof AbortSignal
948
- ? { signal: options }
949
- : options;
950
- let [url, init] = this.prepareFetchOptions(threadId != null
951
- ? `/threads/${threadId}/runs/${runId}/stream`
952
- : `/runs/${runId}/stream`, {
953
- method: "GET",
954
- timeoutMs: null,
955
- signal: opts?.signal,
956
- headers: opts?.lastEventId
957
- ? { "Last-Event-ID": opts.lastEventId }
958
- : undefined,
959
- params: {
960
- cancel_on_disconnect: opts?.cancelOnDisconnect ? "1" : "0",
961
- stream_mode: opts?.streamMode,
962
- },
963
- });
964
- if (this.onRequest != null)
965
- init = await this.onRequest(url, init);
966
- const response = await this.asyncCaller.fetch(url, init);
967
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
968
- const stream = (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() }))
969
- .pipeThrough(BytesLineDecoder())
970
- .pipeThrough(SSEDecoder());
971
- yield* IterableReadableStream.fromReadableStream(stream);
972
- }
973
- /**
974
- * Delete a run.
975
- *
976
- * @param threadId The ID of the thread.
977
- * @param runId The ID of the run.
978
- * @returns
979
- */
980
- async delete(threadId, runId) {
981
- return this.fetch(`/threads/${threadId}/runs/${runId}`, {
982
- method: "DELETE",
983
- });
984
- }
985
- }
986
- export class StoreClient extends BaseClient {
987
- /**
988
- * Store or update an item.
989
- *
990
- * @param namespace A list of strings representing the namespace path.
991
- * @param key The unique identifier for the item within the namespace.
992
- * @param value A dictionary containing the item's data.
993
- * @param options.index Controls search indexing - null (use defaults), false (disable), or list of field paths to index.
994
- * @param options.ttl Optional time-to-live in minutes for the item, or null for no expiration.
995
- * @returns Promise<void>
996
- *
997
- * @example
998
- * ```typescript
999
- * await client.store.putItem(
1000
- * ["documents", "user123"],
1001
- * "item456",
1002
- * { title: "My Document", content: "Hello World" },
1003
- * { ttl: 60 } // expires in 60 minutes
1004
- * );
1005
- * ```
1006
- */
1007
- async putItem(namespace, key, value, options) {
1008
- namespace.forEach((label) => {
1009
- if (label.includes(".")) {
1010
- throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
1011
- }
1012
- });
1013
- const payload = {
1014
- namespace,
1015
- key,
1016
- value,
1017
- index: options?.index,
1018
- ttl: options?.ttl,
1019
- };
1020
- return this.fetch("/store/items", {
1021
- method: "PUT",
1022
- json: payload,
1023
- });
1024
- }
1025
- /**
1026
- * Retrieve a single item.
1027
- *
1028
- * @param namespace A list of strings representing the namespace path.
1029
- * @param key The unique identifier for the item.
1030
- * @param options.refreshTtl Whether to refresh the TTL on this read operation. If null, uses the store's default behavior.
1031
- * @returns Promise<Item>
1032
- *
1033
- * @example
1034
- * ```typescript
1035
- * const item = await client.store.getItem(
1036
- * ["documents", "user123"],
1037
- * "item456",
1038
- * { refreshTtl: true }
1039
- * );
1040
- * console.log(item);
1041
- * // {
1042
- * // namespace: ["documents", "user123"],
1043
- * // key: "item456",
1044
- * // value: { title: "My Document", content: "Hello World" },
1045
- * // createdAt: "2024-07-30T12:00:00Z",
1046
- * // updatedAt: "2024-07-30T12:00:00Z"
1047
- * // }
1048
- * ```
1049
- */
1050
- async getItem(namespace, key, options) {
1051
- namespace.forEach((label) => {
1052
- if (label.includes(".")) {
1053
- throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
1054
- }
1055
- });
1056
- const params = {
1057
- namespace: namespace.join("."),
1058
- key,
1059
- };
1060
- if (options?.refreshTtl !== undefined) {
1061
- params.refresh_ttl = options.refreshTtl;
1062
- }
1063
- const response = await this.fetch("/store/items", {
1064
- params,
1065
- });
1066
- return response
1067
- ? {
1068
- ...response,
1069
- createdAt: response.created_at,
1070
- updatedAt: response.updated_at,
1071
- }
1072
- : null;
1073
- }
1074
- /**
1075
- * Delete an item.
1076
- *
1077
- * @param namespace A list of strings representing the namespace path.
1078
- * @param key The unique identifier for the item.
1079
- * @returns Promise<void>
1080
- */
1081
- async deleteItem(namespace, key) {
1082
- namespace.forEach((label) => {
1083
- if (label.includes(".")) {
1084
- throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
1085
- }
1086
- });
1087
- return this.fetch("/store/items", {
1088
- method: "DELETE",
1089
- json: { namespace, key },
1090
- });
1091
- }
1092
- /**
1093
- * Search for items within a namespace prefix.
1094
- *
1095
- * @param namespacePrefix List of strings representing the namespace prefix.
1096
- * @param options.filter Optional dictionary of key-value pairs to filter results.
1097
- * @param options.limit Maximum number of items to return (default is 10).
1098
- * @param options.offset Number of items to skip before returning results (default is 0).
1099
- * @param options.query Optional search query.
1100
- * @param options.refreshTtl Whether to refresh the TTL on items returned by this search. If null, uses the store's default behavior.
1101
- * @returns Promise<SearchItemsResponse>
1102
- *
1103
- * @example
1104
- * ```typescript
1105
- * const results = await client.store.searchItems(
1106
- * ["documents"],
1107
- * {
1108
- * filter: { author: "John Doe" },
1109
- * limit: 5,
1110
- * refreshTtl: true
1111
- * }
1112
- * );
1113
- * console.log(results);
1114
- * // {
1115
- * // items: [
1116
- * // {
1117
- * // namespace: ["documents", "user123"],
1118
- * // key: "item789",
1119
- * // value: { title: "Another Document", author: "John Doe" },
1120
- * // createdAt: "2024-07-30T12:00:00Z",
1121
- * // updatedAt: "2024-07-30T12:00:00Z"
1122
- * // },
1123
- * // // ... additional items ...
1124
- * // ]
1125
- * // }
1126
- * ```
1127
- */
1128
- async searchItems(namespacePrefix, options) {
1129
- const payload = {
1130
- namespace_prefix: namespacePrefix,
1131
- filter: options?.filter,
1132
- limit: options?.limit ?? 10,
1133
- offset: options?.offset ?? 0,
1134
- query: options?.query,
1135
- refresh_ttl: options?.refreshTtl,
1136
- };
1137
- const response = await this.fetch("/store/items/search", {
1138
- method: "POST",
1139
- json: payload,
1140
- });
1141
- return {
1142
- items: response.items.map((item) => ({
1143
- ...item,
1144
- createdAt: item.created_at,
1145
- updatedAt: item.updated_at,
1146
- })),
1147
- };
1148
- }
1149
- /**
1150
- * List namespaces with optional match conditions.
1151
- *
1152
- * @param options.prefix Optional list of strings representing the prefix to filter namespaces.
1153
- * @param options.suffix Optional list of strings representing the suffix to filter namespaces.
1154
- * @param options.maxDepth Optional integer specifying the maximum depth of namespaces to return.
1155
- * @param options.limit Maximum number of namespaces to return (default is 100).
1156
- * @param options.offset Number of namespaces to skip before returning results (default is 0).
1157
- * @returns Promise<ListNamespaceResponse>
1158
- */
1159
- async listNamespaces(options) {
1160
- const payload = {
1161
- prefix: options?.prefix,
1162
- suffix: options?.suffix,
1163
- max_depth: options?.maxDepth,
1164
- limit: options?.limit ?? 100,
1165
- offset: options?.offset ?? 0,
1166
- };
1167
- return this.fetch("/store/namespaces", {
1168
- method: "POST",
1169
- json: payload,
1170
- });
1171
- }
1172
- }
1173
- class UiClient extends BaseClient {
1174
- static getOrCached(key, fn) {
1175
- if (UiClient.promiseCache[key] != null) {
1176
- return UiClient.promiseCache[key];
1177
- }
1178
- const promise = fn();
1179
- UiClient.promiseCache[key] = promise;
1180
- return promise;
1181
- }
1182
- async getComponent(assistantId, agentName) {
1183
- return UiClient.getOrCached(`${this.apiUrl}-${assistantId}-${agentName}`, async () => {
1184
- let [url, init] = this.prepareFetchOptions(`/ui/${assistantId}`, {
1185
- headers: {
1186
- Accept: "text/html",
1187
- "Content-Type": "application/json",
1188
- },
1189
- method: "POST",
1190
- json: { name: agentName },
1191
- });
1192
- if (this.onRequest != null)
1193
- init = await this.onRequest(url, init);
1194
- const response = await this.asyncCaller.fetch(url, init);
1195
- return response.text();
1196
- });
1197
- }
1198
- }
1199
- Object.defineProperty(UiClient, "promiseCache", {
1200
- enumerable: true,
1201
- configurable: true,
1202
- writable: true,
1203
- value: {}
1204
- });
1205
- export class Client {
1206
- constructor(config) {
1207
- /**
1208
- * The client for interacting with assistants.
1209
- */
1210
- Object.defineProperty(this, "assistants", {
1211
- enumerable: true,
1212
- configurable: true,
1213
- writable: true,
1214
- value: void 0
1215
- });
1216
- /**
1217
- * The client for interacting with threads.
1218
- */
1219
- Object.defineProperty(this, "threads", {
1220
- enumerable: true,
1221
- configurable: true,
1222
- writable: true,
1223
- value: void 0
1224
- });
1225
- /**
1226
- * The client for interacting with runs.
1227
- */
1228
- Object.defineProperty(this, "runs", {
1229
- enumerable: true,
1230
- configurable: true,
1231
- writable: true,
1232
- value: void 0
1233
- });
1234
- /**
1235
- * The client for interacting with cron runs.
1236
- */
1237
- Object.defineProperty(this, "crons", {
1238
- enumerable: true,
1239
- configurable: true,
1240
- writable: true,
1241
- value: void 0
1242
- });
1243
- /**
1244
- * The client for interacting with the KV store.
1245
- */
1246
- Object.defineProperty(this, "store", {
1247
- enumerable: true,
1248
- configurable: true,
1249
- writable: true,
1250
- value: void 0
1251
- });
1252
- /**
1253
- * The client for interacting with the UI.
1254
- * @internal Used by LoadExternalComponent and the API might change in the future.
1255
- */
1256
- Object.defineProperty(this, "~ui", {
1257
- enumerable: true,
1258
- configurable: true,
1259
- writable: true,
1260
- value: void 0
1261
- });
1262
- /**
1263
- * @internal Used to obtain a stable key representing the client.
1264
- */
1265
- Object.defineProperty(this, "~configHash", {
1266
- enumerable: true,
1267
- configurable: true,
1268
- writable: true,
1269
- value: void 0
1270
- });
1271
- this["~configHash"] = (() => JSON.stringify({
1272
- apiUrl: config?.apiUrl,
1273
- apiKey: config?.apiKey,
1274
- timeoutMs: config?.timeoutMs,
1275
- defaultHeaders: config?.defaultHeaders,
1276
- maxConcurrency: config?.callerOptions?.maxConcurrency,
1277
- maxRetries: config?.callerOptions?.maxRetries,
1278
- callbacks: {
1279
- onFailedResponseHook: config?.callerOptions?.onFailedResponseHook != null,
1280
- onRequest: config?.onRequest != null,
1281
- fetch: config?.callerOptions?.fetch != null,
1282
- },
1283
- }))();
1284
- this.assistants = new AssistantsClient(config);
1285
- this.threads = new ThreadsClient(config);
1286
- this.runs = new RunsClient(config);
1287
- this.crons = new CronsClient(config);
1288
- this.store = new StoreClient(config);
1289
- this["~ui"] = new UiClient(config);
1290
- }
76
+ const contentLocation = response.headers.get("Content-Location");
77
+ if (!contentLocation) return void 0;
78
+ const match = REGEX_RUN_METADATA.exec(contentLocation);
79
+ if (!match?.groups?.run_id) return void 0;
80
+ return {
81
+ run_id: match.groups.run_id,
82
+ thread_id: match.groups.thread_id || void 0
83
+ };
1291
84
  }
85
+ var BaseClient = class {
86
+ asyncCaller;
87
+ timeoutMs;
88
+ apiUrl;
89
+ defaultHeaders;
90
+ onRequest;
91
+ constructor(config) {
92
+ const callerOptions = {
93
+ maxRetries: 4,
94
+ maxConcurrency: 4,
95
+ ...config?.callerOptions
96
+ };
97
+ let defaultApiUrl = "http://localhost:8123";
98
+ if (!config?.apiUrl && typeof globalThis === "object" && globalThis != null) {
99
+ const fetchSmb = Symbol.for("langgraph_api:fetch");
100
+ const urlSmb = Symbol.for("langgraph_api:url");
101
+ const global = globalThis;
102
+ if (global[fetchSmb]) callerOptions.fetch ??= global[fetchSmb];
103
+ if (global[urlSmb]) defaultApiUrl = global[urlSmb];
104
+ }
105
+ this.asyncCaller = new AsyncCaller(callerOptions);
106
+ this.timeoutMs = config?.timeoutMs;
107
+ this.apiUrl = config?.apiUrl?.replace(/\/$/, "") || defaultApiUrl;
108
+ this.defaultHeaders = config?.defaultHeaders || {};
109
+ this.onRequest = config?.onRequest;
110
+ const apiKey = getApiKey(config?.apiKey);
111
+ if (apiKey) this.defaultHeaders["x-api-key"] = apiKey;
112
+ }
113
+ prepareFetchOptions(path, options) {
114
+ const mutatedOptions = {
115
+ ...options,
116
+ headers: mergeHeaders(this.defaultHeaders, options?.headers)
117
+ };
118
+ if (mutatedOptions.json) {
119
+ mutatedOptions.body = JSON.stringify(mutatedOptions.json);
120
+ mutatedOptions.headers = mergeHeaders(mutatedOptions.headers, { "content-type": "application/json" });
121
+ delete mutatedOptions.json;
122
+ }
123
+ if (mutatedOptions.withResponse) delete mutatedOptions.withResponse;
124
+ let timeoutSignal = null;
125
+ if (typeof options?.timeoutMs !== "undefined") {
126
+ if (options.timeoutMs != null) timeoutSignal = AbortSignal.timeout(options.timeoutMs);
127
+ } else if (this.timeoutMs != null) timeoutSignal = AbortSignal.timeout(this.timeoutMs);
128
+ mutatedOptions.signal = mergeSignals(timeoutSignal, mutatedOptions.signal);
129
+ const targetUrl = new URL(`${this.apiUrl}${path}`);
130
+ if (mutatedOptions.params) {
131
+ for (const [key, value] of Object.entries(mutatedOptions.params)) {
132
+ if (value == null) continue;
133
+ const strValue = typeof value === "string" || typeof value === "number" ? value.toString() : JSON.stringify(value);
134
+ targetUrl.searchParams.append(key, strValue);
135
+ }
136
+ delete mutatedOptions.params;
137
+ }
138
+ return [targetUrl, mutatedOptions];
139
+ }
140
+ async fetch(path, options) {
141
+ const [url, init] = this.prepareFetchOptions(path, options);
142
+ let finalInit = init;
143
+ if (this.onRequest) finalInit = await this.onRequest(url, init);
144
+ const response = await this.asyncCaller.fetch(url, finalInit);
145
+ const body = (() => {
146
+ if (response.status === 202 || response.status === 204) return void 0;
147
+ return response.json();
148
+ })();
149
+ if (options?.withResponse) return [await body, response];
150
+ return body;
151
+ }
152
+ };
153
+ var CronsClient = class extends BaseClient {
154
+ /**
155
+ *
156
+ * @param threadId The ID of the thread.
157
+ * @param assistantId Assistant ID to use for this cron job.
158
+ * @param payload Payload for creating a cron job.
159
+ * @returns The created background run.
160
+ */
161
+ async createForThread(threadId, assistantId, payload) {
162
+ const json = {
163
+ schedule: payload?.schedule,
164
+ input: payload?.input,
165
+ config: payload?.config,
166
+ context: payload?.context,
167
+ metadata: payload?.metadata,
168
+ assistant_id: assistantId,
169
+ interrupt_before: payload?.interruptBefore,
170
+ interrupt_after: payload?.interruptAfter,
171
+ webhook: payload?.webhook,
172
+ multitask_strategy: payload?.multitaskStrategy,
173
+ if_not_exists: payload?.ifNotExists,
174
+ checkpoint_during: payload?.checkpointDuring,
175
+ durability: payload?.durability
176
+ };
177
+ return this.fetch(`/threads/${threadId}/runs/crons`, {
178
+ method: "POST",
179
+ json
180
+ });
181
+ }
182
+ /**
183
+ *
184
+ * @param assistantId Assistant ID to use for this cron job.
185
+ * @param payload Payload for creating a cron job.
186
+ * @returns
187
+ */
188
+ async create(assistantId, payload) {
189
+ const json = {
190
+ schedule: payload?.schedule,
191
+ input: payload?.input,
192
+ config: payload?.config,
193
+ context: payload?.context,
194
+ metadata: payload?.metadata,
195
+ assistant_id: assistantId,
196
+ interrupt_before: payload?.interruptBefore,
197
+ interrupt_after: payload?.interruptAfter,
198
+ webhook: payload?.webhook,
199
+ multitask_strategy: payload?.multitaskStrategy,
200
+ if_not_exists: payload?.ifNotExists,
201
+ checkpoint_during: payload?.checkpointDuring,
202
+ durability: payload?.durability
203
+ };
204
+ return this.fetch(`/runs/crons`, {
205
+ method: "POST",
206
+ json
207
+ });
208
+ }
209
+ /**
210
+ *
211
+ * @param cronId Cron ID of Cron job to delete.
212
+ */
213
+ async delete(cronId) {
214
+ await this.fetch(`/runs/crons/${cronId}`, { method: "DELETE" });
215
+ }
216
+ /**
217
+ *
218
+ * @param query Query options.
219
+ * @returns List of crons.
220
+ */
221
+ async search(query) {
222
+ return this.fetch("/runs/crons/search", {
223
+ method: "POST",
224
+ json: {
225
+ assistant_id: query?.assistantId ?? void 0,
226
+ thread_id: query?.threadId ?? void 0,
227
+ limit: query?.limit ?? 10,
228
+ offset: query?.offset ?? 0,
229
+ sort_by: query?.sortBy ?? void 0,
230
+ sort_order: query?.sortOrder ?? void 0,
231
+ select: query?.select ?? void 0
232
+ }
233
+ });
234
+ }
235
+ /**
236
+ * Count cron jobs matching filters.
237
+ *
238
+ * @param query.assistantId Assistant ID to filter by.
239
+ * @param query.threadId Thread ID to filter by.
240
+ * @returns Number of cron jobs matching the criteria.
241
+ */
242
+ async count(query) {
243
+ return this.fetch(`/runs/crons/count`, {
244
+ method: "POST",
245
+ json: {
246
+ assistant_id: query?.assistantId ?? void 0,
247
+ thread_id: query?.threadId ?? void 0
248
+ }
249
+ });
250
+ }
251
+ };
252
+ var AssistantsClient = class extends BaseClient {
253
+ /**
254
+ * Get an assistant by ID.
255
+ *
256
+ * @param assistantId The ID of the assistant.
257
+ * @returns Assistant
258
+ */
259
+ async get(assistantId) {
260
+ return this.fetch(`/assistants/${assistantId}`);
261
+ }
262
+ /**
263
+ * Get the JSON representation of the graph assigned to a runnable
264
+ * @param assistantId The ID of the assistant.
265
+ * @param options.xray Whether to include subgraphs in the serialized graph representation. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
266
+ * @returns Serialized graph
267
+ */
268
+ async getGraph(assistantId, options) {
269
+ return this.fetch(`/assistants/${assistantId}/graph`, { params: { xray: options?.xray } });
270
+ }
271
+ /**
272
+ * Get the state and config schema of the graph assigned to a runnable
273
+ * @param assistantId The ID of the assistant.
274
+ * @returns Graph schema
275
+ */
276
+ async getSchemas(assistantId) {
277
+ return this.fetch(`/assistants/${assistantId}/schemas`);
278
+ }
279
+ /**
280
+ * Get the schemas of an assistant by ID.
281
+ *
282
+ * @param assistantId The ID of the assistant to get the schema of.
283
+ * @param options Additional options for getting subgraphs, such as namespace or recursion extraction.
284
+ * @returns The subgraphs of the assistant.
285
+ */
286
+ async getSubgraphs(assistantId, options) {
287
+ if (options?.namespace) return this.fetch(`/assistants/${assistantId}/subgraphs/${options.namespace}`, { params: { recurse: options?.recurse } });
288
+ return this.fetch(`/assistants/${assistantId}/subgraphs`, { params: { recurse: options?.recurse } });
289
+ }
290
+ /**
291
+ * Create a new assistant.
292
+ * @param payload Payload for creating an assistant.
293
+ * @returns The created assistant.
294
+ */
295
+ async create(payload) {
296
+ return this.fetch("/assistants", {
297
+ method: "POST",
298
+ json: {
299
+ graph_id: payload.graphId,
300
+ config: payload.config,
301
+ context: payload.context,
302
+ metadata: payload.metadata,
303
+ assistant_id: payload.assistantId,
304
+ if_exists: payload.ifExists,
305
+ name: payload.name,
306
+ description: payload.description
307
+ }
308
+ });
309
+ }
310
+ /**
311
+ * Update an assistant.
312
+ * @param assistantId ID of the assistant.
313
+ * @param payload Payload for updating the assistant.
314
+ * @returns The updated assistant.
315
+ */
316
+ async update(assistantId, payload) {
317
+ return this.fetch(`/assistants/${assistantId}`, {
318
+ method: "PATCH",
319
+ json: {
320
+ graph_id: payload.graphId,
321
+ config: payload.config,
322
+ context: payload.context,
323
+ metadata: payload.metadata,
324
+ name: payload.name,
325
+ description: payload.description
326
+ }
327
+ });
328
+ }
329
+ /**
330
+ * Delete an assistant.
331
+ *
332
+ * @param assistantId ID of the assistant.
333
+ */
334
+ async delete(assistantId) {
335
+ return this.fetch(`/assistants/${assistantId}`, { method: "DELETE" });
336
+ }
337
+ /**
338
+ * List assistants.
339
+ * @param query Query options.
340
+ * @returns List of assistants.
341
+ */
342
+ async search(query) {
343
+ return this.fetch("/assistants/search", {
344
+ method: "POST",
345
+ json: {
346
+ graph_id: query?.graphId ?? void 0,
347
+ name: query?.name ?? void 0,
348
+ metadata: query?.metadata ?? void 0,
349
+ limit: query?.limit ?? 10,
350
+ offset: query?.offset ?? 0,
351
+ sort_by: query?.sortBy ?? void 0,
352
+ sort_order: query?.sortOrder ?? void 0,
353
+ select: query?.select ?? void 0
354
+ }
355
+ });
356
+ }
357
+ /**
358
+ * Count assistants matching filters.
359
+ *
360
+ * @param query.metadata Metadata to filter by. Exact match for each key/value.
361
+ * @param query.graphId Optional graph id to filter by.
362
+ * @returns Number of assistants matching the criteria.
363
+ */
364
+ async count(query) {
365
+ return this.fetch(`/assistants/count`, {
366
+ method: "POST",
367
+ json: {
368
+ metadata: query?.metadata ?? void 0,
369
+ graph_id: query?.graphId ?? void 0
370
+ }
371
+ });
372
+ }
373
+ /**
374
+ * List all versions of an assistant.
375
+ *
376
+ * @param assistantId ID of the assistant.
377
+ * @returns List of assistant versions.
378
+ */
379
+ async getVersions(assistantId, payload) {
380
+ return this.fetch(`/assistants/${assistantId}/versions`, {
381
+ method: "POST",
382
+ json: {
383
+ metadata: payload?.metadata ?? void 0,
384
+ limit: payload?.limit ?? 10,
385
+ offset: payload?.offset ?? 0
386
+ }
387
+ });
388
+ }
389
+ /**
390
+ * Change the version of an assistant.
391
+ *
392
+ * @param assistantId ID of the assistant.
393
+ * @param version The version to change to.
394
+ * @returns The updated assistant.
395
+ */
396
+ async setLatest(assistantId, version) {
397
+ return this.fetch(`/assistants/${assistantId}/latest`, {
398
+ method: "POST",
399
+ json: { version }
400
+ });
401
+ }
402
+ };
403
+ var ThreadsClient = class extends BaseClient {
404
+ /**
405
+ * Get a thread by ID.
406
+ *
407
+ * @param threadId ID of the thread.
408
+ * @returns The thread.
409
+ */
410
+ async get(threadId) {
411
+ return this.fetch(`/threads/${threadId}`);
412
+ }
413
+ /**
414
+ * Create a new thread.
415
+ *
416
+ * @param payload Payload for creating a thread.
417
+ * @returns The created thread.
418
+ */
419
+ async create(payload) {
420
+ const ttlPayload = typeof payload?.ttl === "number" ? {
421
+ ttl: payload.ttl,
422
+ strategy: "delete"
423
+ } : payload?.ttl;
424
+ return this.fetch(`/threads`, {
425
+ method: "POST",
426
+ json: {
427
+ metadata: {
428
+ ...payload?.metadata,
429
+ graph_id: payload?.graphId
430
+ },
431
+ thread_id: payload?.threadId,
432
+ if_exists: payload?.ifExists,
433
+ supersteps: payload?.supersteps?.map((s) => ({ updates: s.updates.map((u) => ({
434
+ values: u.values,
435
+ command: u.command,
436
+ as_node: u.asNode
437
+ })) })),
438
+ ttl: ttlPayload
439
+ }
440
+ });
441
+ }
442
+ /**
443
+ * Copy an existing thread
444
+ * @param threadId ID of the thread to be copied
445
+ * @returns Newly copied thread
446
+ */
447
+ async copy(threadId) {
448
+ return this.fetch(`/threads/${threadId}/copy`, { method: "POST" });
449
+ }
450
+ /**
451
+ * Update a thread.
452
+ *
453
+ * @param threadId ID of the thread.
454
+ * @param payload Payload for updating the thread.
455
+ * @returns The updated thread.
456
+ */
457
+ async update(threadId, payload) {
458
+ const ttlPayload = typeof payload?.ttl === "number" ? {
459
+ ttl: payload.ttl,
460
+ strategy: "delete"
461
+ } : payload?.ttl;
462
+ return this.fetch(`/threads/${threadId}`, {
463
+ method: "PATCH",
464
+ json: {
465
+ metadata: payload?.metadata,
466
+ ttl: ttlPayload
467
+ }
468
+ });
469
+ }
470
+ /**
471
+ * Delete a thread.
472
+ *
473
+ * @param threadId ID of the thread.
474
+ */
475
+ async delete(threadId) {
476
+ return this.fetch(`/threads/${threadId}`, { method: "DELETE" });
477
+ }
478
+ /**
479
+ * List threads
480
+ *
481
+ * @param query Query options
482
+ * @returns List of threads
483
+ */
484
+ async search(query) {
485
+ return this.fetch("/threads/search", {
486
+ method: "POST",
487
+ json: {
488
+ metadata: query?.metadata ?? void 0,
489
+ ids: query?.ids ?? void 0,
490
+ limit: query?.limit ?? 10,
491
+ offset: query?.offset ?? 0,
492
+ status: query?.status,
493
+ sort_by: query?.sortBy,
494
+ sort_order: query?.sortOrder,
495
+ select: query?.select ?? void 0,
496
+ values: query?.values ?? void 0
497
+ }
498
+ });
499
+ }
500
+ /**
501
+ * Count threads matching filters.
502
+ *
503
+ * @param query.metadata Thread metadata to filter on.
504
+ * @param query.values State values to filter on.
505
+ * @param query.status Thread status to filter on.
506
+ * @returns Number of threads matching the criteria.
507
+ */
508
+ async count(query) {
509
+ return this.fetch(`/threads/count`, {
510
+ method: "POST",
511
+ json: {
512
+ metadata: query?.metadata ?? void 0,
513
+ values: query?.values ?? void 0,
514
+ status: query?.status ?? void 0
515
+ }
516
+ });
517
+ }
518
+ /**
519
+ * Get state for a thread.
520
+ *
521
+ * @param threadId ID of the thread.
522
+ * @returns Thread state.
523
+ */
524
+ async getState(threadId, checkpoint, options) {
525
+ if (checkpoint != null) {
526
+ if (typeof checkpoint !== "string") return this.fetch(`/threads/${threadId}/state/checkpoint`, {
527
+ method: "POST",
528
+ json: {
529
+ checkpoint,
530
+ subgraphs: options?.subgraphs
531
+ }
532
+ });
533
+ return this.fetch(`/threads/${threadId}/state/${checkpoint}`, { params: { subgraphs: options?.subgraphs } });
534
+ }
535
+ return this.fetch(`/threads/${threadId}/state`, { params: { subgraphs: options?.subgraphs } });
536
+ }
537
+ /**
538
+ * Add state to a thread.
539
+ *
540
+ * @param threadId The ID of the thread.
541
+ * @returns
542
+ */
543
+ async updateState(threadId, options) {
544
+ return this.fetch(`/threads/${threadId}/state`, {
545
+ method: "POST",
546
+ json: {
547
+ values: options.values,
548
+ checkpoint_id: options.checkpointId,
549
+ checkpoint: options.checkpoint,
550
+ as_node: options?.asNode
551
+ }
552
+ });
553
+ }
554
+ /**
555
+ * Patch the metadata of a thread.
556
+ *
557
+ * @param threadIdOrConfig Thread ID or config to patch the state of.
558
+ * @param metadata Metadata to patch the state with.
559
+ */
560
+ async patchState(threadIdOrConfig, metadata) {
561
+ let threadId;
562
+ if (typeof threadIdOrConfig !== "string") {
563
+ if (typeof threadIdOrConfig.configurable?.thread_id !== "string") throw new Error("Thread ID is required when updating state with a config.");
564
+ threadId = threadIdOrConfig.configurable.thread_id;
565
+ } else threadId = threadIdOrConfig;
566
+ return this.fetch(`/threads/${threadId}/state`, {
567
+ method: "PATCH",
568
+ json: { metadata }
569
+ });
570
+ }
571
+ /**
572
+ * Get all past states for a thread.
573
+ *
574
+ * @param threadId ID of the thread.
575
+ * @param options Additional options.
576
+ * @returns List of thread states.
577
+ */
578
+ async getHistory(threadId, options) {
579
+ return this.fetch(`/threads/${threadId}/history`, {
580
+ method: "POST",
581
+ json: {
582
+ limit: options?.limit ?? 10,
583
+ before: options?.before,
584
+ metadata: options?.metadata,
585
+ checkpoint: options?.checkpoint
586
+ }
587
+ });
588
+ }
589
+ async *joinStream(threadId, options) {
590
+ let [url, init] = this.prepareFetchOptions(`/threads/${threadId}/stream`, {
591
+ method: "GET",
592
+ headers: options?.lastEventId ? { "Last-Event-ID": options.lastEventId } : void 0,
593
+ params: options?.streamMode ? { stream_mode: options.streamMode } : void 0
594
+ });
595
+ if (this.onRequest != null) init = await this.onRequest(url, init);
596
+ const response = await this.asyncCaller.fetch(url, init);
597
+ const stream = (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() })).pipeThrough(BytesLineDecoder()).pipeThrough(SSEDecoder());
598
+ yield* IterableReadableStream.fromReadableStream(stream);
599
+ }
600
+ };
601
+ var RunsClient = class extends BaseClient {
602
+ /**
603
+ * Create a run and stream the results.
604
+ *
605
+ * @param threadId The ID of the thread.
606
+ * @param assistantId Assistant ID to use for this run.
607
+ * @param payload Payload for creating a run.
608
+ */
609
+ async *stream(threadId, assistantId, payload) {
610
+ const json = {
611
+ input: payload?.input,
612
+ command: payload?.command,
613
+ config: payload?.config,
614
+ context: payload?.context,
615
+ metadata: payload?.metadata,
616
+ stream_mode: payload?.streamMode,
617
+ stream_subgraphs: payload?.streamSubgraphs,
618
+ stream_resumable: payload?.streamResumable,
619
+ feedback_keys: payload?.feedbackKeys,
620
+ assistant_id: assistantId,
621
+ interrupt_before: payload?.interruptBefore,
622
+ interrupt_after: payload?.interruptAfter,
623
+ checkpoint: payload?.checkpoint,
624
+ checkpoint_id: payload?.checkpointId,
625
+ webhook: payload?.webhook,
626
+ multitask_strategy: payload?.multitaskStrategy,
627
+ on_completion: payload?.onCompletion,
628
+ on_disconnect: payload?.onDisconnect,
629
+ after_seconds: payload?.afterSeconds,
630
+ if_not_exists: payload?.ifNotExists,
631
+ checkpoint_during: payload?.checkpointDuring,
632
+ durability: payload?.durability
633
+ };
634
+ const endpoint = threadId == null ? `/runs/stream` : `/threads/${threadId}/runs/stream`;
635
+ let [url, init] = this.prepareFetchOptions(endpoint, {
636
+ method: "POST",
637
+ json,
638
+ timeoutMs: null,
639
+ signal: payload?.signal
640
+ });
641
+ if (this.onRequest != null) init = await this.onRequest(url, init);
642
+ const response = await this.asyncCaller.fetch(url, init);
643
+ const runMetadata = getRunMetadataFromResponse(response);
644
+ if (runMetadata) payload?.onRunCreated?.(runMetadata);
645
+ const stream = (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() })).pipeThrough(BytesLineDecoder()).pipeThrough(SSEDecoder());
646
+ yield* IterableReadableStream.fromReadableStream(stream);
647
+ }
648
+ /**
649
+ * Create a run.
650
+ *
651
+ * @param threadId The ID of the thread.
652
+ * @param assistantId Assistant ID to use for this run.
653
+ * @param payload Payload for creating a run.
654
+ * @returns The created run.
655
+ */
656
+ async create(threadId, assistantId, payload) {
657
+ const json = {
658
+ input: payload?.input,
659
+ command: payload?.command,
660
+ config: payload?.config,
661
+ context: payload?.context,
662
+ metadata: payload?.metadata,
663
+ stream_mode: payload?.streamMode,
664
+ stream_subgraphs: payload?.streamSubgraphs,
665
+ stream_resumable: payload?.streamResumable,
666
+ assistant_id: assistantId,
667
+ interrupt_before: payload?.interruptBefore,
668
+ interrupt_after: payload?.interruptAfter,
669
+ webhook: payload?.webhook,
670
+ checkpoint: payload?.checkpoint,
671
+ checkpoint_id: payload?.checkpointId,
672
+ multitask_strategy: payload?.multitaskStrategy,
673
+ after_seconds: payload?.afterSeconds,
674
+ if_not_exists: payload?.ifNotExists,
675
+ checkpoint_during: payload?.checkpointDuring,
676
+ durability: payload?.durability,
677
+ langsmith_tracer: payload?._langsmithTracer ? {
678
+ project_name: payload?._langsmithTracer?.projectName,
679
+ example_id: payload?._langsmithTracer?.exampleId
680
+ } : void 0
681
+ };
682
+ const endpoint = threadId === null ? "/runs" : `/threads/${threadId}/runs`;
683
+ const [run, response] = await this.fetch(endpoint, {
684
+ method: "POST",
685
+ json,
686
+ signal: payload?.signal,
687
+ withResponse: true
688
+ });
689
+ const runMetadata = getRunMetadataFromResponse(response);
690
+ if (runMetadata) payload?.onRunCreated?.(runMetadata);
691
+ return run;
692
+ }
693
+ /**
694
+ * Create a batch of stateless background runs.
695
+ *
696
+ * @param payloads An array of payloads for creating runs.
697
+ * @returns An array of created runs.
698
+ */
699
+ async createBatch(payloads) {
700
+ const filteredPayloads = payloads.map((payload) => ({
701
+ ...payload,
702
+ assistant_id: payload.assistantId
703
+ })).map((payload) => {
704
+ return Object.fromEntries(Object.entries(payload).filter(([_, v]) => v !== void 0));
705
+ });
706
+ return this.fetch("/runs/batch", {
707
+ method: "POST",
708
+ json: filteredPayloads
709
+ });
710
+ }
711
+ /**
712
+ * Create a run and wait for it to complete.
713
+ *
714
+ * @param threadId The ID of the thread.
715
+ * @param assistantId Assistant ID to use for this run.
716
+ * @param payload Payload for creating a run.
717
+ * @returns The last values chunk of the thread.
718
+ */
719
+ async wait(threadId, assistantId, payload) {
720
+ const json = {
721
+ input: payload?.input,
722
+ command: payload?.command,
723
+ config: payload?.config,
724
+ context: payload?.context,
725
+ metadata: payload?.metadata,
726
+ assistant_id: assistantId,
727
+ interrupt_before: payload?.interruptBefore,
728
+ interrupt_after: payload?.interruptAfter,
729
+ checkpoint: payload?.checkpoint,
730
+ checkpoint_id: payload?.checkpointId,
731
+ webhook: payload?.webhook,
732
+ multitask_strategy: payload?.multitaskStrategy,
733
+ on_completion: payload?.onCompletion,
734
+ on_disconnect: payload?.onDisconnect,
735
+ after_seconds: payload?.afterSeconds,
736
+ if_not_exists: payload?.ifNotExists,
737
+ checkpoint_during: payload?.checkpointDuring,
738
+ durability: payload?.durability,
739
+ langsmith_tracer: payload?._langsmithTracer ? {
740
+ project_name: payload?._langsmithTracer?.projectName,
741
+ example_id: payload?._langsmithTracer?.exampleId
742
+ } : void 0
743
+ };
744
+ const endpoint = threadId == null ? `/runs/wait` : `/threads/${threadId}/runs/wait`;
745
+ const [run, response] = await this.fetch(endpoint, {
746
+ method: "POST",
747
+ json,
748
+ timeoutMs: null,
749
+ signal: payload?.signal,
750
+ withResponse: true
751
+ });
752
+ const runMetadata = getRunMetadataFromResponse(response);
753
+ if (runMetadata) payload?.onRunCreated?.(runMetadata);
754
+ const raiseError = payload?.raiseError !== void 0 ? payload.raiseError : true;
755
+ if (raiseError && "__error__" in run && typeof run.__error__ === "object" && run.__error__ && "error" in run.__error__ && "message" in run.__error__) throw new Error(`${run.__error__?.error}: ${run.__error__?.message}`);
756
+ return run;
757
+ }
758
+ /**
759
+ * List all runs for a thread.
760
+ *
761
+ * @param threadId The ID of the thread.
762
+ * @param options Filtering and pagination options.
763
+ * @returns List of runs.
764
+ */
765
+ async list(threadId, options) {
766
+ return this.fetch(`/threads/${threadId}/runs`, { params: {
767
+ limit: options?.limit ?? 10,
768
+ offset: options?.offset ?? 0,
769
+ status: options?.status ?? void 0,
770
+ select: options?.select ?? void 0
771
+ } });
772
+ }
773
+ /**
774
+ * Get a run by ID.
775
+ *
776
+ * @param threadId The ID of the thread.
777
+ * @param runId The ID of the run.
778
+ * @returns The run.
779
+ */
780
+ async get(threadId, runId) {
781
+ return this.fetch(`/threads/${threadId}/runs/${runId}`);
782
+ }
783
+ /**
784
+ * Cancel a run.
785
+ *
786
+ * @param threadId The ID of the thread.
787
+ * @param runId The ID of the run.
788
+ * @param wait Whether to block when canceling
789
+ * @param action Action to take when cancelling the run. Possible values are `interrupt` or `rollback`. Default is `interrupt`.
790
+ * @returns
791
+ */
792
+ async cancel(threadId, runId, wait = false, action = "interrupt") {
793
+ return this.fetch(`/threads/${threadId}/runs/${runId}/cancel`, {
794
+ method: "POST",
795
+ params: {
796
+ wait: wait ? "1" : "0",
797
+ action
798
+ }
799
+ });
800
+ }
801
+ /**
802
+ * Block until a run is done.
803
+ *
804
+ * @param threadId The ID of the thread.
805
+ * @param runId The ID of the run.
806
+ * @returns
807
+ */
808
+ async join(threadId, runId, options) {
809
+ return this.fetch(`/threads/${threadId}/runs/${runId}/join`, {
810
+ timeoutMs: null,
811
+ signal: options?.signal
812
+ });
813
+ }
814
+ /**
815
+ * Stream output from a run in real-time, until the run is done.
816
+ *
817
+ * @param threadId The ID of the thread. Can be set to `null` | `undefined` for stateless runs.
818
+ * @param runId The ID of the run.
819
+ * @param options Additional options for controlling the stream behavior:
820
+ * - signal: An AbortSignal that can be used to cancel the stream request
821
+ * - lastEventId: The ID of the last event received. Can be used to reconnect to a stream without losing events.
822
+ * - cancelOnDisconnect: When true, automatically cancels the run if the client disconnects from the stream
823
+ * - streamMode: Controls what types of events to receive from the stream (can be a single mode or array of modes)
824
+ * Must be a subset of the stream modes passed when creating the run. Background runs default to having the union of all
825
+ * stream modes enabled.
826
+ * @returns An async generator yielding stream parts.
827
+ */
828
+ async *joinStream(threadId, runId, options) {
829
+ const opts = typeof options === "object" && options != null && options instanceof AbortSignal ? { signal: options } : options;
830
+ let [url, init] = this.prepareFetchOptions(threadId != null ? `/threads/${threadId}/runs/${runId}/stream` : `/runs/${runId}/stream`, {
831
+ method: "GET",
832
+ timeoutMs: null,
833
+ signal: opts?.signal,
834
+ headers: opts?.lastEventId ? { "Last-Event-ID": opts.lastEventId } : void 0,
835
+ params: {
836
+ cancel_on_disconnect: opts?.cancelOnDisconnect ? "1" : "0",
837
+ stream_mode: opts?.streamMode
838
+ }
839
+ });
840
+ if (this.onRequest != null) init = await this.onRequest(url, init);
841
+ const response = await this.asyncCaller.fetch(url, init);
842
+ const stream = (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() })).pipeThrough(BytesLineDecoder()).pipeThrough(SSEDecoder());
843
+ yield* IterableReadableStream.fromReadableStream(stream);
844
+ }
845
+ /**
846
+ * Delete a run.
847
+ *
848
+ * @param threadId The ID of the thread.
849
+ * @param runId The ID of the run.
850
+ * @returns
851
+ */
852
+ async delete(threadId, runId) {
853
+ return this.fetch(`/threads/${threadId}/runs/${runId}`, { method: "DELETE" });
854
+ }
855
+ };
856
+ var StoreClient = class extends BaseClient {
857
+ /**
858
+ * Store or update an item.
859
+ *
860
+ * @param namespace A list of strings representing the namespace path.
861
+ * @param key The unique identifier for the item within the namespace.
862
+ * @param value A dictionary containing the item's data.
863
+ * @param options.index Controls search indexing - null (use defaults), false (disable), or list of field paths to index.
864
+ * @param options.ttl Optional time-to-live in minutes for the item, or null for no expiration.
865
+ * @returns Promise<void>
866
+ *
867
+ * @example
868
+ * ```typescript
869
+ * await client.store.putItem(
870
+ * ["documents", "user123"],
871
+ * "item456",
872
+ * { title: "My Document", content: "Hello World" },
873
+ * { ttl: 60 } // expires in 60 minutes
874
+ * );
875
+ * ```
876
+ */
877
+ async putItem(namespace, key, value, options) {
878
+ namespace.forEach((label) => {
879
+ if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
880
+ });
881
+ const payload = {
882
+ namespace,
883
+ key,
884
+ value,
885
+ index: options?.index,
886
+ ttl: options?.ttl
887
+ };
888
+ return this.fetch("/store/items", {
889
+ method: "PUT",
890
+ json: payload
891
+ });
892
+ }
893
+ /**
894
+ * Retrieve a single item.
895
+ *
896
+ * @param namespace A list of strings representing the namespace path.
897
+ * @param key The unique identifier for the item.
898
+ * @param options.refreshTtl Whether to refresh the TTL on this read operation. If null, uses the store's default behavior.
899
+ * @returns Promise<Item>
900
+ *
901
+ * @example
902
+ * ```typescript
903
+ * const item = await client.store.getItem(
904
+ * ["documents", "user123"],
905
+ * "item456",
906
+ * { refreshTtl: true }
907
+ * );
908
+ * console.log(item);
909
+ * // {
910
+ * // namespace: ["documents", "user123"],
911
+ * // key: "item456",
912
+ * // value: { title: "My Document", content: "Hello World" },
913
+ * // createdAt: "2024-07-30T12:00:00Z",
914
+ * // updatedAt: "2024-07-30T12:00:00Z"
915
+ * // }
916
+ * ```
917
+ */
918
+ async getItem(namespace, key, options) {
919
+ namespace.forEach((label) => {
920
+ if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
921
+ });
922
+ const params = {
923
+ namespace: namespace.join("."),
924
+ key
925
+ };
926
+ if (options?.refreshTtl !== void 0) params.refresh_ttl = options.refreshTtl;
927
+ const response = await this.fetch("/store/items", { params });
928
+ return response ? {
929
+ ...response,
930
+ createdAt: response.created_at,
931
+ updatedAt: response.updated_at
932
+ } : null;
933
+ }
934
+ /**
935
+ * Delete an item.
936
+ *
937
+ * @param namespace A list of strings representing the namespace path.
938
+ * @param key The unique identifier for the item.
939
+ * @returns Promise<void>
940
+ */
941
+ async deleteItem(namespace, key) {
942
+ namespace.forEach((label) => {
943
+ if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
944
+ });
945
+ return this.fetch("/store/items", {
946
+ method: "DELETE",
947
+ json: {
948
+ namespace,
949
+ key
950
+ }
951
+ });
952
+ }
953
+ /**
954
+ * Search for items within a namespace prefix.
955
+ *
956
+ * @param namespacePrefix List of strings representing the namespace prefix.
957
+ * @param options.filter Optional dictionary of key-value pairs to filter results.
958
+ * @param options.limit Maximum number of items to return (default is 10).
959
+ * @param options.offset Number of items to skip before returning results (default is 0).
960
+ * @param options.query Optional search query.
961
+ * @param options.refreshTtl Whether to refresh the TTL on items returned by this search. If null, uses the store's default behavior.
962
+ * @returns Promise<SearchItemsResponse>
963
+ *
964
+ * @example
965
+ * ```typescript
966
+ * const results = await client.store.searchItems(
967
+ * ["documents"],
968
+ * {
969
+ * filter: { author: "John Doe" },
970
+ * limit: 5,
971
+ * refreshTtl: true
972
+ * }
973
+ * );
974
+ * console.log(results);
975
+ * // {
976
+ * // items: [
977
+ * // {
978
+ * // namespace: ["documents", "user123"],
979
+ * // key: "item789",
980
+ * // value: { title: "Another Document", author: "John Doe" },
981
+ * // createdAt: "2024-07-30T12:00:00Z",
982
+ * // updatedAt: "2024-07-30T12:00:00Z"
983
+ * // },
984
+ * // // ... additional items ...
985
+ * // ]
986
+ * // }
987
+ * ```
988
+ */
989
+ async searchItems(namespacePrefix, options) {
990
+ const payload = {
991
+ namespace_prefix: namespacePrefix,
992
+ filter: options?.filter,
993
+ limit: options?.limit ?? 10,
994
+ offset: options?.offset ?? 0,
995
+ query: options?.query,
996
+ refresh_ttl: options?.refreshTtl
997
+ };
998
+ const response = await this.fetch("/store/items/search", {
999
+ method: "POST",
1000
+ json: payload
1001
+ });
1002
+ return { items: response.items.map((item) => ({
1003
+ ...item,
1004
+ createdAt: item.created_at,
1005
+ updatedAt: item.updated_at
1006
+ })) };
1007
+ }
1008
+ /**
1009
+ * List namespaces with optional match conditions.
1010
+ *
1011
+ * @param options.prefix Optional list of strings representing the prefix to filter namespaces.
1012
+ * @param options.suffix Optional list of strings representing the suffix to filter namespaces.
1013
+ * @param options.maxDepth Optional integer specifying the maximum depth of namespaces to return.
1014
+ * @param options.limit Maximum number of namespaces to return (default is 100).
1015
+ * @param options.offset Number of namespaces to skip before returning results (default is 0).
1016
+ * @returns Promise<ListNamespaceResponse>
1017
+ */
1018
+ async listNamespaces(options) {
1019
+ const payload = {
1020
+ prefix: options?.prefix,
1021
+ suffix: options?.suffix,
1022
+ max_depth: options?.maxDepth,
1023
+ limit: options?.limit ?? 100,
1024
+ offset: options?.offset ?? 0
1025
+ };
1026
+ return this.fetch("/store/namespaces", {
1027
+ method: "POST",
1028
+ json: payload
1029
+ });
1030
+ }
1031
+ };
1032
+ var UiClient = class UiClient extends BaseClient {
1033
+ static promiseCache = {};
1034
+ static getOrCached(key, fn) {
1035
+ if (UiClient.promiseCache[key] != null) return UiClient.promiseCache[key];
1036
+ const promise = fn();
1037
+ UiClient.promiseCache[key] = promise;
1038
+ return promise;
1039
+ }
1040
+ async getComponent(assistantId, agentName) {
1041
+ return UiClient.getOrCached(`${this.apiUrl}-${assistantId}-${agentName}`, async () => {
1042
+ let [url, init] = this.prepareFetchOptions(`/ui/${assistantId}`, {
1043
+ headers: {
1044
+ Accept: "text/html",
1045
+ "Content-Type": "application/json"
1046
+ },
1047
+ method: "POST",
1048
+ json: { name: agentName }
1049
+ });
1050
+ if (this.onRequest != null) init = await this.onRequest(url, init);
1051
+ const response = await this.asyncCaller.fetch(url, init);
1052
+ return response.text();
1053
+ });
1054
+ }
1055
+ };
1056
+ var Client = class {
1057
+ /**
1058
+ * The client for interacting with assistants.
1059
+ */
1060
+ assistants;
1061
+ /**
1062
+ * The client for interacting with threads.
1063
+ */
1064
+ threads;
1065
+ /**
1066
+ * The client for interacting with runs.
1067
+ */
1068
+ runs;
1069
+ /**
1070
+ * The client for interacting with cron runs.
1071
+ */
1072
+ crons;
1073
+ /**
1074
+ * The client for interacting with the KV store.
1075
+ */
1076
+ store;
1077
+ /**
1078
+ * The client for interacting with the UI.
1079
+ * @internal Used by LoadExternalComponent and the API might change in the future.
1080
+ */
1081
+ "~ui";
1082
+ /**
1083
+ * @internal Used to obtain a stable key representing the client.
1084
+ */
1085
+ "~configHash";
1086
+ constructor(config) {
1087
+ this["~configHash"] = (() => JSON.stringify({
1088
+ apiUrl: config?.apiUrl,
1089
+ apiKey: config?.apiKey,
1090
+ timeoutMs: config?.timeoutMs,
1091
+ defaultHeaders: config?.defaultHeaders,
1092
+ maxConcurrency: config?.callerOptions?.maxConcurrency,
1093
+ maxRetries: config?.callerOptions?.maxRetries,
1094
+ callbacks: {
1095
+ onFailedResponseHook: config?.callerOptions?.onFailedResponseHook != null,
1096
+ onRequest: config?.onRequest != null,
1097
+ fetch: config?.callerOptions?.fetch != null
1098
+ }
1099
+ }))();
1100
+ this.assistants = new AssistantsClient(config);
1101
+ this.threads = new ThreadsClient(config);
1102
+ this.runs = new RunsClient(config);
1103
+ this.crons = new CronsClient(config);
1104
+ this.store = new StoreClient(config);
1105
+ this["~ui"] = new UiClient(config);
1106
+ }
1107
+ };
1292
1108
  /**
1293
- * @internal Used to obtain a stable key representing the client.
1294
- */
1295
- export function getClientConfigHash(client) {
1296
- return client["~configHash"];
1109
+ * @internal Used to obtain a stable key representing the client.
1110
+ */
1111
+ function getClientConfigHash(client) {
1112
+ return client["~configHash"];
1297
1113
  }
1114
+
1115
+ //#endregion
1116
+ export { AssistantsClient, Client, CronsClient, RunsClient, StoreClient, ThreadsClient, getApiKey, getClientConfigHash };
1117
+ //# sourceMappingURL=client.js.map