@langchain/langgraph-sdk 0.0.1-rc.0 → 0.0.1-rc.10

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.
package/dist/client.d.mts CHANGED
@@ -1,15 +1,17 @@
1
- import { Assistant, AssistantGraph, Config, GraphSchema, Metadata, Run, RunEvent, Thread, ThreadState } from "./schema.js";
1
+ import { Assistant, AssistantGraph, Config, DefaultValues, GraphSchema, Metadata, Run, RunEvent, Thread, ThreadState } from "./schema.js";
2
2
  import { AsyncCaller, AsyncCallerParams } from "./utils/async_caller.mjs";
3
- import { IterableReadableStreamInterface } from "./utils/stream.mjs";
3
+ import { RunsCreatePayload, RunsStreamPayload, RunsWaitPayload } from "./types.mjs";
4
4
  interface ClientConfig {
5
5
  apiUrl?: string;
6
6
  callerOptions?: AsyncCallerParams;
7
7
  timeoutMs?: number;
8
+ defaultHeaders?: Record<string, string | null | undefined>;
8
9
  }
9
10
  declare class BaseClient {
10
11
  protected asyncCaller: AsyncCaller;
11
12
  protected timeoutMs: number;
12
13
  protected apiUrl: string;
14
+ protected defaultHeaders: Record<string, string | null | undefined>;
13
15
  constructor(config?: ClientConfig);
14
16
  protected prepareFetchOptions(path: string, options?: RequestInit & {
15
17
  json?: unknown;
@@ -21,90 +23,245 @@ declare class BaseClient {
21
23
  }): Promise<T>;
22
24
  }
23
25
  declare class AssistantsClient extends BaseClient {
26
+ /**
27
+ * Get an assistant by ID.
28
+ *
29
+ * @param assistantId The ID of the assistant.
30
+ * @returns Assistant
31
+ */
24
32
  get(assistantId: string): Promise<Assistant>;
33
+ /**
34
+ * Get the JSON representation of the graph assigned to a runnable
35
+ * @param assistantId The ID of the assistant.
36
+ * @returns Serialized graph
37
+ */
25
38
  getGraph(assistantId: string): Promise<AssistantGraph>;
39
+ /**
40
+ * Get the state and config schema of the graph assigned to a runnable
41
+ * @param assistantId The ID of the assistant.
42
+ * @returns Graph schema
43
+ */
26
44
  getSchemas(assistantId: string): Promise<GraphSchema>;
45
+ /**
46
+ * Create a new assistant.
47
+ * @param payload Payload for creating an assistant.
48
+ * @returns The created assistant.
49
+ */
27
50
  create(payload: {
28
- graphId?: string;
51
+ graphId: string;
29
52
  config?: Config;
30
53
  metadata?: Metadata;
31
54
  }): Promise<Assistant>;
32
- upsert(assistantId: string, payload: {
33
- graphId?: string;
55
+ /**
56
+ * Update an assistant.
57
+ * @param assistantId ID of the assistant.
58
+ * @param payload Payload for updating the assistant.
59
+ * @returns The updated assistant.
60
+ */
61
+ update(assistantId: string, payload: {
62
+ graphId: string;
34
63
  config?: Config;
35
64
  metadata?: Metadata;
36
65
  }): Promise<Assistant>;
37
- search(query: {
66
+ /**
67
+ * List assistants.
68
+ * @param query Query options.
69
+ * @returns List of assistants.
70
+ */
71
+ search(query?: {
38
72
  metadata?: Metadata;
39
73
  limit?: number;
40
74
  offset?: number;
41
75
  }): Promise<Assistant[]>;
42
76
  }
43
77
  declare class ThreadsClient extends BaseClient {
78
+ /**
79
+ * Get a thread by ID.
80
+ *
81
+ * @param threadId ID of the thread.
82
+ * @returns The thread.
83
+ */
44
84
  get(threadId: string): Promise<Thread>;
45
- create(payload: {
85
+ /**
86
+ * Create a new thread.
87
+ *
88
+ * @param payload Payload for creating a thread.
89
+ * @returns The created thread.
90
+ */
91
+ create(payload?: {
92
+ /**
93
+ * Metadata for the thread.
94
+ */
46
95
  metadata?: Metadata;
47
96
  }): Promise<Thread>;
48
- upsert(threadId: string, payload: {
97
+ /**
98
+ * Update a thread.
99
+ *
100
+ * @param threadId ID of the thread.
101
+ * @param payload Payload for updating the thread.
102
+ * @returns The updated thread.
103
+ */
104
+ update(threadId: string, payload?: {
105
+ /**
106
+ * Metadata for the thread.
107
+ */
49
108
  metadata?: Metadata;
50
109
  }): Promise<Thread>;
110
+ /**
111
+ * Delete a thread.
112
+ *
113
+ * @param threadId ID of the thread.
114
+ */
51
115
  delete(threadId: string): Promise<void>;
52
- search(query: {
116
+ /**
117
+ * List threads
118
+ *
119
+ * @param query Query options
120
+ * @returns List of threads
121
+ */
122
+ search(query?: {
123
+ /**
124
+ * Metadata to filter threads by.
125
+ */
53
126
  metadata?: Metadata;
127
+ /**
128
+ * Maximum number of threads to return.
129
+ * Defaults to 10
130
+ */
54
131
  limit?: number;
132
+ /**
133
+ * Offset to start from.
134
+ */
55
135
  offset?: number;
56
136
  }): Promise<Thread[]>;
57
- getState(threadId: string): Promise<ThreadState>;
58
- updateState(threadIdOrConfig: string | Config, values: Record<string, unknown>, options?: {
137
+ /**
138
+ * Get state for a thread.
139
+ *
140
+ * @param threadId ID of the thread.
141
+ * @returns Thread state.
142
+ */
143
+ getState<ValuesType = DefaultValues>(threadId: string, checkpointId?: string): Promise<ThreadState<ValuesType>>;
144
+ /**
145
+ * Add state to a thread.
146
+ *
147
+ * @param threadId The ID of the thread.
148
+ * @returns
149
+ */
150
+ updateState<ValuesType = DefaultValues>(threadId: string, options: {
151
+ values: ValuesType;
152
+ checkpointId?: string;
59
153
  asNode?: string;
60
154
  }): Promise<void>;
61
- patchState(threadIdOrConfig: string | Config, metadata: Record<string, unknown>): Promise<void>;
62
- getHistory(threadId: string, options?: {
155
+ /**
156
+ * Patch the metadata of a thread.
157
+ *
158
+ * @param threadIdOrConfig Thread ID or config to patch the state of.
159
+ * @param metadata Metadata to patch the state with.
160
+ */
161
+ patchState(threadIdOrConfig: string | Config, metadata: Metadata): Promise<void>;
162
+ /**
163
+ * Get all past states for a thread.
164
+ *
165
+ * @param threadId ID of the thread.
166
+ * @param options Additional options.
167
+ * @returns List of thread states.
168
+ */
169
+ getHistory<ValuesType = DefaultValues>(threadId: string, options?: {
63
170
  limit?: number;
64
171
  before?: Config;
65
- }): Promise<ThreadState[]>;
172
+ metadata?: Metadata;
173
+ }): Promise<ThreadState<ValuesType>[]>;
66
174
  }
67
175
  declare class RunsClient extends BaseClient {
68
- stream(threadId: string, assistantId: string, options?: {
69
- input?: Record<string, unknown>;
70
- streamMode?: "values" | "messages" | "updates" | "events" | "debug";
71
- metadata?: Metadata;
72
- config?: Config;
73
- interruptBefore?: string[];
74
- interruptAfter?: string[];
75
- }): Promise<IterableReadableStreamInterface<{
76
- event: string;
77
- data: unknown;
78
- }>>;
79
- create(threadId: string, assistantId: string, options?: {
80
- input?: Record<string, unknown>;
81
- metadata?: Metadata;
82
- config?: Config;
83
- interruptBefore?: string[];
84
- interruptAfter?: string[];
85
- webhook?: string;
86
- }): Promise<Run>;
87
- wait(threadId: string, assistantId: string, options?: {
88
- input?: Record<string, unknown>;
89
- streamMode?: "values" | "messages" | "updates" | "events" | "debug";
90
- metadata?: Metadata;
91
- config?: Config;
92
- interruptBefore?: string[];
93
- interruptAfter?: string[];
94
- }): Promise<ThreadState["values"]>;
176
+ /**
177
+ * Create a run and stream the results.
178
+ *
179
+ * @param threadId The ID of the thread.
180
+ * @param assistantId Assistant ID to use for this run.
181
+ * @param payload Payload for creating a run.
182
+ */
183
+ stream(threadId: string, assistantId: string, payload?: RunsStreamPayload): AsyncGenerator<{
184
+ event: "events" | "metadata" | "debug" | "updates" | "values" | "messages/partial" | "messages/metadata" | "messages/complete" | (string & {});
185
+ data: any;
186
+ }>;
187
+ /**
188
+ * Create a run.
189
+ *
190
+ * @param threadId The ID of the thread.
191
+ * @param assistantId Assistant ID to use for this run.
192
+ * @param payload Payload for creating a run.
193
+ * @returns The created run.
194
+ */
195
+ create(threadId: string, assistantId: string, payload?: RunsCreatePayload): Promise<Run>;
196
+ /**
197
+ * Create a run and wait for it to complete.
198
+ *
199
+ * @param threadId The ID of the thread.
200
+ * @param assistantId Assistant ID to use for this run.
201
+ * @param payload Payload for creating a run.
202
+ * @returns The last values chunk of the thread.
203
+ */
204
+ wait(threadId: string, assistantId: string, payload?: RunsWaitPayload): Promise<ThreadState["values"]>;
205
+ /**
206
+ * List all runs for a thread.
207
+ *
208
+ * @param threadId The ID of the thread.
209
+ * @param options Filtering and pagination options.
210
+ * @returns List of runs.
211
+ */
95
212
  list(threadId: string, options?: {
213
+ /**
214
+ * Maximum number of runs to return.
215
+ * Defaults to 10
216
+ */
96
217
  limit?: number;
218
+ /**
219
+ * Offset to start from.
220
+ * Defaults to 0.
221
+ */
97
222
  offset?: number;
98
223
  }): Promise<Run[]>;
224
+ /**
225
+ * Get a run by ID.
226
+ *
227
+ * @param threadId The ID of the thread.
228
+ * @param runId The ID of the run.
229
+ * @returns The run.
230
+ */
99
231
  get(threadId: string, runId: string): Promise<Run>;
232
+ /**
233
+ * List all events for a run.
234
+ *
235
+ * @param threadId The ID of the thread.
236
+ * @param runId The ID of the run.
237
+ * @param options Filtering and pagination options.
238
+ * @returns List of events.
239
+ */
100
240
  listEvents(threadId: string, runId: string, options?: {
241
+ /**
242
+ * Maximum number of events to return.
243
+ * Defaults to 10
244
+ */
101
245
  limit?: number;
246
+ /**
247
+ * Offset to start from.
248
+ * Defaults to 0.
249
+ */
102
250
  offset?: number;
103
251
  }): Promise<RunEvent[]>;
104
252
  }
105
253
  export declare class Client {
254
+ /**
255
+ * The client for interacting with assistants.
256
+ */
106
257
  assistants: AssistantsClient;
258
+ /**
259
+ * The client for interacting with threads.
260
+ */
107
261
  threads: ThreadsClient;
262
+ /**
263
+ * The client for interacting with runs.
264
+ */
108
265
  runs: RunsClient;
109
266
  constructor(config?: ClientConfig);
110
267
  }
package/dist/client.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AsyncCaller } from "./utils/async_caller.mjs";
2
2
  import { createParser } from "eventsource-parser";
3
- import { IterableReadableStream, } from "./utils/stream.mjs";
3
+ import { IterableReadableStream } from "./utils/stream.mjs";
4
4
  class BaseClient {
5
5
  constructor(config) {
6
6
  Object.defineProperty(this, "asyncCaller", {
@@ -21,16 +21,26 @@ class BaseClient {
21
21
  writable: true,
22
22
  value: void 0
23
23
  });
24
+ Object.defineProperty(this, "defaultHeaders", {
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true,
28
+ value: void 0
29
+ });
24
30
  this.asyncCaller = new AsyncCaller({
25
- maxRetries: 5,
26
- maxConcurrency: 5,
31
+ maxRetries: 4,
32
+ maxConcurrency: 4,
27
33
  ...config?.callerOptions,
28
34
  });
29
35
  this.timeoutMs = config?.timeoutMs || 12_000;
30
36
  this.apiUrl = config?.apiUrl || "http://localhost:8123";
37
+ this.defaultHeaders = config?.defaultHeaders || {};
31
38
  }
32
39
  prepareFetchOptions(path, options) {
33
- const mutatedOptions = { ...options };
40
+ const mutatedOptions = {
41
+ ...options,
42
+ headers: { ...this.defaultHeaders, ...options?.headers },
43
+ };
34
44
  if (mutatedOptions.json) {
35
45
  mutatedOptions.body = JSON.stringify(mutatedOptions.json);
36
46
  mutatedOptions.headers = {
@@ -59,29 +69,55 @@ class BaseClient {
59
69
  }
60
70
  }
61
71
  class AssistantsClient extends BaseClient {
72
+ /**
73
+ * Get an assistant by ID.
74
+ *
75
+ * @param assistantId The ID of the assistant.
76
+ * @returns Assistant
77
+ */
62
78
  async get(assistantId) {
63
79
  return this.fetch(`/assistants/${assistantId}`);
64
80
  }
81
+ /**
82
+ * Get the JSON representation of the graph assigned to a runnable
83
+ * @param assistantId The ID of the assistant.
84
+ * @returns Serialized graph
85
+ */
65
86
  async getGraph(assistantId) {
66
87
  return this.fetch(`/assistants/${assistantId}/graph`);
67
88
  }
89
+ /**
90
+ * Get the state and config schema of the graph assigned to a runnable
91
+ * @param assistantId The ID of the assistant.
92
+ * @returns Graph schema
93
+ */
68
94
  async getSchemas(assistantId) {
69
95
  return this.fetch(`/assistants/${assistantId}/schemas`);
70
96
  }
97
+ /**
98
+ * Create a new assistant.
99
+ * @param payload Payload for creating an assistant.
100
+ * @returns The created assistant.
101
+ */
71
102
  async create(payload) {
72
103
  return this.fetch("/assistants", {
73
104
  method: "POST",
74
- body: JSON.stringify({
105
+ json: {
75
106
  graph_id: payload.graphId,
76
107
  config: payload.config,
77
108
  metadata: payload.metadata,
78
- }),
79
- headers: { "Content-Type": "application/json" },
109
+ },
80
110
  });
81
111
  }
82
- async upsert(assistantId, payload) {
112
+ /**
113
+ * Update an assistant.
114
+ * @param assistantId ID of the assistant.
115
+ * @param payload Payload for updating the assistant.
116
+ * @returns The updated assistant.
117
+ */
118
+ async update(assistantId, payload) {
83
119
  return this.fetch(`/assistants/${assistantId}`, {
84
- method: "PUT",
120
+ method: "PATCH",
85
121
  json: {
86
122
  graph_id: payload.graphId,
87
123
  config: payload.config,
@@ -89,70 +125,116 @@ class AssistantsClient extends BaseClient {
89
125
  },
90
126
  });
91
127
  }
128
+ /**
129
+ * List assistants.
130
+ * @param query Query options.
131
+ * @returns List of assistants.
132
+ */
92
133
  async search(query) {
93
134
  return this.fetch("/assistants/search", {
94
135
  method: "POST",
95
136
  json: {
96
- metadata: query.metadata ?? undefined,
97
- limit: query.limit ?? 10,
98
- offset: query.offset ?? 0,
137
+ metadata: query?.metadata ?? undefined,
138
+ limit: query?.limit ?? 10,
139
+ offset: query?.offset ?? 0,
99
140
  },
100
141
  });
101
142
  }
102
143
  }
103
144
  class ThreadsClient extends BaseClient {
145
+ /**
146
+ * Get a thread by ID.
147
+ *
148
+ * @param threadId ID of the thread.
149
+ * @returns The thread.
150
+ */
104
151
  async get(threadId) {
105
152
  return this.fetch(`/threads/${threadId}`);
106
153
  }
154
+ /**
155
+ * Create a new thread.
156
+ *
157
+ * @param payload Payload for creating a thread.
158
+ * @returns The created thread.
159
+ */
107
160
  async create(payload) {
108
161
  return this.fetch(`/threads`, {
109
162
  method: "POST",
110
- json: { metadata: payload },
163
+ json: { metadata: payload?.metadata },
111
164
  });
112
165
  }
113
- async upsert(threadId, payload) {
166
+ /**
167
+ * Update a thread.
168
+ *
169
+ * @param threadId ID of the thread.
170
+ * @param payload Payload for updating the thread.
171
+ * @returns The updated thread.
172
+ */
173
+ async update(threadId, payload) {
114
174
  return this.fetch(`/threads/${threadId}`, {
115
- method: "PUT",
116
- json: { metadata: payload },
175
+ method: "PATCH",
176
+ json: { metadata: payload?.metadata },
117
177
  });
118
178
  }
179
+ /**
180
+ * Delete a thread.
181
+ *
182
+ * @param threadId ID of the thread.
183
+ */
119
184
  async delete(threadId) {
120
185
  return this.fetch(`/threads/${threadId}`, {
121
186
  method: "DELETE",
122
187
  });
123
188
  }
189
+ /**
190
+ * List threads
191
+ *
192
+ * @param query Query options
193
+ * @returns List of threads
194
+ */
124
195
  async search(query) {
125
196
  return this.fetch("/threads/search", {
126
197
  method: "POST",
127
198
  json: {
128
- metadata: query.metadata ?? undefined,
129
- limit: query.limit ?? 10,
130
- offset: query.offset ?? 0,
199
+ metadata: query?.metadata ?? undefined,
200
+ limit: query?.limit ?? 10,
201
+ offset: query?.offset ?? 0,
131
202
  },
132
203
  });
133
204
  }
134
- async getState(threadId) {
135
- return this.fetch(`/threads/${threadId}/state`);
205
+ /**
206
+ * Get state for a thread.
207
+ *
208
+ * @param threadId ID of the thread.
209
+ * @returns Thread state.
210
+ */
211
+ async getState(threadId, checkpointId) {
212
+ return this.fetch(checkpointId != null
213
+ ? `/threads/${threadId}/state/${checkpointId}`
214
+ : `/threads/${threadId}/state`);
136
215
  }
137
- async updateState(threadIdOrConfig, values, options) {
138
- let config = undefined;
139
- let threadId;
140
- if (typeof threadIdOrConfig !== "string") {
141
- config = threadIdOrConfig;
142
- if (typeof config.configurable.thread_id !== "string") {
143
- throw new Error("Thread ID is required when updating state with a config.");
144
- }
145
- threadId = config.configurable.thread_id;
146
- }
147
- else {
148
- config = undefined;
149
- threadId = threadIdOrConfig;
150
- }
216
+ /**
217
+ * Add state to a thread.
218
+ *
219
+ * @param threadId The ID of the thread.
220
+ * @returns
221
+ */
222
+ async updateState(threadId, options) {
151
223
  return this.fetch(`/threads/${threadId}/state`, {
152
224
  method: "POST",
153
- json: { values, config, as_node: options?.asNode },
225
+ json: {
226
+ values: options.values,
227
+ checkpoint_id: options.checkpointId,
228
+ as_node: options?.asNode,
229
+ },
154
230
  });
155
231
  }
232
+ /**
233
+ * Patch the metadata of a thread.
234
+ *
235
+ * @param threadIdOrConfig Thread ID or config to patch the state of.
236
+ * @param metadata Metadata to patch the state with.
237
+ */
156
238
  async patchState(threadIdOrConfig, metadata) {
157
239
  let threadId;
158
240
  if (typeof threadIdOrConfig !== "string") {
@@ -169,41 +251,60 @@ class ThreadsClient extends BaseClient {
169
251
  json: { metadata: metadata },
170
252
  });
171
253
  }
254
+ /**
255
+ * Get all past states for a thread.
256
+ *
257
+ * @param threadId ID of the thread.
258
+ * @param options Additional options.
259
+ * @returns List of thread states.
260
+ */
172
261
  async getHistory(threadId, options) {
173
262
  return this.fetch(`/threads/${threadId}/history`, {
174
- params: {
263
+ method: "POST",
264
+ json: {
175
265
  limit: options?.limit ?? 10,
176
266
  before: options?.before,
267
+ metadata: options?.metadata,
177
268
  },
178
269
  });
179
270
  }
180
271
  }
181
272
  class RunsClient extends BaseClient {
182
- async stream(threadId, assistantId, options) {
273
+ /**
274
+ * Create a run and stream the results.
275
+ *
276
+ * @param threadId The ID of the thread.
277
+ * @param assistantId Assistant ID to use for this run.
278
+ * @param payload Payload for creating a run.
279
+ */
280
+ async *stream(threadId, assistantId, payload) {
183
281
  const response = await this.asyncCaller.fetch(...this.prepareFetchOptions(`/threads/${threadId}/runs/stream`, {
184
282
  method: "POST",
185
283
  json: {
186
- input: options?.input,
187
- config: options?.config,
188
- metadata: options?.metadata,
189
- stream_mode: options?.streamMode,
284
+ input: payload?.input,
285
+ config: payload?.config,
286
+ metadata: payload?.metadata,
287
+ stream_mode: payload?.streamMode,
288
+ feedback_keys: payload?.feedbackKeys,
190
289
  assistant_id: assistantId,
191
- interrupt_before: options?.interruptBefore,
192
- interrupt_after: options?.interruptAfter,
290
+ interrupt_before: payload?.interruptBefore,
291
+ interrupt_after: payload?.interruptAfter,
193
292
  },
293
+ signal: payload?.signal,
194
294
  }));
195
295
  let parser;
196
296
  const textDecoder = new TextDecoder();
197
297
  const stream = (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() })).pipeThrough(new TransformStream({
198
298
  async start(ctrl) {
199
299
  parser = createParser((event) => {
200
- if (event.type === "event" && event.data === "[DONE]") {
300
+ if ((payload?.signal && payload.signal.aborted) ||
301
+ (event.type === "event" && event.data === "[DONE]")) {
201
302
  ctrl.terminate();
202
303
  return;
203
304
  }
204
305
  if ("data" in event) {
205
306
  ctrl.enqueue({
206
- event: event.event ?? "event",
307
+ event: event.event ?? "message",
207
308
  data: JSON.parse(event.data),
208
309
  });
209
310
  }
@@ -213,35 +314,60 @@ class RunsClient extends BaseClient {
213
314
  parser.feed(textDecoder.decode(chunk));
214
315
  },
215
316
  }));
216
- return IterableReadableStream.fromReadableStream(stream);
317
+ yield* IterableReadableStream.fromReadableStream(stream);
217
318
  }
218
- async create(threadId, assistantId, options) {
319
+ /**
320
+ * Create a run.
321
+ *
322
+ * @param threadId The ID of the thread.
323
+ * @param assistantId Assistant ID to use for this run.
324
+ * @param payload Payload for creating a run.
325
+ * @returns The created run.
326
+ */
327
+ async create(threadId, assistantId, payload) {
219
328
  return this.fetch(`/threads/${threadId}/runs`, {
220
329
  method: "POST",
221
330
  json: {
222
- input: options?.input,
223
- config: options?.config,
224
- metadata: options?.metadata,
331
+ input: payload?.input,
332
+ config: payload?.config,
333
+ metadata: payload?.metadata,
225
334
  assistant_id: assistantId,
226
- interrupt_before: options?.interruptBefore,
227
- interrupt_after: options?.interruptAfter,
228
- webhook: options?.webhook,
335
+ interrupt_before: payload?.interruptBefore,
336
+ interrupt_after: payload?.interruptAfter,
337
+ webhook: payload?.webhook,
229
338
  },
339
+ signal: payload?.signal,
230
340
  });
231
341
  }
232
- async wait(threadId, assistantId, options) {
342
+ /**
343
+ * Create a run and wait for it to complete.
344
+ *
345
+ * @param threadId The ID of the thread.
346
+ * @param assistantId Assistant ID to use for this run.
347
+ * @param payload Payload for creating a run.
348
+ * @returns The last values chunk of the thread.
349
+ */
350
+ async wait(threadId, assistantId, payload) {
233
351
  return this.fetch(`/threads/${threadId}/runs/wait`, {
234
352
  method: "POST",
235
353
  json: {
236
- input: options?.input,
237
- config: options?.config,
238
- metadata: options?.metadata,
354
+ input: payload?.input,
355
+ config: payload?.config,
356
+ metadata: payload?.metadata,
239
357
  assistant_id: assistantId,
240
- interrupt_before: options?.interruptBefore,
241
- interrupt_after: options?.interruptAfter,
358
+ interrupt_before: payload?.interruptBefore,
359
+ interrupt_after: payload?.interruptAfter,
242
360
  },
361
+ signal: payload?.signal,
243
362
  });
244
363
  }
364
+ /**
365
+ * List all runs for a thread.
366
+ *
367
+ * @param threadId The ID of the thread.
368
+ * @param options Filtering and pagination options.
369
+ * @returns List of runs.
370
+ */
245
371
  async list(threadId, options) {
246
372
  return this.fetch(`/threads/${threadId}/runs`, {
247
373
  params: {
@@ -250,9 +376,24 @@ class RunsClient extends BaseClient {
250
376
  },
251
377
  });
252
378
  }
379
+ /**
380
+ * Get a run by ID.
381
+ *
382
+ * @param threadId The ID of the thread.
383
+ * @param runId The ID of the run.
384
+ * @returns The run.
385
+ */
253
386
  async get(threadId, runId) {
254
387
  return this.fetch(`/threads/${threadId}/runs/${runId}`);
255
388
  }
389
+ /**
390
+ * List all events for a run.
391
+ *
392
+ * @param threadId The ID of the thread.
393
+ * @param runId The ID of the run.
394
+ * @param options Filtering and pagination options.
395
+ * @returns List of events.
396
+ */
256
397
  async listEvents(threadId, runId, options) {
257
398
  return this.fetch(`/threads/${threadId}/runs/${runId}/events`, {
258
399
  params: {
@@ -264,18 +405,27 @@ class RunsClient extends BaseClient {
264
405
  }
265
406
  export class Client {
266
407
  constructor(config) {
408
+ /**
409
+ * The client for interacting with assistants.
410
+ */
267
411
  Object.defineProperty(this, "assistants", {
268
412
  enumerable: true,
269
413
  configurable: true,
270
414
  writable: true,
271
415
  value: void 0
272
416
  });
417
+ /**
418
+ * The client for interacting with threads.
419
+ */
273
420
  Object.defineProperty(this, "threads", {
274
421
  enumerable: true,
275
422
  configurable: true,
276
423
  writable: true,
277
424
  value: void 0
278
425
  });
426
+ /**
427
+ * The client for interacting with runs.
428
+ */
279
429
  Object.defineProperty(this, "runs", {
280
430
  enumerable: true,
281
431
  configurable: true,
package/dist/index.d.mts CHANGED
@@ -1 +1,2 @@
1
1
  export { Client } from "./client.mjs";
2
+ export type { Assistant, AssistantGraph, Config, DefaultValues, GraphSchema, Metadata, Run, RunEvent, Thread, ThreadState, } from "./schema.js";
package/dist/schema.d.ts CHANGED
@@ -1,24 +1,44 @@
1
+ import type { JSONSchema7 } from "json-schema";
1
2
  type Optional<T> = T | null | undefined;
2
3
  export interface Config {
3
4
  /**
4
5
  * Tags for this call and any sub-calls (eg. a Chain calling an LLM).
5
6
  * You can use these to filter calls.
6
7
  */
7
- tags: string[];
8
+ tags?: string[];
8
9
  /**
9
10
  * Maximum number of times a call can recurse.
10
11
  * If not provided, defaults to 25.
11
12
  */
12
- recursion_limit: number;
13
+ recursion_limit?: number;
13
14
  /**
14
15
  * Runtime values for attributes previously made configurable on this Runnable.
15
16
  */
16
- configurable: Record<string, unknown>;
17
+ configurable: {
18
+ /**
19
+ * ID of the thread
20
+ */
21
+ thread_id?: string;
22
+ /**
23
+ * Timestamp of the state checkpoint
24
+ */
25
+ thread_ts?: string;
26
+ [key: string]: unknown;
27
+ };
17
28
  }
18
29
  export interface GraphSchema {
30
+ /**
31
+ * The ID of the graph.
32
+ */
19
33
  graph_id: string;
20
- state_schema: Record<string, unknown>;
21
- config_schema: Record<string, unknown>;
34
+ /**
35
+ * The schema for the graph state
36
+ */
37
+ state_schema: JSONSchema7;
38
+ /**
39
+ * The schema for the graph config
40
+ */
41
+ config_schema: JSONSchema7;
22
42
  }
23
43
  export type Metadata = Optional<Record<string, unknown>>;
24
44
  export interface Assistant {
@@ -36,13 +56,14 @@ export interface Thread {
36
56
  updated_at: string;
37
57
  metadata: Metadata;
38
58
  }
39
- export interface ThreadState {
40
- values: Record<string, unknown>[] | Record<string, unknown>;
59
+ export type DefaultValues = Record<string, unknown>[] | Record<string, unknown>;
60
+ export interface ThreadState<ValuesType = DefaultValues> {
61
+ values: ValuesType;
41
62
  next: string[];
42
- config: Config;
63
+ checkpoint_id: string;
43
64
  metadata: Metadata;
44
65
  created_at: Optional<string>;
45
- parent_config: Optional<Config>;
66
+ parent_checkpoint_id: Optional<string>;
46
67
  }
47
68
  export interface Run {
48
69
  run_id: string;
@@ -0,0 +1,53 @@
1
+ import { Config, Metadata } from "./schema.js";
2
+ export type StreamMode = "values" | "messages" | "updates" | "events" | "debug";
3
+ interface RunsInvokePayload {
4
+ /**
5
+ * Input to the run. Pass `null` to resume from the current state of the thread.
6
+ */
7
+ input?: Record<string, unknown> | null;
8
+ /**
9
+ * Metadata for the run.
10
+ */
11
+ metadata?: Metadata;
12
+ /**
13
+ * Additional configuration for the run.
14
+ */
15
+ config?: Config;
16
+ /**
17
+ * Interrupt execution before entering these nodes.
18
+ */
19
+ interruptBefore?: string[];
20
+ /**
21
+ * Interrupt execution after leaving these nodes.
22
+ */
23
+ interruptAfter?: string[];
24
+ /**
25
+ * Abort controller signal to cancel the run.
26
+ */
27
+ signal?: AbortController["signal"];
28
+ }
29
+ export interface RunsStreamPayload extends RunsInvokePayload {
30
+ /**
31
+ * One of `"values"`, `"messages"`, `"updates"` or `"events"`.
32
+ * - `"values"`: Stream the thread state any time it changes.
33
+ * - `"messages"`: Stream chat messages from thread state and calls to chat models,
34
+ * token-by-token where possible.
35
+ * - `"updates"`: Stream the state updates returned by each node.
36
+ * - `"events"`: Stream all events produced by the run. You can also access these
37
+ * afterwards using the `client.runs.listEvents()` method.
38
+ */
39
+ streamMode?: StreamMode | Array<StreamMode>;
40
+ /**
41
+ * Pass one or more feedbackKeys if you want to request short-lived signed URLs
42
+ * for submitting feedback to LangSmith with this key for this run.
43
+ */
44
+ feedbackKeys?: string[];
45
+ }
46
+ export interface RunsCreatePayload extends RunsInvokePayload {
47
+ /**
48
+ * Webhook to call when the run is complete.
49
+ */
50
+ webhook?: string;
51
+ }
52
+ export type RunsWaitPayload = RunsStreamPayload;
53
+ export {};
package/dist/types.mjs ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -24,8 +24,8 @@ export interface AsyncCallerCallOptions {
24
24
  * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults
25
25
  * to `Infinity`. This means that by default, all calls will be made in parallel.
26
26
  *
27
- * Retries are limited by the `maxRetries` parameter, which defaults to 6. This
28
- * means that by default, each call will be retried up to 6 times, with an
27
+ * Retries are limited by the `maxRetries` parameter, which defaults to 5. This
28
+ * means that by default, each call will be retried up to 5 times, with an
29
29
  * exponential backoff between each attempt.
30
30
  */
31
31
  export declare class AsyncCaller {
@@ -9,10 +9,57 @@ const STATUS_NO_RETRY = [
9
9
  406, // Not Acceptable
10
10
  407, // Proxy Authentication Required
11
11
  408, // Request Timeout
12
+ 422, // Unprocessable Entity
12
13
  ];
13
14
  const STATUS_IGNORE = [
14
15
  409, // Conflict
15
16
  ];
17
+ /**
18
+ * Do not rely on globalThis.Response, rather just
19
+ * do duck typing
20
+ */
21
+ function isResponse(x) {
22
+ if (x == null || typeof x !== "object")
23
+ return false;
24
+ return "status" in x && "statusText" in x && "text" in x;
25
+ }
26
+ /**
27
+ * Utility error to properly handle failed requests
28
+ */
29
+ class HTTPError extends Error {
30
+ constructor(status, message, response) {
31
+ super(`HTTP ${status}: ${message}`);
32
+ Object.defineProperty(this, "status", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: void 0
37
+ });
38
+ Object.defineProperty(this, "text", {
39
+ enumerable: true,
40
+ configurable: true,
41
+ writable: true,
42
+ value: void 0
43
+ });
44
+ Object.defineProperty(this, "response", {
45
+ enumerable: true,
46
+ configurable: true,
47
+ writable: true,
48
+ value: void 0
49
+ });
50
+ this.status = status;
51
+ this.text = message;
52
+ this.response = response;
53
+ }
54
+ static async fromResponse(response, options) {
55
+ try {
56
+ return new HTTPError(response.status, await response.text(), options?.includeResponse ? response : undefined);
57
+ }
58
+ catch {
59
+ return new HTTPError(response.status, response.statusText, options?.includeResponse ? response : undefined);
60
+ }
61
+ }
62
+ }
16
63
  /**
17
64
  * A class that can be used to make async calls with concurrency and retry logic.
18
65
  *
@@ -22,8 +69,8 @@ const STATUS_IGNORE = [
22
69
  * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults
23
70
  * to `Infinity`. This means that by default, all calls will be made in parallel.
24
71
  *
25
- * Retries are limited by the `maxRetries` parameter, which defaults to 6. This
26
- * means that by default, each call will be retried up to 6 times, with an
72
+ * Retries are limited by the `maxRetries` parameter, which defaults to 5. This
73
+ * means that by default, each call will be retried up to 5 times, with an
27
74
  * exponential backoff between each attempt.
28
75
  */
29
76
  export class AsyncCaller {
@@ -53,7 +100,7 @@ export class AsyncCaller {
53
100
  value: void 0
54
101
  });
55
102
  this.maxConcurrency = params.maxConcurrency ?? Infinity;
56
- this.maxRetries = params.maxRetries ?? 6;
103
+ this.maxRetries = params.maxRetries ?? 4;
57
104
  if ("default" in PQueueMod) {
58
105
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
106
  this.queue = new PQueueMod.default({
@@ -69,15 +116,15 @@ export class AsyncCaller {
69
116
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
70
117
  call(callable, ...args) {
71
118
  const onFailedResponseHook = this.onFailedResponseHook;
72
- return this.queue.add(() => pRetry(() => callable(...args).catch((error) => {
119
+ return this.queue.add(() => pRetry(() => callable(...args).catch(async (error) => {
73
120
  // eslint-disable-next-line no-instanceof/no-instanceof
74
- console.error;
75
121
  if (error instanceof Error) {
76
122
  throw error;
77
123
  }
78
- else if (error instanceof Response) {
79
- // TODO: try to parse the response body and throw a more informative error
80
- throw new Error(`HTTP ${error.status}: ${error.statusText}`);
124
+ else if (isResponse(error)) {
125
+ throw await HTTPError.fromResponse(error, {
126
+ includeResponse: !!onFailedResponseHook,
127
+ });
81
128
  }
82
129
  else {
83
130
  throw new Error(error);
@@ -93,18 +140,15 @@ export class AsyncCaller {
93
140
  if (error?.code === "ECONNABORTED") {
94
141
  throw error;
95
142
  }
96
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
- const response = error?.response;
98
- const status = response?.status;
99
- if (status) {
100
- if (STATUS_NO_RETRY.includes(+status)) {
143
+ if (error instanceof HTTPError) {
144
+ if (STATUS_NO_RETRY.includes(error.status)) {
101
145
  throw error;
102
146
  }
103
- else if (STATUS_IGNORE.includes(+status)) {
147
+ else if (STATUS_IGNORE.includes(error.status)) {
104
148
  return;
105
149
  }
106
- if (onFailedResponseHook) {
107
- await onFailedResponseHook(response);
150
+ if (onFailedResponseHook && error.response) {
151
+ await onFailedResponseHook(error.response);
108
152
  }
109
153
  }
110
154
  },
@@ -1,4 +1,4 @@
1
- export type IterableReadableStreamInterface<T> = ReadableStream<T> & AsyncIterable<T>;
1
+ type IterableReadableStreamInterface<T> = ReadableStream<T> & AsyncIterable<T>;
2
2
  export declare class IterableReadableStream<T> extends ReadableStream<T> implements IterableReadableStreamInterface<T> {
3
3
  reader: ReadableStreamDefaultReader<T>;
4
4
  ensureReader(): void;
@@ -9,3 +9,4 @@ export declare class IterableReadableStream<T> extends ReadableStream<T> impleme
9
9
  static fromReadableStream<T>(stream: ReadableStream<T>): IterableReadableStream<T>;
10
10
  static fromAsyncGenerator<T>(generator: AsyncGenerator<T>): IterableReadableStream<T>;
11
11
  }
12
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/langgraph-sdk",
3
- "version": "0.0.1-rc.0",
3
+ "version": "0.0.1-rc.10",
4
4
  "description": "Client library for interacting with the LangGraph API",
5
5
  "type": "module",
6
6
  "packageManager": "yarn@1.22.19",
@@ -9,11 +9,14 @@
9
9
  "build": "yarn clean && yarn build:esm && yarn build:cjs && node scripts/create-entrypoints.js",
10
10
  "build:esm": "rm -f src/package.json && tsc --outDir dist/ && rm -rf dist/tests dist/**/tests",
11
11
  "build:cjs": "echo '{}' > src/package.json && tsc --outDir dist-cjs/ -p tsconfig.cjs.json && node scripts/move-cjs-to-dist.js && rm -r dist-cjs src/package.json",
12
- "prepublish": "yarn run build"
12
+ "prepublish": "yarn run build",
13
+ "format": "prettier --write src",
14
+ "lint": "prettier --check src && tsc --noEmit"
13
15
  },
14
16
  "main": "index.js",
15
17
  "license": "MIT",
16
18
  "dependencies": {
19
+ "@types/json-schema": "^7.0.15",
17
20
  "eventsource-parser": "^1.1.2",
18
21
  "p-queue": "^6.6.2",
19
22
  "p-retry": "4",
@@ -23,6 +26,7 @@
23
26
  "@tsconfig/recommended": "^1.0.2",
24
27
  "@types/node": "^20.12.12",
25
28
  "@types/uuid": "^9.0.1",
29
+ "prettier": "^3.2.5",
26
30
  "typescript": "^5.4.5"
27
31
  },
28
32
  "exports": {