@langgraph-js/sdk 1.6.0 → 1.6.2

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.
package/README.md CHANGED
@@ -1,163 +1,163 @@
1
- # @langgraph-js/sdk
2
-
3
- ![npm version](https://img.shields.io/npm/v/@langgraph-js/sdk)
4
- ![license](https://img.shields.io/npm/l/@langgraph-js/sdk)
5
-
6
- > The missing UI SDK for LangGraph - seamlessly integrate your AI agents with frontend interfaces
7
-
8
- ## Why @langgraph-js/sdk?
9
-
10
- Building AI agent applications is complex, especially when you need to bridge the gap between LangGraph agents and interactive user interfaces. This SDK solves the critical challenges of frontend integration:
11
-
12
- - **Provides a complete UI integration layer** - no more complex custom code to handle tools, streaming, and state management
13
- - **Simplifies human-in-the-loop interactions** - easily incorporate user feedback within agent workflows
14
- - **Handles edge cases automatically** - interruptions, errors, token management and more
15
- - **Offers a rich set of UI components** - ready-to-use elements to display agent interactions
16
-
17
- [DOCS](https://langgraph-js.netlify.app)
18
-
19
- ## Installation
20
-
21
- ```bash
22
- # Using npm
23
- npm install @langgraph-js/sdk
24
-
25
- # Using yarn
26
- yarn add @langgraph-js/sdk
27
-
28
- # Using pnpm
29
- pnpm add @langgraph-js/sdk
30
- ```
31
-
32
- ## Key Features
33
-
34
- ### Generative UI
35
-
36
- - ✅ Custom Tool Messages
37
- - ✅ Token Counter
38
- - ✅ Stop Graph Progress
39
- - ✅ Interrupt Handling
40
- - ✅ Error Handling
41
- - ✅ Spend Time Tracking
42
- - ✅ Time Persistence
43
-
44
- ### Frontend Actions
45
-
46
- - ✅ Definition of Union Tools
47
- - ✅ Frontend Functions As Tools
48
- - ✅ Human-in-the-Loop Interaction
49
- - ✅ Interrupt Mode
50
-
51
- ### Authorization
52
-
53
- - ✅ Cookie-Based Authentication
54
- - ✅ Custom Token Authentication
55
-
56
- ### Persistence
57
-
58
- - ✅ Read History from LangGraph
59
-
60
- ## Advanced Usage
61
-
62
- ### Creating a Chat Store
63
-
64
- You can easily create a reactive store for your LangGraph client:
65
-
66
- ```typescript
67
- import { createChatStore } from "@langgraph-js/sdk";
68
-
69
- export const globalChatStore = createChatStore(
70
- "agent",
71
- {
72
- // Custom LangGraph backend interaction
73
- apiUrl: "http://localhost:8123",
74
- // Custom headers for authentication
75
- defaultHeaders: JSON.parse(localStorage.getItem("code") || "{}"),
76
- callerOptions: {
77
- // Example for including cookies
78
- // fetch(url: string, options: RequestInit) {
79
- // options.credentials = "include";
80
- // return fetch(url, options);
81
- // },
82
- },
83
- },
84
- {
85
- onInit(client) {
86
- client.tools.bindTools([]);
87
- },
88
- }
89
- );
90
- ```
91
-
92
- ### React Integration
93
-
94
- First, install the nanostores React integration:
95
-
96
- ```bash
97
- pnpm i @nanostores/react
98
- ```
99
-
100
- Then create a context provider for your chat:
101
-
102
- ```tsx
103
- import React, { createContext, useContext, useEffect } from "react";
104
- import { globalChatStore } from "../store"; // Import your store
105
- import { UnionStore, useUnionStore } from "@langgraph-js/sdk";
106
- import { useStore } from "@nanostores/react";
107
-
108
- type ChatContextType = UnionStore<typeof globalChatStore>;
109
-
110
- const ChatContext = createContext<ChatContextType | undefined>(undefined);
111
-
112
- export const useChat = () => {
113
- const context = useContext(ChatContext);
114
- if (!context) {
115
- throw new Error("useChat must be used within a ChatProvider");
116
- }
117
- return context;
118
- };
119
-
120
- export const ChatProvider = ({ children }) => {
121
- // Use store to ensure React gets reactive state updates
122
- const store = useUnionStore(globalChatStore, useStore);
123
-
124
- useEffect(() => {
125
- // Initialize client
126
- store.initClient().then(() => {
127
- // Initialize conversation history
128
- store.refreshHistoryList();
129
- });
130
- }, [store.currentAgent]);
131
-
132
- return <ChatContext.Provider value={store}>{children}</ChatContext.Provider>;
133
- };
134
- ```
135
-
136
- Use it in your components:
137
-
138
- ```tsx
139
- export const MyChat = () => {
140
- return (
141
- <ChatProvider>
142
- <ChatComp></ChatComp>
143
- </ChatProvider>
144
- );
145
- };
146
-
147
- function ChatComp() {
148
- const chat = useChat();
149
- // Use chat store methods and state here
150
- }
151
- ```
152
-
153
- ## Documentation
154
-
155
- For complete documentation, visit our [official docs](https://langgraph-js.netlify.app).
156
-
157
- ## Contributing
158
-
159
- Contributions are welcome! Please feel free to submit a Pull Request.
160
-
161
- ## License
162
-
163
- This project is licensed under the Apache-2.0 License.
1
+ # @langgraph-js/sdk
2
+
3
+ ![npm version](https://img.shields.io/npm/v/@langgraph-js/sdk)
4
+ ![license](https://img.shields.io/npm/l/@langgraph-js/sdk)
5
+
6
+ > The missing UI SDK for LangGraph - seamlessly integrate your AI agents with frontend interfaces
7
+
8
+ ## Why @langgraph-js/sdk?
9
+
10
+ Building AI agent applications is complex, especially when you need to bridge the gap between LangGraph agents and interactive user interfaces. This SDK solves the critical challenges of frontend integration:
11
+
12
+ - **Provides a complete UI integration layer** - no more complex custom code to handle tools, streaming, and state management
13
+ - **Simplifies human-in-the-loop interactions** - easily incorporate user feedback within agent workflows
14
+ - **Handles edge cases automatically** - interruptions, errors, token management and more
15
+ - **Offers a rich set of UI components** - ready-to-use elements to display agent interactions
16
+
17
+ [DOCS](https://langgraph-js.netlify.app)
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ # Using npm
23
+ npm install @langgraph-js/sdk
24
+
25
+ # Using yarn
26
+ yarn add @langgraph-js/sdk
27
+
28
+ # Using pnpm
29
+ pnpm add @langgraph-js/sdk
30
+ ```
31
+
32
+ ## Key Features
33
+
34
+ ### Generative UI
35
+
36
+ - ✅ Custom Tool Messages
37
+ - ✅ Token Counter
38
+ - ✅ Stop Graph Progress
39
+ - ✅ Interrupt Handling
40
+ - ✅ Error Handling
41
+ - ✅ Spend Time Tracking
42
+ - ✅ Time Persistence
43
+
44
+ ### Frontend Actions
45
+
46
+ - ✅ Definition of Union Tools
47
+ - ✅ Frontend Functions As Tools
48
+ - ✅ Human-in-the-Loop Interaction
49
+ - ✅ Interrupt Mode
50
+
51
+ ### Authorization
52
+
53
+ - ✅ Cookie-Based Authentication
54
+ - ✅ Custom Token Authentication
55
+
56
+ ### Persistence
57
+
58
+ - ✅ Read History from LangGraph
59
+
60
+ ## Advanced Usage
61
+
62
+ ### Creating a Chat Store
63
+
64
+ You can easily create a reactive store for your LangGraph client:
65
+
66
+ ```typescript
67
+ import { createChatStore } from "@langgraph-js/sdk";
68
+
69
+ export const globalChatStore = createChatStore(
70
+ "agent",
71
+ {
72
+ // Custom LangGraph backend interaction
73
+ apiUrl: "http://localhost:8123",
74
+ // Custom headers for authentication
75
+ defaultHeaders: JSON.parse(localStorage.getItem("code") || "{}"),
76
+ callerOptions: {
77
+ // Example for including cookies
78
+ // fetch(url: string, options: RequestInit) {
79
+ // options.credentials = "include";
80
+ // return fetch(url, options);
81
+ // },
82
+ },
83
+ },
84
+ {
85
+ onInit(client) {
86
+ client.tools.bindTools([]);
87
+ },
88
+ }
89
+ );
90
+ ```
91
+
92
+ ### React Integration
93
+
94
+ First, install the nanostores React integration:
95
+
96
+ ```bash
97
+ pnpm i @nanostores/react
98
+ ```
99
+
100
+ Then create a context provider for your chat:
101
+
102
+ ```tsx
103
+ import React, { createContext, useContext, useEffect } from "react";
104
+ import { globalChatStore } from "../store"; // Import your store
105
+ import { UnionStore, useUnionStore } from "@langgraph-js/sdk";
106
+ import { useStore } from "@nanostores/react";
107
+
108
+ type ChatContextType = UnionStore<typeof globalChatStore>;
109
+
110
+ const ChatContext = createContext<ChatContextType | undefined>(undefined);
111
+
112
+ export const useChat = () => {
113
+ const context = useContext(ChatContext);
114
+ if (!context) {
115
+ throw new Error("useChat must be used within a ChatProvider");
116
+ }
117
+ return context;
118
+ };
119
+
120
+ export const ChatProvider = ({ children }) => {
121
+ // Use store to ensure React gets reactive state updates
122
+ const store = useUnionStore(globalChatStore, useStore);
123
+
124
+ useEffect(() => {
125
+ // Initialize client
126
+ store.initClient().then(() => {
127
+ // Initialize conversation history
128
+ store.refreshHistoryList();
129
+ });
130
+ }, [store.currentAgent]);
131
+
132
+ return <ChatContext.Provider value={store}>{children}</ChatContext.Provider>;
133
+ };
134
+ ```
135
+
136
+ Use it in your components:
137
+
138
+ ```tsx
139
+ export const MyChat = () => {
140
+ return (
141
+ <ChatProvider>
142
+ <ChatComp></ChatComp>
143
+ </ChatProvider>
144
+ );
145
+ };
146
+
147
+ function ChatComp() {
148
+ const chat = useChat();
149
+ // Use chat store methods and state here
150
+ }
151
+ ```
152
+
153
+ ## Documentation
154
+
155
+ For complete documentation, visit our [official docs](https://langgraph-js.netlify.app).
156
+
157
+ ## Contributing
158
+
159
+ Contributions are welcome! Please feel free to submit a Pull Request.
160
+
161
+ ## License
162
+
163
+ This project is licensed under the Apache-2.0 License.
@@ -1,4 +1,4 @@
1
- import { Client, Thread, Message, Assistant, HumanMessage, ToolMessage, Command } from "@langchain/langgraph-sdk";
1
+ import { Client, Thread, Message, Assistant, HumanMessage, AIMessage, ToolMessage, Command } from "@langchain/langgraph-sdk";
2
2
  import { ToolManager } from "./ToolManager.js";
3
3
  import { CallToolResult } from "./tool/createTool.js";
4
4
  interface AsyncCallerParams {
@@ -71,8 +71,8 @@ export interface LangGraphClientConfig {
71
71
  export declare class StreamingMessageType {
72
72
  static isUser(m: Message): m is HumanMessage;
73
73
  static isTool(m: Message): m is ToolMessage;
74
- static isAssistant(m: Message): boolean;
75
- static isToolAssistant(m: Message): any;
74
+ static isAssistant(m: Message): m is AIMessage;
75
+ static isToolAssistant(m: Message): m is AIMessage;
76
76
  }
77
77
  type StreamingUpdateEvent = {
78
78
  type: "message" | "value" | "update" | "error" | "thread" | "done" | "start";
@@ -120,7 +120,6 @@ export declare class LangGraphClient extends Client {
120
120
  graphMessages: RenderMessage[];
121
121
  cloneMessage(message: Message): Message;
122
122
  private updateStreamingMessage;
123
- private replaceMessageWithValuesMessage;
124
123
  /** 将 graphMessages 和 streamingMessage 合并,并返回新的消息数组 */
125
124
  private combineGraphMessagesWithStreamingMessages;
126
125
  /**
@@ -167,6 +166,16 @@ export declare class LangGraphClient extends Client {
167
166
  * @en Sends a message to the LangGraph backend.
168
167
  */
169
168
  sendMessage(input: string | Message[], { extraParams, _debug, command }?: SendMessageOptions): Promise<any[]>;
169
+ /** 当前子图位置,但是依赖 stream,不太适合稳定使用*/
170
+ private graphPosition;
171
+ getGraphPosition(): {
172
+ id: string;
173
+ name: string;
174
+ }[];
175
+ getGraphNodeNow(): {
176
+ id: string;
177
+ name: string;
178
+ };
170
179
  /** 子图的数据需要通过 merge 的方式重新进行合并更新 */
171
180
  private mergeSubGraphMessagesToStreamingMessages;
172
181
  private runFETool;
@@ -37,6 +37,8 @@ export class LangGraphClient extends Client {
37
37
  /** 图发过来的更新信息 */
38
38
  this.graphMessages = [];
39
39
  this.graphState = {};
40
+ /** 当前子图位置,但是依赖 stream,不太适合稳定使用*/
41
+ this.graphPosition = "";
40
42
  }
41
43
  listAssistants() {
42
44
  return this.assistants.search({
@@ -134,18 +136,6 @@ export class LangGraphClient extends Client {
134
136
  }
135
137
  this.streamingMessage[this.streamingMessage.length - 1] = message;
136
138
  }
137
- replaceMessageWithValuesMessage(message, isTool = false) {
138
- const key = (isTool ? "tool_call_id" : "id");
139
- const valuesMessage = this.graphMessages.find((i) => i[key] === message[key]);
140
- if (valuesMessage) {
141
- return {
142
- ...valuesMessage,
143
- /** @ts-ignore */
144
- tool_input: message.tool_input,
145
- };
146
- }
147
- return message;
148
- }
149
139
  /** 将 graphMessages 和 streamingMessage 合并,并返回新的消息数组 */
150
140
  combineGraphMessagesWithStreamingMessages() {
151
141
  const idMap = new Map(this.streamingMessage.map((i) => [i.id, i]));
@@ -171,6 +161,7 @@ export class LangGraphClient extends Client {
171
161
  const closedToolCallIds = new Set();
172
162
  const result = [];
173
163
  const inputMessages = this.combineGraphMessagesWithStreamingMessages();
164
+ console.log(inputMessages);
174
165
  // 从后往前遍历,这样可以保证最新的消息在前面
175
166
  for (let i = inputMessages.length - 1; i >= 0; i--) {
176
167
  const message = this.cloneMessage(inputMessages[i]);
@@ -178,8 +169,13 @@ export class LangGraphClient extends Client {
178
169
  result.unshift(message);
179
170
  continue;
180
171
  }
172
+ if (message.type === "ai") {
173
+ /** @ts-ignore */
174
+ if (!message.name)
175
+ message.name = this.getGraphNodeNow().name;
176
+ }
181
177
  if (StreamingMessageType.isToolAssistant(message)) {
182
- const m = this.replaceMessageWithValuesMessage(message);
178
+ const m = message;
183
179
  // 记录这个 id 的消息,并添加到结果中
184
180
  previousMessage.set(message.id, m);
185
181
  /** @ts-ignore */
@@ -190,7 +186,7 @@ export class LangGraphClient extends Client {
190
186
  })
191
187
  .map((tool, index) => {
192
188
  var _a, _b, _c, _d;
193
- return this.replaceMessageWithValuesMessage({
189
+ return {
194
190
  type: "tool",
195
191
  additional_kwargs: {},
196
192
  /** @ts-ignore */
@@ -199,7 +195,8 @@ export class LangGraphClient extends Client {
199
195
  name: tool.name,
200
196
  response_metadata: {},
201
197
  tool_call_id: tool.id,
202
- }, true);
198
+ content: "",
199
+ };
203
200
  });
204
201
  for (const tool of new_tool_calls) {
205
202
  if (!previousMessage.has(tool.id)) {
@@ -213,10 +210,8 @@ export class LangGraphClient extends Client {
213
210
  if (message.type === "tool" && message.tool_call_id) {
214
211
  closedToolCallIds.add(message.tool_call_id);
215
212
  }
216
- // 记录这个 id 的消息,并添加到结果中
217
- const m = this.replaceMessageWithValuesMessage(message);
218
- previousMessage.set(message.id, m);
219
- result.unshift(m);
213
+ previousMessage.set(message.id, message);
214
+ result.unshift(message);
220
215
  }
221
216
  }
222
217
  return this.attachInfoForMessage(this.composeToolMessages(result));
@@ -255,7 +250,7 @@ export class LangGraphClient extends Client {
255
250
  * @en Composes tool messages, associating AI tool calls with tool execution results.
256
251
  */
257
252
  composeToolMessages(messages) {
258
- var _a;
253
+ var _a, _b;
259
254
  const result = [];
260
255
  const assistantToolMessages = new Map();
261
256
  const toolParentMessage = new Map();
@@ -288,6 +283,10 @@ export class LangGraphClient extends Client {
288
283
  if (parentMessage) {
289
284
  message.usage_metadata = parentMessage.usage_metadata;
290
285
  message.node_name = parentMessage.name;
286
+ // 修补特殊情况下,tool name 丢失的问题
287
+ if (!message.name) {
288
+ message.name = (_b = parentMessage.tool_calls.find((i) => i.id === message.tool_call_id)) === null || _b === void 0 ? void 0 : _b.name;
289
+ }
291
290
  }
292
291
  }
293
292
  result.push(message);
@@ -347,6 +346,7 @@ export class LangGraphClient extends Client {
347
346
  * @en Sends a message to the LangGraph backend.
348
347
  */
349
348
  async sendMessage(input, { extraParams, _debug, command } = {}) {
349
+ var _a;
350
350
  if (!this.currentAssistant) {
351
351
  throw new Error("Thread or Assistant not initialized");
352
352
  }
@@ -424,9 +424,10 @@ export class LangGraphClient extends Client {
424
424
  }
425
425
  else if (chunk.event.startsWith("values|")) {
426
426
  // 这个 values 必然是子 values
427
- if (chunk.data.messages) {
427
+ if ((_a = chunk.data) === null || _a === void 0 ? void 0 : _a.messages) {
428
428
  this.mergeSubGraphMessagesToStreamingMessages(chunk.data.messages);
429
429
  }
430
+ this.graphPosition = chunk.event.split("|")[1];
430
431
  }
431
432
  }
432
433
  const data = await this.runFETool();
@@ -441,6 +442,19 @@ export class LangGraphClient extends Client {
441
442
  this.streamingMessage = [];
442
443
  return streamRecord;
443
444
  }
445
+ getGraphPosition() {
446
+ return this.graphPosition.split("|").map((i) => {
447
+ const [name, id] = i.split(":");
448
+ return {
449
+ id,
450
+ name,
451
+ };
452
+ });
453
+ }
454
+ getGraphNodeNow() {
455
+ const position = this.getGraphPosition();
456
+ return position[position.length - 1];
457
+ }
444
458
  /** 子图的数据需要通过 merge 的方式重新进行合并更新 */
445
459
  mergeSubGraphMessagesToStreamingMessages(messages) {
446
460
  const map = new Map(messages.filter((i) => i.id).map((i) => [i.id, i]));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langgraph-js/sdk",
3
- "version": "1.6.0",
3
+ "version": "1.6.2",
4
4
  "description": "The UI SDK for LangGraph - seamlessly integrate your AI agents with frontend interfaces",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",