先决条件
useStream() React hook 提供了一种无缝的方式将 LangGraph 集成到 React 应用程序中。它处理流式传输、状态管理和分支逻辑的所有复杂性,让您专注于构建出色的聊天体验。
主要功能:
- 消息流式传输:处理消息块流以形成完整消息
- 消息、中断、加载状态和错误的自动状态管理
- 对话分支:从聊天历史记录的任何点创建备用对话路径
- UI 无关设计:带上您自己的组件和样式
useStream()。
useStream() 为创建定制聊天体验提供了坚实的基础。对于预构建的聊天组件和界面,我们还建议查看 CopilotKit 和 assistant-ui。
安装
示例
自定义您的 UI
useStream() hook 在幕后处理所有复杂的状态管理,为您提供简单的界面来构建 UI。以下是您开箱即用的功能:
- 线程状态管理
- 加载和错误状态
- 中断
- 消息处理和更新
- 分支支持
加载状态
isLoading 属性告诉您流何时处于活动状态,使您能够:
- 显示加载指示器
- 在处理期间禁用输入字段
- 显示取消按钮
Resume a stream after page refresh
TheuseStream() hook can automatically resume an ongoing run upon mounting by setting reconnectOnMount: true. This is useful for continuing a stream after a page refresh, ensuring no messages and events generated during the downtime are lost.
window.sessionStorage, which can be swapped by passing a custom storage in reconnectOnMount instead. The storage is used to persist the in-flight run ID for a thread (under lg:stream:${threadId} key).
joinStream function to resume the stream. Make sure to pass streamResumable: true when creating the run; otherwise some events might be lost.
Thread Management
Keep track of conversations with built-in thread management. You can access the current thread ID and get notified when new threads are created:threadId in your URL’s query parameters to let users resume conversations after page refreshes.
Messages Handling
TheuseStream() hook will keep track of the message chunks received from the server and concatenate them together to form a complete message. The completed message chunks can be retrieved via the messages property.
By default, the messagesKey is set to messages, where it will append the new messages chunks to values["messages"]. If you store messages in a different key, you can change the value of messagesKey.
useStream() hook will use the streamMode: "messages-tuple" to receive a stream of messages (i.e. individual LLM tokens) from any LangChain chat model invocations inside your graph nodes. Learn more about messages streaming in the streaming guide.
Interrupts
TheuseStream() hook exposes the interrupt property, which will be filled with the last interrupt from the thread. You can use interrupts to:
- Render a confirmation UI before executing a node
- Wait for human input, allowing agent to ask the user with clarifying questions
Branching
For each message, you can usegetMessagesMetadata() to get the first checkpoint from which the message has been first seen. You can then create a new run from the checkpoint preceding the first seen checkpoint to create a new branch in a thread.
A branch can be created in following ways:
- Edit a previous user message.
- Request a regeneration of a previous assistant message.
experimental_branchTree property to get the tree representation of the thread, which can be used to render branching controls for non-message based graphs.
Optimistic Updates
You can optimistically update the client state before performing a network request to the agent, allowing you to provide immediate feedback to the user, such as showing the user message immediately before the agent has seen the request.Cached Thread Display
Use theinitialValues option to display cached thread data immediately while the history is being loaded from the server. This improves user experience by showing cached data instantly when navigating to existing threads.
Optimistic Thread Creation
Use thethreadId option in submit function to enable optimistic UI patterns where you need to know the thread ID before the thread is actually created.
TypeScript
TheuseStream() hook is friendly for apps written in TypeScript and you can specify types for the state to get better type safety and IDE support.
ConfigurableType: Type for theconfig.configurableproperty (default:Record<string, unknown>)InterruptType: Type for the interrupt value - i.e. contents ofinterrupt(...)function (default:unknown)CustomEventType: Type for the custom events (default:unknown)UpdateType: Type for the submit function (default:Partial<State>)
import type { ... } directive).
Event Handling
TheuseStream() hook provides several callback options to help you respond to different events:
onError: Called when an error occurs.onFinish: Called when the stream is finished.onUpdateEvent: Called when an update event is received.onCustomEvent: Called when a custom event is received. See the streaming guide to learn how to stream custom events.onMetadataEvent: Called when a metadata event is received, which contains the Run ID and Thread ID.