@langgraph-js/sdk 1.1.8 → 1.2.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.
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.
@@ -43,6 +43,8 @@ export type RenderMessage = Message & {
43
43
  spend_time?: number;
44
44
  /** 渲染时的唯一 id,聚合而来*/
45
45
  unique_id?: string;
46
+ /** 工具调用是否完成 */
47
+ done?: boolean;
46
48
  };
47
49
  export type SendMessageOptions = {
48
50
  extraParams?: Record<string, any>;
@@ -90,7 +92,7 @@ export declare class LangGraphClient extends Client {
90
92
  * @zh 初始化 Assistant。
91
93
  * @en Initializes the Assistant.
92
94
  */
93
- initAssistant(agentName: string): Promise<void>;
95
+ initAssistant(agentName?: string): Promise<void>;
94
96
  /**
95
97
  * @zh 创建一个新的 Thread。
96
98
  * @en Creates a new Thread.
@@ -98,6 +100,7 @@ export declare class LangGraphClient extends Client {
98
100
  createThread({ threadId, }?: {
99
101
  threadId?: string;
100
102
  }): Promise<Thread<import("@langchain/langgraph-sdk").DefaultValues>>;
103
+ graphVisualize(): Promise<import("@langchain/langgraph-sdk").AssistantGraph>;
101
104
  /**
102
105
  * @zh 列出所有的 Thread。
103
106
  * @en Lists all Threads.
@@ -54,9 +54,15 @@ export class LangGraphClient extends Client {
54
54
  const assistants = await this.listAssistants();
55
55
  this.availableAssistants = assistants;
56
56
  if (assistants.length > 0) {
57
- this.currentAssistant = assistants.find((assistant) => assistant.graph_id === agentName) || null;
58
- if (!this.currentAssistant) {
59
- throw new Error("Agent not found: " + agentName);
57
+ if (agentName) {
58
+ console.log("agentName", agentName);
59
+ this.currentAssistant = assistants.find((assistant) => assistant.graph_id === agentName) || null;
60
+ if (!this.currentAssistant) {
61
+ throw new Error("Agent not found: " + agentName);
62
+ }
63
+ }
64
+ else {
65
+ this.currentAssistant = assistants[0];
60
66
  }
61
67
  }
62
68
  else {
@@ -84,6 +90,12 @@ export class LangGraphClient extends Client {
84
90
  throw error;
85
91
  }
86
92
  }
93
+ graphVisualize() {
94
+ var _a;
95
+ return this.assistants.getGraph((_a = this.currentAssistant) === null || _a === void 0 ? void 0 : _a.assistant_id, {
96
+ xray: true,
97
+ });
98
+ }
87
99
  /**
88
100
  * @zh 列出所有的 Thread。
89
101
  * @en Lists all Threads.
@@ -238,8 +250,10 @@ export class LangGraphClient extends Client {
238
250
  message.tool_input = typeof assistantToolMessage.args !== "string" ? JSON.stringify(assistantToolMessage.args) : assistantToolMessage.args;
239
251
  if (message.additional_kwargs) {
240
252
  message.additional_kwargs.done = true;
253
+ message.done = true;
241
254
  }
242
255
  else {
256
+ message.done = true;
243
257
  message.additional_kwargs = {
244
258
  done: true,
245
259
  };
@@ -1,5 +1,5 @@
1
1
  import { LangGraphClient, LangGraphClientConfig, RenderMessage, SendMessageOptions } from "../LangGraphClient.js";
2
- import { Message, Thread } from "@langchain/langgraph-sdk";
2
+ import { AssistantGraph, Message, Thread } from "@langchain/langgraph-sdk";
3
3
  /**
4
4
  * @zh 格式化日期对象为时间字符串。
5
5
  * @en Formats a Date object into a time string.
@@ -25,6 +25,8 @@ export declare const getHistoryContent: (thread: Thread) => string | any[];
25
25
  * @en Creates a state manager (store) for the chat interface.
26
26
  */
27
27
  export declare const createChatStore: (initClientName: string, config: LangGraphClientConfig, context?: {
28
+ showHistory?: boolean;
29
+ showGraph?: boolean;
28
30
  onInit?: (client: LangGraphClient) => void;
29
31
  }) => {
30
32
  data: {
@@ -40,9 +42,11 @@ export declare const createChatStore: (initClientName: string, config: LangGraph
40
42
  messages: Message[];
41
43
  }>[]> & object;
42
44
  currentChatId: import("nanostores").PreinitializedWritableAtom<string | null> & object;
45
+ showGraph: import("nanostores").PreinitializedWritableAtom<boolean> & object;
46
+ graphVisualize: import("nanostores").PreinitializedWritableAtom<AssistantGraph | null> & object;
43
47
  };
44
48
  mutations: {
45
- initClient: () => Promise<void>;
49
+ initClient: () => Promise<LangGraphClient>;
46
50
  sendMessage: (message?: Message[], extraData?: SendMessageOptions) => Promise<void>;
47
51
  stopGeneration: () => void;
48
52
  toggleToolCollapse: (toolId: string) => void;
@@ -61,6 +65,8 @@ export declare const createChatStore: (initClientName: string, config: LangGraph
61
65
  * @en Sets the current Agent and reinitializes the client.
62
66
  */
63
67
  setCurrentAgent(agent: string): Promise<void>;
68
+ toggleGraphVisible(): void;
69
+ refreshGraph: () => Promise<void>;
64
70
  /**
65
71
  * @zh 创建一个新的聊天会话。
66
72
  * @en Creates a new chat session.
@@ -1,5 +1,6 @@
1
1
  import { atom } from "nanostores";
2
2
  import { LangGraphClient } from "../LangGraphClient.js";
3
+ import { rafDebounce } from "./rafDebounce.js";
3
4
  /**
4
5
  * @zh 格式化日期对象为时间字符串。
5
6
  * @en Formats a Date object into a time string.
@@ -62,15 +63,27 @@ export const getHistoryContent = (thread) => {
62
63
  * @en Creates a state manager (store) for the chat interface.
63
64
  */
64
65
  export const createChatStore = (initClientName, config, context = {}) => {
66
+ var _a, _b;
65
67
  const client = atom(null);
66
68
  const renderMessages = atom([]);
67
69
  const userInput = atom("");
68
70
  const loading = atom(false);
69
71
  const collapsedTools = atom([]);
70
72
  const inChatError = atom(null);
71
- const showHistory = atom(true);
73
+ const showHistory = atom((_a = context.showHistory) !== null && _a !== void 0 ? _a : false);
72
74
  const currentAgent = atom(initClientName);
73
75
  const currentChatId = atom(null);
76
+ // 显示 langgraph 可视化图
77
+ const showGraph = atom((_b = context.showGraph) !== null && _b !== void 0 ? _b : false);
78
+ const graphVisualize = atom(null);
79
+ const refreshGraph = async () => {
80
+ var _a;
81
+ if (showGraph.get())
82
+ graphVisualize.set((await ((_a = client.get()) === null || _a === void 0 ? void 0 : _a.graphVisualize())) || null);
83
+ };
84
+ const updateUI = rafDebounce((newClient) => {
85
+ renderMessages.set(newClient.renderMessage);
86
+ });
74
87
  /**
75
88
  * @zh 初始化 LangGraph 客户端。
76
89
  * @en Initializes the LangGraph client.
@@ -79,6 +92,7 @@ export const createChatStore = (initClientName, config, context = {}) => {
79
92
  var _a;
80
93
  const newClient = new LangGraphClient(config);
81
94
  await newClient.initAssistant(currentAgent.get());
95
+ currentAgent.set(newClient.getCurrentAssistant().graph_id);
82
96
  // 不再需要创建,sendMessage 会自动创建
83
97
  // await newClient.createThread();
84
98
  inChatError.set(null);
@@ -93,13 +107,15 @@ export const createChatStore = (initClientName, config, context = {}) => {
93
107
  inChatError.set(event.data);
94
108
  }
95
109
  // console.log(newClient.renderMessage);
96
- renderMessages.set(newClient.renderMessage);
110
+ updateUI(newClient);
97
111
  });
98
112
  (_a = context.onInit) === null || _a === void 0 ? void 0 : _a.call(context, newClient);
99
113
  newClient.graphState = {};
100
114
  client.set(newClient);
115
+ if (showGraph.get())
116
+ refreshGraph();
117
+ return newClient;
101
118
  }
102
- ;
103
119
  /**
104
120
  * @zh 发送消息。
105
121
  * @en Sends a message.
@@ -136,6 +152,9 @@ export const createChatStore = (initClientName, config, context = {}) => {
136
152
  */
137
153
  const toggleHistoryVisible = () => {
138
154
  showHistory.set(!showHistory.get());
155
+ if (showHistory.get()) {
156
+ refreshHistoryList();
157
+ }
139
158
  };
140
159
  const historyList = atom([]);
141
160
  /**
@@ -174,6 +193,8 @@ export const createChatStore = (initClientName, config, context = {}) => {
174
193
  showHistory,
175
194
  historyList,
176
195
  currentChatId,
196
+ showGraph,
197
+ graphVisualize,
177
198
  },
178
199
  mutations: {
179
200
  initClient,
@@ -197,9 +218,21 @@ export const createChatStore = (initClientName, config, context = {}) => {
197
218
  setCurrentAgent(agent) {
198
219
  currentAgent.set(agent);
199
220
  return initClient().then(() => {
200
- refreshHistoryList();
221
+ if (showHistory.get()) {
222
+ refreshHistoryList();
223
+ }
224
+ if (showGraph.get()) {
225
+ refreshGraph();
226
+ }
201
227
  });
202
228
  },
229
+ toggleGraphVisible() {
230
+ showGraph.set(!showGraph.get());
231
+ if (showGraph.get()) {
232
+ refreshGraph();
233
+ }
234
+ },
235
+ refreshGraph,
203
236
  /**
204
237
  * @zh 创建一个新的聊天会话。
205
238
  * @en Creates a new chat session.
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Creates a debounced function that executes once per animation frame
3
+ * @param callback - The function to debounce
4
+ * @returns A function that executes the callback on the next animation frame
5
+ */
6
+ export declare function rafDebounce<T extends (...args: any[]) => any>(callback: T): (...args: Parameters<T>) => void;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Creates a debounced function that executes once per animation frame
3
+ * @param callback - The function to debounce
4
+ * @returns A function that executes the callback on the next animation frame
5
+ */
6
+ export function rafDebounce(callback) {
7
+ let rafId = null;
8
+ let lastArgs = null;
9
+ // Return the debounced function
10
+ return function (...args) {
11
+ // Store the most recent arguments
12
+ lastArgs = args;
13
+ // Cancel any pending animation frame
14
+ if (rafId !== null) {
15
+ cancelAnimationFrame(rafId);
16
+ }
17
+ // Schedule execution on the next animation frame
18
+ rafId = requestAnimationFrame(() => {
19
+ if (lastArgs !== null) {
20
+ callback(...lastArgs);
21
+ lastArgs = null;
22
+ }
23
+ rafId = null;
24
+ });
25
+ };
26
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langgraph-js/sdk",
3
- "version": "1.1.8",
3
+ "version": "1.2.0",
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",
@@ -29,7 +29,7 @@
29
29
  "url": "https://github.com/KonghaYao/YaoAgent/issues"
30
30
  },
31
31
  "dependencies": {
32
- "@langchain/langgraph-sdk": "^0.0.74",
32
+ "@langchain/langgraph-sdk": "^0.0.76",
33
33
  "nanostores": "^1.0.1",
34
34
  "zod": "^3.24.3",
35
35
  "zod-to-json-schema": "^3.24.3"