@assistant-ui/react-langchain 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AgentbaseAI Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ import type { useExternalMessageConverter } from "@assistant-ui/core/react";
2
+ import type { LangChainBaseMessage } from "./types.js";
3
+ export declare const convertLangChainBaseMessage: useExternalMessageConverter.Callback<LangChainBaseMessage>;
4
+ //# sourceMappingURL=convertMessages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertMessages.d.ts","sourceRoot":"","sources":["../src/convertMessages.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAE5E,OAAO,KAAK,EAAE,oBAAoB,EAAyB,mBAAgB;AAyD3E,eAAO,MAAM,2BAA2B,EAAE,2BAA2B,CAAC,QAAQ,CAC5E,oBAAoB,CA0ErB,CAAC"}
@@ -0,0 +1,115 @@
1
+ "use client";
2
+ const getMessageType = (message) => {
3
+ if (typeof message._getType === "function")
4
+ return message._getType();
5
+ if ("type" in message)
6
+ return message.type;
7
+ throw new Error("Cannot determine message type");
8
+ };
9
+ const contentToParts = (content) => {
10
+ if (typeof content === "string")
11
+ return [{ type: "text", text: content }];
12
+ const parts = content;
13
+ return parts
14
+ .map((part) => {
15
+ const type = part.type;
16
+ switch (type) {
17
+ case "text":
18
+ case "text_delta":
19
+ return { type: "text", text: part.text };
20
+ case "image_url":
21
+ if (typeof part.image_url === "string") {
22
+ return { type: "image", image: part.image_url };
23
+ }
24
+ return { type: "image", image: part.image_url.url };
25
+ case "thinking":
26
+ return { type: "reasoning", text: part.thinking };
27
+ case "reasoning":
28
+ return {
29
+ type: "reasoning",
30
+ text: part.summary.map((s) => s.text).join("\n\n\n"),
31
+ };
32
+ case "tool_use":
33
+ case "input_json_delta":
34
+ return null;
35
+ default:
36
+ return null;
37
+ }
38
+ })
39
+ .filter((p) => p !== null);
40
+ };
41
+ const getCustomMetadata = (additionalKwargs) => additionalKwargs?.metadata ?? {};
42
+ const getStringContent = (content) => {
43
+ if (typeof content === "string")
44
+ return content;
45
+ const parts = content;
46
+ return parts
47
+ .filter((c) => c.type === "text")
48
+ .map((c) => c.text)
49
+ .join("");
50
+ };
51
+ export const convertLangChainBaseMessage = (message) => {
52
+ const type = getMessageType(message);
53
+ switch (type) {
54
+ case "system":
55
+ return {
56
+ role: "system",
57
+ id: message.id,
58
+ content: [{ type: "text", text: getStringContent(message.content) }],
59
+ metadata: {
60
+ custom: getCustomMetadata(message.additional_kwargs),
61
+ },
62
+ };
63
+ case "human":
64
+ return {
65
+ role: "user",
66
+ id: message.id,
67
+ content: contentToParts(message.content),
68
+ metadata: {
69
+ custom: getCustomMetadata(message.additional_kwargs),
70
+ },
71
+ };
72
+ case "ai": {
73
+ const toolCallParts = message.tool_calls?.map((tc) => ({
74
+ type: "tool-call",
75
+ toolCallId: tc.id,
76
+ toolName: tc.name,
77
+ args: tc.args,
78
+ argsText: JSON.stringify(tc.args),
79
+ })) ?? [];
80
+ const assistantStatus = typeof message.status === "object" ? message.status : undefined;
81
+ return {
82
+ role: "assistant",
83
+ id: message.id,
84
+ content: [...contentToParts(message.content), ...toolCallParts],
85
+ metadata: {
86
+ custom: getCustomMetadata(message.additional_kwargs),
87
+ },
88
+ ...(assistantStatus && { status: assistantStatus }),
89
+ };
90
+ }
91
+ case "tool":
92
+ return {
93
+ role: "tool",
94
+ toolName: message.name ?? "",
95
+ toolCallId: message.tool_call_id ?? "",
96
+ result: message.content,
97
+ artifact: message.artifact,
98
+ isError: message.status === "error",
99
+ };
100
+ default:
101
+ return {
102
+ role: "system",
103
+ id: message.id,
104
+ content: [
105
+ {
106
+ type: "text",
107
+ text: typeof message.content === "string"
108
+ ? message.content
109
+ : JSON.stringify(message.content),
110
+ },
111
+ ],
112
+ };
113
+ }
114
+ };
115
+ //# sourceMappingURL=convertMessages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertMessages.js","sourceRoot":"","sources":["../src/convertMessages.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAMb,MAAM,cAAc,GAAG,CAAC,OAA6B,EAAU,EAAE;IAC/D,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC,QAAQ,EAAE,CAAC;IACtE,IAAI,MAAM,IAAI,OAAO;QACnB,OAAQ,OAAmC,CAAC,IAAc,CAAC;IAC7D,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC,CAAC;AAEF,MAAM,cAAc,GAAG,CAAC,OAAgB,EAAE,EAAE;IAC1C,IAAI,OAAO,OAAO,KAAK,QAAQ;QAC7B,OAAO,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IA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4BACjB,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC;qBACtC;iBACF;aACF,CAAC;IACN,CAAC;AACH,CAAC,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { useStreamRuntime, useLangChainInterruptState, useLangChainSubmit, } from "./useStreamRuntime.js";
2
+ export type { UseStreamRuntimeOptions } from "./useStreamRuntime.js";
3
+ export { convertLangChainBaseMessage } from "./convertMessages.js";
4
+ export type { LangChainBaseMessage, LangChainContentBlock, LangChainToolCall, } from "./types.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,0BAA0B,EAC1B,kBAAkB,GACnB,8BAA2B;AAC5B,YAAY,EAAE,uBAAuB,EAAE,8BAA2B;AAElE,OAAO,EAAE,2BAA2B,EAAE,6BAA0B;AAEhE,YAAY,EACV,oBAAoB,EACpB,qBAAqB,EACrB,iBAAiB,GAClB,mBAAgB"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { useStreamRuntime, useLangChainInterruptState, useLangChainSubmit, } from "./useStreamRuntime.js";
2
+ export { convertLangChainBaseMessage } from "./convertMessages.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,0BAA0B,EAC1B,kBAAkB,GACnB,8BAA2B;AAG5B,OAAO,EAAE,2BAA2B,EAAE,6BAA0B"}
@@ -0,0 +1,53 @@
1
+ import type { MessageStatus } from "@assistant-ui/core";
2
+ /** Known content block types from @langchain/core messages. */
3
+ export type LangChainContentBlock = {
4
+ type: "text";
5
+ text: string;
6
+ } | {
7
+ type: "text_delta";
8
+ text: string;
9
+ } | {
10
+ type: "image_url";
11
+ image_url: string | {
12
+ url: string;
13
+ };
14
+ } | {
15
+ type: "thinking";
16
+ thinking: string;
17
+ } | {
18
+ type: "reasoning";
19
+ summary: Array<{
20
+ type: "summary_text";
21
+ text: string;
22
+ }>;
23
+ } | {
24
+ type: "tool_use" | "input_json_delta";
25
+ };
26
+ export type LangChainToolCall = {
27
+ id: string;
28
+ name: string;
29
+ args: Record<string, unknown>;
30
+ };
31
+ /**
32
+ * Minimal duck-typed interface for BaseMessage class instances returned by
33
+ * `useStream`. Used internally by the message converter.
34
+ *
35
+ * Uses `unknown` for `content` to remain compatible with
36
+ * `@langchain/core`'s `MessageContent` union.
37
+ */
38
+ export type LangChainBaseMessage = {
39
+ _getType: () => string;
40
+ content: unknown;
41
+ id?: string | undefined;
42
+ name?: string | undefined;
43
+ additional_kwargs?: Record<string, unknown> | undefined;
44
+ /** Present on AIMessage */
45
+ tool_calls?: readonly LangChainToolCall[] | undefined;
46
+ /** Present on ToolMessage */
47
+ tool_call_id?: string | undefined;
48
+ /** Completion status (AIMessage) or outcome status (ToolMessage) */
49
+ status?: MessageStatus | "success" | "error" | undefined;
50
+ /** Present on ToolMessage */
51
+ artifact?: unknown;
52
+ };
53
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,+DAA+D;AAC/D,MAAM,MAAM,qBAAqB,GAC7B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,SAAS,EAAE,MAAM,GAAG;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GAC1D;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GACtC;IACE,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACxD,GACD;IAAE,IAAI,EAAE,UAAU,GAAG,kBAAkB,CAAA;CAAE,CAAC;AAE9C,MAAM,MAAM,iBAAiB,GAAG;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC/B,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,QAAQ,EAAE,MAAM,MAAM,CAAC;IACvB,OAAO,EAAE,OAAO,CAAC;IACjB,EAAE,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;IACxD,2BAA2B;IAC3B,UAAU,CAAC,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,CAAC;IACtD,6BAA6B;IAC7B,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,oEAAoE;IACpE,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;IACzD,6BAA6B;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,51 @@
1
+ import type { AttachmentAdapter, FeedbackAdapter, SpeechSynthesisAdapter } from "@assistant-ui/core";
2
+ import type { AssistantCloud } from "assistant-cloud";
3
+ import { type UseStreamOptions } from "@langchain/react";
4
+ export type UseStreamRuntimeOptions = UseStreamOptions & {
5
+ cloud?: AssistantCloud | undefined;
6
+ adapters?: {
7
+ attachments?: AttachmentAdapter | undefined;
8
+ speech?: SpeechSynthesisAdapter | undefined;
9
+ feedback?: FeedbackAdapter | undefined;
10
+ } | undefined;
11
+ /** The key in the LangGraph state that contains messages. Defaults to "messages". */
12
+ messagesKey?: string | undefined;
13
+ };
14
+ /**
15
+ * Creates an assistant-ui runtime backed by LangChain's `useStream` hook.
16
+ * Accepts the same options as `useStream` from `@langchain/react`, plus
17
+ * `cloud` and `adapters`.
18
+ *
19
+ * @example
20
+ * ```tsx
21
+ * import { useStreamRuntime } from "@assistant-ui/react-langchain";
22
+ * import { AssistantRuntimeProvider, Thread } from "@assistant-ui/react";
23
+ *
24
+ * function App() {
25
+ * const runtime = useStreamRuntime({
26
+ * assistantId: "agent",
27
+ * apiUrl: "http://localhost:2024",
28
+ * });
29
+ *
30
+ * return (
31
+ * <AssistantRuntimeProvider runtime={runtime}>
32
+ * <Thread />
33
+ * </AssistantRuntimeProvider>
34
+ * );
35
+ * }
36
+ * ```
37
+ */
38
+ export declare const useStreamRuntime: ({ cloud, ...options }: UseStreamRuntimeOptions) => import("@assistant-ui/core").AssistantRuntime;
39
+ /**
40
+ * Read the current LangGraph interrupt state from the runtime extras.
41
+ */
42
+ export declare const useLangChainInterruptState: () => {
43
+ value?: unknown;
44
+ } | undefined;
45
+ /**
46
+ * Returns a function to submit raw state updates to the LangGraph agent,
47
+ * bypassing the normal message flow. Useful for sending interrupt resume
48
+ * commands.
49
+ */
50
+ export declare const useLangChainSubmit: () => (values: Record<string, unknown> | null | undefined, options?: Record<string, unknown>) => Promise<void>;
51
+ //# sourceMappingURL=useStreamRuntime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useStreamRuntime.d.ts","sourceRoot":"","sources":["../src/useStreamRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,iBAAiB,EACjB,eAAe,EACf,sBAAsB,EACvB,MAAM,oBAAoB,CAAC;AAU5B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAa,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AA4BpE,MAAM,MAAM,uBAAuB,GAAG,gBAAgB,GAAG;IACvD,KAAK,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IACnC,QAAQ,CAAC,EACL;QACE,WAAW,CAAC,EAAE,iBAAiB,GAAG,SAAS,CAAC;QAC5C,MAAM,CAAC,EAAE,sBAAsB,GAAG,SAAS,CAAC;QAC5C,QAAQ,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC;KACxC,GACD,SAAS,CAAC;IACd,qFAAqF;IACrF,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAClC,CAAC;AAoKF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,gBAAgB,GAAI,uBAG9B,uBAAuB,kDAYzB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,0BAA0B;YA/OhB,OAAO;aAqP7B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,SAG3B,QAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,SAAS,EAClD,UAAU,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,kBAMpC,CAAC"}
@@ -0,0 +1,196 @@
1
+ "use client";
2
+ import { useMemo, useRef, useState } from "react";
3
+ import { useCloudThreadListAdapter, useExternalStoreRuntime, useExternalMessageConverter, useRemoteThreadListRuntime, useToolInvocations, } from "@assistant-ui/core/react";
4
+ import { useAui, useAuiState } from "@assistant-ui/store";
5
+ import { useStream } from "@langchain/react";
6
+ import { convertLangChainBaseMessage } from "./convertMessages.js";
7
+ const symbolLangChainRuntimeExtras = Symbol("langchain-runtime-extras");
8
+ const asLangChainRuntimeExtras = (extras) => {
9
+ if (typeof extras !== "object" ||
10
+ extras == null ||
11
+ !(symbolLangChainRuntimeExtras in extras))
12
+ throw new Error("This method can only be called when you are using useStreamRuntime");
13
+ return extras;
14
+ };
15
+ const getMessageContent = (msg) => {
16
+ const allContent = [
17
+ ...msg.content,
18
+ ...(msg.attachments?.flatMap((a) => a.content) ?? []),
19
+ ];
20
+ const hasNonText = allContent.some((part) => part.type === "file" || part.type === "image");
21
+ const hasText = allContent.some((part) => part.type === "text");
22
+ if (hasNonText && !hasText) {
23
+ allContent.unshift({ type: "text", text: " " });
24
+ }
25
+ const content = allContent.map((part) => {
26
+ const type = part.type;
27
+ switch (type) {
28
+ case "text":
29
+ return { type: "text", text: part.text };
30
+ case "image":
31
+ return { type: "image_url", image_url: { url: part.image } };
32
+ case "file":
33
+ return {
34
+ type: "file",
35
+ data: part.data,
36
+ mime_type: part.mimeType,
37
+ metadata: { filename: part.filename ?? "file" },
38
+ source_type: "base64",
39
+ };
40
+ case "tool-call":
41
+ throw new Error("Tool call appends are not supported.");
42
+ default: {
43
+ const _exhaustiveCheck = type;
44
+ throw new Error(`Unsupported append message part type: ${_exhaustiveCheck}`);
45
+ }
46
+ }
47
+ });
48
+ if (content.length === 1 && content[0]?.type === "text") {
49
+ return content[0].text ?? "";
50
+ }
51
+ return content;
52
+ };
53
+ const useStreamThreadRuntime = ({ adapters, messagesKey = "messages", ...streamOptions }) => {
54
+ const externalId = useAuiState((s) => s.threadListItem.externalId);
55
+ const stream = useStream({
56
+ ...streamOptions,
57
+ threadId: externalId,
58
+ });
59
+ const [toolStatuses, setToolStatuses] = useState({});
60
+ const hasExecutingTools = Object.values(toolStatuses).some((s) => s?.type === "executing");
61
+ const effectiveIsRunning = stream.isLoading || hasExecutingTools;
62
+ const threadMessages = useExternalMessageConverter({
63
+ callback: convertLangChainBaseMessage,
64
+ messages: stream.messages,
65
+ isRunning: effectiveIsRunning,
66
+ });
67
+ const [runtimeRef] = useState(() => ({
68
+ get current() {
69
+ return runtime;
70
+ },
71
+ }));
72
+ const streamRef = useRef(stream);
73
+ streamRef.current = stream;
74
+ const toolInvocations = useToolInvocations({
75
+ state: {
76
+ messages: threadMessages,
77
+ isRunning: effectiveIsRunning,
78
+ },
79
+ getTools: () => runtimeRef.current.thread.getModelContext().tools,
80
+ onResult: (command) => {
81
+ if (command.type === "add-tool-result") {
82
+ void streamRef.current.submit({
83
+ [messagesKey]: [
84
+ {
85
+ type: "tool",
86
+ name: command.toolName,
87
+ tool_call_id: command.toolCallId,
88
+ content: JSON.stringify(command.result),
89
+ status: command.isError ? "error" : "success",
90
+ },
91
+ ],
92
+ }, {});
93
+ }
94
+ },
95
+ setToolStatuses,
96
+ });
97
+ const extras = useMemo(() => ({
98
+ [symbolLangChainRuntimeExtras]: true,
99
+ interrupt: stream.interrupt,
100
+ interrupts: stream.interrupts,
101
+ submit: stream.submit,
102
+ }), [stream.interrupt, stream.interrupts, stream.submit]);
103
+ const runtime = useExternalStoreRuntime({
104
+ isRunning: effectiveIsRunning,
105
+ messages: threadMessages,
106
+ adapters,
107
+ extras,
108
+ onNew: async (msg) => {
109
+ await toolInvocations.abort();
110
+ const content = getMessageContent(msg);
111
+ await stream.submit({
112
+ [messagesKey]: [{ type: "human", content }],
113
+ });
114
+ },
115
+ onAddToolResult: async ({ toolCallId, toolName, result, isError, artifact, }) => {
116
+ await stream.submit({
117
+ [messagesKey]: [
118
+ {
119
+ type: "tool",
120
+ name: toolName,
121
+ tool_call_id: toolCallId,
122
+ content: JSON.stringify(result),
123
+ ...(artifact !== undefined && { artifact }),
124
+ status: isError ? "error" : "success",
125
+ },
126
+ ],
127
+ });
128
+ },
129
+ onCancel: async () => {
130
+ await stream.stop();
131
+ await toolInvocations.abort();
132
+ },
133
+ });
134
+ return runtime;
135
+ };
136
+ /**
137
+ * Creates an assistant-ui runtime backed by LangChain's `useStream` hook.
138
+ * Accepts the same options as `useStream` from `@langchain/react`, plus
139
+ * `cloud` and `adapters`.
140
+ *
141
+ * @example
142
+ * ```tsx
143
+ * import { useStreamRuntime } from "@assistant-ui/react-langchain";
144
+ * import { AssistantRuntimeProvider, Thread } from "@assistant-ui/react";
145
+ *
146
+ * function App() {
147
+ * const runtime = useStreamRuntime({
148
+ * assistantId: "agent",
149
+ * apiUrl: "http://localhost:2024",
150
+ * });
151
+ *
152
+ * return (
153
+ * <AssistantRuntimeProvider runtime={runtime}>
154
+ * <Thread />
155
+ * </AssistantRuntimeProvider>
156
+ * );
157
+ * }
158
+ * ```
159
+ */
160
+ export const useStreamRuntime = ({ cloud, ...options }) => {
161
+ const optionsRef = useRef(options);
162
+ optionsRef.current = options;
163
+ const cloudAdapter = useCloudThreadListAdapter({ cloud });
164
+ return useRemoteThreadListRuntime({
165
+ runtimeHook: function RuntimeHook() {
166
+ return useStreamThreadRuntime(optionsRef.current);
167
+ },
168
+ adapter: cloudAdapter,
169
+ allowNesting: true,
170
+ });
171
+ };
172
+ /**
173
+ * Read the current LangGraph interrupt state from the runtime extras.
174
+ */
175
+ export const useLangChainInterruptState = () => {
176
+ return useAuiState((s) => {
177
+ const extras = s.thread.extras;
178
+ if (!extras)
179
+ return undefined;
180
+ return asLangChainRuntimeExtras(extras).interrupt;
181
+ });
182
+ };
183
+ /**
184
+ * Returns a function to submit raw state updates to the LangGraph agent,
185
+ * bypassing the normal message flow. Useful for sending interrupt resume
186
+ * commands.
187
+ */
188
+ export const useLangChainSubmit = () => {
189
+ const aui = useAui();
190
+ return (values, options) => {
191
+ const extras = aui.thread().getState().extras;
192
+ const { submit } = asLangChainRuntimeExtras(extras);
193
+ return submit(values, options);
194
+ };
195
+ };
196
+ //# sourceMappingURL=useStreamRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useStreamRuntime.js","sourceRoot":"","sources":["../src/useStreamRuntime.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CA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ACvB,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC;QAC/B,IAAI,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC;QAC9B,OAAO,wBAAwB,CAAC,MAAM,CAAC,CAAC,SAAS,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,EAAE;IACrC,MAAM,GAAG,GAAG,MAAM,EAAE,CAAC;IACrB,OAAO,CACL,MAAkD,EAClD,OAAiC,EACjC,EAAE;QACF,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC;QAC9C,MAAM,EAAE,MAAM,EAAE,GAAG,wBAAwB,CAAC,MAAM,CAAC,CAAC;QACpD,OAAO,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,CAAC,CAAC;AACJ,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@assistant-ui/react-langchain",
3
+ "version": "0.0.1",
4
+ "description": "LangChain useStream adapter for assistant-ui",
5
+ "keywords": [
6
+ "langchain",
7
+ "langgraph",
8
+ "assistant-ui",
9
+ "react",
10
+ "ai",
11
+ "chat",
12
+ "agents"
13
+ ],
14
+ "author": "AgentbaseAI Inc.",
15
+ "license": "MIT",
16
+ "type": "module",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ }
22
+ },
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "files": [
26
+ "dist",
27
+ "src",
28
+ "README.md"
29
+ ],
30
+ "sideEffects": false,
31
+ "dependencies": {
32
+ "@assistant-ui/core": "^0.1.13",
33
+ "@assistant-ui/store": "^0.2.6",
34
+ "assistant-cloud": "*",
35
+ "assistant-stream": "^0.3.10"
36
+ },
37
+ "peerDependencies": {
38
+ "@langchain/react": "^0.3.3",
39
+ "@types/react": "*",
40
+ "react": "^18 || ^19"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "@types/react": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "devDependencies": {
48
+ "@langchain/core": "^1.1.39",
49
+ "@langchain/langgraph-sdk": "^1.8.8",
50
+ "@langchain/react": "^0.3.3",
51
+ "@types/react": "^19.2.14",
52
+ "react": "^19.2.5",
53
+ "@assistant-ui/x-buildutils": "0.0.4"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public",
57
+ "provenance": true
58
+ },
59
+ "homepage": "https://www.assistant-ui.com/",
60
+ "repository": {
61
+ "type": "git",
62
+ "url": "git+https://github.com/assistant-ui/assistant-ui.git",
63
+ "directory": "packages/react-langchain"
64
+ },
65
+ "bugs": {
66
+ "url": "https://github.com/assistant-ui/assistant-ui/issues"
67
+ },
68
+ "scripts": {
69
+ "build": "aui-build"
70
+ }
71
+ }
@@ -0,0 +1,137 @@
1
+ "use client";
2
+
3
+ import type { useExternalMessageConverter } from "@assistant-ui/core/react";
4
+ import type { ReadonlyJSONObject } from "assistant-stream/utils";
5
+ import type { LangChainBaseMessage, LangChainContentBlock } from "./types";
6
+
7
+ const getMessageType = (message: LangChainBaseMessage): string => {
8
+ if (typeof message._getType === "function") return message._getType();
9
+ if ("type" in message)
10
+ return (message as Record<string, unknown>).type as string;
11
+ throw new Error("Cannot determine message type");
12
+ };
13
+
14
+ const contentToParts = (content: unknown) => {
15
+ if (typeof content === "string")
16
+ return [{ type: "text" as const, text: content }];
17
+
18
+ const parts = content as readonly LangChainContentBlock[];
19
+ return parts
20
+ .map((part) => {
21
+ const type = part.type;
22
+ switch (type) {
23
+ case "text":
24
+ case "text_delta":
25
+ return { type: "text" as const, text: part.text };
26
+ case "image_url":
27
+ if (typeof part.image_url === "string") {
28
+ return { type: "image" as const, image: part.image_url };
29
+ }
30
+ return { type: "image" as const, image: part.image_url.url };
31
+ case "thinking":
32
+ return { type: "reasoning" as const, text: part.thinking };
33
+ case "reasoning":
34
+ return {
35
+ type: "reasoning" as const,
36
+ text: part.summary.map((s) => s.text).join("\n\n\n"),
37
+ };
38
+ case "tool_use":
39
+ case "input_json_delta":
40
+ return null;
41
+ default:
42
+ return null;
43
+ }
44
+ })
45
+ .filter((p) => p !== null);
46
+ };
47
+
48
+ const getCustomMetadata = (
49
+ additionalKwargs: Record<string, unknown> | undefined,
50
+ ): Record<string, unknown> =>
51
+ (additionalKwargs?.metadata as Record<string, unknown>) ?? {};
52
+
53
+ const getStringContent = (content: unknown): string => {
54
+ if (typeof content === "string") return content;
55
+ const parts = content as readonly LangChainContentBlock[];
56
+ return parts
57
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
58
+ .map((c) => c.text)
59
+ .join("");
60
+ };
61
+
62
+ export const convertLangChainBaseMessage: useExternalMessageConverter.Callback<
63
+ LangChainBaseMessage
64
+ > = (message) => {
65
+ const type = getMessageType(message);
66
+
67
+ switch (type) {
68
+ case "system":
69
+ return {
70
+ role: "system",
71
+ id: message.id,
72
+ content: [{ type: "text", text: getStringContent(message.content) }],
73
+ metadata: {
74
+ custom: getCustomMetadata(message.additional_kwargs),
75
+ },
76
+ };
77
+
78
+ case "human":
79
+ return {
80
+ role: "user",
81
+ id: message.id,
82
+ content: contentToParts(message.content),
83
+ metadata: {
84
+ custom: getCustomMetadata(message.additional_kwargs),
85
+ },
86
+ };
87
+
88
+ case "ai": {
89
+ const toolCallParts =
90
+ message.tool_calls?.map((tc) => ({
91
+ type: "tool-call" as const,
92
+ toolCallId: tc.id,
93
+ toolName: tc.name,
94
+ args: tc.args as ReadonlyJSONObject,
95
+ argsText: JSON.stringify(tc.args),
96
+ })) ?? [];
97
+
98
+ const assistantStatus =
99
+ typeof message.status === "object" ? message.status : undefined;
100
+
101
+ return {
102
+ role: "assistant",
103
+ id: message.id,
104
+ content: [...contentToParts(message.content), ...toolCallParts],
105
+ metadata: {
106
+ custom: getCustomMetadata(message.additional_kwargs),
107
+ },
108
+ ...(assistantStatus && { status: assistantStatus }),
109
+ };
110
+ }
111
+
112
+ case "tool":
113
+ return {
114
+ role: "tool",
115
+ toolName: message.name ?? "",
116
+ toolCallId: message.tool_call_id ?? "",
117
+ result: message.content,
118
+ artifact: message.artifact,
119
+ isError: message.status === "error",
120
+ };
121
+
122
+ default:
123
+ return {
124
+ role: "system",
125
+ id: message.id,
126
+ content: [
127
+ {
128
+ type: "text",
129
+ text:
130
+ typeof message.content === "string"
131
+ ? message.content
132
+ : JSON.stringify(message.content),
133
+ },
134
+ ],
135
+ };
136
+ }
137
+ };
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export {
2
+ useStreamRuntime,
3
+ useLangChainInterruptState,
4
+ useLangChainSubmit,
5
+ } from "./useStreamRuntime";
6
+ export type { UseStreamRuntimeOptions } from "./useStreamRuntime";
7
+
8
+ export { convertLangChainBaseMessage } from "./convertMessages";
9
+
10
+ export type {
11
+ LangChainBaseMessage,
12
+ LangChainContentBlock,
13
+ LangChainToolCall,
14
+ } from "./types";
package/src/types.ts ADDED
@@ -0,0 +1,42 @@
1
+ import type { MessageStatus } from "@assistant-ui/core";
2
+
3
+ /** Known content block types from @langchain/core messages. */
4
+ export type LangChainContentBlock =
5
+ | { type: "text"; text: string }
6
+ | { type: "text_delta"; text: string }
7
+ | { type: "image_url"; image_url: string | { url: string } }
8
+ | { type: "thinking"; thinking: string }
9
+ | {
10
+ type: "reasoning";
11
+ summary: Array<{ type: "summary_text"; text: string }>;
12
+ }
13
+ | { type: "tool_use" | "input_json_delta" };
14
+
15
+ export type LangChainToolCall = {
16
+ id: string;
17
+ name: string;
18
+ args: Record<string, unknown>;
19
+ };
20
+
21
+ /**
22
+ * Minimal duck-typed interface for BaseMessage class instances returned by
23
+ * `useStream`. Used internally by the message converter.
24
+ *
25
+ * Uses `unknown` for `content` to remain compatible with
26
+ * `@langchain/core`'s `MessageContent` union.
27
+ */
28
+ export type LangChainBaseMessage = {
29
+ _getType: () => string;
30
+ content: unknown;
31
+ id?: string | undefined;
32
+ name?: string | undefined;
33
+ additional_kwargs?: Record<string, unknown> | undefined;
34
+ /** Present on AIMessage */
35
+ tool_calls?: readonly LangChainToolCall[] | undefined;
36
+ /** Present on ToolMessage */
37
+ tool_call_id?: string | undefined;
38
+ /** Completion status (AIMessage) or outcome status (ToolMessage) */
39
+ status?: MessageStatus | "success" | "error" | undefined;
40
+ /** Present on ToolMessage */
41
+ artifact?: unknown;
42
+ };
@@ -0,0 +1,290 @@
1
+ "use client";
2
+
3
+ import { useMemo, useRef, useState } from "react";
4
+ import type {
5
+ AppendMessage,
6
+ AttachmentAdapter,
7
+ FeedbackAdapter,
8
+ SpeechSynthesisAdapter,
9
+ } from "@assistant-ui/core";
10
+ import {
11
+ useCloudThreadListAdapter,
12
+ useExternalStoreRuntime,
13
+ useExternalMessageConverter,
14
+ useRemoteThreadListRuntime,
15
+ useToolInvocations,
16
+ type ToolExecutionStatus,
17
+ } from "@assistant-ui/core/react";
18
+ import { useAui, useAuiState } from "@assistant-ui/store";
19
+ import type { AssistantCloud } from "assistant-cloud";
20
+ import { useStream, type UseStreamOptions } from "@langchain/react";
21
+ import type { LangChainBaseMessage } from "./types";
22
+ import { convertLangChainBaseMessage } from "./convertMessages";
23
+
24
+ const symbolLangChainRuntimeExtras = Symbol("langchain-runtime-extras");
25
+
26
+ type LangChainRuntimeExtras = {
27
+ [symbolLangChainRuntimeExtras]: true;
28
+ interrupt: { value?: unknown } | undefined;
29
+ interrupts: readonly { value?: unknown }[];
30
+ submit: (
31
+ values: Record<string, unknown> | null | undefined,
32
+ options?: Record<string, unknown>,
33
+ ) => Promise<void>;
34
+ };
35
+
36
+ const asLangChainRuntimeExtras = (extras: unknown): LangChainRuntimeExtras => {
37
+ if (
38
+ typeof extras !== "object" ||
39
+ extras == null ||
40
+ !(symbolLangChainRuntimeExtras in extras)
41
+ )
42
+ throw new Error(
43
+ "This method can only be called when you are using useStreamRuntime",
44
+ );
45
+ return extras as LangChainRuntimeExtras;
46
+ };
47
+
48
+ export type UseStreamRuntimeOptions = UseStreamOptions & {
49
+ cloud?: AssistantCloud | undefined;
50
+ adapters?:
51
+ | {
52
+ attachments?: AttachmentAdapter | undefined;
53
+ speech?: SpeechSynthesisAdapter | undefined;
54
+ feedback?: FeedbackAdapter | undefined;
55
+ }
56
+ | undefined;
57
+ /** The key in the LangGraph state that contains messages. Defaults to "messages". */
58
+ messagesKey?: string | undefined;
59
+ };
60
+
61
+ const getMessageContent = (msg: AppendMessage) => {
62
+ const allContent = [
63
+ ...msg.content,
64
+ ...(msg.attachments?.flatMap((a) => a.content) ?? []),
65
+ ];
66
+
67
+ const hasNonText = allContent.some(
68
+ (part) => part.type === "file" || part.type === "image",
69
+ );
70
+ const hasText = allContent.some((part) => part.type === "text");
71
+ if (hasNonText && !hasText) {
72
+ allContent.unshift({ type: "text", text: " " });
73
+ }
74
+
75
+ const content = allContent.map((part) => {
76
+ const type = part.type;
77
+ switch (type) {
78
+ case "text":
79
+ return { type: "text" as const, text: part.text };
80
+ case "image":
81
+ return { type: "image_url" as const, image_url: { url: part.image } };
82
+ case "file":
83
+ return {
84
+ type: "file" as const,
85
+ data: part.data,
86
+ mime_type: part.mimeType,
87
+ metadata: { filename: part.filename ?? "file" },
88
+ source_type: "base64" as const,
89
+ };
90
+ case "tool-call":
91
+ throw new Error("Tool call appends are not supported.");
92
+ default: {
93
+ const _exhaustiveCheck: "reasoning" | "source" | "audio" | "data" =
94
+ type;
95
+ throw new Error(
96
+ `Unsupported append message part type: ${_exhaustiveCheck}`,
97
+ );
98
+ }
99
+ }
100
+ });
101
+
102
+ if (content.length === 1 && content[0]?.type === "text") {
103
+ return content[0].text ?? "";
104
+ }
105
+ return content;
106
+ };
107
+
108
+ const useStreamThreadRuntime = ({
109
+ adapters,
110
+ messagesKey = "messages",
111
+ ...streamOptions
112
+ }: Omit<UseStreamRuntimeOptions, "cloud">) => {
113
+ const externalId = useAuiState((s) => s.threadListItem.externalId) as
114
+ | string
115
+ | null;
116
+
117
+ const stream = useStream({
118
+ ...streamOptions,
119
+ threadId: externalId,
120
+ });
121
+
122
+ const [toolStatuses, setToolStatuses] = useState<
123
+ Record<string, ToolExecutionStatus>
124
+ >({});
125
+ const hasExecutingTools = Object.values(toolStatuses).some(
126
+ (s) => s?.type === "executing",
127
+ );
128
+ const effectiveIsRunning = stream.isLoading || hasExecutingTools;
129
+
130
+ const threadMessages = useExternalMessageConverter({
131
+ callback: convertLangChainBaseMessage,
132
+ messages: stream.messages as LangChainBaseMessage[],
133
+ isRunning: effectiveIsRunning,
134
+ });
135
+
136
+ const [runtimeRef] = useState(() => ({
137
+ get current() {
138
+ return runtime;
139
+ },
140
+ }));
141
+
142
+ const streamRef = useRef(stream);
143
+ streamRef.current = stream;
144
+
145
+ const toolInvocations = useToolInvocations({
146
+ state: {
147
+ messages: threadMessages,
148
+ isRunning: effectiveIsRunning,
149
+ },
150
+ getTools: () => runtimeRef.current.thread.getModelContext().tools,
151
+ onResult: (command) => {
152
+ if (command.type === "add-tool-result") {
153
+ void streamRef.current.submit(
154
+ {
155
+ [messagesKey]: [
156
+ {
157
+ type: "tool",
158
+ name: command.toolName,
159
+ tool_call_id: command.toolCallId,
160
+ content: JSON.stringify(command.result),
161
+ status: command.isError ? "error" : "success",
162
+ },
163
+ ],
164
+ },
165
+ {},
166
+ );
167
+ }
168
+ },
169
+ setToolStatuses,
170
+ });
171
+
172
+ const extras = useMemo(
173
+ (): LangChainRuntimeExtras => ({
174
+ [symbolLangChainRuntimeExtras]: true,
175
+ interrupt: stream.interrupt,
176
+ interrupts: stream.interrupts,
177
+ submit: stream.submit,
178
+ }),
179
+ [stream.interrupt, stream.interrupts, stream.submit],
180
+ );
181
+
182
+ const runtime = useExternalStoreRuntime({
183
+ isRunning: effectiveIsRunning,
184
+ messages: threadMessages,
185
+ adapters,
186
+ extras,
187
+ onNew: async (msg) => {
188
+ await toolInvocations.abort();
189
+ const content = getMessageContent(msg);
190
+ await stream.submit({
191
+ [messagesKey]: [{ type: "human", content }],
192
+ });
193
+ },
194
+ onAddToolResult: async ({
195
+ toolCallId,
196
+ toolName,
197
+ result,
198
+ isError,
199
+ artifact,
200
+ }) => {
201
+ await stream.submit({
202
+ [messagesKey]: [
203
+ {
204
+ type: "tool",
205
+ name: toolName,
206
+ tool_call_id: toolCallId,
207
+ content: JSON.stringify(result),
208
+ ...(artifact !== undefined && { artifact }),
209
+ status: isError ? "error" : "success",
210
+ },
211
+ ],
212
+ });
213
+ },
214
+ onCancel: async () => {
215
+ await stream.stop();
216
+ await toolInvocations.abort();
217
+ },
218
+ });
219
+
220
+ return runtime;
221
+ };
222
+
223
+ /**
224
+ * Creates an assistant-ui runtime backed by LangChain's `useStream` hook.
225
+ * Accepts the same options as `useStream` from `@langchain/react`, plus
226
+ * `cloud` and `adapters`.
227
+ *
228
+ * @example
229
+ * ```tsx
230
+ * import { useStreamRuntime } from "@assistant-ui/react-langchain";
231
+ * import { AssistantRuntimeProvider, Thread } from "@assistant-ui/react";
232
+ *
233
+ * function App() {
234
+ * const runtime = useStreamRuntime({
235
+ * assistantId: "agent",
236
+ * apiUrl: "http://localhost:2024",
237
+ * });
238
+ *
239
+ * return (
240
+ * <AssistantRuntimeProvider runtime={runtime}>
241
+ * <Thread />
242
+ * </AssistantRuntimeProvider>
243
+ * );
244
+ * }
245
+ * ```
246
+ */
247
+ export const useStreamRuntime = ({
248
+ cloud,
249
+ ...options
250
+ }: UseStreamRuntimeOptions) => {
251
+ const optionsRef = useRef(options);
252
+ optionsRef.current = options;
253
+
254
+ const cloudAdapter = useCloudThreadListAdapter({ cloud });
255
+ return useRemoteThreadListRuntime({
256
+ runtimeHook: function RuntimeHook() {
257
+ return useStreamThreadRuntime(optionsRef.current);
258
+ },
259
+ adapter: cloudAdapter,
260
+ allowNesting: true,
261
+ });
262
+ };
263
+
264
+ /**
265
+ * Read the current LangGraph interrupt state from the runtime extras.
266
+ */
267
+ export const useLangChainInterruptState = () => {
268
+ return useAuiState((s) => {
269
+ const extras = s.thread.extras;
270
+ if (!extras) return undefined;
271
+ return asLangChainRuntimeExtras(extras).interrupt;
272
+ });
273
+ };
274
+
275
+ /**
276
+ * Returns a function to submit raw state updates to the LangGraph agent,
277
+ * bypassing the normal message flow. Useful for sending interrupt resume
278
+ * commands.
279
+ */
280
+ export const useLangChainSubmit = () => {
281
+ const aui = useAui();
282
+ return (
283
+ values: Record<string, unknown> | null | undefined,
284
+ options?: Record<string, unknown>,
285
+ ) => {
286
+ const extras = aui.thread().getState().extras;
287
+ const { submit } = asLangChainRuntimeExtras(extras);
288
+ return submit(values, options);
289
+ };
290
+ };