跳至主要内容

REFERENCE

SDK 範例

@asgard-js/core 與 @asgard-js/react 的用法與可以直接操作的範例。

私有機器人

連線到一個需要 API key 的私有 bot provider。SDK 會自動處理 未認證 → needApiKey → authenticated 的狀態轉換。

  1. 程式範例​

    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");
    }}
    />
    );
    }
  2. 認證流程​

    步驟AuthStateSDK 行為
    1. 初始needApiKey顯示 API key 輸入表單
    2. 送出 key—觸發 onApiKeySubmit
    3. 驗證成功authenticated建立 SSE 連線
    4. key 無效invalidApiKey顯示錯誤提示,可重新輸入

    另見 認證狀態 Demo 查看所有 7 種 AuthState。

  3. 深入閱讀​

    平台端的認證設計,見 Asgard 開發者文件:

準備好開始了嗎?

想知道 Asgard 怎麼用在你的團隊?跟我們聊聊。

聯絡我們