跳至主要内容

快速開始

本頁帶你從零安裝、跑出第一個可以對話的 <Chatbot>

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}

在 Asgard 平台後台建立 Bot Provider 後即可取得。SDK 會自動從這個 base URL 衍生出 SSE endpoint (${botProviderEndpoint}/message/sse) 與 blob upload endpoint。

注意

@asgard-js/core@1.x 之前的 endpoint 欄位已 deprecated,請一律 使用 botProviderEndpoint。下一個 major 版會移除 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 依賴 windowMediaRecorderResizeObserver 等瀏覽器 API,不能在 server 上執行。所有 SSR 框架都要做 client-only 包裝:

Next.js (App Router)

"use client";

import dynamic from "next/dynamic";

const Chatbot = dynamic(
() => import("@asgard-js/react").then((m) => m.Chatbot),
{ ssr: false },
);

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,不需要額外處理。

下一步