将 LangGraph 集成到 React 应用
如何将 LangGraph 集成到你的 React 应用中# 如何将 LangGraph 集成到你的 React 应用中
useStream()
React Hook 提供了一种无缝的方式,将 LangGraph 集成到你的 React 应用程序中。它处理了流式传输、状态管理以及分支逻辑的所有复杂性,让你专注于构建出色的聊天体验。
关键特性:
- 消息流式传输:处理消息片段的流,以形成完整消息
- 自动管理消息、中断、加载状态和错误的状态
- 对话分支:从聊天历史中的任何一点创建替代对话路径
- 与 UI 无关的设计:你可以使用自己的组件和样式
让我们来探讨如何在你的 React 应用中使用 useStream()
。
useStream()
为创建定制化的聊天体验提供了坚实的基础。对于预构建的聊天组件和界面,我们还推荐查看 CopilotKit 和 assistant-ui。
安装¶
示例¶
"use client";
import { useStream } from "@langchain/langgraph-sdk/react";
import type { Message } from "@langchain/langgraph-sdk";
export default function App() {
const thread = useStream<{ messages: Message[] }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
return (
<div>
<div>
{thread.messages.map((message) => (
<div key={message.id}>{message.content as string}</div>
))}
</div>
<form
onSubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const message = new FormData(form).get("message") as string;
form.reset();
thread.submit({ messages: [{ type: "human", content: message }] });
}}
>
<input type="text" name="message" />
{thread.isLoading ? (
<button key="stop" type="button" onClick={() => thread.stop()}>
停止
</button>
) : (
<button keytype="submit">发送</button>
)}
</form>
</div>
);
}
自定义您的 UI¶
useStream()
钩子负责处理后台所有复杂的状态管理,为您提供简单的接口来构建您的 UI。开箱即用的功能包括:
- 线程状态管理
- 加载和错误状态
- 中断
- 消息处理和更新
- 分支支持
以下是一些有效使用这些功能的示例:
加载状态¶
isLoading
属性会告诉您流是否处于活动状态,从而让您能够:
- 显示加载指示器
- 在处理过程中禁用输入字段
- 显示取消按钮
export default function App() {
const { isLoading, stop } = useStream<{ messages: Message[] }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
return (
<form>
{isLoading && (
<button key="stop" type="button" onClick={() => stop()}>
停止
</button>
)}
</form>
);
}
页面刷新后恢复流¶
通过将 reconnectOnMount: true
设置为 useStream()
钩子,可以在挂载时自动恢复正在进行的运行。这对于在页面刷新后继续流非常有用,确保在停机期间生成的消息和事件不会丢失。
const thread = useStream<{ messages: Message[] }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
reconnectOnMount: true,
});
默认情况下,创建的运行 ID 存储在 window.sessionStorage
中,可以通过在 reconnectOnMount
中传递自定义存储进行替换。该存储用于持久化线程的飞行中运行 ID(键为 lg:stream:${threadId}
)。
const thread = useStream<{ messages: Message[] }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
reconnectOnMount: () => window.localStorage,
});
您也可以通过使用运行回调来手动管理恢复过程,以持久化运行元数据,并通过 joinStream
函数恢复流。确保在创建运行时传入 streamResumable: true
;否则可能会丢失一些事件。
import type { Message } from "@langchain/langgraph-sdk";
import { useStream } from "@langchain/langgraph-sdk/react";
import { useCallback, useState, useEffect, useRef } from "react";
export default function App() {
const [threadId, onThreadId] = useSearchParam("threadId");
const thread = useStream<{ messages: Message[] }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
threadId,
onThreadId,
onCreated: (run) => {
window.sessionStorage.setItem(`resume:${run.thread_id}`, run.run_id);
},
onFinish: (_, run) => {
window.sessionStorage.removeItem(`resume:${run?.thread_id}`);
},
});
// 确保每个线程只加入一次流。
const joinedThreadId = useRef<string | null>(null);
useEffect(() => {
if (!threadId) return;
const resume = window.sessionStorage.getItem(`resume:${threadId}`);
if (resume && joinedThreadId.current !== threadId) {
thread.joinStream(resume);
joinedThreadId.current = threadId;
}
}, [threadId]);
return (
<form
onSubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const message = new FormData(form).get("message") as string;
thread.submit(
{ messages: [{ type: "human", content: message }] },
{ streamResumable: true }
);
}}
>
<div>
{thread.messages.map((message) => (
<div key={message.id}>{message.content as string}</div>
))}
</div>
<input type="text" name="message" />
<button type="submit">发送</button>
</form>
);
}
// 实用方法,用于从 URL 的搜索参数中获取并持久化数据
function useSearchParam(key: string) {
const [value, setValue] = useState<string | null>(() => {
const params = new URLSearchParams(window.location.search);
return params.get(key) ?? null;
});
const update = useCallback(
(value: string | null) => {
setValue(value);
const url = new URL(window.location.href);
if (value == null) {
url.searchParams.delete(key);
} else {
url.searchParams.set(key, value);
}
window.history.pushState({}, "", url.toString());
},
[key]
);
return [value, update] as const;
}
线程管理¶
通过内置的线程管理功能,您可以跟踪对话。您可以访问当前的线程 ID,并在新线程创建时收到通知:
const [threadId, setThreadId] = useState<string | null>(null);
const thread = useStream<{ messages: Message[] }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
threadId: threadId,
onThreadId: setThreadId,
});
````
我们建议将 `threadId` 存储在 URL 的查询参数中,以便用户在页面刷新后可以继续对话。
### 消息处理
`useStream()` 钩子会跟踪从服务器接收到的消息片段,并将它们连接在一起形成完整消息。可以通过 `messages` 属性检索到完成的消息片段。
默认情况下,`messagesKey` 设置为 `messages`,它会将新的消息片段追加到 `values["messages"]`。如果您在不同的键中存储消息,可以更改 `messagesKey` 的值。
```tsx
import type { Message } from "@langchain/langgraph-sdk";
import { useStream } from "@langchain/langgraph-sdk/react";
export default function HomePage() {
const thread = useStream<{ messages: Message[] }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
return (
<div>
{thread.messages.map((message) => (
<div key={message.id}>{message.content as string}</div>
))}
</div>
);
}
在内部,useStream()
钩子会使用 streamMode: "messages-tuple"
来接收来自任何 LangChain 聊天模型调用的消息流(即单个 LLM 令牌)。有关消息流的更多信息,请参阅 流 指南。
中断¶
useStream()
钩子暴露了 interrupt
属性,其中包含线程中的最后一个中断。您可以使用中断来:
- 在执行节点之前渲染确认 UI
- 等待用户输入,允许代理向用户提问澄清问题
有关中断的更多信息,请参阅 如何处理中断 指南。
const thread = useStream<{ messages: Message[] }, { InterruptType: string }>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
if (thread.interrupt) {
return (
<div>
已中断!{thread.interrupt.value}
<button
type="button"
onClick={() => {
// `resume` 可以是代理接受的任何值
thread.submit(undefined, { command: { resume: true } });
}}
>
继续
</button>
</div>
);
}
分支¶
对于每条消息,您可以使用 getMessagesMetadata()
获取第一条检查点,这是消息首次看到的位置。然后您可以从首次看到的检查点之前的检查点创建一个新运行,从而在线程中创建一个新的分支。
创建分支的方法有以下几种:
- 编辑一条以前的用户消息。
- 请求重新生成一条以前的助手消息。
"use client";
import type { Message } from "@langchain/langgraph-sdk";
import { useStream } from "@langchain/langgraph-sdk/react";
import { useState } from "react";
function BranchSwitcher({
branch,
branchOptions,
onSelect,
}: {
branch: string | undefined;
branchOptions: string[] | undefined;
onSelect: (branch: string) => void;
}) {
if (!branchOptions || !branch) return null;
const index = branchOptions.indexOf(branch);
return (
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => {
const prevBranch = branchOptions[index - 1];
if (!prevBranch) return;
onSelect(prevBranch);
}}
>
上一个
</button>
<span>
{index + 1} / {branchOptions.length}
</span>
<button
type="button"
onClick={() => {
const nextBranch = branchOptions[index + 1];
if (!nextBranch) return;
onSelect(nextBranch);
}}
>
下一个
</button>
</div>
);
}
function EditMessage({
message,
onEdit,
}: {
message: Message;
onEdit: (message: Message) => void;
}) {
const [editing, setEditing] = useState(false);
if (!editing) {
return (
<button type="button" onClick={() => setEditing(true)}>
编辑
</button>
);
}
return (
<form
onSubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const content = new FormData(form).get("content") as string;
form.reset();
onEdit({ type: "human", content });
setEditing(false);
}}
>
<input name="content" defaultValue={message.content as string} />
<button type="submit">保存</button>
</form>
);
}
export default function App() {
const thread = useStream({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
return (
<div>
<div>
{thread.messages.map((message) => {
const meta = thread.getMessagesMetadata(message);
const parentCheckpoint = meta?.firstSeenState?.parent_checkpoint;
return (
<div key={message.id}>
<div>{message.content as string}</div>
{message.type === "human" && (
<EditMessage
message={message}
onEdit={(message) =>
thread.submit(
{ messages: [message] },
{ checkpoint: parentCheckpoint }
)
}
/>
)}
{message.type === "ai" && (
<button
type="button"
onClick={() =>
thread.submit(undefined, { checkpoint: parentCheckpoint })
}
>
<span>重新生成</span>
</button>
)}
<BranchSwitcher
branch={meta?.branch}
branchOptions={meta?.branchOptions}
onSelect={(branch) => thread.setBranch(branch)}
/>
</div>
);
})}
</div>
<form
onSubmit={(e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const message = new FormData(form).get("message") as string;
form.reset();
thread.submit({ messages: [message] });
}}
>
<input type="text" name="message" />
{thread.isLoading ? (
<button key="stop" type="button" onClick={() => thread.stop()}>
停止
</button>
) : (
<button key="submit" type="submit">
发送
</button>
)}
</form>
</div>
);
}
对于高级用例,您可以使用 experimental_branchTree
属性获取线程的树表示,这可用于非基于消息的图的分支控制渲染。
乐观更新¶
您可以在执行对代理的网络请求前,乐观地更新客户端状态,从而允许您立即向用户提供反馈,例如在代理看到请求之前立即显示用户消息。
const stream = useStream({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
const handleSubmit = (text: string) => {
const newMessage = { type: "human" as const, content: text };
stream.submit(
{ messages: [newMessage] },
{
optimisticValues(prev) {
const prevMessages = prev.messages ?? [];
const newMessages = [...prevMessages, newMessage];
return { ...prev, messages: newMessages };
},
}
);
};
TypeScript¶
useStream()
钩子对使用 TypeScript 编写的应用程序非常友好,您可以指定状态的类型以获得更好的类型安全性和 IDE 支持。
// 定义您的类型
type State = {
messages: Message[];
context?: Record<string, unknown>;
};
// 使用钩子
const thread = useStream<State>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
您还可以可选地为不同场景指定类型,例如:
ConfigurableType
:config.configurable
属性的类型(默认:Record<string, unknown>
)InterruptType
: 中断值的类型 - 即interrupt(...)
函数的内容(默认:unknown
)CustomEventType
: 自定义事件的类型(默认:unknown
)UpdateType
: 提交函数的类型(默认:Partial<State>
)
const thread = useStream<
State,
{
UpdateType: {
messages: Message[] | Message;
context?: Record<string, unknown>;
};
InterruptType: string;
CustomEventType: {
type: "progress" | "debug";
payload: unknown;
};
ConfigurableType: {
model: string;
};
}
>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
如果您使用的是 LangGraph.js,您还可以重用您图的注解类型。但是,请确保仅导入注解模式的类型,以避免导入整个 LangGraph.js 运行时(即通过 import type { ... }
指令)。
import {
Annotation,
MessagesAnnotation,
type StateType,
type UpdateType,
} from "@langchain/langgraph/web";
const AgentState = Annotation.Root({
...MessagesAnnotation.spec,
context: Annotation<string>(),
});
const thread = useStream<
StateType<typeof AgentState.spec>,
{ UpdateType: UpdateType<typeof AgentState.spec> }
>({
apiUrl: "http://localhost:2024",
assistantId: "agent",
messagesKey: "messages",
});
事件处理¶
useStream()
钩子提供了多个回调选项,帮助您响应不同的事件:
onError
: 当发生错误时调用。onFinish
: 当流结束时调用。onUpdateEvent
: 当接收到更新事件时调用。onCustomEvent
: 当接收到自定义事件时调用。请参阅流式传输指南,了解如何流式传输自定义事件。onMetadataEvent
: 当接收到元数据事件时调用,其中包含 Run ID 和 Thread ID。