React SDK (@asgard-js/react)
@asgard-js/react 在 @asgard-js/core 之上提供現成的 React 聊天室 UI 元件與 hooks,讓 React 應用程式能快速整合 Asgard 聊天功能。
建議先看完整指南
模式選型、進階設定、常見問題等完整說明在 前端 SDK 使用指南, 每個功能都有可實際操作的範例在 SDK Demo。
安裝
@asgard-js/react 以 @asgard-js/core 為 peer dependency,請同時安裝:
npm install @asgard-js/react @asgard-js/core
CSS 樣式引入
import "@asgard-js/react/style";
這一行只需執行一次,否則 chatbot 會沒有樣式。
<Chatbot> 元件
import { Chatbot } from "@asgard-js/react";
import "@asgard-js/react/style";
export default function App() {
return (
<div style={{ height: "100vh" }}>
<Chatbot
title="我的 AI 助理"
customChannelId="user-123"
config={{
botProviderEndpoint:
"https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}",
}}
/>
</div>
);
}
必填 Props
| Prop | 型別 | 說明 |
|---|---|---|
config.botProviderEndpoint | string | Bot Provider 的 endpoint URL |
customChannelId | string | 對話頻道識別 ID,通常用 user id 或 session id |
完整 props 清單見 Props Reference。
SSR 框架(Next.js)
@asgard-js/react 依賴瀏覽器 API(window、MediaRecorder、ResizeObserver 等),不能在 server 端執行。
Next.js App Router
"use client";
import dynamic from "next/dynamic";
import "@asgard-js/react/style";
const Chatbot = dynamic(
() => import("@asgard-js/react").then((m) => m.Chatbot),
{ ssr: false },
);
export default function ChatPage() {
return (
<div style={{ height: "100vh" }}>
<Chatbot
title="我的 AI 助理"
customChannelId="user-123"
config={{
botProviderEndpoint:
"https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}",
}}
/>
</div>
);
}
Next.js Pages Router
import dynamic from "next/dynamic";
const Chatbot = dynamic(
() => import("@asgard-js/react").then((m) => m.Chatbot),
{ ssr: false },
);
Docusaurus / Gatsby
import BrowserOnly from "@docusaurus/BrowserOnly";
export default function MyPage() {
return (
<BrowserOnly>
{() => {
const { Chatbot } = require("@asgard-js/react");
require("@asgard-js/react/style");
return (
<Chatbot
title="..."
customChannelId="..."
config={{ botProviderEndpoint: "..." }}
/>
);
}}
</BrowserOnly>
);
}
自訂 UI(useAsgardContext)
在 renderHeader、renderFooter 等自訂渲染 props 中,可用 useAsgardContext 存取對話狀態:
import { useAsgardContext } from "@asgard-js/react";
function CustomHeader() {
const { resetChannel, isConnecting } = useAsgardContext();
return (
<div>
<span>My Bot</span>
<button onClick={resetChannel} disabled={isConnecting}>
重置對話
</button>
</div>
);
}
互動式 Demo
每個 prop 與功能(訊息模板、主題、客製渲染、認證、tool call 等)都有可操作的範例:sdk-demo.asgard-ai.com
延伸閱讀
- 前端 SDK 使用指南 — 完整模式選型、props、常見問題
- JavaScript SDK 參考文件 —
@asgard-js/core底層 API