@langgraph-js/sdk 3.7.0 → 3.8.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 (45) hide show
  1. package/README.md +29 -0
  2. package/dist/History.d.ts +115 -0
  3. package/dist/History.js +226 -0
  4. package/dist/LangGraphClient.d.ts +23 -2
  5. package/dist/LangGraphClient.js +118 -80
  6. package/dist/MessageProcessor.js +18 -24
  7. package/dist/SpendTime.js +4 -9
  8. package/dist/TestKit.d.ts +1 -1
  9. package/dist/TestKit.js +16 -15
  10. package/dist/ToolManager.js +4 -7
  11. package/dist/artifacts/index.js +1 -1
  12. package/dist/client/LanggraphServer.js +1 -1
  13. package/dist/client/LowJSServer.d.ts +3 -0
  14. package/dist/client/LowJSServer.js +80 -0
  15. package/dist/client/index.d.ts +2 -0
  16. package/dist/client/index.js +2 -0
  17. package/dist/client/utils/sse.d.ts +8 -0
  18. package/dist/client/utils/sse.js +151 -0
  19. package/dist/client/utils/stream.d.ts +15 -0
  20. package/dist/client/utils/stream.js +104 -0
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.js +2 -0
  23. package/dist/react/ChatContext.d.ts +31 -20
  24. package/dist/react/ChatContext.js +10 -4
  25. package/dist/tool/ToolUI.js +3 -2
  26. package/dist/tool/createTool.js +3 -6
  27. package/dist/tool/utils.js +3 -4
  28. package/dist/ui-store/createChatStore.d.ts +33 -66
  29. package/dist/ui-store/createChatStore.js +261 -247
  30. package/dist/vue/ChatContext.d.ts +41 -21
  31. package/dist/vue/ChatContext.js +8 -2
  32. package/package.json +3 -1
  33. package/src/History.ts +294 -0
  34. package/src/LangGraphClient.ts +98 -48
  35. package/src/client/LanggraphServer.ts +1 -2
  36. package/src/client/LowJSServer.ts +80 -0
  37. package/src/client/index.ts +2 -0
  38. package/src/client/utils/sse.ts +176 -0
  39. package/src/client/utils/stream.ts +114 -0
  40. package/src/index.ts +2 -0
  41. package/src/react/ChatContext.ts +25 -16
  42. package/src/ui-store/createChatStore.ts +310 -236
  43. package/src/vue/ChatContext.ts +12 -0
  44. package/test/TestKit.test.ts +10 -2
  45. package/tsconfig.json +1 -1
package/README.md CHANGED
@@ -57,6 +57,35 @@ pnpm add @langgraph-js/sdk
57
57
 
58
58
  - ✅ Read History from LangGraph
59
59
 
60
+ ## Legacy Mode
61
+
62
+ Legacy mode is designed to be compatible with environments that don't support `AsyncGeneratorFunction` (such as WeChat Mini Programs). In these environments, standard async iterators may not work properly.
63
+
64
+ ### Legacy Mode Example
65
+
66
+ ```typescript
67
+ import { TestLangGraphChat, createChatStore, createLowerJSClient } from "@langgraph-js/sdk";
68
+
69
+ const client = await createLowerJSClient({
70
+ apiUrl: "http://localhost:8123",
71
+ defaultHeaders: {
72
+ Authorization: "Bearer 123",
73
+ },
74
+ });
75
+
76
+ createChatStore(
77
+ "graph",
78
+ {
79
+ defaultHeaders: {
80
+ Authorization: "Bearer 123",
81
+ },
82
+ client,
83
+ legacyMode: true,
84
+ },
85
+ {}
86
+ );
87
+ ```
88
+
60
89
  ## Advanced Usage
61
90
 
62
91
  ### Creating a Chat Store
@@ -0,0 +1,115 @@
1
+ import { LangGraphClient, LangGraphClientConfig } from "./LangGraphClient.js";
2
+ import type { Thread } from "@langchain/langgraph-sdk";
3
+ export interface SessionInfo {
4
+ /** 会话唯一标识,同时也是 threadId */
5
+ sessionId: string;
6
+ /** LangGraphClient 实例(懒加载) */
7
+ client?: LangGraphClient;
8
+ /** Thread 信息(懒加载,第一条消息后才创建) */
9
+ thread?: Thread<any>;
10
+ /** Agent 名称 */
11
+ agentName: string;
12
+ }
13
+ export interface CreateSessionOptions {
14
+ /** 会话 ID / Thread ID,不提供则自动生成 */
15
+ sessionId?: string;
16
+ /** Agent 名称 */
17
+ agentName?: string;
18
+ /** 是否从已有 Thread 恢复会话 */
19
+ restore?: boolean;
20
+ /** Graph ID */
21
+ graphId?: string;
22
+ }
23
+ /**
24
+ * @zh History 类用于管理多个 LangGraphClient 实例,支持多会话场景
25
+ * @en History class manages multiple LangGraphClient instances for multi-session scenarios
26
+ */
27
+ export declare class History {
28
+ /** 存储所有会话的 Map */
29
+ private sessions;
30
+ /** 当前活跃的会话 ID */
31
+ private activeSessionId;
32
+ /** 客户端配置,用于创建新的 LangGraphClient 实例 */
33
+ private clientConfig;
34
+ /** 虚拟 Client,用于查询操作(不绑定特定 Thread) */
35
+ private virtualClient;
36
+ constructor(clientConfig: LangGraphClientConfig);
37
+ /**
38
+ * @zh 创建新会话(延迟创建 Thread,直到发送第一条消息)
39
+ * @en Creates a new session (lazy Thread creation until first message)
40
+ */
41
+ createSession(options?: CreateSessionOptions): Promise<SessionInfo>;
42
+ /**
43
+ * @zh 激活指定会话(懒加载创建 Client)
44
+ * @en Activates the specified session (lazy load client)
45
+ */
46
+ activateSession(sessionId: string): Promise<SessionInfo>;
47
+ /**
48
+ * @zh 获取当前活跃的会话
49
+ * @en Gets the current active session
50
+ */
51
+ getActiveSession(): SessionInfo | null;
52
+ /**
53
+ * @zh 获取指定会话
54
+ * @en Gets the specified session
55
+ */
56
+ getSession(sessionId: string): SessionInfo | null;
57
+ /**
58
+ * @zh 获取所有会话
59
+ * @en Gets all sessions
60
+ */
61
+ getAllSessions(): SessionInfo[];
62
+ /**
63
+ * @zh 删除指定会话
64
+ * @en Deletes the specified session
65
+ */
66
+ deleteSession(sessionId: string): Promise<boolean>;
67
+ /**
68
+ * @zh 清空所有会话
69
+ * @en Clears all sessions
70
+ */
71
+ clearAllSessions(): Promise<void>;
72
+ /**
73
+ * @zh 获取会话数量
74
+ * @en Gets the number of sessions
75
+ */
76
+ getSessionCount(): number;
77
+ /**
78
+ * @zh 生成会话 ID (UUID v4 格式)
79
+ * @en Generates a session ID (UUID v4 format)
80
+ */
81
+ private generateSessionId;
82
+ /**
83
+ * @zh 从已有的 Thread 添加会话(仅添加元数据,不创建 Client)
84
+ * @en Adds a session from an existing Thread (metadata only, no client created)
85
+ */
86
+ addSessionFromThread(threadId: string, agentName?: string): Promise<SessionInfo>;
87
+ /**
88
+ * @zh 获取当前活跃的客户端
89
+ * @en Gets the current active client
90
+ */
91
+ getActiveClient(): LangGraphClient | null;
92
+ /**
93
+ * @zh 从远程列出所有会话
94
+ * @en Lists all sessions from remote
95
+ */
96
+ listRemoteSessions(options?: {
97
+ sortOrder?: "asc" | "desc";
98
+ sortBy?: "created_at" | "updated_at";
99
+ offset?: number;
100
+ limit?: number;
101
+ }): Promise<Thread<unknown>[]>;
102
+ /**
103
+ * @zh 从远程同步会话到本地(仅同步元数据,不创建 Client)
104
+ * @en Syncs sessions from remote to local (metadata only, no client created)
105
+ */
106
+ syncFromRemote(options?: {
107
+ limit?: number;
108
+ agentName?: string;
109
+ }): Promise<SessionInfo[]>;
110
+ /**
111
+ * @zh 初始化 History(必须先调用)
112
+ * @en Initializes History (must be called first)
113
+ */
114
+ init(agentName?: string): Promise<import("@langchain/langgraph-sdk").Assistant | undefined>;
115
+ }
@@ -0,0 +1,226 @@
1
+ import { LangGraphClient } from "./LangGraphClient.js";
2
+ /**
3
+ * @zh History 类用于管理多个 LangGraphClient 实例,支持多会话场景
4
+ * @en History class manages multiple LangGraphClient instances for multi-session scenarios
5
+ */
6
+ export class History {
7
+ /** 存储所有会话的 Map */
8
+ sessions = new Map();
9
+ /** 当前活跃的会话 ID */
10
+ activeSessionId = null;
11
+ /** 客户端配置,用于创建新的 LangGraphClient 实例 */
12
+ clientConfig;
13
+ /** 虚拟 Client,用于查询操作(不绑定特定 Thread) */
14
+ virtualClient;
15
+ constructor(clientConfig) {
16
+ this.clientConfig = clientConfig;
17
+ this.virtualClient = new LangGraphClient(clientConfig);
18
+ }
19
+ /**
20
+ * @zh 创建新会话(延迟创建 Thread,直到发送第一条消息)
21
+ * @en Creates a new session (lazy Thread creation until first message)
22
+ */
23
+ async createSession(options = {}) {
24
+ const sessionId = options.sessionId || this.generateSessionId();
25
+ const agentName = options.agentName || this.virtualClient.getCurrentAssistant()?.graph_id;
26
+ if (!agentName) {
27
+ throw new Error("Agent name is required. Please call init() first or provide agentName.");
28
+ }
29
+ if (this.sessions.has(sessionId)) {
30
+ throw new Error(`Session ${sessionId} already exists`);
31
+ }
32
+ const sessionInfo = {
33
+ sessionId,
34
+ agentName,
35
+ };
36
+ // 如果是从已有 Thread 恢复,则立即获取 Thread
37
+ if (options.restore) {
38
+ sessionInfo.thread = (await this.virtualClient.threads.get(sessionId));
39
+ }
40
+ // 否则 thread 为 undefined,等待第一条消息时由 Client 自动创建
41
+ this.sessions.set(sessionId, sessionInfo);
42
+ return sessionInfo;
43
+ }
44
+ /**
45
+ * @zh 激活指定会话(懒加载创建 Client)
46
+ * @en Activates the specified session (lazy load client)
47
+ */
48
+ async activateSession(sessionId) {
49
+ const session = this.sessions.get(sessionId);
50
+ if (!session) {
51
+ throw new Error(`Session ${sessionId} not found`);
52
+ }
53
+ // 懒加载:只在激活时创建 Client
54
+ if (!session.client) {
55
+ const client = new LangGraphClient(this.clientConfig);
56
+ await client.initAssistant(session.agentName);
57
+ // 只有在有 thread 的情况下才重置(恢复已有会话)
58
+ // 新会话的 thread 会在发送第一条消息时自动创建
59
+ if (session.thread) {
60
+ await client.resetThread(session.agentName, sessionId);
61
+ }
62
+ session.client = client;
63
+ }
64
+ const lastSession = this.activeSessionId && this.sessions.get(this.activeSessionId);
65
+ // 空闲的 client 就需要销毁
66
+ if (lastSession && lastSession.client?.status === "idle") {
67
+ lastSession.client?.reset();
68
+ lastSession.client = undefined;
69
+ }
70
+ this.activeSessionId = sessionId;
71
+ return session;
72
+ }
73
+ /**
74
+ * @zh 获取当前活跃的会话
75
+ * @en Gets the current active session
76
+ */
77
+ getActiveSession() {
78
+ if (!this.activeSessionId) {
79
+ return null;
80
+ }
81
+ return this.sessions.get(this.activeSessionId) || null;
82
+ }
83
+ /**
84
+ * @zh 获取指定会话
85
+ * @en Gets the specified session
86
+ */
87
+ getSession(sessionId) {
88
+ return this.sessions.get(sessionId) || null;
89
+ }
90
+ /**
91
+ * @zh 获取所有会话
92
+ * @en Gets all sessions
93
+ */
94
+ getAllSessions() {
95
+ return Array.from(this.sessions.values());
96
+ }
97
+ /**
98
+ * @zh 删除指定会话
99
+ * @en Deletes the specified session
100
+ */
101
+ async deleteSession(sessionId) {
102
+ const session = this.sessions.get(sessionId);
103
+ if (!session) {
104
+ return false;
105
+ }
106
+ // 如果删除的是当前活跃会话,清空活跃会话
107
+ if (this.activeSessionId === sessionId) {
108
+ this.activeSessionId = null;
109
+ }
110
+ // 删除对应的远程 Thread
111
+ try {
112
+ await this.virtualClient.deleteThread(sessionId);
113
+ }
114
+ catch (error) {
115
+ console.warn(`Failed to delete thread for session ${sessionId}:`, error);
116
+ }
117
+ this.sessions.delete(sessionId);
118
+ return true;
119
+ }
120
+ /**
121
+ * @zh 清空所有会话
122
+ * @en Clears all sessions
123
+ */
124
+ async clearAllSessions() {
125
+ const sessionIds = Array.from(this.sessions.keys());
126
+ for (const sessionId of sessionIds) {
127
+ await this.deleteSession(sessionId);
128
+ }
129
+ this.activeSessionId = null;
130
+ }
131
+ /**
132
+ * @zh 获取会话数量
133
+ * @en Gets the number of sessions
134
+ */
135
+ getSessionCount() {
136
+ return this.sessions.size;
137
+ }
138
+ /**
139
+ * @zh 生成会话 ID (UUID v4 格式)
140
+ * @en Generates a session ID (UUID v4 format)
141
+ */
142
+ generateSessionId() {
143
+ // 优先使用 crypto.randomUUID (Node.js 15.6+, 浏览器支持)
144
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
145
+ return crypto.randomUUID();
146
+ }
147
+ // 降级方案:生成符合 UUID v4 格式的随机 ID
148
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
149
+ const r = (Math.random() * 16) | 0;
150
+ const v = c === "x" ? r : (r & 0x3) | 0x8;
151
+ return v.toString(16);
152
+ });
153
+ }
154
+ /**
155
+ * @zh 从已有的 Thread 添加会话(仅添加元数据,不创建 Client)
156
+ * @en Adds a session from an existing Thread (metadata only, no client created)
157
+ */
158
+ async addSessionFromThread(threadId, agentName) {
159
+ const agent = agentName || this.virtualClient.getCurrentAssistant()?.graph_id;
160
+ if (!agent) {
161
+ throw new Error("Agent name is required. Please call init() first or provide agentName.");
162
+ }
163
+ return this.createSession({
164
+ sessionId: threadId,
165
+ agentName: agent,
166
+ restore: true,
167
+ });
168
+ }
169
+ /**
170
+ * @zh 获取当前活跃的客户端
171
+ * @en Gets the current active client
172
+ */
173
+ getActiveClient() {
174
+ const session = this.getActiveSession();
175
+ return session?.client || null;
176
+ }
177
+ /**
178
+ * @zh 从远程列出所有会话
179
+ * @en Lists all sessions from remote
180
+ */
181
+ async listRemoteSessions(options = {}) {
182
+ return this.virtualClient.listThreads(options);
183
+ }
184
+ /**
185
+ * @zh 从远程同步会话到本地(仅同步元数据,不创建 Client)
186
+ * @en Syncs sessions from remote to local (metadata only, no client created)
187
+ */
188
+ async syncFromRemote(options = {}) {
189
+ const agentName = options.agentName || this.virtualClient.getCurrentAssistant()?.graph_id;
190
+ if (!agentName) {
191
+ throw new Error("Agent name is required. Please call init() first or provide agentName.");
192
+ }
193
+ const threads = await this.listRemoteSessions({
194
+ limit: options.limit || 100,
195
+ sortBy: "updated_at",
196
+ sortOrder: "desc",
197
+ });
198
+ const syncedSessions = [];
199
+ for (const thread of threads) {
200
+ const threadId = thread.thread_id;
201
+ // 更新或创建会话信息
202
+ if (this.sessions.has(threadId)) {
203
+ const session = this.sessions.get(threadId);
204
+ session.thread = thread;
205
+ syncedSessions.push(session);
206
+ }
207
+ else {
208
+ const sessionInfo = {
209
+ sessionId: threadId,
210
+ thread,
211
+ agentName,
212
+ };
213
+ this.sessions.set(threadId, sessionInfo);
214
+ syncedSessions.push(sessionInfo);
215
+ }
216
+ }
217
+ return syncedSessions;
218
+ }
219
+ /**
220
+ * @zh 初始化 History(必须先调用)
221
+ * @en Initializes History (must be called first)
222
+ */
223
+ async init(agentName) {
224
+ return this.virtualClient.initAssistant(agentName);
225
+ }
226
+ }
@@ -84,6 +84,8 @@ export interface LangGraphClientConfig {
84
84
  defaultHeaders?: Record<string, string | null | undefined>;
85
85
  /** 自定义客户端实现,如果不提供则使用官方 Client */
86
86
  client: ILangGraphClient<any>;
87
+ /** 是否使用 legacy 模式,默认 false */
88
+ legacyMode?: boolean;
87
89
  }
88
90
  export interface LangGraphEvents {
89
91
  /** 流开始事件 */
@@ -136,11 +138,17 @@ export declare class LangGraphClient<TStateType = unknown> extends EventEmitter<
136
138
  stopController: AbortController | null;
137
139
  /** Message 处理器 */
138
140
  private messageProcessor;
141
+ private legacyMode;
142
+ /** 当前流式状态 */
143
+ private _status;
139
144
  constructor(config: LangGraphClientConfig);
140
145
  /** 代理 assistants 属性到内部 client */
141
146
  get assistants(): {
142
147
  search(query?: {
143
- graphId?: string;
148
+ graphId? /**
149
+ * The maximum number of concurrent calls that can be made.
150
+ * Defaults to `Infinity`, which means no limit.
151
+ */: string;
144
152
  metadata?: import("@langchain/langgraph-sdk").Metadata;
145
153
  limit?: number;
146
154
  offset?: number;
@@ -173,6 +181,8 @@ export declare class LangGraphClient<TStateType = unknown> extends EventEmitter<
173
181
  };
174
182
  /** 代理 runs 属性到内部 client */
175
183
  get runs(): ILangGraphClient["runs"];
184
+ /** 获取当前流式状态 */
185
+ get status(): "error" | "idle" | "busy" | "interrupted";
176
186
  private listAssistants;
177
187
  /**
178
188
  * @zh 初始化 Assistant。
@@ -194,7 +204,12 @@ export declare class LangGraphClient<TStateType = unknown> extends EventEmitter<
194
204
  * @zh 列出所有的 Thread。
195
205
  * @en Lists all Threads.
196
206
  */
197
- listThreads(): Promise<Thread<TStateType>[]>;
207
+ listThreads(options?: {
208
+ sortOrder?: "asc" | "desc";
209
+ sortBy?: "created_at" | "updated_at";
210
+ offset?: number;
211
+ limit?: number;
212
+ }): Promise<Thread<TStateType>[]>;
198
213
  deleteThread(threadId: string): Promise<void>;
199
214
  /**
200
215
  * @zh 从历史中恢复 Thread 数据。
@@ -248,6 +263,12 @@ export declare class LangGraphClient<TStateType = unknown> extends EventEmitter<
248
263
  id: string;
249
264
  name: string;
250
265
  };
266
+ /**
267
+ * @zh 处理流式响应的单个 chunk。
268
+ * @en Processes a single chunk from the stream response.
269
+ * @returns 是否需要跳过后续处理 (continue)
270
+ */
271
+ private processStreamChunk;
251
272
  private runFETool;
252
273
  private callFETool;
253
274
  extraParams: Record<string, any>;