@langgraph-js/pure-graph 1.4.2 → 1.4.4

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.
@@ -1,303 +0,0 @@
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,130 +0,0 @@
1
- import { CancelEventMessage } from '../../queue/event_message.js';
2
- import { BaseStreamQueue } from '../../queue/stream_queue.js';
3
- import { createClient } from 'redis';
4
- /**
5
- * Redis 实现的消息队列,用于存储消息
6
- */
7
- export class RedisStreamQueue extends BaseStreamQueue {
8
- id;
9
- static redis = createClient({ url: process.env.REDIS_URL });
10
- static subscriberRedis = createClient({ url: process.env.REDIS_URL });
11
- redis;
12
- subscriberRedis;
13
- queueKey;
14
- channelKey;
15
- isConnected = false;
16
- cancelSignal;
17
- constructor(id = 'default') {
18
- super(id, true);
19
- this.id = id;
20
- this.queueKey = `queue:${this.id}`;
21
- this.channelKey = `channel:${this.id}`;
22
- this.redis = RedisStreamQueue.redis;
23
- this.subscriberRedis = RedisStreamQueue.subscriberRedis;
24
- this.cancelSignal = new AbortController();
25
- // 连接 Redis 客户端
26
- this.redis.connect();
27
- this.subscriberRedis.connect();
28
- this.isConnected = true;
29
- }
30
- /**
31
- * 推送消息到 Redis 队列
32
- */
33
- async push(item) {
34
- const data = await this.encodeData(item);
35
- const serializedData = Buffer.from(data);
36
- // 推送到队列
37
- await this.redis.lPush(this.queueKey, serializedData);
38
- // 设置队列 TTL 为 300 秒
39
- await this.redis.expire(this.queueKey, 300);
40
- // 发布到频道通知有新数据
41
- await this.redis.publish(this.channelKey, serializedData);
42
- this.emit('dataChange', data);
43
- }
44
- /**
45
- * 异步生成器:支持 for await...of 方式消费队列数据
46
- */
47
- async *onDataReceive() {
48
- let queue = [];
49
- let pendingResolve = null;
50
- let isStreamEnded = false;
51
- const handleMessage = async (message) => {
52
- const data = (await this.decodeData(message));
53
- queue.push(data);
54
- // 检查是否为流结束或错误信号
55
- if (data.event === '__stream_end__' ||
56
- data.event === '__stream_error__' ||
57
- data.event === '__stream_cancel__') {
58
- setTimeout(() => {
59
- isStreamEnded = true;
60
- if (pendingResolve) {
61
- pendingResolve();
62
- pendingResolve = null;
63
- }
64
- }, 300);
65
- if (data.event === '__stream_cancel__') {
66
- this.cancel();
67
- }
68
- }
69
- if (pendingResolve) {
70
- pendingResolve();
71
- pendingResolve = null;
72
- }
73
- };
74
- // 订阅 Redis 频道
75
- await this.subscriberRedis.subscribe(this.channelKey, (message) => {
76
- handleMessage(message);
77
- });
78
- try {
79
- while (!isStreamEnded) {
80
- if (queue.length > 0) {
81
- for (const item of queue) {
82
- yield item;
83
- }
84
- queue = [];
85
- }
86
- else {
87
- await new Promise((resolve) => {
88
- pendingResolve = resolve;
89
- });
90
- }
91
- }
92
- }
93
- finally {
94
- await this.subscriberRedis.unsubscribe(this.channelKey);
95
- }
96
- }
97
- /**
98
- * 获取队列中的所有数据
99
- */
100
- async getAll() {
101
- const data = await this.redis.lRange(this.queueKey, 0, -1);
102
- if (!data || data.length === 0) {
103
- return [];
104
- }
105
- if (this.compressMessages) {
106
- return (await Promise.all(data.map(async (item) => {
107
- const parsed = JSON.parse(item);
108
- return (await this.decodeData(parsed));
109
- })));
110
- }
111
- else {
112
- return data.map((item) => JSON.parse(item));
113
- }
114
- }
115
- /**
116
- * 清空队列
117
- */
118
- clear() {
119
- if (this.isConnected) {
120
- this.redis.del(this.queueKey);
121
- }
122
- }
123
- /**
124
- * 取消操作
125
- */
126
- cancel() {
127
- this.push(new CancelEventMessage());
128
- this.cancelSignal.abort('user cancel this run');
129
- }
130
- }
@@ -1,14 +0,0 @@
1
- let Database;
2
- /** @ts-ignore */
3
- if (globalThis.Bun) {
4
- console.debug('LG | Using Bun Sqlite, pid:', process.pid);
5
- const BunSqlite = await import('bun:sqlite');
6
- /** @ts-ignore */
7
- Database = BunSqlite.default;
8
- }
9
- else {
10
- /** @ts-ignore */
11
- const CommonSqlite = await import('better-sqlite3');
12
- Database = CommonSqlite.default;
13
- }
14
- export { Database };