@langgraph-js/pure-graph 1.4.2 → 1.4.5

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 (51) hide show
  1. package/dist/adapter/hono/index.js +104 -7
  2. package/dist/adapter/hono/index.js.map +1 -0
  3. package/dist/adapter/nextjs/index.js +175 -2
  4. package/dist/adapter/nextjs/index.js.map +1 -0
  5. package/dist/{checkpoint-BHKV54sL.js → checkpoint-BQME4ngM.js} +2 -2
  6. package/dist/{checkpoint-BHKV54sL.js.map → checkpoint-BQME4ngM.js.map} +1 -1
  7. package/dist/{index-DcXE-SZb.js → createEndpoint-BcVhF-uq.js} +6 -17
  8. package/dist/createEndpoint-BcVhF-uq.js.map +1 -0
  9. package/dist/index.js +16 -5
  10. package/dist/index.js.map +1 -1
  11. package/dist/{queue-C6iEVbd2.js → queue-pSZu1PVS.js} +2 -2
  12. package/dist/{queue-C6iEVbd2.js.map → queue-pSZu1PVS.js.map} +1 -1
  13. package/dist/{threads-BUgBiCiK.js → threads-amMaxKul.js} +2 -2
  14. package/dist/{threads-BUgBiCiK.js.map → threads-amMaxKul.js.map} +1 -1
  15. package/dist/zod-BaCzVUl8.js +107 -0
  16. package/dist/zod-BaCzVUl8.js.map +1 -0
  17. package/package.json +2 -2
  18. package/dist/__vite-browser-external-DGN5jhtd.js +0 -4
  19. package/dist/__vite-browser-external-DGN5jhtd.js.map +0 -1
  20. package/dist/adapter/hono/assistants.js +0 -21
  21. package/dist/adapter/hono/endpoint.js +0 -2
  22. package/dist/adapter/hono/runs.js +0 -54
  23. package/dist/adapter/hono/threads.js +0 -30
  24. package/dist/adapter/nextjs/endpoint.js +0 -2
  25. package/dist/adapter/nextjs/router.js +0 -179
  26. package/dist/adapter/zod.js +0 -127
  27. package/dist/createEndpoint.js +0 -77
  28. package/dist/global.js +0 -13
  29. package/dist/graph/stream.js +0 -195
  30. package/dist/graph/stringify.js +0 -214
  31. package/dist/index-DcXE-SZb.js.map +0 -1
  32. package/dist/queue/JsonPlusSerializer.js +0 -138
  33. package/dist/queue/event_message.js +0 -27
  34. package/dist/queue/stream_queue.js +0 -177
  35. package/dist/storage/index.js +0 -64
  36. package/dist/storage/memory/checkpoint.js +0 -2
  37. package/dist/storage/memory/queue.js +0 -81
  38. package/dist/storage/memory/threads.js +0 -145
  39. package/dist/storage/pg/checkpoint.js +0 -9
  40. package/dist/storage/pg/threads.js +0 -303
  41. package/dist/storage/redis/queue.js +0 -130
  42. package/dist/storage/sqlite/DB.js +0 -14
  43. package/dist/storage/sqlite/checkpoint.js +0 -374
  44. package/dist/storage/sqlite/threads.js +0 -299
  45. package/dist/storage/sqlite/type.js +0 -1
  46. package/dist/threads/index.js +0 -1
  47. package/dist/tsconfig.tsbuildinfo +0 -1
  48. package/dist/types.js +0 -1
  49. package/dist/utils/createEntrypointGraph.js +0 -11
  50. package/dist/utils/getGraph.js +0 -18
  51. package/dist/utils/getLangGraphCommand.js +0 -13
@@ -1,64 +0,0 @@
1
- import { StreamQueueManager } from '../queue/stream_queue';
2
- import { MemorySaver } from './memory/checkpoint';
3
- import { MemoryStreamQueue } from './memory/queue';
4
- import { MemoryThreadsManager } from './memory/threads';
5
- import { SQLiteThreadsManager } from './sqlite/threads';
6
- // 所有的适配实现,都请写到这里,通过环境变量进行判断使用哪种方式进行适配
7
- export const createCheckPointer = async () => {
8
- if ((process.env.REDIS_URL && process.env.CHECKPOINT_TYPE === 'redis') ||
9
- process.env.CHECKPOINT_TYPE === 'shallow/redis') {
10
- if (process.env.CHECKPOINT_TYPE === 'redis') {
11
- console.debug('LG | Using redis as checkpoint');
12
- const { RedisSaver } = await import('@langchain/langgraph-checkpoint-redis');
13
- return await RedisSaver.fromUrl(process.env.REDIS_URL, {
14
- defaultTTL: 60, // TTL in minutes
15
- refreshOnRead: true,
16
- });
17
- }
18
- if (process.env.CHECKPOINT_TYPE === 'shallow/redis') {
19
- console.debug('LG | Using shallow redis as checkpoint');
20
- const { ShallowRedisSaver } = await import('@langchain/langgraph-checkpoint-redis/shallow');
21
- return await ShallowRedisSaver.fromUrl(process.env.REDIS_URL);
22
- }
23
- }
24
- if (process.env.DATABASE_URL) {
25
- console.debug('LG | Using postgres as checkpoint');
26
- const { createPGCheckpoint } = await import('./pg/checkpoint');
27
- return createPGCheckpoint();
28
- }
29
- if (process.env.SQLITE_DATABASE_URI) {
30
- console.debug('LG | Using sqlite as checkpoint');
31
- const { SqliteSaver } = await import('./sqlite/checkpoint');
32
- const db = SqliteSaver.fromConnString(process.env.SQLITE_DATABASE_URI);
33
- return db;
34
- }
35
- return new MemorySaver();
36
- };
37
- export const createMessageQueue = async () => {
38
- let q;
39
- if (process.env.REDIS_URL) {
40
- console.debug('LG | Using redis as stream queue');
41
- const { RedisStreamQueue } = await import('./redis/queue');
42
- q = RedisStreamQueue;
43
- }
44
- else {
45
- q = MemoryStreamQueue;
46
- }
47
- return new StreamQueueManager(q);
48
- };
49
- export const createThreadManager = async (config) => {
50
- if (process.env.DATABASE_URL && config.checkpointer) {
51
- const { PostgresThreadsManager } = await import('./pg/threads');
52
- const threadsManager = new PostgresThreadsManager(config.checkpointer);
53
- if (process.env.DATABASE_INIT === 'true') {
54
- await threadsManager.setup();
55
- }
56
- return threadsManager;
57
- }
58
- if (process.env.SQLITE_DATABASE_URI && config.checkpointer) {
59
- const threadsManager = new SQLiteThreadsManager(config.checkpointer);
60
- await threadsManager.setup();
61
- return threadsManager;
62
- }
63
- return new MemoryThreadsManager();
64
- };
@@ -1,2 +0,0 @@
1
- import { MemorySaver } from '@langchain/langgraph-checkpoint';
2
- export { MemorySaver };
@@ -1,81 +0,0 @@
1
- import { CancelEventMessage } from '../../queue/event_message.js';
2
- import { BaseStreamQueue } from '../../queue/stream_queue.js';
3
- /** 内存实现的消息队列,用于存储消息 */
4
- export class MemoryStreamQueue extends BaseStreamQueue {
5
- data = [];
6
- async push(item) {
7
- const data = this.compressMessages ? (await this.encodeData(item)) : item;
8
- this.data.push(data);
9
- this.emit('dataChange', data);
10
- }
11
- onDataChange(listener) {
12
- this.on('dataChange', async (item) => {
13
- listener(this.compressMessages ? (await this.decodeData(item)) : item);
14
- });
15
- return () => this.off('dataChange', listener);
16
- }
17
- /**
18
- * 异步生成器:支持 for await...of 方式消费队列数据
19
- */
20
- async *onDataReceive() {
21
- let queue = [];
22
- let pendingResolve = null;
23
- let isStreamEnded = false;
24
- const handleData = async (item) => {
25
- const data = this.compressMessages ? (await this.decodeData(item)) : item;
26
- queue.push(data);
27
- // 检查是否为流结束或错误信号
28
- if (data.event === '__stream_end__' ||
29
- data.event === '__stream_error__' ||
30
- data.event === '__stream_cancel__') {
31
- setTimeout(() => {
32
- isStreamEnded = true;
33
- if (pendingResolve) {
34
- pendingResolve();
35
- pendingResolve = null;
36
- }
37
- }, 300);
38
- if (data.event === '__stream_cancel__') {
39
- this.cancel();
40
- }
41
- }
42
- if (pendingResolve) {
43
- pendingResolve();
44
- pendingResolve = null;
45
- }
46
- };
47
- // todo 这个框架的事件监听的数据返回顺序有误
48
- this.on('dataChange', handleData);
49
- try {
50
- while (!isStreamEnded) {
51
- if (queue.length > 0) {
52
- for (const item of queue) {
53
- yield item;
54
- }
55
- queue = [];
56
- }
57
- else {
58
- await new Promise((resolve) => {
59
- pendingResolve = resolve;
60
- });
61
- }
62
- }
63
- }
64
- finally {
65
- this.off('dataChange', handleData);
66
- }
67
- }
68
- async getAll() {
69
- return this.compressMessages
70
- ? (await Promise.all(this.data.map((i) => this.decodeData(i))))
71
- : this.data;
72
- }
73
- clear() {
74
- this.data = [];
75
- }
76
- cancelSignal = new AbortController();
77
- cancel() {
78
- this.push(new CancelEventMessage());
79
- this.cancelSignal.abort('user cancel this run');
80
- }
81
- }
@@ -1,145 +0,0 @@
1
- import { getGraph } from '../../utils/getGraph.js';
2
- import { serialiseAsDict } from '../../graph/stream.js';
3
- export class MemoryThreadsManager {
4
- threads = [];
5
- async setup() {
6
- return;
7
- }
8
- async create(payload) {
9
- const threadId = payload?.threadId || crypto.randomUUID();
10
- if (payload?.ifExists === 'raise' && this.threads.some((t) => t.thread_id === threadId)) {
11
- throw new Error(`Thread with ID ${threadId} already exists.`);
12
- }
13
- const thread = {
14
- thread_id: threadId,
15
- created_at: new Date().toISOString(),
16
- updated_at: new Date().toISOString(),
17
- metadata: payload?.metadata || {},
18
- status: 'idle',
19
- values: null,
20
- interrupts: {},
21
- };
22
- this.threads.push(thread);
23
- return thread;
24
- }
25
- async search(query) {
26
- let filteredThreads = [...this.threads];
27
- if (query?.status) {
28
- filteredThreads = filteredThreads.filter((t) => t.status === query.status);
29
- }
30
- if (query?.metadata) {
31
- for (const key in query.metadata) {
32
- if (Object.prototype.hasOwnProperty.call(query.metadata, key)) {
33
- filteredThreads = filteredThreads.filter((t) => t.metadata && t.metadata[key] === query.metadata?.[key]);
34
- }
35
- }
36
- }
37
- if (query?.sortBy) {
38
- filteredThreads.sort((a, b) => {
39
- let aValue;
40
- let bValue;
41
- switch (query.sortBy) {
42
- case 'created_at':
43
- aValue = new Date(a.created_at).getTime();
44
- bValue = new Date(b.created_at).getTime();
45
- break;
46
- case 'updated_at':
47
- aValue = new Date(a.updated_at).getTime();
48
- bValue = new Date(b.updated_at).getTime();
49
- break;
50
- default:
51
- return 0;
52
- }
53
- if (query.sortOrder === 'desc') {
54
- return bValue - aValue;
55
- }
56
- else {
57
- return aValue - bValue;
58
- }
59
- });
60
- }
61
- const offset = query?.offset || 0;
62
- const limit = query?.limit || filteredThreads.length;
63
- return filteredThreads.slice(offset, offset + limit);
64
- }
65
- async get(threadId) {
66
- const thread = this.threads.find((t) => t.thread_id === threadId);
67
- if (!thread) {
68
- throw new Error(`Thread with ID ${threadId} not found.`);
69
- }
70
- return thread;
71
- }
72
- async set(threadId, thread) {
73
- const index = this.threads.findIndex((t) => t.thread_id === threadId);
74
- if (index === -1) {
75
- throw new Error(`Thread with ID ${threadId} not found.`);
76
- }
77
- this.threads[index] = { ...this.threads[index], ...thread };
78
- }
79
- async delete(threadId) {
80
- const initialLength = this.threads.length;
81
- this.threads = this.threads.filter((t) => t.thread_id !== threadId);
82
- if (this.threads.length === initialLength) {
83
- throw new Error(`Thread with ID ${threadId} not found.`);
84
- }
85
- }
86
- async updateState(threadId, thread) {
87
- const index = this.threads.findIndex((t) => t.thread_id === threadId);
88
- if (index === -1) {
89
- throw new Error(`Thread with ID ${threadId} not found.`);
90
- }
91
- const targetThread = this.threads[index];
92
- if (targetThread.status === 'busy') {
93
- throw new Error(`Thread with ID ${threadId} is busy, can't update state.`);
94
- }
95
- this.threads[index] = { ...targetThread, values: thread.values };
96
- if (!targetThread.metadata?.graph_id) {
97
- throw new Error(`Thread with ID ${threadId} has no graph_id.`);
98
- }
99
- const graphId = targetThread.metadata?.graph_id;
100
- const config = {
101
- configurable: {
102
- thread_id: threadId,
103
- graph_id: graphId,
104
- },
105
- };
106
- const graph = await getGraph(graphId, config);
107
- const nextConfig = await graph.updateState(config, thread.values);
108
- const graphState = await graph.getState(config);
109
- await this.set(threadId, { values: JSON.parse(serialiseAsDict(graphState.values)) });
110
- return nextConfig;
111
- }
112
- runs = [];
113
- async createRun(threadId, assistantId, payload) {
114
- const runId = crypto.randomUUID();
115
- const run = {
116
- run_id: runId,
117
- thread_id: threadId,
118
- assistant_id: assistantId,
119
- created_at: new Date().toISOString(),
120
- updated_at: new Date().toISOString(),
121
- status: 'pending',
122
- metadata: payload?.metadata ?? {},
123
- multitask_strategy: 'reject',
124
- };
125
- this.runs.push(run);
126
- return run;
127
- }
128
- async listRuns(threadId, options) {
129
- let filteredRuns = [...this.runs];
130
- if (options?.status) {
131
- filteredRuns = filteredRuns.filter((r) => r.status === options.status);
132
- }
133
- if (options?.limit) {
134
- filteredRuns = filteredRuns.slice(options.offset || 0, (options.offset || 0) + options.limit);
135
- }
136
- return filteredRuns;
137
- }
138
- async updateRun(runId, run) {
139
- const index = this.runs.findIndex((r) => r.run_id === runId);
140
- if (index === -1) {
141
- throw new Error(`Run with ID ${runId} not found.`);
142
- }
143
- this.runs[index] = { ...this.runs[index], ...run };
144
- }
145
- }
@@ -1,9 +0,0 @@
1
- import { PostgresSaver } from '@langchain/langgraph-checkpoint-postgres';
2
- export const createPGCheckpoint = async () => {
3
- const checkpointer = PostgresSaver.fromConnString(process.env.DATABASE_URL);
4
- if (process.env.DATABASE_INIT === 'true') {
5
- console.debug('LG | Initializing postgres checkpoint');
6
- await checkpointer.setup();
7
- }
8
- return checkpointer;
9
- };
@@ -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
- }