@langgraph-js/pure-graph 1.3.0 → 1.4.1

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