私有機器人
連線到一個需要 API key 的私有 bot provider。SDK 會自動處理
未認證 → needApiKey → authenticated 的狀態轉換。
私有機器人認證
此 Demo 連線到需要 API key 的私有 bot provider。當 SDK 偵測到未認證狀態時,會自動提示輸入 key。
認證流程
- 需要 API Key 才能存取
- Auth 狀態管理
- 未授權錯誤處理
聊天機器人載入中…
程式範例
import { useState } from "react";
import { Chatbot } from "@asgard-js/react";
import type { AuthState } from "@asgard-js/core";
export function PrivateBot() {
const [authState, setAuthState] = useState<AuthState>("needApiKey");
return (
<Chatbot
title="私有機器人"
config={{
botProviderEndpoint: "https://...",
apiKey: authState === "authenticated" ? storedKey : undefined,
}}
customChannelId="private-channel"
authState={authState}
onApiKeySubmit={async (key) => {
// 驗證 key 後切換狀態
setAuthState("authenticated");
}}
onAuthError={(error) => {
if (error.isAuthError) setAuthState("needApiKey");
}}
/>
);
}
認證流程
| 步驟 | AuthState | SDK 行為 |
|---|---|---|
| 1. 初始 | needApiKey | 顯示 API key 輸入表單 |
| 2. 送出 key | — | 觸發 onApiKeySubmit |
| 3. 驗證成功 | authenticated | 建立 SSE 連線 |
| 4. key 無效 | invalidApiKey | 顯示錯誤提示,可重新輸入 |
另見 認證狀態 Demo 查看所有 7 種 AuthState。