LangSmith 支持将您的 React 组件与图代码放在一起。这使您能够专注于为图构建特定的 UI 组件,同时轻松插入现有的聊天界面,例如 Agent Chat,并仅在实际需要时加载代码。
教程
1. 定义和配置 UI 组件
首先,创建您的第一个 UI 组件。对于每个组件,您需要提供一个唯一的标识符,该标识符将用于在图代码中引用该组件。src/agent/ui.tsx
langgraph.json 配置中定义 UI 组件:
ui 部分指向图将使用的 UI 组件。默认情况下,我们建议使用与图名称相同的键,但您可以按照自己的喜好拆分组件,有关更多详细信息,请参阅自定义 UI 组件的命名空间。
LangSmith 将自动捆绑您的 UI 组件代码和样式,并将它们作为外部资产提供,可以由 LoadExternalComponent 组件加载。一些依赖项(例如 react 和 react-dom)将自动从捆绑包中排除。
CSS 和 Tailwind 4.x 也是开箱即用的支持,因此您可以在 UI 组件中自由使用 Tailwind 类以及 shadcn/ui。
- src/agent/ui.tsx
- src/agent/styles.css
2. 在图中发送 UI 组件
- Python
- JS
src/agent.py
3. Handle UI elements in your React application
On the client side, you can useuseStream() and LoadExternalComponent to display the UI elements.
src/app/page.tsx
LoadExternalComponent will fetch the JS and CSS for the UI components from LangSmith and render them in a shadow DOM, thus ensuring style isolation from the rest of your application.
How-to guides
Provide custom components on the client side
If you already have the components loaded in your client application, you can provide a map of such components to be rendered directly without fetching the UI code from LangSmith.Show loading UI when components are loading
You can provide a fallback UI to be rendered when the components are loading.Customise the namespace of UI components.
By defaultLoadExternalComponent will use the assistantId from useStream() hook to fetch the code for UI components. You can customise this by providing a namespace prop to the LoadExternalComponent component.
- src/app/page.tsx
- langgraph.json
Access and interact with the thread state from the UI component
You can access the thread state inside the UI component by using theuseStreamContext hook.
Pass additional context to the client components
You can pass additional context to the client components by providing ameta prop to the LoadExternalComponent component.
meta prop in the UI component by using the useStreamContext hook.
Streaming UI messages from the server
You can stream UI messages before the node execution is finished by using theonCustomEvent callback of the useStream() hook. This is especially useful when updating the UI component as the LLM is generating the response.
ui.push() / push_ui_message() with the same ID as the UI message you wish to update.
- Python
- JS
- ui.tsx
Remove UI messages from state
Similar to how messages can be removed from the state by appending a RemoveMessage you can remove an UI message from the state by callingremove_ui_message / ui.delete with the ID of the UI message.
- Python
- JS