Skip to main content
Asgard SDK 安裝、設定與快速開始

SDK 總覽

Asgard 提供官方 JavaScript 與 React SDK,讓開發者能快速整合聊天機器人功能,無需自行處理底層 API 細節。

SDK 提供什麼

  • 簡化 API 存取:封裝 REST API 請求,統一管理驗證與端點設定
  • SSE 串流處理:自動處理 Server-Sent Events,即時接收機器人回應
  • Channel 管理:內建 session 持久化,支援多輪對話
  • React 元件@asgard-js/react 提供現成的聊天室 UI 元件與 Hook

安裝

JavaScript SDK

適用於所有 JavaScript 環境(Node.js、瀏覽器、框架無關):

npm install @asgard-js/core

React SDK

適用於 React 應用程式,包含 UI 元件與 Hook:

npm install @asgard-js/react

@asgard-js/react@asgard-js/core 為 peer dependency,請確保兩者都已安裝。

快速開始

以下範例展示如何使用 @asgard-js/core 底層 API 送出訊息並接收串流回應:

import { AsgardServiceClient, Channel, Conversation } from '@asgard-js/core';

const client = new AsgardServiceClient({
botProviderEndpoint:
'https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}',
});

const conversation = new Conversation({ messages: new Map() });

const channel = await Channel.reset({
client,
customChannelId: 'channel-123',
conversation,
statesObserver: (states) => {
console.log('Messages:', Array.from(states.conversation.messages.values()));
},
});

await channel.sendMessage({ text: '你好,請介紹一下你自己' });

如果使用 React,推薦直接用 <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>
);
}

SDK 與直接呼叫 REST API 比較

功能SDKREST API
SSE 串流處理自動處理需自行實作
驗證設定初始化一次,自動帶入每次請求需手動加入 header
Channel 管理內建 session 持久化需自行維護 channelId
React 整合提供 Hook 與元件需自行封裝
錯誤處理統一錯誤介面需自行解析各類錯誤
TypeScript 支援完整型別定義需自行定義型別

延伸閱讀

GitHub

原始碼與最新版本:asgard-ai-platform/asgard-js-sdk