# 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エージェント](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/build/guide/settings-guide.md#%E3%82%A8%E3%83%BC%E3%82%B8%E3%82%A7%E3%83%B3%E3%83%88%E8%A8%AD%E5%AE%9A)）。`GET /v1/marketplace-agents` でも一覧を取れます。

### 認証情報の例

```text
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 フロー を使用して、アクセストークンを取得します。サーバー側で以下のリクエストを実行してください。

### リクエスト例

**Obtain access token**

**curl**

```curl
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"
```

**Python**

```python
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)
```

**TypeScript**

```typescript
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);
```

**Go**

```go
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 で確認したシークレット

### レスポンス例

```json
{
  "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`）も、引き続き使えます。詳しくは[認証ガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/auth-guide.md)を参照してください。

> **トークンの有効期限**
>
> `expires_in` に指定された秒数の間、トークンが有効です。期限切れ前に新しいトークンを取得してください。Client Credentials フローではリフレッシュトークンは発行されないため、期限切れ後は同じリクエストを再度実行してください。

## Step 3: Chat API 呼び出し

取得したアクセストークンを使用して、SSE（Server-Sent Events）経由で Chat API を呼び出します。ストリーム形式でエージェントからのリアルタイム応答を受け取ります。

### リクエスト例

**Create chat completion**

**curl**

```curl
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": "こんにちは"
    }
  ]
}'
```

**Python**

```python
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)
```

**TypeScript**

```typescript
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 ?? "");
  }
}
}
```

**Go**

```go
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 で確認したエージェントID
- `stream: true`: SSE ストリーミングを有効化
- `messages`: ユーザーからのメッセージ。配列形式で複数メッセージも可能

### レスポンス例（SSE ストリーム）

```text
data: {"choices":[{"delta":{"content":"こんにちは"}}]}

data: {"choices":[{"delta":{"content":"、お手伝い"}}]}

data: {"choices":[{"delta":{"content":"できることはありますか"}}]}

data: [DONE]
```

上記は読みやすさのため `delta.content` のみを抜粋しています。実際のチャンクには `createdAt` / `model` / `choices[].index` / `finishReason` などの追加フィールドが含まれます。完全なフォーマットは [API リファレンス](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/api-reference.md#chat) を参照してください。

> **SSE ストリーミングについて**
>
> レスポンスは Server-Sent Events（SSE）形式で、チャンク単位でリアルタイムに送信されます。各チャンクは `data: JSON` 形式です。`data: [DONE]` で会話が完了します。詳細は[ストリーミングガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md)を参照してください。

## 次のステップ

さらに詳しい情報と実装パターンについて、以下のドキュメントを参照してください。

[ストリーミングガイド→](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md)

[SSE接続ライフサイクル・イベント処理・再接続・エラーハンドリング](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/guide/streaming-guide.md)

[システム連携 API リファレンス→](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/api-reference.md)

[エンドポイント仕様・リクエスト/レスポンス形式・エラーコード](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/api-reference.md)

[認証 API リファレンス（MP）→](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/auth-mp-ref.md)

[JWT 構造・トークン取得仕様](https://developers.fd.agenticstar.tm.softbank.jp/docs/marketplace/api/reference/auth-mp-ref.md)
