API を呼び出す
Client Credentials 認証でトークンを取得し、SSE 経由でエージェントと会話するまでの手順を解説します。
はじめに
マーケットプレイス版の API を利用するための最短ステップを紹介します。以下の3つのステップでエージェントとの会話を開始できます。
- マーケットプレイスで購入した AGENTIC STAR 環境のセットアップが完了していること
- 管理コンソールでサービスアカウントを作成済みであること
- ベース URL、Client ID、Client Secret、Agent ID が手元にあること
Step 1: 認証情報の確認
Chat API を呼び出すために必要な情報を、管理者と管理コンソールで確認します。確かめる所が異なる点に注意してください。
管理者に確かめる情報
- Base URL — 外部 API のドメイン(
https://<your-domain>)。構築の時に管理者が決めたものです - 認証サービスのドメイン — トークンを取る所(
https://<auth-domain>)。構築の時に管理者が決めたものです
サービスアカウント詳細画面で確認する情報
- Client ID — サービスアカウントに発行されたクライアント ID
- Client Secret — サービスアカウントに発行されたシークレット
管理コンソールで確認する情報
- Agent ID — Chat API の
agentIdパラメータに指定するエージェントの識別子。管理コンソールの「AIエージェント」→「マーケットプレイスのAIエージェント」から対象エージェントの詳細画面で確認できます(設定ガイド — マーケットプレイスのAIエージェント)。GET /v1/marketplace-agentsでも一覧を取れます。
認証情報の例
Base URL: https://<your-domain>
Auth URL: https://<auth-domain>
Client ID: mp-service-001
Client Secret: (hidden)
Agent ID: agent-ai-bot
Step 2: トークンの取得
Client Credentials フロー を使用して、アクセストークンを取得します。サーバー側で以下のリクエストを実行してください。
リクエスト例
1curl -X POST https://<auth-domain>/api/v1/oauth/token \2-u "<your-client-id>:<your-client-secret>" \3-H "Content-Type: application/x-www-form-urlencoded" \4-d "grant_type=client_credentials"curl -X POST https://<auth-domain>/api/v1/oauth/token \ -u "<your-client-id>:<your-client-secret>" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials"
import requests
response = requests.post(
"https://<auth-domain>/api/v1/oauth/token",
auth=("<your-client-id>", "<your-client-secret>"),
data={"grant_type": "client_credentials"},
)
token = response.json()["access_token"]
print(token)const credentials = btoa("<your-client-id>:<your-client-secret>");
const response = await fetch("https://<auth-domain>/api/v1/oauth/token", {
method: "POST",
headers: {
Authorization: `Basic ${credentials}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({ grant_type: "client_credentials" }),
});
const { access_token } = await response.json();
console.log(access_token);package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
func main() {
form := url.Values{"grant_type": {"client_credentials"}}
req, _ := http.NewRequest(
"POST",
"https://<auth-domain>/api/v1/oauth/token",
strings.NewReader(form.Encode()),
)
req.SetBasicAuth("<your-client-id>", "<your-client-secret>")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result["access_token"])
}パラメータ
<auth-domain>: Step 1 で確認した認証サービスのドメイン(例: auth.example.com)<your-client-id>: Step 1 で確認したクライアント ID<your-client-secret>: Step 1 で確認したシークレット
レスポンス例
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 86400,
"scope": "openid profile email"
}
これまでの POST https://<auth-domain>/api/v1/auth/external-service-token(本文は JSON の client_id・client_secret)も、引き続き使えます。詳しくは認証ガイドを参照してください。
expires_in に指定された秒数の間、トークンが有効です。期限切れ前に新しいトークンを取得してください。Client Credentials フローではリフレッシュトークンは発行されないため、期限切れ後は同じリクエストを再度実行してください。
Step 3: Chat API 呼び出し
取得したアクセストークンを使用して、SSE(Server-Sent Events)経由で Chat API を呼び出します。ストリーム形式でエージェントからのリアルタイム応答を受け取ります。
リクエスト例
1curl -X POST https://<your-domain>/api/v1/chat/completions \2-H "Authorization: Bearer <access_token>" \3-H "Content-Type: application/json" \4-d '{5 "model": "AGENTIC STAR",6 "stream": true,7 "agentId": "<your-agent-id>",8 "messages": [9 {10 "role": "user",11 "content": "こんにちは"12 }13 ]14}'curl -X POST https://<your-domain>/api/v1/chat/completions \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{
"model": "AGENTIC STAR",
"stream": true,
"agentId": "<your-agent-id>",
"messages": [
{
"role": "user",
"content": "こんにちは"
}
]
}'import requests
import json
response = requests.post(
"https://<your-domain>/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
json={
"model": "AGENTIC STAR",
"stream": True,
"agentId": "<your-agent-id>",
"messages": [{"role": "user", "content": "こんにちは"}],
},
stream=True,
)
for line in response.iter_lines():
if line:
data = line.decode("utf-8")
if data == "data: [DONE]":
break
if data.startswith("data: "):
chunk = json.loads(data[6:])
content = chunk["choices"][0]["delta"].get("content", "")
print(content, end="", flush=True)const response = await fetch(
"https://<your-domain>/api/v1/chat/completions",
{
method: "POST",
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "AGENTIC STAR",
stream: true,
agentId: "<your-agent-id>",
messages: [{ role: "user", content: "こんにちは" }],
}),
}
);
const reader = response.body?.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader?.read() || { done: true };
if (done) break;
for (const line of decoder.decode(value).split("\n")) {
if (line.startsWith("data: ") && line !== "data: [DONE]") {
const chunk = JSON.parse(line.slice(6));
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
}
}package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
)
func main() {
token := "<access_token>" // Step 2 で取得したアクセストークン
body, _ := json.Marshal(map[string]interface{}{
"model": "AGENTIC STAR",
"stream": true,
"agentId": "<your-agent-id>",
"messages": []map[string]string{
{"role": "user", "content": "こんにちは"},
},
})
req, _ := http.NewRequest("POST",
"https://<your-domain>/api/v1/chat/completions",
bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
data := line[6:]
if data == "[DONE]" { break }
var chunk map[string]interface{}
json.Unmarshal([]byte(data), &chunk)
choices, _ := chunk["choices"].([]interface{})
if len(choices) > 0 {
delta, _ := choices[0].(map[string]interface{})["delta"].(map[string]interface{})
if content, ok := delta["content"].(string); ok {
fmt.Print(content)
}
}
}
}
}パラメータ
<access_token>: Step 2 で取得したアクセストークン<your-agent-id>: Step 1 で確認したエージェントIDstream: true: SSE ストリーミングを有効化messages: ユーザーからのメッセージ。配列形式で複数メッセージも可能
レスポンス例(SSE ストリーム)
data: {"choices":[{"delta":{"content":"こんにちは"}}]}
data: {"choices":[{"delta":{"content":"、お手伝い"}}]}
data: {"choices":[{"delta":{"content":"できることはありますか"}}]}
data: [DONE]
上記は読みやすさのため delta.content のみを抜粋しています。実際のチャンクには createdAt / model / choices[].index / finishReason などの追加フィールドが含まれます。完全なフォーマットは API リファレンス を参照してください。
レスポンスは Server-Sent Events(SSE)形式で、チャンク単位でリアルタイムに送信されます。各チャンクは data: JSON 形式です。data: [DONE] で会話が完了します。詳細はストリーミングガイドを参照してください。
次のステップ
さらに詳しい情報と実装パターンについて、以下のドキュメントを参照してください。