@langchain/langgraph-sdk 0.1.4 → 0.1.6

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.
@@ -1,463 +1,16 @@
1
- /* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */
2
- "use client";
3
- import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, } from "react";
4
- import { findLast, unique } from "./utils.js";
5
- import { StreamError } from "./errors.js";
6
- import { getBranchContext } from "./branching.js";
7
- import { StreamManager } from "./manager.js";
8
- import { Client, getClientConfigHash } from "../client.js";
9
- import { MessageTupleManager } from "./messages.js";
10
- function fetchHistory(client, threadId, options) {
11
- if (options?.limit === false) {
12
- return client.threads.getState(threadId).then((state) => {
13
- if (state.checkpoint == null)
14
- return [];
15
- return [state];
16
- });
17
- }
18
- const limit = typeof options?.limit === "number" ? options.limit : 10;
19
- return client.threads.getHistory(threadId, { limit });
20
- }
21
- function useThreadHistory(threadId, client, limit, clearCallbackRef, submittingRef, onErrorRef) {
22
- const [history, setHistory] = useState(undefined);
23
- const [isLoading, setIsLoading] = useState(() => {
24
- if (threadId == null)
25
- return false;
26
- return true;
27
- });
28
- const [error, setError] = useState(undefined);
29
- const clientHash = getClientConfigHash(client);
30
- const clientRef = useRef(client);
31
- clientRef.current = client;
32
- const fetcher = useCallback((threadId) => {
33
- if (threadId != null) {
34
- const client = clientRef.current;
35
- setIsLoading(true);
36
- return fetchHistory(client, threadId, {
37
- limit,
38
- })
39
- .then((history) => {
40
- setHistory(history);
41
- return history;
42
- }, (error) => {
43
- setError(error);
44
- onErrorRef.current?.(error);
45
- return Promise.reject(error);
46
- })
47
- .finally(() => {
48
- setIsLoading(false);
49
- });
50
- }
51
- setHistory(undefined);
52
- setError(undefined);
53
- setIsLoading(false);
54
- clearCallbackRef.current?.();
55
- return Promise.resolve([]);
56
- }, [clearCallbackRef, onErrorRef, limit]);
57
- useEffect(() => {
58
- if (submittingRef.current)
59
- return;
60
- void fetcher(threadId);
61
- }, [fetcher, submittingRef, clientHash, limit, threadId]);
62
- return {
63
- data: history,
64
- isLoading,
65
- error,
66
- mutate: (mutateId) => fetcher(mutateId ?? threadId),
67
- };
1
+ import { useState } from "react";
2
+ import { useStreamLGP } from "./stream.lgp.js";
3
+ import { useStreamCustom } from "./stream.custom.js";
4
+ function isCustomOptions(options) {
5
+ return "transport" in options;
68
6
  }
69
- const useControllableThreadId = (options) => {
70
- const [localThreadId, _setLocalThreadId] = useState(options?.threadId ?? null);
71
- const onThreadIdRef = useRef(options?.onThreadId);
72
- onThreadIdRef.current = options?.onThreadId;
73
- const onThreadId = useCallback((threadId) => {
74
- _setLocalThreadId(threadId);
75
- onThreadIdRef.current?.(threadId);
76
- }, []);
77
- if (!options || !("threadId" in options)) {
78
- return [localThreadId, onThreadId];
79
- }
80
- return [options.threadId ?? null, onThreadId];
81
- };
82
7
  export function useStream(options) {
83
- const reconnectOnMountRef = useRef(options.reconnectOnMount);
84
- const runMetadataStorage = useMemo(() => {
85
- if (typeof window === "undefined")
86
- return null;
87
- const storage = reconnectOnMountRef.current;
88
- if (storage === true)
89
- return window.sessionStorage;
90
- if (typeof storage === "function")
91
- return storage();
92
- return null;
93
- }, []);
94
- const client = useMemo(() => options.client ??
95
- new Client({
96
- apiUrl: options.apiUrl,
97
- apiKey: options.apiKey,
98
- callerOptions: options.callerOptions,
99
- defaultHeaders: options.defaultHeaders,
100
- }), [
101
- options.client,
102
- options.apiKey,
103
- options.apiUrl,
104
- options.callerOptions,
105
- options.defaultHeaders,
106
- ]);
107
- const [messageManager] = useState(() => new MessageTupleManager());
108
- const [stream] = useState(() => new StreamManager(messageManager));
109
- useSyncExternalStore(stream.subscribe, stream.getSnapshot, stream.getSnapshot);
110
- const [threadId, onThreadId] = useControllableThreadId(options);
111
- const trackStreamModeRef = useRef([]);
112
- const trackStreamMode = useCallback((...mode) => {
113
- const ref = trackStreamModeRef.current;
114
- for (const m of mode) {
115
- if (!ref.includes(m))
116
- ref.push(m);
117
- }
118
- }, []);
119
- const hasUpdateListener = options.onUpdateEvent != null;
120
- const hasCustomListener = options.onCustomEvent != null;
121
- const hasLangChainListener = options.onLangChainEvent != null;
122
- const hasDebugListener = options.onDebugEvent != null;
123
- const hasCheckpointListener = options.onCheckpointEvent != null;
124
- const hasTaskListener = options.onTaskEvent != null;
125
- const callbackStreamMode = useMemo(() => {
126
- const modes = [];
127
- if (hasUpdateListener)
128
- modes.push("updates");
129
- if (hasCustomListener)
130
- modes.push("custom");
131
- if (hasLangChainListener)
132
- modes.push("events");
133
- if (hasDebugListener)
134
- modes.push("debug");
135
- if (hasCheckpointListener)
136
- modes.push("checkpoints");
137
- if (hasTaskListener)
138
- modes.push("tasks");
139
- return modes;
140
- }, [
141
- hasUpdateListener,
142
- hasCustomListener,
143
- hasLangChainListener,
144
- hasDebugListener,
145
- hasCheckpointListener,
146
- hasTaskListener,
147
- ]);
148
- const clearCallbackRef = useRef(null);
149
- clearCallbackRef.current = stream.clear;
150
- const submittingRef = useRef(false);
151
- submittingRef.current = stream.isLoading;
152
- const onErrorRef = useRef(undefined);
153
- onErrorRef.current = options.onError;
154
- const historyLimit = typeof options.fetchStateHistory === "object" &&
155
- options.fetchStateHistory != null
156
- ? options.fetchStateHistory.limit ?? false
157
- : options.fetchStateHistory ?? false;
158
- const history = useThreadHistory(threadId, client, historyLimit, clearCallbackRef, submittingRef, onErrorRef);
159
- const getMessages = (value) => {
160
- const messagesKey = options.messagesKey ?? "messages";
161
- return Array.isArray(value[messagesKey]) ? value[messagesKey] : [];
162
- };
163
- const setMessages = (current, messages) => {
164
- const messagesKey = options.messagesKey ?? "messages";
165
- return { ...current, [messagesKey]: messages };
166
- };
167
- const [branch, setBranch] = useState("");
168
- const branchContext = getBranchContext(branch, history.data);
169
- const historyValues = branchContext.threadHead?.values ??
170
- options.initialValues ??
171
- {};
172
- const historyError = (() => {
173
- const error = branchContext.threadHead?.tasks?.at(-1)?.error;
174
- if (error == null)
175
- return undefined;
176
- try {
177
- const parsed = JSON.parse(error);
178
- if (StreamError.isStructuredError(parsed))
179
- return new StreamError(parsed);
180
- return parsed;
181
- }
182
- catch {
183
- // do nothing
184
- }
185
- return error;
186
- })();
187
- const messageMetadata = (() => {
188
- const alreadyShown = new Set();
189
- return getMessages(historyValues).map((message, idx) => {
190
- const messageId = message.id ?? idx;
191
- // Find the first checkpoint where the message was seen
192
- const firstSeenState = findLast(history.data ?? [], (state) => getMessages(state.values)
193
- .map((m, idx) => m.id ?? idx)
194
- .includes(messageId));
195
- const checkpointId = firstSeenState?.checkpoint?.checkpoint_id;
196
- let branch = checkpointId != null
197
- ? branchContext.branchByCheckpoint[checkpointId]
198
- : undefined;
199
- if (!branch?.branch?.length)
200
- branch = undefined;
201
- // serialize branches
202
- const optionsShown = branch?.branchOptions?.flat(2).join(",");
203
- if (optionsShown) {
204
- if (alreadyShown.has(optionsShown))
205
- branch = undefined;
206
- alreadyShown.add(optionsShown);
207
- }
208
- return {
209
- messageId: messageId.toString(),
210
- firstSeenState,
211
- branch: branch?.branch,
212
- branchOptions: branch?.branchOptions,
213
- };
214
- });
215
- })();
216
- const stop = () => stream.stop(historyValues, { onStop: options.onStop });
217
- // --- TRANSPORT ---
218
- const submit = async (values, submitOptions) => {
219
- // Unbranch things
220
- const checkpointId = submitOptions?.checkpoint?.checkpoint_id;
221
- setBranch(checkpointId != null
222
- ? branchContext.branchByCheckpoint[checkpointId]?.branch ?? ""
223
- : "");
224
- stream.setStreamValues(() => {
225
- if (submitOptions?.optimisticValues != null) {
226
- return {
227
- ...historyValues,
228
- ...(typeof submitOptions.optimisticValues === "function"
229
- ? submitOptions.optimisticValues(historyValues)
230
- : submitOptions.optimisticValues),
231
- };
232
- }
233
- return { ...historyValues };
234
- });
235
- // When `fetchStateHistory` is requested, thus we assume that branching
236
- // is enabled. We then need to include the implicit branch.
237
- const includeImplicitBranch = historyLimit === true || typeof historyLimit === "number";
238
- let callbackMeta;
239
- let rejoinKey;
240
- let usableThreadId = threadId;
241
- await stream.start(async (signal) => {
242
- if (!usableThreadId) {
243
- const thread = await client.threads.create({
244
- threadId: submitOptions?.threadId,
245
- metadata: submitOptions?.metadata,
246
- });
247
- onThreadId(thread.thread_id);
248
- usableThreadId = thread.thread_id;
249
- }
250
- if (!usableThreadId) {
251
- throw new Error("Failed to obtain valid thread ID.");
252
- }
253
- const streamMode = unique([
254
- ...(submitOptions?.streamMode ?? []),
255
- ...trackStreamModeRef.current,
256
- ...callbackStreamMode,
257
- ]);
258
- let checkpoint = submitOptions?.checkpoint ??
259
- (includeImplicitBranch
260
- ? branchContext.threadHead?.checkpoint
261
- : undefined) ??
262
- undefined;
263
- // Avoid specifying a checkpoint if user explicitly set it to null
264
- if (submitOptions?.checkpoint === null)
265
- checkpoint = undefined;
266
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
267
- // @ts-expect-error
268
- if (checkpoint != null)
269
- delete checkpoint.thread_id;
270
- const streamResumable = submitOptions?.streamResumable ?? !!runMetadataStorage;
271
- return client.runs.stream(usableThreadId, options.assistantId, {
272
- input: values,
273
- config: submitOptions?.config,
274
- context: submitOptions?.context,
275
- command: submitOptions?.command,
276
- interruptBefore: submitOptions?.interruptBefore,
277
- interruptAfter: submitOptions?.interruptAfter,
278
- metadata: submitOptions?.metadata,
279
- multitaskStrategy: submitOptions?.multitaskStrategy,
280
- onCompletion: submitOptions?.onCompletion,
281
- onDisconnect: submitOptions?.onDisconnect ??
282
- (streamResumable ? "continue" : "cancel"),
283
- signal,
284
- checkpoint,
285
- streamMode,
286
- streamSubgraphs: submitOptions?.streamSubgraphs,
287
- streamResumable,
288
- durability: submitOptions?.durability,
289
- onRunCreated(params) {
290
- callbackMeta = {
291
- run_id: params.run_id,
292
- thread_id: params.thread_id ?? usableThreadId,
293
- };
294
- if (runMetadataStorage) {
295
- rejoinKey = `lg:stream:${usableThreadId}`;
296
- runMetadataStorage.setItem(rejoinKey, callbackMeta.run_id);
297
- }
298
- options.onCreated?.(callbackMeta);
299
- },
300
- });
301
- }, {
302
- getMessages,
303
- setMessages,
304
- initialValues: historyValues,
305
- callbacks: options,
306
- async onSuccess() {
307
- if (rejoinKey)
308
- runMetadataStorage?.removeItem(rejoinKey);
309
- const shouldRefetch =
310
- // We're expecting the whole thread state in onFinish
311
- options.onFinish != null ||
312
- // We're fetching history, thus we need the latest checkpoint
313
- // to ensure we're not accidentally submitting to a wrong branch
314
- includeImplicitBranch;
315
- if (shouldRefetch) {
316
- const newHistory = await history.mutate(usableThreadId);
317
- const lastHead = newHistory.at(0);
318
- if (lastHead) {
319
- // We now have the latest update from /history
320
- // Thus we can clear the local stream state
321
- options.onFinish?.(lastHead, callbackMeta);
322
- return null;
323
- }
324
- }
325
- return undefined;
326
- },
327
- onError(error) {
328
- options.onError?.(error, callbackMeta);
329
- },
330
- });
331
- };
332
- const joinStream = async (runId, lastEventId, joinOptions) => {
333
- // eslint-disable-next-line no-param-reassign
334
- lastEventId ??= "-1";
335
- if (!threadId)
336
- return;
337
- const callbackMeta = {
338
- thread_id: threadId,
339
- run_id: runId,
340
- };
341
- await stream.start(async (signal) => {
342
- return client.runs.joinStream(threadId, runId, {
343
- signal,
344
- lastEventId,
345
- streamMode: joinOptions?.streamMode,
346
- });
347
- }, {
348
- getMessages,
349
- setMessages,
350
- initialValues: historyValues,
351
- callbacks: options,
352
- async onSuccess() {
353
- runMetadataStorage?.removeItem(`lg:stream:${threadId}`);
354
- const newHistory = await history.mutate(threadId);
355
- const lastHead = newHistory.at(0);
356
- if (lastHead)
357
- options.onFinish?.(lastHead, callbackMeta);
358
- },
359
- onError(error) {
360
- options.onError?.(error, callbackMeta);
361
- },
362
- });
363
- };
364
- const reconnectKey = useMemo(() => {
365
- if (!runMetadataStorage || stream.isLoading)
366
- return undefined;
367
- if (typeof window === "undefined")
368
- return undefined;
369
- const runId = runMetadataStorage?.getItem(`lg:stream:${threadId}`);
370
- if (!runId)
371
- return undefined;
372
- return { runId, threadId };
373
- }, [runMetadataStorage, stream.isLoading, threadId]);
374
- const shouldReconnect = !!runMetadataStorage;
375
- const reconnectRef = useRef({ threadId, shouldReconnect });
376
- const joinStreamRef = useRef(joinStream);
377
- joinStreamRef.current = joinStream;
378
- useEffect(() => {
379
- // reset shouldReconnect when switching threads
380
- if (reconnectRef.current.threadId !== threadId) {
381
- reconnectRef.current = { threadId, shouldReconnect };
382
- }
383
- }, [threadId, shouldReconnect]);
384
- useEffect(() => {
385
- if (reconnectKey && reconnectRef.current.shouldReconnect) {
386
- reconnectRef.current.shouldReconnect = false;
387
- void joinStreamRef.current?.(reconnectKey.runId);
388
- }
389
- }, [reconnectKey]);
390
- // --- END TRANSPORT ---
391
- const error = stream.error ?? historyError ?? history.error;
392
- const values = stream.values ?? historyValues;
393
- return {
394
- get values() {
395
- trackStreamMode("values");
396
- return values;
397
- },
398
- client,
399
- assistantId: options.assistantId,
400
- error,
401
- isLoading: stream.isLoading,
402
- stop,
403
- submit,
404
- joinStream,
405
- branch,
406
- setBranch,
407
- get history() {
408
- if (historyLimit === false) {
409
- throw new Error("`fetchStateHistory` must be set to `true` to use `history`");
410
- }
411
- return branchContext.flatHistory;
412
- },
413
- isThreadLoading: history.isLoading && history.data == null,
414
- get experimental_branchTree() {
415
- if (historyLimit === false) {
416
- throw new Error("`fetchStateHistory` must be set to `true` to use `experimental_branchTree`");
417
- }
418
- return branchContext.branchTree;
419
- },
420
- get interrupt() {
421
- if (values != null &&
422
- "__interrupt__" in values &&
423
- Array.isArray(values.__interrupt__)) {
424
- const valueInterrupts = values.__interrupt__;
425
- if (valueInterrupts.length === 0)
426
- return { when: "breakpoint" };
427
- if (valueInterrupts.length === 1)
428
- return valueInterrupts[0];
429
- // TODO: fix the typing of interrupts if multiple interrupts are returned
430
- return valueInterrupts;
431
- }
432
- // If we're deferring to old interrupt detection logic, don't show the interrupt if the stream is loading
433
- if (stream.isLoading)
434
- return undefined;
435
- const interrupts = branchContext.threadHead?.tasks?.at(-1)?.interrupts;
436
- if (interrupts == null || interrupts.length === 0) {
437
- // check if there's a next task present
438
- const next = branchContext.threadHead?.next ?? [];
439
- if (!next.length || error != null)
440
- return undefined;
441
- return { when: "breakpoint" };
442
- }
443
- // Return only the current interrupt
444
- return interrupts.at(-1);
445
- },
446
- get messages() {
447
- trackStreamMode("messages-tuple", "values");
448
- return getMessages(values);
449
- },
450
- getMessagesMetadata(message, index) {
451
- trackStreamMode("values");
452
- const streamMetadata = messageManager.get(message.id)?.metadata;
453
- const historyMetadata = messageMetadata?.find((m) => m.messageId === (message.id ?? index));
454
- if (streamMetadata != null || historyMetadata != null) {
455
- return {
456
- ...historyMetadata,
457
- streamMetadata,
458
- };
459
- }
460
- return undefined;
461
- },
462
- };
8
+ // Store this in useState to make sure we're not changing the implementation in re-renders
9
+ const [isCustom] = useState(isCustomOptions(options));
10
+ if (isCustom) {
11
+ // eslint-disable-next-line react-hooks/rules-of-hooks
12
+ return useStreamCustom(options);
13
+ }
14
+ // eslint-disable-next-line react-hooks/rules-of-hooks
15
+ return useStreamLGP(options);
463
16
  }