跳至主要内容
@asgard-js/core JavaScript SDK 參考文件

JavaScript SDK (@asgard-js/core)

@asgard-js/core 是框架無關的 JavaScript SDK,適用於 Node.js、瀏覽器及任何 JavaScript 環境。

安裝

npm install @asgard-js/core

初始化 AsgardClient

所有操作都透過 AsgardClient 實例進行。初始化時需提供連線與驗證設定:

import { AsgardClient } from '@asgard-js/core';

const client = new AsgardClient({
baseUrl: 'https://api.asgard.example.com',
namespace: 'my-namespace',
botProviderName: 'my-bot',
apiKey: 'your-api-key',
});

設定選項

參數型別必填說明
baseUrlstringAPI 伺服器基礎 URL
namespacestring命名空間識別碼
botProviderNamestringBot Provider 名稱
apiKeystringAPI 金鑰,對應 X-API-KEY header

SDK 底層呼叫的端點為 POST {baseUrl}/generic/ns/{namespace}/bot-provider/{botProviderName}/message/sse,並自動帶入 X-API-KEY header。

發送訊息

使用 sendMessage 方法發送訊息並透過 SSE 串流接收回應:

await client.sendMessage({
message: '請說明什麼是機器學習',
onMessage: (content) => {
// 每次收到串流 delta 時觸發
process.stdout.write(content);
},
onComplete: (fullMessage) => {
// 訊息接收完整後觸發
console.log('\n完整回應:', fullMessage);
},
onError: (error) => {
console.error('錯誤:', error.message);
},
});

sendMessage 參數

參數型別必填說明
messagestring使用者訊息內容
onMessage(delta: string) => void收到串流 delta 時的回呼
onComplete(fullMessage: string) => void訊息完整接收後的回呼
onError(error: Error) => void發生錯誤時的回呼
customChannelIdstring指定 channel ID,用於持續對話
filesFile[]附加檔案(支援圖片與文件)

處理 SSE 事件

SDK 底層基於以下 SSE 事件協議,開發者通常不需要直接處理,但了解事件流程有助於除錯:

事件說明
asgard.run.init請求已接收,開始處理
asgard.message.start機器人開始產生回應
asgard.message.delta回應片段,包含部分文字內容
asgard.message.complete單則訊息接收完成
asgard.run.done整個 run 結束

如需直接監聽原始事件,可使用 onEvent 回呼:

await client.sendMessage({
message: '你好',
onEvent: (event) => {
console.log('事件類型:', event.type);
console.log('事件資料:', event.data);
},
});

Channel 管理

Channel 用於維持對話 session,使機器人能記住上下文。

使用自訂 Channel ID

const channelId = 'user-123-session-abc';

await client.sendMessage({
message: '繼續上次的討論',
customChannelId: channelId,
});

取得目前 Channel ID

const currentChannelId = client.getChannelId();
console.log('目前 Channel:', currentChannelId);

重置 Channel

開啟新對話時,可重置 channel 以清除對話記憶:

client.resetChannel();
// 下次 sendMessage 將使用新的 channel

檔案上傳

sendMessage 支援同時附加檔案(需後端支援):

const fileInput = document.querySelector('input[type="file"]');
const files = Array.from(fileInput.files);

await client.sendMessage({
message: '請分析這張圖片',
files: files,
onMessage: (content) => {
console.log(content);
},
});

錯誤處理

建議同時處理 Promise rejection 與 onError 回呼:

try {
await client.sendMessage({
message: '你好',
onError: (error) => {
// 串流過程中的錯誤
console.error('串流錯誤:', error.message);
},
});
} catch (error) {
// 連線或請求層級的錯誤
if (error.status === 401) {
console.error('API 金鑰無效或已過期');
} else if (error.status === 404) {
console.error('Bot Provider 不存在');
} else {
console.error('未預期的錯誤:', error.message);
}
}

常見錯誤碼

HTTP 狀態碼說明
401API 金鑰無效
403無權限存取該 namespace 或 bot
404Bot Provider 不存在
429請求頻率超過限制
500伺服器內部錯誤

TypeScript 支援

@asgard-js/core 內建完整 TypeScript 型別定義,無需額外安裝 @types 套件:

import { AsgardClient, AsgardClientConfig, SendMessageOptions } from '@asgard-js/core';

const config: AsgardClientConfig = {
baseUrl: 'https://api.asgard.example.com',
namespace: 'my-namespace',
botProviderName: 'my-bot',
apiKey: 'your-api-key',
};

const client = new AsgardClient(config);

const options: SendMessageOptions = {
message: '你好',
onMessage: (delta: string) => console.log(delta),
onComplete: (full: string) => console.log('完成:', full),
};

await client.sendMessage(options);