@langgraph-js/pure-graph 1.2.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 (79) hide show
  1. package/README.md +22 -14
  2. package/dist/adapter/hono/runs.js +18 -1
  3. package/dist/adapter/nextjs/router.js +18 -7
  4. package/dist/adapter/zod.d.ts +15 -8
  5. package/dist/adapter/zod.js +8 -0
  6. package/dist/global.d.ts +3 -2
  7. package/dist/storage/index.d.ts +4 -3
  8. package/dist/storage/index.js +13 -1
  9. package/dist/storage/memory/threads.d.ts +3 -2
  10. package/dist/storage/memory/threads.js +29 -2
  11. package/dist/storage/pg/checkpoint.d.ts +2 -0
  12. package/dist/storage/pg/checkpoint.js +9 -0
  13. package/dist/storage/pg/threads.d.ts +43 -0
  14. package/dist/storage/pg/threads.js +304 -0
  15. package/dist/storage/sqlite/threads.d.ts +3 -2
  16. package/dist/storage/sqlite/threads.js +37 -3
  17. package/dist/threads/index.d.ts +3 -2
  18. package/dist/threads/index.js +1 -26
  19. package/dist/tsconfig.tsbuildinfo +1 -0
  20. package/dist/types.d.ts +2 -1
  21. package/package.json +38 -5
  22. package/.prettierrc +0 -11
  23. package/bun.lock +0 -209
  24. package/dist/adapter/nextjs/zod.d.ts +0 -203
  25. package/dist/adapter/nextjs/zod.js +0 -60
  26. package/examples/nextjs/README.md +0 -36
  27. package/examples/nextjs/app/api/langgraph/[...path]/route.ts +0 -10
  28. package/examples/nextjs/app/favicon.ico +0 -0
  29. package/examples/nextjs/app/globals.css +0 -26
  30. package/examples/nextjs/app/layout.tsx +0 -34
  31. package/examples/nextjs/app/page.tsx +0 -211
  32. package/examples/nextjs/next.config.ts +0 -26
  33. package/examples/nextjs/package.json +0 -24
  34. package/examples/nextjs/postcss.config.mjs +0 -5
  35. package/examples/nextjs/tsconfig.json +0 -27
  36. package/packages/agent-graph/demo.json +0 -35
  37. package/packages/agent-graph/package.json +0 -18
  38. package/packages/agent-graph/src/index.ts +0 -47
  39. package/packages/agent-graph/src/tools/tavily.ts +0 -9
  40. package/packages/agent-graph/src/tools.ts +0 -38
  41. package/packages/agent-graph/src/types.ts +0 -42
  42. package/pnpm-workspace.yaml +0 -4
  43. package/src/adapter/hono/assistants.ts +0 -24
  44. package/src/adapter/hono/endpoint.ts +0 -3
  45. package/src/adapter/hono/index.ts +0 -14
  46. package/src/adapter/hono/runs.ts +0 -65
  47. package/src/adapter/hono/threads.ts +0 -37
  48. package/src/adapter/nextjs/endpoint.ts +0 -2
  49. package/src/adapter/nextjs/index.ts +0 -2
  50. package/src/adapter/nextjs/router.ts +0 -193
  51. package/src/adapter/nextjs/zod.ts +0 -66
  52. package/src/adapter/zod.ts +0 -135
  53. package/src/createEndpoint.ts +0 -116
  54. package/src/e.d.ts +0 -3
  55. package/src/global.ts +0 -11
  56. package/src/graph/stream.ts +0 -263
  57. package/src/graph/stringify.ts +0 -219
  58. package/src/index.ts +0 -6
  59. package/src/queue/JsonPlusSerializer.ts +0 -143
  60. package/src/queue/event_message.ts +0 -30
  61. package/src/queue/stream_queue.ts +0 -237
  62. package/src/storage/index.ts +0 -52
  63. package/src/storage/memory/checkpoint.ts +0 -2
  64. package/src/storage/memory/queue.ts +0 -91
  65. package/src/storage/memory/threads.ts +0 -154
  66. package/src/storage/redis/queue.ts +0 -148
  67. package/src/storage/sqlite/DB.ts +0 -16
  68. package/src/storage/sqlite/checkpoint.ts +0 -503
  69. package/src/storage/sqlite/threads.ts +0 -366
  70. package/src/storage/sqlite/type.ts +0 -12
  71. package/src/threads/index.ts +0 -51
  72. package/src/types.ts +0 -116
  73. package/src/utils/createEntrypointGraph.ts +0 -20
  74. package/src/utils/getGraph.ts +0 -44
  75. package/src/utils/getLangGraphCommand.ts +0 -21
  76. package/test/graph/entrypoint.ts +0 -21
  77. package/test/graph/index.ts +0 -60
  78. package/test/hono.ts +0 -15
  79. package/tsconfig.json +0 -20
@@ -0,0 +1,304 @@
1
+ import { getGraph } from '../../utils/getGraph.js';
2
+ import { serialiseAsDict } from '../../graph/stream.js';
3
+ export class PostgresThreadsManager {
4
+ pool;
5
+ isSetup = false;
6
+ constructor(checkpointer) {
7
+ // 访问 PostgresSaver 的 pool 属性(虽然是 private,但在运行时可以访问)
8
+ this.pool = checkpointer.pool;
9
+ this.setup();
10
+ }
11
+ async setup() {
12
+ if (this.isSetup) {
13
+ return;
14
+ }
15
+ // 创建 threads 表
16
+ await this.pool.query(`
17
+ CREATE TABLE IF NOT EXISTS threads (
18
+ thread_id TEXT PRIMARY KEY,
19
+ created_at TIMESTAMP NOT NULL,
20
+ updated_at TIMESTAMP NOT NULL,
21
+ metadata JSONB NOT NULL DEFAULT '{}',
22
+ status TEXT NOT NULL DEFAULT 'idle',
23
+ "values" JSONB,
24
+ interrupts JSONB NOT NULL DEFAULT '{}'
25
+ )
26
+ `);
27
+ // 创建 runs 表
28
+ await this.pool.query(`
29
+ CREATE TABLE IF NOT EXISTS runs (
30
+ run_id TEXT PRIMARY KEY,
31
+ thread_id TEXT NOT NULL,
32
+ assistant_id TEXT NOT NULL,
33
+ created_at TIMESTAMP NOT NULL,
34
+ updated_at TIMESTAMP NOT NULL,
35
+ status TEXT NOT NULL DEFAULT 'pending',
36
+ metadata JSONB NOT NULL DEFAULT '{}',
37
+ multitask_strategy TEXT NOT NULL DEFAULT 'reject',
38
+ FOREIGN KEY (thread_id) REFERENCES threads(thread_id) ON DELETE CASCADE
39
+ )
40
+ `);
41
+ // 创建索引以提高查询性能
42
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_threads_status ON threads(status)`);
43
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_threads_created_at ON threads(created_at)`);
44
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_threads_updated_at ON threads(updated_at)`);
45
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_runs_thread_id ON runs(thread_id)`);
46
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status)`);
47
+ this.isSetup = true;
48
+ }
49
+ async create(payload) {
50
+ const threadId = payload?.threadId || crypto.randomUUID();
51
+ // 检查线程是否已存在
52
+ if (payload?.ifExists === 'raise') {
53
+ const result = await this.pool.query('SELECT thread_id FROM threads WHERE thread_id = $1', [threadId]);
54
+ if (result.rows.length > 0) {
55
+ throw new Error(`Thread with ID ${threadId} already exists.`);
56
+ }
57
+ }
58
+ const now = new Date();
59
+ const metadata = payload?.metadata || {};
60
+ const interrupts = {};
61
+ const thread = {
62
+ thread_id: threadId,
63
+ created_at: now.toISOString(),
64
+ updated_at: now.toISOString(),
65
+ metadata,
66
+ status: 'idle',
67
+ values: null,
68
+ interrupts,
69
+ };
70
+ // 插入到数据库
71
+ await this.pool.query(`
72
+ INSERT INTO threads (thread_id, created_at, updated_at, metadata, status, "values", interrupts)
73
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
74
+ `, [threadId, now, now, JSON.stringify(metadata), 'idle', null, JSON.stringify(interrupts)]);
75
+ return thread;
76
+ }
77
+ async search(query) {
78
+ let sql = 'SELECT * FROM threads';
79
+ const whereConditions = [];
80
+ const params = [];
81
+ let paramIndex = 1;
82
+ // 构建 WHERE 条件
83
+ if (query?.status) {
84
+ whereConditions.push(`status = $${paramIndex++}`);
85
+ params.push(query.status);
86
+ }
87
+ if (query?.metadata) {
88
+ for (const [key, value] of Object.entries(query.metadata)) {
89
+ whereConditions.push(`metadata->$${paramIndex} = $${paramIndex + 1}`);
90
+ params.push(key, JSON.stringify(value));
91
+ paramIndex += 2;
92
+ }
93
+ }
94
+ if (whereConditions.length > 0) {
95
+ sql += ' WHERE ' + whereConditions.join(' AND ');
96
+ }
97
+ // 添加排序
98
+ if (query?.sortBy) {
99
+ sql += ` ORDER BY ${query.sortBy}`;
100
+ if (query.sortOrder === 'desc') {
101
+ sql += ' DESC';
102
+ }
103
+ else {
104
+ sql += ' ASC';
105
+ }
106
+ }
107
+ // 添加分页
108
+ if (query?.limit) {
109
+ sql += ` LIMIT $${paramIndex++}`;
110
+ params.push(query.limit);
111
+ if (query?.offset) {
112
+ sql += ` OFFSET $${paramIndex++}`;
113
+ params.push(query.offset);
114
+ }
115
+ }
116
+ const result = await this.pool.query(sql, params);
117
+ return result.rows.map((row) => ({
118
+ thread_id: row.thread_id,
119
+ created_at: new Date(row.created_at).toISOString(),
120
+ updated_at: new Date(row.updated_at).toISOString(),
121
+ metadata: row.metadata,
122
+ status: row.status,
123
+ values: row.values || null,
124
+ interrupts: row.interrupts,
125
+ }));
126
+ }
127
+ async get(threadId) {
128
+ const result = await this.pool.query('SELECT * FROM threads WHERE thread_id = $1', [threadId]);
129
+ if (result.rows.length === 0) {
130
+ throw new Error(`Thread with ID ${threadId} not found.`);
131
+ }
132
+ const row = result.rows[0];
133
+ return {
134
+ thread_id: row.thread_id,
135
+ created_at: new Date(row.created_at).toISOString(),
136
+ updated_at: new Date(row.updated_at).toISOString(),
137
+ metadata: row.metadata,
138
+ status: row.status,
139
+ values: row.values || null,
140
+ interrupts: row.interrupts,
141
+ };
142
+ }
143
+ async set(threadId, thread) {
144
+ // 检查线程是否存在
145
+ const existingThread = await this.pool.query('SELECT thread_id FROM threads WHERE thread_id = $1', [threadId]);
146
+ if (existingThread.rows.length === 0) {
147
+ throw new Error(`Thread with ID ${threadId} not found.`);
148
+ }
149
+ const updateFields = [];
150
+ const values = [];
151
+ let paramIndex = 1;
152
+ if (thread.metadata !== undefined) {
153
+ updateFields.push(`metadata = $${paramIndex++}`);
154
+ values.push(JSON.stringify(thread.metadata));
155
+ }
156
+ if (thread.status !== undefined) {
157
+ updateFields.push(`status = $${paramIndex++}`);
158
+ values.push(thread.status);
159
+ }
160
+ if (thread.values !== undefined) {
161
+ updateFields.push(`"values" = $${paramIndex++}`);
162
+ values.push(thread.values ? JSON.stringify(thread.values) : null);
163
+ }
164
+ if (thread.interrupts !== undefined) {
165
+ updateFields.push(`interrupts = $${paramIndex++}`);
166
+ values.push(JSON.stringify(thread.interrupts));
167
+ }
168
+ // 总是更新 updated_at
169
+ updateFields.push(`updated_at = $${paramIndex++}`);
170
+ values.push(new Date());
171
+ if (updateFields.length > 0) {
172
+ values.push(threadId);
173
+ await this.pool.query(`
174
+ UPDATE threads
175
+ SET ${updateFields.join(', ')}
176
+ WHERE thread_id = $${paramIndex}
177
+ `, values);
178
+ }
179
+ }
180
+ async updateState(threadId, thread) {
181
+ // 从数据库查询线程信息
182
+ const result = await this.pool.query('SELECT * FROM threads WHERE thread_id = $1', [threadId]);
183
+ if (result.rows.length === 0) {
184
+ throw new Error(`Thread with ID ${threadId} not found.`);
185
+ }
186
+ const row = result.rows[0];
187
+ const targetThread = {
188
+ thread_id: row.thread_id,
189
+ created_at: new Date(row.created_at).toISOString(),
190
+ updated_at: new Date(row.updated_at).toISOString(),
191
+ metadata: row.metadata,
192
+ status: row.status,
193
+ values: row.values || null,
194
+ interrupts: row.interrupts,
195
+ };
196
+ if (targetThread.status === 'busy') {
197
+ throw new Error(`Thread with ID ${threadId} is busy, can't update state.`);
198
+ }
199
+ if (!targetThread.metadata?.graph_id) {
200
+ throw new Error(`Thread with ID ${threadId} has no graph_id.`);
201
+ }
202
+ const graphId = targetThread.metadata?.graph_id;
203
+ const config = {
204
+ configurable: {
205
+ thread_id: threadId,
206
+ graph_id: graphId,
207
+ },
208
+ };
209
+ const graph = await getGraph(graphId, config);
210
+ const nextConfig = await graph.updateState(config, thread.values);
211
+ const graphState = await graph.getState(config);
212
+ await this.set(threadId, { values: JSON.parse(serialiseAsDict(graphState.values)) });
213
+ return nextConfig;
214
+ }
215
+ async delete(threadId) {
216
+ const result = await this.pool.query('DELETE FROM threads WHERE thread_id = $1', [threadId]);
217
+ if (result.rowCount === 0) {
218
+ throw new Error(`Thread with ID ${threadId} not found.`);
219
+ }
220
+ }
221
+ async createRun(threadId, assistantId, payload) {
222
+ const runId = crypto.randomUUID();
223
+ const now = new Date();
224
+ const metadata = payload?.metadata ?? {};
225
+ const run = {
226
+ run_id: runId,
227
+ thread_id: threadId,
228
+ assistant_id: assistantId,
229
+ created_at: now.toISOString(),
230
+ updated_at: now.toISOString(),
231
+ status: 'pending',
232
+ metadata,
233
+ multitask_strategy: 'reject',
234
+ };
235
+ // 插入到数据库
236
+ await this.pool.query(`
237
+ INSERT INTO runs (run_id, thread_id, assistant_id, created_at, updated_at, status, metadata, multitask_strategy)
238
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
239
+ `, [runId, threadId, assistantId, now, now, 'pending', JSON.stringify(metadata), 'reject']);
240
+ return run;
241
+ }
242
+ async listRuns(threadId, options) {
243
+ let sql = 'SELECT * FROM runs WHERE thread_id = $1';
244
+ const params = [threadId];
245
+ let paramIndex = 2;
246
+ if (options?.status) {
247
+ sql += ` AND status = $${paramIndex++}`;
248
+ params.push(options.status);
249
+ }
250
+ sql += ' ORDER BY created_at DESC';
251
+ if (options?.limit) {
252
+ sql += ` LIMIT $${paramIndex++}`;
253
+ params.push(options.limit);
254
+ if (options?.offset) {
255
+ sql += ` OFFSET $${paramIndex++}`;
256
+ params.push(options.offset);
257
+ }
258
+ }
259
+ const result = await this.pool.query(sql, params);
260
+ return result.rows.map((row) => ({
261
+ run_id: row.run_id,
262
+ thread_id: row.thread_id,
263
+ assistant_id: row.assistant_id,
264
+ created_at: new Date(row.created_at).toISOString(),
265
+ updated_at: new Date(row.updated_at).toISOString(),
266
+ status: row.status,
267
+ metadata: row.metadata,
268
+ multitask_strategy: row.multitask_strategy,
269
+ }));
270
+ }
271
+ async updateRun(runId, run) {
272
+ // 检查运行是否存在
273
+ const existingRun = await this.pool.query('SELECT run_id FROM runs WHERE run_id = $1', [runId]);
274
+ if (existingRun.rows.length === 0) {
275
+ throw new Error(`Run with ID ${runId} not found.`);
276
+ }
277
+ const updateFields = [];
278
+ const values = [];
279
+ let paramIndex = 1;
280
+ if (run.status !== undefined) {
281
+ updateFields.push(`status = $${paramIndex++}`);
282
+ values.push(run.status);
283
+ }
284
+ if (run.metadata !== undefined) {
285
+ updateFields.push(`metadata = $${paramIndex++}`);
286
+ values.push(JSON.stringify(run.metadata));
287
+ }
288
+ if (run.multitask_strategy !== undefined) {
289
+ updateFields.push(`multitask_strategy = $${paramIndex++}`);
290
+ values.push(run.multitask_strategy);
291
+ }
292
+ // 总是更新 updated_at
293
+ updateFields.push(`updated_at = $${paramIndex++}`);
294
+ values.push(new Date());
295
+ if (updateFields.length > 0) {
296
+ values.push(runId);
297
+ await this.pool.query(`
298
+ UPDATE runs
299
+ SET ${updateFields.join(', ')}
300
+ WHERE run_id = $${paramIndex}
301
+ `, values);
302
+ }
303
+ }
304
+ }
@@ -1,8 +1,8 @@
1
1
  import { BaseThreadsManager } from '../../threads/index.js';
2
- import { Command, Metadata, OnConflictBehavior, Run, RunStatus, SortOrder, Thread, ThreadSortBy, ThreadStatus } from '@langgraph-js/sdk';
2
+ import { Command, Config, Metadata, OnConflictBehavior, Run, RunStatus, SortOrder, Thread, ThreadSortBy, ThreadStatus } from '@langgraph-js/sdk';
3
3
  import type { SqliteSaver } from './checkpoint.js';
4
4
  import type { DatabaseType } from './type.js';
5
- export declare class SQLiteThreadsManager<ValuesType = unknown> extends BaseThreadsManager {
5
+ export declare class SQLiteThreadsManager<ValuesType = unknown> implements BaseThreadsManager<ValuesType> {
6
6
  db: DatabaseType;
7
7
  private isSetup;
8
8
  constructor(checkpointer: SqliteSaver);
@@ -30,6 +30,7 @@ export declare class SQLiteThreadsManager<ValuesType = unknown> extends BaseThre
30
30
  }): Promise<Thread<ValuesType>[]>;
31
31
  get(threadId: string): Promise<Thread<ValuesType>>;
32
32
  set(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<void>;
33
+ updateState(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<Pick<Config, 'configurable'>>;
33
34
  delete(threadId: string): Promise<void>;
34
35
  createRun(threadId: string, assistantId: string, payload?: {
35
36
  metadata?: Metadata;
@@ -1,9 +1,9 @@
1
- import { BaseThreadsManager } from '../../threads/index.js';
2
- export class SQLiteThreadsManager extends BaseThreadsManager {
1
+ import { getGraph } from '../../utils/getGraph.js';
2
+ import { serialiseAsDict } from '../../graph/stream.js';
3
+ export class SQLiteThreadsManager {
3
4
  db;
4
5
  isSetup = false;
5
6
  constructor(checkpointer) {
6
- super();
7
7
  this.db = checkpointer.db;
8
8
  this.setup();
9
9
  }
@@ -174,6 +174,40 @@ export class SQLiteThreadsManager extends BaseThreadsManager {
174
174
  .run(...values);
175
175
  }
176
176
  }
177
+ async updateState(threadId, thread) {
178
+ // 从数据库查询线程信息
179
+ const row = this.db.prepare('SELECT * FROM threads WHERE thread_id = ?').get(threadId);
180
+ if (!row) {
181
+ throw new Error(`Thread with ID ${threadId} not found.`);
182
+ }
183
+ const targetThread = {
184
+ thread_id: row.thread_id,
185
+ created_at: row.created_at,
186
+ updated_at: row.updated_at,
187
+ metadata: JSON.parse(row.metadata),
188
+ status: row.status,
189
+ values: row.values ? JSON.parse(row.values) : null,
190
+ interrupts: JSON.parse(row.interrupts),
191
+ };
192
+ if (targetThread.status === 'busy') {
193
+ throw new Error(`Thread with ID ${threadId} is busy, can't update state.`);
194
+ }
195
+ if (!targetThread.metadata?.graph_id) {
196
+ throw new Error(`Thread with ID ${threadId} has no graph_id.`);
197
+ }
198
+ const graphId = targetThread.metadata?.graph_id;
199
+ const config = {
200
+ configurable: {
201
+ thread_id: threadId,
202
+ graph_id: graphId,
203
+ },
204
+ };
205
+ const graph = await getGraph(graphId, config);
206
+ const nextConfig = await graph.updateState(config, thread.values);
207
+ const graphState = await graph.getState(config);
208
+ await this.set(threadId, { values: JSON.parse(serialiseAsDict(graphState.values)) });
209
+ return nextConfig;
210
+ }
177
211
  async delete(threadId) {
178
212
  const result = this.db.prepare('DELETE FROM threads WHERE thread_id = ?').run(threadId);
179
213
  if (result.changes === 0) {
@@ -1,5 +1,5 @@
1
- import { Command, Metadata, OnConflictBehavior, Run, RunStatus, SortOrder, Thread, ThreadSortBy, ThreadStatus } from '@langgraph-js/sdk';
2
- export declare class BaseThreadsManager<ValuesType = unknown> {
1
+ import { Command, Config, Metadata, OnConflictBehavior, Run, RunStatus, SortOrder, Thread, ThreadSortBy, ThreadStatus } from '@langgraph-js/sdk';
2
+ export interface BaseThreadsManager<ValuesType = unknown> {
3
3
  create(payload?: {
4
4
  metadata?: Metadata;
5
5
  threadId?: string;
@@ -24,6 +24,7 @@ export declare class BaseThreadsManager<ValuesType = unknown> {
24
24
  }): Promise<Thread<ValuesType>[]>;
25
25
  get(threadId: string): Promise<Thread<ValuesType>>;
26
26
  delete(threadId: string): Promise<void>;
27
+ updateState(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<Pick<Config, 'configurable'>>;
27
28
  createRun(threadId: string, assistantId: string, payload?: {
28
29
  metadata?: Metadata;
29
30
  }): Promise<Run>;
@@ -1,26 +1 @@
1
- export class BaseThreadsManager {
2
- create(payload) {
3
- throw new Error('Function not implemented.');
4
- }
5
- set(threadId, thread) {
6
- throw new Error('Function not implemented.');
7
- }
8
- search(query) {
9
- throw new Error('Function not implemented.');
10
- }
11
- get(threadId) {
12
- throw new Error('Function not implemented.');
13
- }
14
- delete(threadId) {
15
- throw new Error('Function not implemented.');
16
- }
17
- createRun(threadId, assistantId, payload) {
18
- throw new Error('Function not implemented.');
19
- }
20
- listRuns(threadId, options) {
21
- throw new Error('Function not implemented.');
22
- }
23
- updateRun(runId, run) {
24
- throw new Error('Function not implemented.');
25
- }
26
- }
1
+ export {};