@langgraph-js/pure-graph 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +22 -14
  2. package/dist/adapter/nextjs/router.js +6 -6
  3. package/dist/global.d.ts +3 -2
  4. package/dist/storage/index.d.ts +4 -3
  5. package/dist/storage/index.js +13 -1
  6. package/dist/storage/pg/checkpoint.d.ts +2 -0
  7. package/dist/storage/pg/checkpoint.js +9 -0
  8. package/dist/storage/pg/threads.d.ts +43 -0
  9. package/dist/storage/pg/threads.js +304 -0
  10. package/dist/tsconfig.tsbuildinfo +1 -0
  11. package/package.json +38 -5
  12. package/.prettierrc +0 -11
  13. package/bun.lock +0 -209
  14. package/dist/adapter/hono/zod.d.ts +0 -203
  15. package/dist/adapter/hono/zod.js +0 -43
  16. package/dist/adapter/nextjs/zod.d.ts +0 -203
  17. package/dist/adapter/nextjs/zod.js +0 -60
  18. package/examples/nextjs/README.md +0 -36
  19. package/examples/nextjs/app/api/langgraph/[...path]/route.ts +0 -10
  20. package/examples/nextjs/app/favicon.ico +0 -0
  21. package/examples/nextjs/app/globals.css +0 -26
  22. package/examples/nextjs/app/layout.tsx +0 -34
  23. package/examples/nextjs/app/page.tsx +0 -211
  24. package/examples/nextjs/next.config.ts +0 -26
  25. package/examples/nextjs/package.json +0 -24
  26. package/examples/nextjs/postcss.config.mjs +0 -5
  27. package/examples/nextjs/tsconfig.json +0 -27
  28. package/packages/agent-graph/demo.json +0 -35
  29. package/packages/agent-graph/package.json +0 -18
  30. package/packages/agent-graph/src/index.ts +0 -47
  31. package/packages/agent-graph/src/tools/tavily.ts +0 -9
  32. package/packages/agent-graph/src/tools.ts +0 -38
  33. package/packages/agent-graph/src/types.ts +0 -42
  34. package/pnpm-workspace.yaml +0 -4
  35. package/src/adapter/hono/assistants.ts +0 -24
  36. package/src/adapter/hono/endpoint.ts +0 -3
  37. package/src/adapter/hono/index.ts +0 -14
  38. package/src/adapter/hono/runs.ts +0 -92
  39. package/src/adapter/hono/threads.ts +0 -37
  40. package/src/adapter/nextjs/endpoint.ts +0 -2
  41. package/src/adapter/nextjs/index.ts +0 -2
  42. package/src/adapter/nextjs/router.ts +0 -206
  43. package/src/adapter/nextjs/zod.ts +0 -66
  44. package/src/adapter/zod.ts +0 -144
  45. package/src/createEndpoint.ts +0 -116
  46. package/src/e.d.ts +0 -3
  47. package/src/global.ts +0 -11
  48. package/src/graph/stream.ts +0 -263
  49. package/src/graph/stringify.ts +0 -219
  50. package/src/index.ts +0 -6
  51. package/src/queue/JsonPlusSerializer.ts +0 -143
  52. package/src/queue/event_message.ts +0 -30
  53. package/src/queue/stream_queue.ts +0 -237
  54. package/src/storage/index.ts +0 -52
  55. package/src/storage/memory/checkpoint.ts +0 -2
  56. package/src/storage/memory/queue.ts +0 -91
  57. package/src/storage/memory/threads.ts +0 -183
  58. package/src/storage/redis/queue.ts +0 -148
  59. package/src/storage/sqlite/DB.ts +0 -16
  60. package/src/storage/sqlite/checkpoint.ts +0 -502
  61. package/src/storage/sqlite/threads.ts +0 -405
  62. package/src/storage/sqlite/type.ts +0 -12
  63. package/src/threads/index.ts +0 -37
  64. package/src/types.ts +0 -118
  65. package/src/utils/createEntrypointGraph.ts +0 -20
  66. package/src/utils/getGraph.ts +0 -44
  67. package/src/utils/getLangGraphCommand.ts +0 -21
  68. package/test/graph/entrypoint.ts +0 -21
  69. package/test/graph/index.ts +0 -60
  70. package/test/hono.ts +0 -15
  71. package/tsconfig.json +0 -20
@@ -1,405 +0,0 @@
1
- import { BaseThreadsManager } from '../../threads/index.js';
2
- import {
3
- Command,
4
- Config,
5
- Metadata,
6
- OnConflictBehavior,
7
- Run,
8
- RunStatus,
9
- SortOrder,
10
- Thread,
11
- ThreadSortBy,
12
- ThreadStatus,
13
- } from '@langgraph-js/sdk';
14
- import type { SqliteSaver } from './checkpoint.js';
15
- import type { DatabaseType } from './type.js';
16
- import { getGraph } from '../../utils/getGraph.js';
17
- import { serialiseAsDict } from '../../graph/stream.js';
18
- interface ThreadRow {
19
- thread_id: string;
20
- created_at: string;
21
- updated_at: string;
22
- metadata: string;
23
- status: string;
24
- values: string;
25
- interrupts: string;
26
- }
27
-
28
- interface RunRow {
29
- run_id: string;
30
- thread_id: string;
31
- assistant_id: string;
32
- created_at: string;
33
- updated_at: string;
34
- status: string;
35
- metadata: string;
36
- multitask_strategy: string;
37
- }
38
-
39
- export class SQLiteThreadsManager<ValuesType = unknown> implements BaseThreadsManager<ValuesType> {
40
- db: DatabaseType;
41
- private isSetup: boolean = false;
42
-
43
- constructor(checkpointer: SqliteSaver) {
44
- this.db = checkpointer.db;
45
- this.setup();
46
- }
47
-
48
- private setup(): void {
49
- if (this.isSetup) {
50
- return;
51
- }
52
-
53
- // 创建 threads 表
54
- this.db.exec(`
55
- CREATE TABLE IF NOT EXISTS threads (
56
- thread_id TEXT PRIMARY KEY,
57
- created_at TEXT NOT NULL,
58
- updated_at TEXT NOT NULL,
59
- metadata TEXT NOT NULL DEFAULT '{}',
60
- status TEXT NOT NULL DEFAULT 'idle',
61
- [values] TEXT,
62
- interrupts TEXT NOT NULL DEFAULT '{}'
63
- )
64
- `);
65
-
66
- // 创建 runs 表
67
- this.db.exec(`
68
- CREATE TABLE IF NOT EXISTS runs (
69
- run_id TEXT PRIMARY KEY,
70
- thread_id TEXT NOT NULL,
71
- assistant_id TEXT NOT NULL,
72
- created_at TEXT NOT NULL,
73
- updated_at TEXT NOT NULL,
74
- status TEXT NOT NULL DEFAULT 'pending',
75
- metadata TEXT NOT NULL DEFAULT '{}',
76
- multitask_strategy TEXT NOT NULL DEFAULT 'reject',
77
- FOREIGN KEY (thread_id) REFERENCES threads(thread_id) ON DELETE CASCADE
78
- )
79
- `);
80
-
81
- // 创建索引以提高查询性能
82
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_threads_status ON threads(status)`);
83
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_threads_created_at ON threads(created_at)`);
84
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_threads_updated_at ON threads(updated_at)`);
85
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_runs_thread_id ON runs(thread_id)`);
86
- this.db.exec(`CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status)`);
87
-
88
- this.isSetup = true;
89
- }
90
-
91
- async create(payload?: {
92
- metadata?: Metadata;
93
- threadId?: string;
94
- ifExists?: OnConflictBehavior;
95
- graphId?: string;
96
- supersteps?: Array<{ updates: Array<{ values: unknown; command?: Command; asNode: string }> }>;
97
- }): Promise<Thread<ValuesType>> {
98
- const threadId = payload?.threadId || crypto.randomUUID();
99
-
100
- // 检查线程是否已存在
101
- if (payload?.ifExists === 'raise') {
102
- const existingThread = this.db.prepare('SELECT thread_id FROM threads WHERE thread_id = ?').get(threadId);
103
- if (existingThread) {
104
- throw new Error(`Thread with ID ${threadId} already exists.`);
105
- }
106
- }
107
-
108
- const now = new Date().toISOString();
109
- const metadata = JSON.stringify(payload?.metadata || {});
110
- const interrupts = JSON.stringify({});
111
-
112
- const thread: Thread<ValuesType> = {
113
- thread_id: threadId,
114
- created_at: now,
115
- updated_at: now,
116
- metadata: payload?.metadata || {},
117
- status: 'idle',
118
- values: null as unknown as ValuesType,
119
- interrupts: {},
120
- };
121
-
122
- // 插入到数据库
123
- this.db
124
- .prepare(
125
- `
126
- INSERT INTO threads (thread_id, created_at, updated_at, metadata, status, [values], interrupts)
127
- VALUES (?, ?, ?, ?, ?, ?, ?)
128
- `,
129
- )
130
- .run(threadId, now, now, metadata, 'idle', null, interrupts);
131
-
132
- return thread;
133
- }
134
-
135
- async search(query?: {
136
- metadata?: Metadata;
137
- limit?: number;
138
- offset?: number;
139
- status?: ThreadStatus;
140
- sortBy?: ThreadSortBy;
141
- sortOrder?: SortOrder;
142
- }): Promise<Thread<ValuesType>[]> {
143
- let sql = 'SELECT * FROM threads';
144
- const whereConditions: string[] = [];
145
- const params: any[] = [];
146
-
147
- // 构建 WHERE 条件
148
- if (query?.status) {
149
- whereConditions.push('status = ?');
150
- params.push(query.status);
151
- }
152
-
153
- if (query?.metadata) {
154
- for (const [key, value] of Object.entries(query.metadata)) {
155
- whereConditions.push(`json_extract(metadata, '$.${key}') = ?`);
156
- params.push(JSON.stringify(value));
157
- }
158
- }
159
-
160
- if (whereConditions.length > 0) {
161
- sql += ' WHERE ' + whereConditions.join(' AND ');
162
- }
163
-
164
- // 添加排序
165
- if (query?.sortBy) {
166
- sql += ` ORDER BY ${query.sortBy}`;
167
- if (query.sortOrder === 'desc') {
168
- sql += ' DESC';
169
- } else {
170
- sql += ' ASC';
171
- }
172
- }
173
-
174
- // 添加分页
175
- if (query?.limit) {
176
- sql += ` LIMIT ${query.limit}`;
177
- if (query?.offset) {
178
- sql += ` OFFSET ${query.offset}`;
179
- }
180
- }
181
-
182
- const rows = this.db.prepare(sql).all(...params) as ThreadRow[];
183
-
184
- return rows.map((row) => ({
185
- thread_id: row.thread_id,
186
- created_at: row.created_at,
187
- updated_at: row.updated_at,
188
- metadata: JSON.parse(row.metadata),
189
- status: row.status as ThreadStatus,
190
- values: row.values ? JSON.parse(row.values) : (null as unknown as ValuesType),
191
- interrupts: JSON.parse(row.interrupts),
192
- }));
193
- }
194
-
195
- async get(threadId: string): Promise<Thread<ValuesType>> {
196
- const row = this.db.prepare('SELECT * FROM threads WHERE thread_id = ?').get(threadId) as ThreadRow;
197
- if (!row) {
198
- throw new Error(`Thread with ID ${threadId} not found.`);
199
- }
200
-
201
- return {
202
- thread_id: row.thread_id,
203
- created_at: row.created_at,
204
- updated_at: row.updated_at,
205
- metadata: JSON.parse(row.metadata),
206
- status: row.status as ThreadStatus,
207
- values: row.values ? JSON.parse(row.values) : (null as unknown as ValuesType),
208
- interrupts: JSON.parse(row.interrupts),
209
- };
210
- }
211
- async set(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<void> {
212
- // 检查线程是否存在
213
- const existingThread = this.db.prepare('SELECT thread_id FROM threads WHERE thread_id = ?').get(threadId);
214
- if (!existingThread) {
215
- throw new Error(`Thread with ID ${threadId} not found.`);
216
- }
217
-
218
- const updateFields: string[] = [];
219
- const values: any[] = [];
220
-
221
- if (thread.metadata !== undefined) {
222
- updateFields.push('metadata = ?');
223
- values.push(JSON.stringify(thread.metadata));
224
- }
225
-
226
- if (thread.status !== undefined) {
227
- updateFields.push('status = ?');
228
- values.push(thread.status);
229
- }
230
-
231
- if (thread.values !== undefined) {
232
- updateFields.push('[values] = ?');
233
- values.push(thread.values ? JSON.stringify(thread.values) : null);
234
- }
235
-
236
- if (thread.interrupts !== undefined) {
237
- updateFields.push('interrupts = ?');
238
- values.push(JSON.stringify(thread.interrupts));
239
- }
240
-
241
- // 总是更新 updated_at
242
- updateFields.push('updated_at = ?');
243
- values.push(new Date().toISOString());
244
-
245
- if (updateFields.length > 0) {
246
- values.push(threadId);
247
- this.db
248
- .prepare(
249
- `
250
- UPDATE threads
251
- SET ${updateFields.join(', ')}
252
- WHERE thread_id = ?
253
- `,
254
- )
255
- .run(...values);
256
- }
257
- }
258
- async updateState(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<Pick<Config, 'configurable'>> {
259
- // 从数据库查询线程信息
260
- const row = this.db.prepare('SELECT * FROM threads WHERE thread_id = ?').get(threadId) as ThreadRow;
261
- if (!row) {
262
- throw new Error(`Thread with ID ${threadId} not found.`);
263
- }
264
-
265
- const targetThread = {
266
- thread_id: row.thread_id,
267
- created_at: row.created_at,
268
- updated_at: row.updated_at,
269
- metadata: JSON.parse(row.metadata),
270
- status: row.status as ThreadStatus,
271
- values: row.values ? JSON.parse(row.values) : (null as unknown as ValuesType),
272
- interrupts: JSON.parse(row.interrupts),
273
- };
274
-
275
- if (targetThread.status === 'busy') {
276
- throw new Error(`Thread with ID ${threadId} is busy, can't update state.`);
277
- }
278
-
279
- if (!targetThread.metadata?.graph_id) {
280
- throw new Error(`Thread with ID ${threadId} has no graph_id.`);
281
- }
282
- const graphId = targetThread.metadata?.graph_id as string;
283
- const config = {
284
- configurable: {
285
- thread_id: threadId,
286
- graph_id: graphId,
287
- },
288
- };
289
- const graph = await getGraph(graphId, config);
290
- const nextConfig = await graph.updateState(config, thread.values);
291
- const graphState = await graph.getState(config);
292
- await this.set(threadId, { values: JSON.parse(serialiseAsDict(graphState.values)) as ValuesType });
293
- return nextConfig;
294
- }
295
- async delete(threadId: string): Promise<void> {
296
- const result = this.db.prepare('DELETE FROM threads WHERE thread_id = ?').run(threadId);
297
- if (result.changes === 0) {
298
- throw new Error(`Thread with ID ${threadId} not found.`);
299
- }
300
- }
301
- async createRun(threadId: string, assistantId: string, payload?: { metadata?: Metadata }): Promise<Run> {
302
- const runId = crypto.randomUUID();
303
- const now = new Date().toISOString();
304
- const metadata = JSON.stringify(payload?.metadata ?? {});
305
-
306
- const run: Run = {
307
- run_id: runId,
308
- thread_id: threadId,
309
- assistant_id: assistantId,
310
- created_at: now,
311
- updated_at: now,
312
- status: 'pending',
313
- metadata: payload?.metadata ?? {},
314
- multitask_strategy: 'reject',
315
- };
316
-
317
- // 插入到数据库
318
- this.db
319
- .prepare(
320
- `
321
- INSERT INTO runs (run_id, thread_id, assistant_id, created_at, updated_at, status, metadata, multitask_strategy)
322
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
323
- `,
324
- )
325
- .run(runId, threadId, assistantId, now, now, 'pending', metadata, 'reject');
326
-
327
- return run;
328
- }
329
- async listRuns(
330
- threadId: string,
331
- options?: { limit?: number; offset?: number; status?: RunStatus },
332
- ): Promise<Run[]> {
333
- let sql = 'SELECT * FROM runs WHERE thread_id = ?';
334
- const params: any[] = [threadId];
335
-
336
- if (options?.status) {
337
- sql += ' AND status = ?';
338
- params.push(options.status);
339
- }
340
-
341
- sql += ' ORDER BY created_at DESC';
342
-
343
- if (options?.limit) {
344
- sql += ` LIMIT ${options.limit}`;
345
- if (options?.offset) {
346
- sql += ` OFFSET ${options.offset}`;
347
- }
348
- }
349
-
350
- const rows = this.db.prepare(sql).all(...params) as RunRow[];
351
-
352
- return rows.map((row) => ({
353
- run_id: row.run_id,
354
- thread_id: row.thread_id,
355
- assistant_id: row.assistant_id,
356
- created_at: row.created_at,
357
- updated_at: row.updated_at,
358
- status: row.status as RunStatus,
359
- metadata: JSON.parse(row.metadata),
360
- multitask_strategy: row.multitask_strategy as 'reject',
361
- }));
362
- }
363
- async updateRun(runId: string, run: Partial<Run>): Promise<void> {
364
- // 检查运行是否存在
365
- const existingRun = this.db.prepare('SELECT run_id FROM runs WHERE run_id = ?').get(runId);
366
- if (!existingRun) {
367
- throw new Error(`Run with ID ${runId} not found.`);
368
- }
369
-
370
- const updateFields: string[] = [];
371
- const values: any[] = [];
372
-
373
- if (run.status !== undefined) {
374
- updateFields.push('status = ?');
375
- values.push(run.status);
376
- }
377
-
378
- if (run.metadata !== undefined) {
379
- updateFields.push('metadata = ?');
380
- values.push(JSON.stringify(run.metadata));
381
- }
382
-
383
- if (run.multitask_strategy !== undefined) {
384
- updateFields.push('multitask_strategy = ?');
385
- values.push(run.multitask_strategy);
386
- }
387
-
388
- // 总是更新 updated_at
389
- updateFields.push('updated_at = ?');
390
- values.push(new Date().toISOString());
391
-
392
- if (updateFields.length > 0) {
393
- values.push(runId);
394
- this.db
395
- .prepare(
396
- `
397
- UPDATE runs
398
- SET ${updateFields.join(', ')}
399
- WHERE run_id = ?
400
- `,
401
- )
402
- .run(...values);
403
- }
404
- }
405
- }
@@ -1,12 +0,0 @@
1
- export interface DatabaseType {
2
- prepare(sql: string): Statement;
3
- exec(sql: string): void;
4
- close(): void;
5
- transaction<T extends any[]>(fn: (...args: T) => void): (...args: T) => void;
6
- }
7
-
8
- interface Statement {
9
- run(...params: any[]): { changes: number; lastInsertRowid: number };
10
- get(...params: any[]): any;
11
- all(...params: any[]): any[];
12
- }
@@ -1,37 +0,0 @@
1
- import {
2
- Command,
3
- Config,
4
- Metadata,
5
- OnConflictBehavior,
6
- Run,
7
- RunStatus,
8
- SortOrder,
9
- Thread,
10
- ThreadSortBy,
11
- ThreadStatus,
12
- } from '@langgraph-js/sdk';
13
-
14
- export interface BaseThreadsManager<ValuesType = unknown> {
15
- create(payload?: {
16
- metadata?: Metadata;
17
- threadId?: string;
18
- ifExists?: OnConflictBehavior;
19
- graphId?: string;
20
- supersteps?: Array<{ updates: Array<{ values: unknown; command?: Command; asNode: string }> }>;
21
- }): Promise<Thread<ValuesType>>;
22
- set(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<void>;
23
- search(query?: {
24
- metadata?: Metadata;
25
- limit?: number;
26
- offset?: number;
27
- status?: ThreadStatus;
28
- sortBy?: ThreadSortBy;
29
- sortOrder?: SortOrder;
30
- }): Promise<Thread<ValuesType>[]>;
31
- get(threadId: string): Promise<Thread<ValuesType>>;
32
- delete(threadId: string): Promise<void>;
33
- updateState(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<Pick<Config, 'configurable'>>;
34
- createRun(threadId: string, assistantId: string, payload?: { metadata?: Metadata }): Promise<Run>;
35
- listRuns(threadId: string, options?: { limit?: number; offset?: number; status?: RunStatus }): Promise<Run[]>;
36
- updateRun(runId: string, run: Partial<Run>): Promise<void>;
37
- }
package/src/types.ts DELETED
@@ -1,118 +0,0 @@
1
- import {
2
- Thread,
3
- Assistant,
4
- Run,
5
- StreamMode,
6
- Command,
7
- Metadata,
8
- AssistantGraph,
9
- OnConflictBehavior,
10
- ThreadStatus,
11
- Checkpoint,
12
- Config,
13
- } from '@langchain/langgraph-sdk';
14
- import { StreamEvent } from '@langchain/core/tracers/log_stream';
15
- import { EventMessage } from './queue/event_message';
16
- import { RunnableConfig } from '@langchain/core/runnables';
17
-
18
- // 基础类型定义
19
- export type AssistantSortBy = 'assistant_id' | 'graph_id' | 'name' | 'created_at' | 'updated_at';
20
- export type ThreadSortBy = 'thread_id' | 'status' | 'created_at' | 'updated_at';
21
- export type SortOrder = 'asc' | 'desc';
22
- export type RunStatus = 'pending' | 'running' | 'error' | 'success' | 'timeout' | 'interrupted';
23
- export type MultitaskStrategy = 'reject' | 'interrupt' | 'rollback' | 'enqueue';
24
- export type DisconnectMode = 'cancel' | 'continue';
25
- export type OnCompletionBehavior = 'complete' | 'continue';
26
- export type CancelAction = 'interrupt' | 'rollback';
27
-
28
- export type StreamInputData = {
29
- input?: Record<string, unknown> | null;
30
- metadata?: Metadata;
31
- config?: RunnableConfig;
32
- checkpointId?: string;
33
- checkpoint?: Omit<Checkpoint, 'thread_id'>;
34
- checkpoint_during?: boolean;
35
- interrupt_before?: '*' | string[];
36
- interrupt_after?: '*' | string[];
37
- multitask_strategy?: MultitaskStrategy;
38
- on_completion?: OnCompletionBehavior;
39
- signal?: AbortController['signal'];
40
- webhook?: string;
41
- on_disconnect?: DisconnectMode;
42
- after_seconds?: number;
43
- if_not_exists?: 'create' | 'reject';
44
- command?: Command;
45
- onRunCreated?: (params: { run_id: string; thread_id?: string }) => void;
46
- stream_mode?: StreamMode[];
47
- stream_subgraphs?: boolean;
48
- stream_resumable?: boolean;
49
- feedback_keys?: string[];
50
- temporary?: boolean;
51
- };
52
- /**
53
- * 兼容 LangGraph SDK 的接口定义,方便进行无侵入式的扩展
54
- */
55
- export interface ILangGraphClient<TStateType = unknown> {
56
- assistants: {
57
- search(query?: {
58
- graphId?: string;
59
- metadata?: Metadata;
60
- limit?: number;
61
- offset?: number;
62
- sortBy?: AssistantSortBy;
63
- sortOrder?: SortOrder;
64
- }): Promise<Assistant[]>;
65
- getGraph(assistantId: string, options?: { xray?: boolean | number }): Promise<AssistantGraph>;
66
- };
67
- threads: {
68
- create(payload?: {
69
- metadata?: Metadata;
70
- thread_id?: string;
71
- if_exists?: OnConflictBehavior;
72
- graph_id?: string;
73
- // supersteps?: Array<{
74
- // updates: Array<{
75
- // values: unknown;
76
- // command?: Command;
77
- // as_node: string;
78
- // }>;
79
- // }>;
80
- }): Promise<Thread<TStateType>>;
81
- search(query?: {
82
- metadata?: Metadata;
83
- limit?: number;
84
- offset?: number;
85
- status?: ThreadStatus;
86
- sortBy?: ThreadSortBy;
87
- sortOrder?: SortOrder;
88
- }): Promise<Thread<TStateType>[]>;
89
- get(threadId: string): Promise<Thread<TStateType>>;
90
- delete(threadId: string): Promise<void>;
91
- updateState(threadId: string, thread: Partial<Thread<TStateType>>): Promise<Pick<Config, 'configurable'>>;
92
- };
93
- runs: {
94
- list(
95
- threadId: string,
96
- options?: {
97
- limit?: number;
98
- offset?: number;
99
- status?: RunStatus;
100
- },
101
- ): Promise<Run[]>;
102
-
103
- stream(threadId: string, assistantId: string, payload?: StreamInputData): AsyncGenerator<EventMessage>;
104
- joinStream(
105
- threadId: string,
106
- runId: string,
107
- options?:
108
- | {
109
- signal?: AbortSignal;
110
- cancelOnDisconnect?: boolean;
111
- lastEventId?: string;
112
- streamMode?: StreamMode | StreamMode[];
113
- }
114
- | AbortSignal,
115
- ): AsyncGenerator<{ id?: string; event: StreamEvent; data: any }>;
116
- cancel(threadId: string, runId: string, wait?: boolean, action?: CancelAction): Promise<void>;
117
- };
118
- }
@@ -1,20 +0,0 @@
1
- import { AnnotationRoot, Pregel, StateGraph } from '@langchain/langgraph';
2
-
3
- export const createEntrypointGraph = <StateType extends AnnotationRoot<any>, ConfigType extends AnnotationRoot<any>>({
4
- stateSchema,
5
- config,
6
- graph,
7
- }: {
8
- stateSchema: StateType;
9
- config?: ConfigType;
10
- graph: Pregel<any, any>;
11
- }) => {
12
- const name = graph.getName();
13
- return new StateGraph(stateSchema, config)
14
- .addNode(name, (state, config) => graph.invoke(state, config))
15
- .addEdge('__start__', name)
16
- .addEdge(name, '__end__')
17
- .compile({
18
- name,
19
- });
20
- };
@@ -1,44 +0,0 @@
1
- import {
2
- BaseCheckpointSaver,
3
- BaseStore,
4
- CompiledGraph,
5
- CompiledStateGraph,
6
- LangGraphRunnableConfig,
7
- } from '@langchain/langgraph';
8
- import { LangGraphGlobal } from '../global';
9
-
10
- export type CompiledGraphFactory<T extends string> = (config: {
11
- configurable?: Record<string, unknown>;
12
- }) => Promise<CompiledGraph<T>>;
13
-
14
- export const GRAPHS: Record<string, CompiledGraph<string> | CompiledGraphFactory<string>> = {};
15
-
16
- export async function registerGraph(
17
- graphId: string,
18
- graph: CompiledGraph<any> | CompiledStateGraph<any, any, any, any, any, any, any> | CompiledGraphFactory<any>,
19
- ) {
20
- GRAPHS[graphId] = graph;
21
- }
22
- export async function getGraph(
23
- graphId: string,
24
- config: LangGraphRunnableConfig | undefined,
25
- options?: {
26
- checkpointer?: BaseCheckpointSaver | null;
27
- store?: BaseStore;
28
- },
29
- ) {
30
- if (!GRAPHS[graphId]) throw new Error(`Graph "${graphId}" not found`);
31
-
32
- const compiled =
33
- typeof GRAPHS[graphId] === 'function' ? await GRAPHS[graphId](config ?? { configurable: {} }) : GRAPHS[graphId];
34
-
35
- if (typeof options?.checkpointer !== 'undefined') {
36
- compiled.checkpointer = options?.checkpointer ?? LangGraphGlobal.globalCheckPointer;
37
- } else {
38
- compiled.checkpointer = LangGraphGlobal.globalCheckPointer;
39
- }
40
-
41
- compiled.store = options?.store ?? undefined;
42
-
43
- return compiled;
44
- }
@@ -1,21 +0,0 @@
1
- import { Command, Send } from '@langchain/langgraph';
2
- import { Command as ClientCommand } from '@langgraph-js/sdk';
3
- export interface RunSend {
4
- node: string;
5
- input?: unknown;
6
- }
7
-
8
- export interface RunCommand extends ClientCommand {}
9
-
10
- export const getLangGraphCommand = (command: RunCommand) => {
11
- let goto = command.goto != null && !Array.isArray(command.goto) ? [command.goto] : command.goto;
12
-
13
- return new Command({
14
- goto: goto?.map((item: string | RunSend) => {
15
- if (typeof item !== 'string') return new Send(item.node, item.input);
16
- return item;
17
- }),
18
- update: command.update ?? undefined,
19
- resume: command.resume,
20
- });
21
- };
@@ -1,21 +0,0 @@
1
- import { entrypoint } from '@langchain/langgraph';
2
- import { createReactAgent, createReactAgentAnnotation } from '@langchain/langgraph/prebuilt';
3
- import { createState } from '@langgraph-js/pro';
4
- import { createEntrypointGraph } from '../../src/';
5
- import { ChatOpenAI } from '@langchain/openai';
6
- const State = createState(createReactAgentAnnotation()).build({});
7
- const workflow = entrypoint('test-entrypoint', async (state: typeof State.State) => {
8
- const agent = createReactAgent({
9
- llm: new ChatOpenAI({
10
- model: 'qwen-plus',
11
- }),
12
- prompt: '你是一个智能助手',
13
- tools: [],
14
- });
15
- return agent.invoke(state);
16
- });
17
-
18
- export const graph = createEntrypointGraph({
19
- stateSchema: State,
20
- graph: workflow,
21
- });