@assistant-ui/react-langgraph 0.4.5 → 0.5.1

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 (37) hide show
  1. package/dist/LangGraphMessageAccumulator.d.ts +20 -0
  2. package/dist/LangGraphMessageAccumulator.d.ts.map +1 -0
  3. package/dist/LangGraphMessageAccumulator.js +36 -0
  4. package/dist/LangGraphMessageAccumulator.js.map +1 -0
  5. package/dist/appendLangChainChunk.d.ts +3 -0
  6. package/dist/appendLangChainChunk.d.ts.map +1 -0
  7. package/dist/appendLangChainChunk.js +44 -0
  8. package/dist/appendLangChainChunk.js.map +1 -0
  9. package/dist/convertLangChainMessages.d.ts +3 -0
  10. package/dist/convertLangChainMessages.d.ts.map +1 -0
  11. package/dist/convertLangChainMessages.js +71 -0
  12. package/dist/convertLangChainMessages.js.map +1 -0
  13. package/dist/index.d.ts +11 -150
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +16 -415
  16. package/dist/index.js.map +1 -1
  17. package/dist/types.d.ts +66 -0
  18. package/dist/types.d.ts.map +1 -0
  19. package/dist/types.js +1 -0
  20. package/dist/types.js.map +1 -0
  21. package/dist/useLangGraphMessages.d.ts +34 -0
  22. package/dist/useLangGraphMessages.d.ts.map +1 -0
  23. package/dist/useLangGraphMessages.js +53 -0
  24. package/dist/useLangGraphMessages.js.map +1 -0
  25. package/dist/useLangGraphRuntime.js +195 -0
  26. package/dist/useLangGraphRuntime.js.map +1 -0
  27. package/package.json +17 -17
  28. package/src/LangGraphMessageAccumulator.ts +63 -0
  29. package/src/appendLangChainChunk.ts +55 -0
  30. package/src/convertLangChainMessages.ts +81 -0
  31. package/src/index.ts +31 -0
  32. package/src/types.ts +76 -0
  33. package/src/useLangGraphMessages.ts +102 -0
  34. package/src/useLangGraphRuntime.ts +273 -0
  35. package/dist/index.d.mts +0 -150
  36. package/dist/index.mjs +0 -394
  37. package/dist/index.mjs.map +0 -1
@@ -0,0 +1,102 @@
1
+ import { useState, useCallback, useRef } from "react";
2
+ import { v4 as uuidv4 } from "uuid";
3
+ import { LangGraphMessageAccumulator } from "./LangGraphMessageAccumulator";
4
+
5
+ export type LangGraphCommand = {
6
+ resume: string;
7
+ };
8
+
9
+ export type LangGraphSendMessageConfig = {
10
+ command?: LangGraphCommand;
11
+ runConfig?: unknown;
12
+ };
13
+
14
+ export type LangGraphMessagesEvent<TMessage> = {
15
+ event:
16
+ | "messages"
17
+ | "messages/partial"
18
+ | "messages/complete"
19
+ | "metadata"
20
+ | "updates"
21
+ | string;
22
+ data: TMessage[] | any;
23
+ };
24
+ export type LangGraphStreamCallback<TMessage> = (
25
+ messages: TMessage[],
26
+ config: LangGraphSendMessageConfig & { abortSignal: AbortSignal },
27
+ ) =>
28
+ | Promise<AsyncGenerator<LangGraphMessagesEvent<TMessage>>>
29
+ | AsyncGenerator<LangGraphMessagesEvent<TMessage>>;
30
+
31
+ export type LangGraphInterruptState = {
32
+ value?: any;
33
+ resumable?: boolean;
34
+ when: string;
35
+ ns?: string[];
36
+ };
37
+
38
+ const DEFAULT_APPEND_MESSAGE = <TMessage>(
39
+ _: TMessage | undefined,
40
+ curr: TMessage,
41
+ ) => curr;
42
+
43
+ export const useLangGraphMessages = <TMessage extends { id?: string }>({
44
+ stream,
45
+ appendMessage = DEFAULT_APPEND_MESSAGE,
46
+ }: {
47
+ stream: LangGraphStreamCallback<TMessage>;
48
+ appendMessage?: (prev: TMessage | undefined, curr: TMessage) => TMessage;
49
+ }) => {
50
+ const [interrupt, setInterrupt] = useState<
51
+ LangGraphInterruptState | undefined
52
+ >();
53
+ const [messages, setMessages] = useState<TMessage[]>([]);
54
+ const abortControllerRef = useRef<AbortController | null>(null);
55
+
56
+ const sendMessage = useCallback(
57
+ async (newMessages: TMessage[], config: LangGraphSendMessageConfig) => {
58
+ // ensure all messages have an ID
59
+ newMessages = newMessages.map((m) => (m.id ? m : { ...m, id: uuidv4() }));
60
+
61
+ const accumulator = new LangGraphMessageAccumulator({
62
+ initialMessages: messages,
63
+ appendMessage,
64
+ });
65
+ setMessages(accumulator.addMessages(newMessages));
66
+
67
+ const abortController = new AbortController();
68
+ abortControllerRef.current = abortController;
69
+ const response = await stream(newMessages, {
70
+ ...config,
71
+ abortSignal: abortController.signal,
72
+ });
73
+
74
+ for await (const chunk of response) {
75
+ if (
76
+ chunk.event === "messages/partial" ||
77
+ chunk.event === "messages/complete"
78
+ ) {
79
+ setMessages(accumulator.addMessages(chunk.data));
80
+ } else if (chunk.event === "updates") {
81
+ setInterrupt(chunk.data.__interrupt__?.[0]);
82
+ }
83
+ }
84
+ },
85
+ [messages, stream, appendMessage],
86
+ );
87
+
88
+ const cancel = useCallback(() => {
89
+ if (abortControllerRef.current) {
90
+ abortControllerRef.current.abort();
91
+ }
92
+ }, [abortControllerRef]);
93
+
94
+ return {
95
+ interrupt,
96
+ messages,
97
+ sendMessage,
98
+ cancel,
99
+ setInterrupt,
100
+ setMessages,
101
+ };
102
+ };
@@ -0,0 +1,273 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { LangChainMessage, LangChainToolCall } from "./types";
3
+ import {
4
+ useExternalMessageConverter,
5
+ useExternalStoreRuntime,
6
+ useThread,
7
+ useThreadListItemRuntime,
8
+ } from "@assistant-ui/react";
9
+ import { convertLangChainMessages } from "./convertLangChainMessages";
10
+ import {
11
+ LangGraphCommand,
12
+ LangGraphInterruptState,
13
+ LangGraphSendMessageConfig,
14
+ LangGraphStreamCallback,
15
+ useLangGraphMessages,
16
+ } from "./useLangGraphMessages";
17
+ import { AttachmentAdapter } from "@assistant-ui/react";
18
+ import { AppendMessage } from "@assistant-ui/react";
19
+ import { ExternalStoreAdapter } from "@assistant-ui/react";
20
+ import { FeedbackAdapter } from "@assistant-ui/react";
21
+ import { SpeechSynthesisAdapter } from "@assistant-ui/react";
22
+ import { appendLangChainChunk } from "./appendLangChainChunk";
23
+
24
+ const getPendingToolCalls = (messages: LangChainMessage[]) => {
25
+ const pendingToolCalls = new Map<string, LangChainToolCall>();
26
+ for (const message of messages) {
27
+ if (message.type === "ai") {
28
+ for (const toolCall of message.tool_calls ?? []) {
29
+ pendingToolCalls.set(toolCall.id, toolCall);
30
+ }
31
+ }
32
+ if (message.type === "tool") {
33
+ pendingToolCalls.delete(message.tool_call_id);
34
+ }
35
+ }
36
+
37
+ return [...pendingToolCalls.values()];
38
+ };
39
+
40
+ const getMessageContent = (msg: AppendMessage) => {
41
+ const allContent = [
42
+ ...msg.content,
43
+ ...(msg.attachments?.flatMap((a) => a.content) ?? []),
44
+ ];
45
+ const content = allContent.map((part) => {
46
+ const type = part.type;
47
+ switch (type) {
48
+ case "text":
49
+ return { type: "text" as const, text: part.text };
50
+ case "image":
51
+ return { type: "image_url" as const, image_url: { url: part.image } };
52
+
53
+ case "tool-call":
54
+ throw new Error("Tool call appends are not supported.");
55
+
56
+ default:
57
+ const _exhaustiveCheck: "reasoning" | "source" | "file" | "audio" =
58
+ type;
59
+ throw new Error(
60
+ `Unsupported append content part type: ${_exhaustiveCheck}`,
61
+ );
62
+ }
63
+ });
64
+
65
+ if (content.length === 1 && content[0]?.type === "text") {
66
+ return content[0].text ?? "";
67
+ }
68
+
69
+ return content;
70
+ };
71
+
72
+ const symbolLangGraphRuntimeExtras = Symbol("langgraph-runtime-extras");
73
+ type LangGraphRuntimeExtras = {
74
+ [symbolLangGraphRuntimeExtras]: true;
75
+ send: (
76
+ messages: LangChainMessage[],
77
+ config: LangGraphSendMessageConfig,
78
+ ) => Promise<void>;
79
+ interrupt: LangGraphInterruptState | undefined;
80
+ };
81
+
82
+ const asLangGraphRuntimeExtras = (extras: unknown): LangGraphRuntimeExtras => {
83
+ if (
84
+ typeof extras !== "object" ||
85
+ extras == null ||
86
+ !(symbolLangGraphRuntimeExtras in extras)
87
+ )
88
+ throw new Error(
89
+ "This method can only be called when you are using useLangGraphRuntime",
90
+ );
91
+
92
+ return extras as LangGraphRuntimeExtras;
93
+ };
94
+
95
+ export const useLangGraphInterruptState = () => {
96
+ const { interrupt } = useThread((t) => asLangGraphRuntimeExtras(t.extras));
97
+ return interrupt;
98
+ };
99
+
100
+ export const useLangGraphSend = () => {
101
+ const { send } = useThread((t) => asLangGraphRuntimeExtras(t.extras));
102
+ return send;
103
+ };
104
+
105
+ export const useLangGraphSendCommand = () => {
106
+ const send = useLangGraphSend();
107
+ return (command: LangGraphCommand) => send([], { command });
108
+ };
109
+
110
+ export const useLangGraphRuntime = ({
111
+ autoCancelPendingToolCalls,
112
+ adapters: { attachments, feedback, speech } = {},
113
+ unstable_allowCancellation,
114
+ stream,
115
+ threadId,
116
+ onSwitchToNewThread,
117
+ onSwitchToThread,
118
+ }: {
119
+ /**
120
+ * @deprecated For thread management use `useCloudThreadListRuntime` instead. This option will be removed in a future version.
121
+ */
122
+ threadId?: string | undefined;
123
+ autoCancelPendingToolCalls?: boolean | undefined;
124
+ unstable_allowCancellation?: boolean | undefined;
125
+ stream: LangGraphStreamCallback<LangChainMessage>;
126
+ /**
127
+ * @deprecated For thread management use `useCloudThreadListRuntime` instead. This option will be removed in a future version.
128
+ */
129
+ onSwitchToNewThread?: () => Promise<void> | void;
130
+ onSwitchToThread?: (threadId: string) => Promise<{
131
+ messages: LangChainMessage[];
132
+ interrupts?: LangGraphInterruptState[];
133
+ }>;
134
+ adapters?:
135
+ | {
136
+ attachments?: AttachmentAdapter;
137
+ speech?: SpeechSynthesisAdapter;
138
+ feedback?: FeedbackAdapter;
139
+ }
140
+ | undefined;
141
+ }) => {
142
+ const {
143
+ interrupt,
144
+ setInterrupt,
145
+ messages,
146
+ sendMessage,
147
+ cancel,
148
+ setMessages,
149
+ } = useLangGraphMessages({
150
+ appendMessage: appendLangChainChunk,
151
+ stream,
152
+ });
153
+
154
+ const [isRunning, setIsRunning] = useState(false);
155
+ const handleSendMessage = async (
156
+ messages: LangChainMessage[],
157
+ config: LangGraphSendMessageConfig,
158
+ ) => {
159
+ try {
160
+ setIsRunning(true);
161
+ await sendMessage(messages, config);
162
+ } catch (error) {
163
+ console.error("Error streaming messages:", error);
164
+ } finally {
165
+ setIsRunning(false);
166
+ }
167
+ };
168
+
169
+ const threadMessages = useExternalMessageConverter({
170
+ callback: convertLangChainMessages,
171
+ messages,
172
+ isRunning,
173
+ });
174
+
175
+ const switchToThread = !onSwitchToThread
176
+ ? undefined
177
+ : async (externalId: string) => {
178
+ const { messages, interrupts } = await onSwitchToThread(externalId);
179
+ setMessages(messages);
180
+ setInterrupt(interrupts?.[0]);
181
+ };
182
+
183
+ const threadList: NonNullable<
184
+ ExternalStoreAdapter["adapters"]
185
+ >["threadList"] = {
186
+ threadId,
187
+ onSwitchToNewThread: !onSwitchToNewThread
188
+ ? undefined
189
+ : async () => {
190
+ await onSwitchToNewThread();
191
+ setMessages([]);
192
+ },
193
+ onSwitchToThread: switchToThread,
194
+ };
195
+
196
+ const loadingRef = useRef(false);
197
+ const threadListItemRuntime = useThreadListItemRuntime({ optional: true });
198
+ useEffect(() => {
199
+ if (!threadListItemRuntime || !switchToThread || loadingRef.current) return;
200
+
201
+ const externalId = threadListItemRuntime.getState().externalId;
202
+ if (externalId) {
203
+ loadingRef.current = true;
204
+ switchToThread(externalId).finally(() => {
205
+ loadingRef.current = false;
206
+ });
207
+ }
208
+ // eslint-disable-next-line react-hooks/exhaustive-deps
209
+ }, []);
210
+
211
+ return useExternalStoreRuntime({
212
+ isRunning,
213
+ messages: threadMessages,
214
+ adapters: {
215
+ attachments,
216
+ feedback,
217
+ speech,
218
+ threadList,
219
+ },
220
+ extras: {
221
+ [symbolLangGraphRuntimeExtras]: true,
222
+ interrupt,
223
+ send: handleSendMessage,
224
+ } satisfies LangGraphRuntimeExtras,
225
+ onNew: (msg) => {
226
+ const cancellations =
227
+ autoCancelPendingToolCalls !== false
228
+ ? getPendingToolCalls(messages).map(
229
+ (t) =>
230
+ ({
231
+ type: "tool",
232
+ name: t.name,
233
+ tool_call_id: t.id,
234
+ content: JSON.stringify({ cancelled: true }),
235
+ }) satisfies LangChainMessage & { type: "tool" },
236
+ )
237
+ : [];
238
+
239
+ return handleSendMessage(
240
+ [
241
+ ...cancellations,
242
+ {
243
+ type: "human",
244
+ content: getMessageContent(msg),
245
+ },
246
+ ],
247
+ {
248
+ runConfig: msg.runConfig,
249
+ },
250
+ );
251
+ },
252
+ onAddToolResult: async ({ toolCallId, toolName, result }) => {
253
+ // TODO parallel human in the loop calls
254
+ await handleSendMessage(
255
+ [
256
+ {
257
+ type: "tool",
258
+ name: toolName,
259
+ tool_call_id: toolCallId,
260
+ content: JSON.stringify(result),
261
+ },
262
+ ],
263
+ // TODO reuse runconfig here!
264
+ {},
265
+ );
266
+ },
267
+ onCancel: unstable_allowCancellation
268
+ ? async () => {
269
+ cancel();
270
+ }
271
+ : undefined,
272
+ });
273
+ };
package/dist/index.d.mts DELETED
@@ -1,150 +0,0 @@
1
- import * as _assistant_ui_react_internal from '@assistant-ui/react/internal';
2
- import { ReadonlyJSONObject } from 'assistant-stream/utils';
3
- import * as react from 'react';
4
- import { AttachmentAdapter, SpeechSynthesisAdapter, FeedbackAdapter, useExternalMessageConverter } from '@assistant-ui/react';
5
-
6
- type LangChainToolCallChunk = {
7
- index: number;
8
- id: string;
9
- name: string;
10
- args: string;
11
- };
12
- type LangChainToolCall = {
13
- id: string;
14
- name: string;
15
- argsText: string;
16
- args: ReadonlyJSONObject;
17
- };
18
- type MessageContentText = {
19
- type: "text";
20
- text: string;
21
- };
22
- type MessageContentImageUrl = {
23
- type: "image_url";
24
- image_url: string | {
25
- url: string;
26
- };
27
- };
28
- type MessageContentToolUse = {
29
- type: "tool_use";
30
- };
31
- type UserMessageContentComplex = MessageContentText | MessageContentImageUrl;
32
- type AssistantMessageContentComplex = MessageContentText | MessageContentToolUse;
33
- type UserMessageContent = string | UserMessageContentComplex[];
34
- type AssistantMessageContent = string | AssistantMessageContentComplex[];
35
- type LangChainMessage = {
36
- id?: string;
37
- type: "system";
38
- content: string;
39
- } | {
40
- id?: string;
41
- type: "human";
42
- content: UserMessageContent;
43
- } | {
44
- id?: string;
45
- type: "tool";
46
- content: string;
47
- tool_call_id: string;
48
- name: string;
49
- artifact?: any;
50
- } | {
51
- id?: string;
52
- type: "ai";
53
- content: AssistantMessageContent;
54
- tool_call_chunks?: LangChainToolCallChunk[];
55
- tool_calls?: LangChainToolCall[];
56
- };
57
- type LangChainMessageChunk = {
58
- id: string;
59
- type: "AIMessageChunk";
60
- content: (AssistantMessageContentComplex & {
61
- index: number;
62
- })[];
63
- tool_call_chunks: LangChainToolCallChunk[];
64
- };
65
- type LangChainEvent = {
66
- event: "messages/partial" | "messages/complete";
67
- data: LangChainMessage[];
68
- };
69
-
70
- type LangGraphCommand = {
71
- resume: string;
72
- };
73
- type LangGraphSendMessageConfig = {
74
- command?: LangGraphCommand;
75
- runConfig?: unknown;
76
- };
77
- type LangGraphMessagesEvent<TMessage> = {
78
- event: "messages" | "messages/partial" | "messages/complete" | "metadata" | "updates" | string;
79
- data: TMessage[] | any;
80
- };
81
- type LangGraphStreamCallback<TMessage> = (messages: TMessage[], config: LangGraphSendMessageConfig & {
82
- abortSignal: AbortSignal;
83
- }) => Promise<AsyncGenerator<LangGraphMessagesEvent<TMessage>>> | AsyncGenerator<LangGraphMessagesEvent<TMessage>>;
84
- type LangGraphInterruptState = {
85
- value?: any;
86
- resumable?: boolean;
87
- when: string;
88
- ns?: string[];
89
- };
90
- declare const useLangGraphMessages: <TMessage extends {
91
- id?: string;
92
- }>({ stream, appendMessage, }: {
93
- stream: LangGraphStreamCallback<TMessage>;
94
- appendMessage?: (prev: TMessage | undefined, curr: TMessage) => TMessage;
95
- }) => {
96
- interrupt: LangGraphInterruptState | undefined;
97
- messages: TMessage[];
98
- sendMessage: (newMessages: TMessage[], config: LangGraphSendMessageConfig) => Promise<void>;
99
- cancel: () => void;
100
- setInterrupt: react.Dispatch<react.SetStateAction<LangGraphInterruptState | undefined>>;
101
- setMessages: react.Dispatch<react.SetStateAction<TMessage[]>>;
102
- };
103
-
104
- declare const useLangGraphInterruptState: () => LangGraphInterruptState | undefined;
105
- declare const useLangGraphSend: () => (messages: LangChainMessage[], config: LangGraphSendMessageConfig) => Promise<void>;
106
- declare const useLangGraphSendCommand: () => (command: LangGraphCommand) => Promise<void>;
107
- declare const useLangGraphRuntime: ({ autoCancelPendingToolCalls, adapters: { attachments, feedback, speech }, unstable_allowCancellation, stream, threadId, onSwitchToNewThread, onSwitchToThread, }: {
108
- /**
109
- * @deprecated For thread management use `useCloudThreadListRuntime` instead. This option will be removed in a future version.
110
- */
111
- threadId?: string | undefined;
112
- autoCancelPendingToolCalls?: boolean | undefined;
113
- unstable_allowCancellation?: boolean | undefined;
114
- stream: LangGraphStreamCallback<LangChainMessage>;
115
- /**
116
- * @deprecated For thread management use `useCloudThreadListRuntime` instead. This option will be removed in a future version.
117
- */
118
- onSwitchToNewThread?: () => Promise<void> | void;
119
- onSwitchToThread?: (threadId: string) => Promise<{
120
- messages: LangChainMessage[];
121
- interrupts?: LangGraphInterruptState[];
122
- }>;
123
- adapters?: {
124
- attachments?: AttachmentAdapter;
125
- speech?: SpeechSynthesisAdapter;
126
- feedback?: FeedbackAdapter;
127
- } | undefined;
128
- }) => _assistant_ui_react_internal.AssistantRuntimeImpl;
129
-
130
- declare const convertLangChainMessages: useExternalMessageConverter.Callback<LangChainMessage>;
131
-
132
- type LangGraphStateAccumulatorConfig<TMessage> = {
133
- initialMessages?: TMessage[];
134
- appendMessage?: (prev: TMessage | undefined, curr: TMessage) => TMessage;
135
- };
136
- declare class LangGraphMessageAccumulator<TMessage extends {
137
- id?: string;
138
- }> {
139
- private messagesMap;
140
- private appendMessage;
141
- constructor({ initialMessages, appendMessage, }?: LangGraphStateAccumulatorConfig<TMessage>);
142
- private ensureMessageId;
143
- addMessages(newMessages: TMessage[]): TMessage[];
144
- getMessages(): TMessage[];
145
- clear(): void;
146
- }
147
-
148
- declare const appendLangChainChunk: (prev: LangChainMessage | undefined, curr: LangChainMessage | LangChainMessageChunk) => LangChainMessage;
149
-
150
- export { type LangChainEvent, type LangChainMessage, type LangChainToolCall, type LangChainToolCallChunk, type LangGraphCommand, type LangGraphInterruptState, LangGraphMessageAccumulator, type LangGraphSendMessageConfig, type LangGraphStreamCallback, appendLangChainChunk, convertLangChainMessages, convertLangChainMessages as convertLangchainMessages, useLangGraphInterruptState, useLangGraphMessages, useLangGraphRuntime, useLangGraphSend, useLangGraphSendCommand };