メインコンテンツまでスキップ

REFERENCE

開発者リファレンス

認証、API、SDK、Flow Agent のプロセッサ、パラメータ解決のリファレンスです。

メッセージを送る

Asgard REST API でテキストメッセージを送り、応答を受け取る完全な例

この例では、Asgard REST API を使って Bot Provider にメッセージを送り、応答を受け取ります。

  1. API のエンドポイント​

    POST {{base_url}}/generic/ns/{{namespace}}/bot-provider/{{bot_provider_name}}/message/sse
  2. customChannelId について​

    customChannelId は対話の識別子で、同じセッションの記憶を保つために使います。同じ customChannelId で複数のメッセージを送ると、Bot は直前までのやり取りを覚えています。新しい対話を始めるときは別の値を使ってください。

  3. cURL の例​

    curl -X POST "https://api.asgard-ai.com/generic/ns/your-namespace/bot-provider/your-bot-provider/message/sse" \
    -H "Content-Type: application/json" \
    -H "X-API-KEY: your-api-key" \
    -d '{
    "customChannelId": "channel-001",
    "customMessageId": "msg-001",
    "text": "パスワードの再設定方法を教えてください",
    "action": "NONE"
    }'
  4. JavaScript(fetch)の例​

    const BASE_URL = 'https://api.asgard-ai.com';
    const NAMESPACE = 'your-namespace';
    const BOT_PROVIDER = 'your-bot-provider';
    const API_KEY = process.env.ASGARD_API_KEY;

    async function sendMessage(channelId, messageId, text) {
    const url = `${BASE_URL}/generic/ns/${NAMESPACE}/bot-provider/${BOT_PROVIDER}/message/sse`;

    const response = await fetch(url, {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'X-API-KEY': API_KEY,
    },
    body: JSON.stringify({
    customChannelId: channelId,
    customMessageId: messageId,
    text: text,
    action: 'NONE',
    }),
    });

    if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
    }

    // SSE のストリームを読み、応答全体を積み上げる
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let fullText = '';

    while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value, { stream: true });
    const lines = chunk.split('\n');

    for (const line of lines) {
    if (!line.startsWith('data:')) continue;

    const jsonStr = line.slice(5).trim();
    if (!jsonStr) continue;

    try {
    const event = JSON.parse(jsonStr);

    if (event.eventType === 'asgard.message.delta') {
    fullText += event.fact.messageDelta.message.text;
    }

    if (event.eventType === 'asgard.message.complete') {
    console.log('応答全体:', fullText);
    }

    if (event.eventType === 'asgard.run.done') {
    console.log('リクエスト完了');
    return fullText;
    }
    } catch (e) {
    // 解析できない行は無視する
    }
    }
    }

    return fullText;
    }

    // 使用例
    sendMessage('channel-001', 'msg-001', 'パスワードの再設定方法を教えてください')
    .then((reply) => console.log('Bot の返信:', reply))
    .catch(console.error);
  5. Python(requests)の例​

    import requests
    import json
    import os

    BASE_URL = "https://api.asgard-ai.com"
    NAMESPACE = "your-namespace"
    BOT_PROVIDER = "your-bot-provider"
    API_KEY = os.environ.get("ASGARD_API_KEY")

    def send_message(channel_id: str, message_id: str, text: str) -> str:
    url = f"{BASE_URL}/generic/ns/{NAMESPACE}/bot-provider/{BOT_PROVIDER}/message/sse"

    headers = {
    "Content-Type": "application/json",
    "X-API-KEY": API_KEY,
    }

    payload = {
    "customChannelId": channel_id,
    "customMessageId": message_id,
    "text": text,
    "action": "NONE",
    }

    full_text = ""

    with requests.post(url, headers=headers, json=payload, stream=True) as response:
    response.raise_for_status()

    for line in response.iter_lines():
    if not line:
    continue

    decoded = line.decode("utf-8")
    if not decoded.startswith("data:"):
    continue

    json_str = decoded[5:].strip()
    if not json_str:
    continue

    try:
    event = json.loads(json_str)
    event_type = event.get("eventType")

    if event_type == "asgard.message.delta":
    text_chunk = event["fact"]["messageDelta"]["message"]["text"]
    full_text += text_chunk

    elif event_type == "asgard.message.complete":
    print(f"応答全体: {full_text}")

    elif event_type == "asgard.run.done":
    print("リクエスト完了")
    break

    except json.JSONDecodeError:
    pass

    return full_text


    if __name__ == "__main__":
    reply = send_message("channel-001", "msg-001", "パスワードの再設定方法を教えてください")
    print(f"Bot の返信: {reply}")
  6. 応答イベントの説明​

    メッセージを送ると、API は SSE(Server-Sent Events)のストリームとして一連のイベントを返します。

    イベント種別説明
    asgard.run.initリクエストの初期化。runId などの情報を含みます
    asgard.message.deltaメッセージの断片。タイプライター風の表示に使います
    asgard.message.complete完全なメッセージ。template の描画データを含みます
    asgard.run.doneリクエストの終了。ストリームが閉じます

    イベントの詳しい形式は SSE 応答イベントの説明 をご覧ください。

  7. 次に読む​

始める準備はできましたか?

Asgard をチームでどう活用できるか、お気軽にご相談ください。

お問い合わせ