@langgraph-js/pure-graph 1.0.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 +16 -0
  2. package/dist/adapter/hono/assistants.d.ts +3 -0
  3. package/dist/adapter/hono/assistants.js +27 -0
  4. package/dist/adapter/hono/endpoint.d.ts +1 -0
  5. package/dist/adapter/hono/endpoint.js +3 -0
  6. package/dist/adapter/hono/index.d.ts +3 -0
  7. package/dist/adapter/hono/index.js +11 -0
  8. package/dist/adapter/hono/runs.d.ts +3 -0
  9. package/dist/adapter/hono/runs.js +71 -0
  10. package/dist/adapter/hono/threads.d.ts +3 -0
  11. package/dist/adapter/hono/threads.js +71 -0
  12. package/dist/adapter/hono/zod.d.ts +203 -0
  13. package/dist/adapter/hono/zod.js +43 -0
  14. package/dist/createEndpoint.d.ts +5 -0
  15. package/dist/createEndpoint.js +77 -0
  16. package/dist/global.d.ts +4 -0
  17. package/dist/global.js +5 -0
  18. package/dist/graph/stream.d.ts +39 -0
  19. package/dist/graph/stream.js +187 -0
  20. package/dist/graph/stringify.d.ts +1 -0
  21. package/dist/graph/stringify.js +214 -0
  22. package/dist/index.d.ts +4 -0
  23. package/dist/index.js +4 -0
  24. package/dist/queue/JsonPlusSerializer.d.ts +7 -0
  25. package/dist/queue/JsonPlusSerializer.js +138 -0
  26. package/dist/queue/event_message.d.ts +15 -0
  27. package/dist/queue/event_message.js +27 -0
  28. package/dist/queue/stream_queue.d.ts +161 -0
  29. package/dist/queue/stream_queue.js +175 -0
  30. package/dist/storage/index.d.ts +5 -0
  31. package/dist/storage/index.js +11 -0
  32. package/dist/storage/memory/checkpoint.d.ts +2 -0
  33. package/dist/storage/memory/checkpoint.js +2 -0
  34. package/dist/storage/memory/queue.d.ts +17 -0
  35. package/dist/storage/memory/queue.js +72 -0
  36. package/dist/storage/memory/threads.d.ts +39 -0
  37. package/dist/storage/memory/threads.js +115 -0
  38. package/dist/threads/index.d.ts +36 -0
  39. package/dist/threads/index.js +26 -0
  40. package/dist/types.d.ts +94 -0
  41. package/dist/types.js +1 -0
  42. package/dist/utils/getGraph.d.ts +10 -0
  43. package/dist/utils/getGraph.js +18 -0
  44. package/dist/utils/getLangGraphCommand.d.ts +9 -0
  45. package/dist/utils/getLangGraphCommand.js +13 -0
  46. package/package.json +39 -0
  47. package/src/adapter/hono/assistants.ts +41 -0
  48. package/src/adapter/hono/endpoint.ts +4 -0
  49. package/src/adapter/hono/index.ts +14 -0
  50. package/src/adapter/hono/runs.ts +102 -0
  51. package/src/adapter/hono/threads.ts +92 -0
  52. package/src/adapter/hono/zod.ts +49 -0
  53. package/src/createEndpoint.ts +106 -0
  54. package/src/global.ts +6 -0
  55. package/src/graph/stream.ts +253 -0
  56. package/src/graph/stringify.ts +219 -0
  57. package/src/index.ts +5 -0
  58. package/src/queue/JsonPlusSerializer.ts +143 -0
  59. package/src/queue/event_message.ts +30 -0
  60. package/src/queue/stream_queue.ts +236 -0
  61. package/src/storage/index.ts +14 -0
  62. package/src/storage/memory/checkpoint.ts +2 -0
  63. package/src/storage/memory/queue.ts +83 -0
  64. package/src/storage/memory/threads.ts +154 -0
  65. package/src/threads/index.ts +51 -0
  66. package/src/types.ts +116 -0
  67. package/src/utils/getGraph.ts +44 -0
  68. package/src/utils/getLangGraphCommand.ts +21 -0
  69. package/test/graph/index.ts +21 -0
  70. package/test/hono.ts +10 -0
  71. package/tsconfig.json +20 -0
@@ -0,0 +1,236 @@
1
+ import { EventEmitter } from 'eventemitter3';
2
+ import { JsonPlusSerializer } from './JsonPlusSerializer.js';
3
+ import { EventMessage } from './event_message.js';
4
+
5
+ /**
6
+ * 流队列事件接口
7
+ * Stream queue events interface
8
+ */
9
+ interface StreamQueueEvents<T extends EventMessage> {
10
+ /** 数据事件:当有新数据时触发 / Data event: triggered when new data arrives */
11
+ data: (data: T) => void;
12
+ /** 其他事件 / Other events */
13
+ [key: string]: ((...args: any[]) => void) | undefined;
14
+ }
15
+
16
+ /**
17
+ * 基础流队列类
18
+ * Base stream queue class
19
+ */
20
+ export class BaseStreamQueue extends EventEmitter<StreamQueueEvents<EventMessage>> {
21
+ /** 序列化器实例 / Serializer instance */
22
+ serializer = new JsonPlusSerializer();
23
+
24
+ /**
25
+ * 构造函数
26
+ * Constructor
27
+ * @param compressMessages 是否压缩消息 / Whether to compress messages
28
+ */
29
+ constructor(readonly compressMessages: boolean = true) {
30
+ super();
31
+ }
32
+
33
+ /**
34
+ * 编码数据为 Uint8Array
35
+ * Encode data to Uint8Array
36
+ * @param message 要编码的消息 / Message to encode
37
+ * @returns 编码后的 Uint8Array / Encoded Uint8Array
38
+ */
39
+ async encodeData(message: EventMessage): Promise<Uint8Array> {
40
+ const [_, serializedMessage] = await this.serializer.dumpsTyped(message);
41
+ return serializedMessage;
42
+ }
43
+
44
+ /**
45
+ * 解码数据为 EventMessage
46
+ * Decode data to EventMessage
47
+ * @param serializedMessage 要解码的消息 / Message to decode
48
+ * @returns 解码后的 EventMessage / Decoded EventMessage
49
+ */
50
+ async decodeData(serializedMessage: string | Uint8Array): Promise<EventMessage> {
51
+ const message = (await this.serializer.loadsTyped('json', serializedMessage)) as EventMessage;
52
+ return message;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * 基础流队列接口
58
+ * Base stream queue interface
59
+ */
60
+ export interface BaseStreamQueueInterface {
61
+ /** 是否压缩消息 / Whether to compress messages */
62
+ compressMessages: boolean;
63
+ /**
64
+ * 推送数据项到队列
65
+ * Push item to queue
66
+ * @param item 要推送的数据项 / Item to push
67
+ */
68
+ push(item: EventMessage): Promise<void>;
69
+ /** 获取所有数据 / Get all data */
70
+ getAll(): Promise<EventMessage[]>;
71
+ /** 清空队列 / Clear queue */
72
+ clear(): void;
73
+ /**
74
+ * 监听数据变化
75
+ * Listen for data changes
76
+ * @param listener 数据变化监听器 / Data change listener
77
+ * @returns 取消监听函数 / Unsubscribe function
78
+ */
79
+ onDataChange(listener: (data: EventMessage) => void): () => void;
80
+ /** 取消信号控制器 / Cancel signal controller */
81
+ cancelSignal: AbortController;
82
+ /** 取消操作 / Cancel operation */
83
+ cancel(): void;
84
+ }
85
+
86
+ /**
87
+ * StreamQueue 管理器,通过 id 管理多个队列实例
88
+ * StreamQueue manager, manages multiple queue instances by id
89
+ */
90
+ export class StreamQueueManager<Q extends BaseStreamQueueInterface> {
91
+ /** 存储队列实例的 Map / Map storing queue instances */
92
+ private queues: Map<string, Q> = new Map();
93
+ /** 默认是否压缩消息 / Default compress messages setting */
94
+ private defaultCompressMessages: boolean;
95
+ /** 队列构造函数 / Queue constructor */
96
+ private queueConstructor: new (compressMessages: boolean) => Q;
97
+
98
+ /**
99
+ * 构造函数
100
+ * Constructor
101
+ * @param queueConstructor 队列构造函数 / Queue constructor
102
+ * @param options 配置选项 / Configuration options
103
+ */
104
+ constructor(
105
+ queueConstructor: new (compressMessages: boolean) => Q,
106
+ options: {
107
+ /** 默认是否压缩消息 / Default compress messages setting */
108
+ defaultCompressMessages?: boolean;
109
+ } = {},
110
+ ) {
111
+ this.defaultCompressMessages = options.defaultCompressMessages ?? true;
112
+ this.queueConstructor = queueConstructor;
113
+ }
114
+
115
+ /**
116
+ * 创建指定 id 的队列
117
+ * Create queue with specified id
118
+ * @param id 队列 ID / Queue ID
119
+ * @param compressMessages 是否压缩消息 / Whether to compress messages
120
+ * @returns 创建的队列实例 / Created queue instance
121
+ */
122
+ createQueue(id: string, compressMessages?: boolean): Q {
123
+ const compress = compressMessages ?? this.defaultCompressMessages;
124
+ this.queues.set(id, new this.queueConstructor(compress));
125
+ return this.queues.get(id)!;
126
+ }
127
+
128
+ /**
129
+ * 获取或创建指定 id 的队列
130
+ * Get or create queue with specified id
131
+ * @param id 队列 ID / Queue ID
132
+ * @param compressMessages 是否压缩消息,默认为构造函数中的默认值 / Whether to compress messages, defaults to constructor default
133
+ * @returns StreamQueue 实例 / StreamQueue instance
134
+ */
135
+ getQueue(id: string): Q {
136
+ const queue = this.queues.get(id);
137
+ if (!queue) {
138
+ throw new Error(`Queue with id '${id}' does not exist`);
139
+ }
140
+ return queue;
141
+ }
142
+
143
+ /**
144
+ * 取消指定 id 的队列
145
+ * Cancel queue with specified id
146
+ * @param id 队列 ID / Queue ID
147
+ */
148
+ cancelQueue(id: string): void {
149
+ const queue = this.queues.get(id);
150
+ if (queue) {
151
+ queue.cancel();
152
+ this.removeQueue(id);
153
+ }
154
+ }
155
+ /**
156
+ * 向指定 id 的队列推送数据
157
+ * Push data to queue with specified id
158
+ * @param id 队列 ID / Queue ID
159
+ * @param item 要推送的数据项 / Item to push
160
+ * @param compressMessages 是否压缩消息,默认为构造函数中的默认值 / Whether to compress messages, defaults to constructor default
161
+ */
162
+ async pushToQueue(id: string, item: EventMessage, compressMessages?: boolean): Promise<void> {
163
+ const queue = this.getQueue(id);
164
+ await queue.push(item);
165
+ }
166
+
167
+ /**
168
+ * 获取指定 id 队列中的所有数据
169
+ * Get all data from queue with specified id
170
+ * @param id 队列 ID / Queue ID
171
+ * @returns 队列中的所有数据 / All data in the queue
172
+ */
173
+ async getQueueData(id: string): Promise<EventMessage[]> {
174
+ const queue = this.queues.get(id);
175
+ if (!queue) {
176
+ throw new Error(`Queue with id '${id}' does not exist`);
177
+ }
178
+ return await queue.getAll();
179
+ }
180
+
181
+ /**
182
+ * 清空指定 id 的队列
183
+ * Clear queue with specified id
184
+ * @param id 队列 ID / Queue ID
185
+ */
186
+ clearQueue(id: string): void {
187
+ const queue = this.queues.get(id);
188
+ if (queue) {
189
+ queue.clear();
190
+ }
191
+ }
192
+
193
+ /**
194
+ * 删除指定 id 的队列
195
+ * Remove queue with specified id
196
+ * @param id 队列 ID / Queue ID
197
+ * @returns 是否成功删除 / Whether successfully deleted
198
+ */
199
+ removeQueue(id: string) {
200
+ setTimeout(() => {
201
+ return this.queues.delete(id);
202
+ }, 500);
203
+ }
204
+
205
+ /**
206
+ * 获取所有队列的 ID
207
+ * Get all queue IDs
208
+ * @returns 所有队列 ID 的数组 / Array of all queue IDs
209
+ */
210
+ getAllQueueIds(): string[] {
211
+ return Array.from(this.queues.keys());
212
+ }
213
+
214
+ /**
215
+ * 获取所有队列及其数据的快照
216
+ * Get snapshot of all queues and their data
217
+ * @returns 包含所有队列数据的结果对象 / Result object containing all queue data
218
+ */
219
+ async getAllQueuesData(): Promise<Record<string, EventMessage[]>> {
220
+ const result: Record<string, EventMessage[]> = {};
221
+ for (const [id, queue] of this.queues) {
222
+ result[id] = await queue.getAll();
223
+ }
224
+ return result;
225
+ }
226
+
227
+ /**
228
+ * 清空所有队列
229
+ * Clear all queues
230
+ */
231
+ clearAllQueues(): void {
232
+ for (const queue of this.queues.values()) {
233
+ queue.clear();
234
+ }
235
+ }
236
+ }
@@ -0,0 +1,14 @@
1
+ import { StreamQueueManager } from '../queue/stream_queue';
2
+ import { MemorySaver } from './memory/checkpoint';
3
+ import { MemoryStreamQueue } from './memory/queue';
4
+
5
+ // 所有的适配实现,都请写到这里,通过环境变量进行判断使用哪种方式进行适配
6
+
7
+ export const createCheckPointer = () => {
8
+ return new MemorySaver();
9
+ };
10
+
11
+ export const createMessageQueue = () => {
12
+ const q: new (compressMessages: boolean) => MemoryStreamQueue = MemoryStreamQueue;
13
+ return new StreamQueueManager(q);
14
+ };
@@ -0,0 +1,2 @@
1
+ import { MemorySaver } from '@langchain/langgraph-checkpoint';
2
+ export { MemorySaver };
@@ -0,0 +1,83 @@
1
+ import { CancelEventMessage, EventMessage } from '../../queue/event_message.js';
2
+ import { BaseStreamQueue } from '../../queue/stream_queue.js';
3
+ import { BaseStreamQueueInterface } from '../../queue/stream_queue.js';
4
+ /** 内存实现的消息队列,用于存储消息 */
5
+ export class MemoryStreamQueue extends BaseStreamQueue implements BaseStreamQueueInterface {
6
+ private data: EventMessage[] = [];
7
+ async push(item: EventMessage): Promise<void> {
8
+ const data = this.compressMessages ? ((await this.encodeData(item)) as unknown as EventMessage) : item;
9
+ this.data.push(data);
10
+ this.emit('dataChange', data);
11
+ }
12
+
13
+ onDataChange(listener: (data: EventMessage) => void): () => void {
14
+ this.on('dataChange', async (item) => {
15
+ listener(this.compressMessages ? ((await this.decodeData(item)) as EventMessage) : item);
16
+ });
17
+ return () => this.off('dataChange', listener);
18
+ }
19
+
20
+ /**
21
+ * 异步生成器:支持 for await...of 方式消费队列数据
22
+ */
23
+ async *onDataReceive(): AsyncGenerator<EventMessage, void, unknown> {
24
+ const queue: EventMessage[] = [];
25
+ let pendingResolve: (() => void) | null = null;
26
+ let isStreamEnded = false;
27
+ const handleData = async (item: EventMessage) => {
28
+ const data = this.compressMessages ? ((await this.decodeData(item as any)) as EventMessage) : item;
29
+ queue.push(data);
30
+
31
+ // 检查是否为流结束或错误信号
32
+ if (
33
+ data.event === '__stream_end__' ||
34
+ data.event === '__stream_error__' ||
35
+ data.event === '__stream_cancel__'
36
+ ) {
37
+ isStreamEnded = true;
38
+ if (data.event === '__stream_cancel__') {
39
+ this.cancel();
40
+ }
41
+ }
42
+
43
+ if (pendingResolve) {
44
+ pendingResolve();
45
+ pendingResolve = null;
46
+ }
47
+ };
48
+
49
+ this.on('dataChange', handleData as any);
50
+
51
+ try {
52
+ while (!isStreamEnded) {
53
+ if (queue.length > 0) {
54
+ const item = queue.shift() as EventMessage;
55
+ yield item;
56
+ } else {
57
+ await new Promise((resolve) => {
58
+ pendingResolve = resolve as () => void;
59
+ });
60
+ }
61
+ }
62
+ } finally {
63
+ this.off('dataChange', handleData as any);
64
+ }
65
+ }
66
+
67
+ async getAll(): Promise<EventMessage[]> {
68
+ return this.compressMessages
69
+ ? ((await Promise.all(
70
+ this.data.map((i) => this.decodeData(i as unknown as string | Uint8Array)),
71
+ )) as unknown as EventMessage[])
72
+ : this.data;
73
+ }
74
+
75
+ clear(): void {
76
+ this.data = [];
77
+ }
78
+ public cancelSignal = new AbortController();
79
+ cancel(): void {
80
+ this.push(new CancelEventMessage());
81
+ this.cancelSignal.abort('user cancel this run');
82
+ }
83
+ }
@@ -0,0 +1,154 @@
1
+ import { BaseThreadsManager } from '../../threads/index.js';
2
+ import {
3
+ Command,
4
+ Metadata,
5
+ OnConflictBehavior,
6
+ Run,
7
+ RunStatus,
8
+ SortOrder,
9
+ Thread,
10
+ ThreadSortBy,
11
+ ThreadStatus,
12
+ } from '@langgraph-js/sdk';
13
+
14
+ export class MemoryThreadsManager<ValuesType = unknown> extends BaseThreadsManager {
15
+ private threads: Thread<ValuesType>[] = [];
16
+
17
+ async create(payload?: {
18
+ metadata?: Metadata;
19
+ threadId?: string;
20
+ ifExists?: OnConflictBehavior;
21
+ graphId?: string;
22
+ supersteps?: Array<{ updates: Array<{ values: unknown; command?: Command; asNode: string }> }>;
23
+ }): Promise<Thread<ValuesType>> {
24
+ const threadId = payload?.threadId || crypto.randomUUID();
25
+ if (payload?.ifExists === 'raise' && this.threads.some((t) => t.thread_id === threadId)) {
26
+ throw new Error(`Thread with ID ${threadId} already exists.`);
27
+ }
28
+
29
+ const thread: Thread<ValuesType> = {
30
+ thread_id: threadId,
31
+ created_at: new Date().toISOString(),
32
+ updated_at: new Date().toISOString(),
33
+ metadata: payload?.metadata || {},
34
+ status: 'idle',
35
+ values: null as unknown as ValuesType,
36
+ interrupts: {},
37
+ };
38
+ this.threads.push(thread);
39
+ return thread;
40
+ }
41
+
42
+ async search(query?: {
43
+ metadata?: Metadata;
44
+ limit?: number;
45
+ offset?: number;
46
+ status?: ThreadStatus;
47
+ sortBy?: ThreadSortBy;
48
+ sortOrder?: SortOrder;
49
+ }): Promise<Thread<ValuesType>[]> {
50
+ let filteredThreads = [...this.threads];
51
+ if (query?.status) {
52
+ filteredThreads = filteredThreads.filter((t) => t.status === query.status);
53
+ }
54
+
55
+ if (query?.metadata) {
56
+ for (const key in query.metadata) {
57
+ if (Object.prototype.hasOwnProperty.call(query.metadata, key)) {
58
+ filteredThreads = filteredThreads.filter(
59
+ (t) => t.metadata && t.metadata[key] === query.metadata?.[key],
60
+ );
61
+ }
62
+ }
63
+ }
64
+
65
+ if (query?.sortBy) {
66
+ filteredThreads.sort((a, b) => {
67
+ let aValue: any;
68
+ let bValue: any;
69
+
70
+ switch (query.sortBy) {
71
+ case 'created_at':
72
+ aValue = new Date(a.created_at).getTime();
73
+ bValue = new Date(b.created_at).getTime();
74
+ break;
75
+ case 'updated_at':
76
+ aValue = new Date(a.updated_at).getTime();
77
+ bValue = new Date(b.updated_at).getTime();
78
+ break;
79
+ default:
80
+ return 0;
81
+ }
82
+
83
+ if (query.sortOrder === 'desc') {
84
+ return bValue - aValue;
85
+ } else {
86
+ return aValue - bValue;
87
+ }
88
+ });
89
+ }
90
+
91
+ const offset = query?.offset || 0;
92
+ const limit = query?.limit || filteredThreads.length;
93
+
94
+ return filteredThreads.slice(offset, offset + limit);
95
+ }
96
+
97
+ async get(threadId: string): Promise<Thread<ValuesType>> {
98
+ const thread = this.threads.find((t) => t.thread_id === threadId);
99
+ if (!thread) {
100
+ throw new Error(`Thread with ID ${threadId} not found.`);
101
+ }
102
+ return thread;
103
+ }
104
+ async set(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<void> {
105
+ const index = this.threads.findIndex((t) => t.thread_id === threadId);
106
+ if (index === -1) {
107
+ throw new Error(`Thread with ID ${threadId} not found.`);
108
+ }
109
+ this.threads[index] = { ...this.threads[index], ...thread };
110
+ }
111
+ async delete(threadId: string): Promise<void> {
112
+ const initialLength = this.threads.length;
113
+ this.threads = this.threads.filter((t) => t.thread_id !== threadId);
114
+ if (this.threads.length === initialLength) {
115
+ throw new Error(`Thread with ID ${threadId} not found.`);
116
+ }
117
+ }
118
+ runs: Run[] = [];
119
+ async createRun(threadId: string, assistantId: string, payload?: { metadata?: Metadata }): Promise<Run> {
120
+ const runId = crypto.randomUUID();
121
+ const run: Run = {
122
+ run_id: runId,
123
+ thread_id: threadId,
124
+ assistant_id: assistantId,
125
+ created_at: new Date().toISOString(),
126
+ updated_at: new Date().toISOString(),
127
+ status: 'pending',
128
+ metadata: payload?.metadata ?? {},
129
+ multitask_strategy: 'reject',
130
+ };
131
+ this.runs.push(run);
132
+ return run;
133
+ }
134
+ async listRuns(
135
+ threadId: string,
136
+ options?: { limit?: number; offset?: number; status?: RunStatus },
137
+ ): Promise<Run[]> {
138
+ let filteredRuns = [...this.runs];
139
+ if (options?.status) {
140
+ filteredRuns = filteredRuns.filter((r) => r.status === options.status);
141
+ }
142
+ if (options?.limit) {
143
+ filteredRuns = filteredRuns.slice(options.offset || 0, (options.offset || 0) + options.limit);
144
+ }
145
+ return filteredRuns;
146
+ }
147
+ async updateRun(runId: string, run: Partial<Run>): Promise<void> {
148
+ const index = this.runs.findIndex((r) => r.run_id === runId);
149
+ if (index === -1) {
150
+ throw new Error(`Run with ID ${runId} not found.`);
151
+ }
152
+ this.runs[index] = { ...this.runs[index], ...run };
153
+ }
154
+ }
@@ -0,0 +1,51 @@
1
+ import {
2
+ Command,
3
+ Metadata,
4
+ OnConflictBehavior,
5
+ Run,
6
+ RunStatus,
7
+ SortOrder,
8
+ Thread,
9
+ ThreadSortBy,
10
+ ThreadStatus,
11
+ } from '@langgraph-js/sdk';
12
+
13
+ export class BaseThreadsManager<ValuesType = unknown> {
14
+ create(payload?: {
15
+ metadata?: Metadata;
16
+ threadId?: string;
17
+ ifExists?: OnConflictBehavior;
18
+ graphId?: string;
19
+ supersteps?: Array<{ updates: Array<{ values: unknown; command?: Command; asNode: string }> }>;
20
+ }): Promise<Thread<ValuesType>> {
21
+ throw new Error('Function not implemented.');
22
+ }
23
+ set(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<void> {
24
+ throw new Error('Function not implemented.');
25
+ }
26
+ search(query?: {
27
+ metadata?: Metadata;
28
+ limit?: number;
29
+ offset?: number;
30
+ status?: ThreadStatus;
31
+ sortBy?: ThreadSortBy;
32
+ sortOrder?: SortOrder;
33
+ }): Promise<Thread<ValuesType>[]> {
34
+ throw new Error('Function not implemented.');
35
+ }
36
+ get(threadId: string): Promise<Thread<ValuesType>> {
37
+ throw new Error('Function not implemented.');
38
+ }
39
+ delete(threadId: string): Promise<void> {
40
+ throw new Error('Function not implemented.');
41
+ }
42
+ createRun(threadId: string, assistantId: string, payload?: { metadata?: Metadata }): Promise<Run> {
43
+ throw new Error('Function not implemented.');
44
+ }
45
+ listRuns(threadId: string, options?: { limit?: number; offset?: number; status?: RunStatus }): Promise<Run[]> {
46
+ throw new Error('Function not implemented.');
47
+ }
48
+ updateRun(runId: string, run: Partial<Run>): Promise<void> {
49
+ throw new Error('Function not implemented.');
50
+ }
51
+ }
package/src/types.ts ADDED
@@ -0,0 +1,116 @@
1
+ import {
2
+ Thread,
3
+ Assistant,
4
+ Run,
5
+ StreamMode,
6
+ Command,
7
+ Metadata,
8
+ AssistantGraph,
9
+ OnConflictBehavior,
10
+ ThreadStatus,
11
+ Checkpoint,
12
+ } from '@langchain/langgraph-sdk';
13
+ import { StreamEvent } from '@langchain/core/tracers/log_stream';
14
+ import { EventMessage } from './queue/event_message';
15
+ import { RunnableConfig } from '@langchain/core/runnables';
16
+
17
+ // 基础类型定义
18
+ export type AssistantSortBy = 'assistant_id' | 'graph_id' | 'name' | 'created_at' | 'updated_at';
19
+ export type ThreadSortBy = 'thread_id' | 'status' | 'created_at' | 'updated_at';
20
+ export type SortOrder = 'asc' | 'desc';
21
+ export type RunStatus = 'pending' | 'running' | 'error' | 'success' | 'timeout' | 'interrupted';
22
+ export type MultitaskStrategy = 'reject' | 'interrupt' | 'rollback' | 'enqueue';
23
+ export type DisconnectMode = 'cancel' | 'continue';
24
+ export type OnCompletionBehavior = 'complete' | 'continue';
25
+ export type CancelAction = 'interrupt' | 'rollback';
26
+
27
+ export type StreamInputData = {
28
+ input?: Record<string, unknown> | null;
29
+ metadata?: Metadata;
30
+ config?: RunnableConfig;
31
+ checkpointId?: string;
32
+ checkpoint?: Omit<Checkpoint, 'thread_id'>;
33
+ checkpoint_during?: boolean;
34
+ interrupt_before?: '*' | string[];
35
+ interrupt_after?: '*' | string[];
36
+ multitask_strategy?: MultitaskStrategy;
37
+ on_completion?: OnCompletionBehavior;
38
+ signal?: AbortController['signal'];
39
+ webhook?: string;
40
+ on_disconnect?: DisconnectMode;
41
+ after_seconds?: number;
42
+ if_not_exists?: 'create' | 'reject';
43
+ command?: Command;
44
+ onRunCreated?: (params: { run_id: string; thread_id?: string }) => void;
45
+ stream_mode?: StreamMode[];
46
+ stream_subgraphs?: boolean;
47
+ stream_resumable?: boolean;
48
+ feedback_keys?: string[];
49
+ temporary?: boolean;
50
+ };
51
+ /**
52
+ * 兼容 LangGraph SDK 的接口定义,方便进行无侵入式的扩展
53
+ */
54
+ export interface ILangGraphClient<TStateType = unknown> {
55
+ assistants: {
56
+ search(query?: {
57
+ graphId?: string;
58
+ metadata?: Metadata;
59
+ limit?: number;
60
+ offset?: number;
61
+ sortBy?: AssistantSortBy;
62
+ sortOrder?: SortOrder;
63
+ }): Promise<Assistant[]>;
64
+ getGraph(assistantId: string, options?: { xray?: boolean | number }): Promise<AssistantGraph>;
65
+ };
66
+ threads: {
67
+ create(payload?: {
68
+ metadata?: Metadata;
69
+ thread_id?: string;
70
+ if_exists?: OnConflictBehavior;
71
+ graph_id?: string;
72
+ // supersteps?: Array<{
73
+ // updates: Array<{
74
+ // values: unknown;
75
+ // command?: Command;
76
+ // as_node: string;
77
+ // }>;
78
+ // }>;
79
+ }): Promise<Thread<TStateType>>;
80
+ search(query?: {
81
+ metadata?: Metadata;
82
+ limit?: number;
83
+ offset?: number;
84
+ status?: ThreadStatus;
85
+ sortBy?: ThreadSortBy;
86
+ sortOrder?: SortOrder;
87
+ }): Promise<Thread<TStateType>[]>;
88
+ get(threadId: string): Promise<Thread<TStateType>>;
89
+ delete(threadId: string): Promise<void>;
90
+ };
91
+ runs: {
92
+ list(
93
+ threadId: string,
94
+ options?: {
95
+ limit?: number;
96
+ offset?: number;
97
+ status?: RunStatus;
98
+ },
99
+ ): Promise<Run[]>;
100
+
101
+ stream(threadId: string, assistantId: string, payload?: StreamInputData): AsyncGenerator<EventMessage>;
102
+ joinStream(
103
+ threadId: string,
104
+ runId: string,
105
+ options?:
106
+ | {
107
+ signal?: AbortSignal;
108
+ cancelOnDisconnect?: boolean;
109
+ lastEventId?: string;
110
+ streamMode?: StreamMode | StreamMode[];
111
+ }
112
+ | AbortSignal,
113
+ ): AsyncGenerator<{ id?: string; event: StreamEvent; data: any }>;
114
+ cancel(threadId: string, runId: string, wait?: boolean, action?: CancelAction): Promise<void>;
115
+ };
116
+ }