快速開始
本頁帶你從零安裝、跑出第一個可以對話的 <Chatbot>。
本頁假設你已經有一個 Bot Provider endpoint。如果還沒有,先看 整合總覽:了解完整開發流程、如何在 Odin 建立 Bot, 以及該選哪種整合模式(Direct Connect / Backend Relay / Hosted Embed)。
1. 安裝套件
npm install @asgard-js/core @asgard-js/react
兩個套件都必要:
@asgard-js/core— 底層 SSE client、channel、conversation 模型@asgard-js/react— React 元件、hooks、與內建聊天室 UI
2. 取得 Bot Provider Endpoint
Endpoint 格式固定為:
https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}
在 Odin Studio 建立並發佈 Bot Provider 後即可取得 endpoint 與憑證。完整步驟見:
- 建立一個簡單的 Chatbot
- 整合總覽 — 從建立到前端上線的全流程
SDK 會自動從這個 base URL 衍生出 SSE endpoint
(${botProviderEndpoint}/message/sse) 與 blob upload endpoint。
3. 引入 CSS
import "@asgard-js/react/style";
這一行務必執行一次,否則 chatbot 會沒有樣式。CSS 對應到
@asgard-js/react/dist/index.css。
4. 渲染 <Chatbot>
import { Chatbot } from "@asgard-js/react";
import "@asgard-js/react/style";
export function App() {
return (
<Chatbot
title="我的聊天機器人"
customChannelId="user-123"
config={{
botProviderEndpoint:
"https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}",
}}
/>
);
}
兩個必填,加一個常用的:
| Prop | 必填 | 說明 |
|---|---|---|
config.botProviderEndpoint | ✓ | 上一步取得的 URL |
customChannelId | ✓ | 你這端唯一代表一個對話頻道的 ID,通常用 user id 或 session id |
title | 顯示在 header 的標題 |
完整 props 表請見 Chatbot Props。
5. SSR / Next.js / Docusaurus 注意事項
@asgard-js/react 依賴 window、MediaRecorder、ResizeObserver
等瀏覽器 API,不能在 server 上執行。所有 SSR 框架都要做 client-only
包裝:
Next.js (App Router)
@asgard-js/react 依賴瀏覽器 API,即使在 "use client" 元件中仍需搭配 dynamic + ssr: false 避免 server-side pre-render 失敗。Style import 放在 dynamic 之外,讓 Next.js 靜態分析到 CSS:
"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="我的聊天機器人"
customChannelId="user-123"
config={{
botProviderEndpoint:
"https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}",
}}
/>
</div>
);
}
<Chatbot> 會填滿父容器高度,因此父元素需要有明確的高度(範例用 100vh)。
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>
);
}
Vite / CRA
純 SPA 沒有 SSR,可以直接 top-level import,不需要額外處理。
下一步
- Chatbot Props — 所有可用 props 的完整表
- 訊息模板 — 內建模板
- 功能開關 — 檔案上傳 / 匯出 / 文件上傳
- Headless 用法 — 不使用
<Chatbot>,自己組 UI