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