> ## Documentation Index
> Fetch the complete documentation index at: https://www.krea.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent API

> API キーで HTTP 経由で Krea Agent のセッションを開始し、ターンの完了を待って結果を読み取り、フォローアップを送信する方法を解説します。

Agent API を使うと、独自のアプリケーションから Krea Agent にタスクを渡せます。リクエストとレスポンスでは camelCase の JSON フィールドを使用します。Agent はバックグラウンドで作業し、その間にアプリケーションが進捗と結果を読み取ります。

| エンドポイント | 用途 |
| - | - |
| [`POST /agent/send-message`](/docs/api-reference/agent/send-agent-message) | セッションを開始する、またはフォローアップのターンを送信します。 |
| [`GET /agent/session/{sessionId}`](/docs/api-reference/agent/get-agent-session) | 待機せずに現在のセッションを読み取ります。 |
| [`POST /agent/wait-for-session`](/docs/api-reference/agent/wait-for-agent-session) | タイムアウトまでの間、ターンの完了を待ちます。 |

<Warning>
  Agent はバックグラウンドで作業します。質問はせず、コストや権限の確認は自動的に承認されます。すべての要件と制約をプロンプトに含めてください。送信前にタスクの内容を確認してください。
</Warning>

## 認証、アクセス、請求

`https://api.krea.ai` へのすべてのリクエストに `Authorization: Bearer KREA_API_KEY` を付けて送信します。個人用、サービス用、レガシーの API キーは、標準の [公開 API 認証](/docs/ja/developers/api-keys-and-billing) を使用します。

読み取りや継続ができるのは、認証されたワークスペース内で、認証された呼び出し元が所有するセッションのみです。セッション ID を知っていてもアクセス権は付与されません。Krea のファイル添付も、そのワークスペース内でその呼び出し元がアクセスできるものである必要があります。

<Info>
  Agent のターンはワークスペースの compute units 残高を使用します。API 残高は**使用しません**。Agent プランの利用権限と Free プランのメッセージ上限は引き続き適用されます。[Agent のプラン、アクセス、クレジット](/docs/ja/user-guide/agent/plans-and-credits) を参照してください。
</Info>

各レスポンスには `url` が含まれており、適切なアカウントとワークスペースのアクセス権があれば、Krea アプリでセッションを開くことができます。

## セッションを開始して結果を待つ

まず環境変数に `KREA_API_KEY` を設定します。`curl` と `jq` を使う Bash、`requests` を使う Python、または組み込みの `fetch` か Krea SDK を使う Node.js から選んでください。

<Steps>
  <Step title="最初のターンを送信する">
    セッションを作成するには `sessionId` を省略します。返された `sessionId` と `runId` を保存してください。レスポンスは `status: "running"` で即座に返されます。
  </Step>

  <Step title="このターンを待つ">
    両方の ID を `wait-for-session` に渡します。`timedOut` が `true` の場合は、同じ ID で再度呼び出してください。タイムアウトしてもターンはキャンセルされません。
  </Step>

  <Step title="結果を読み取る">
    `finished` が `true` になったら `status` を確認します。`text`、`media`、および `error` があればそれを確認するか、返された `url` を開いてください。
  </Step>
</Steps>

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
  set -euo pipefail
  : "${KREA_API_KEY:?Set your Krea API key}"

  START=$(curl --fail-with-body --silent --show-error --max-time 60 \
    https://api.krea.ai/agent/send-message \
    -H "Authorization: Bearer $KREA_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "Create three square product images for a ceramic coffee mug on a neutral studio background. Use no text or logos.",
      "name": "Coffee mug campaign"
    }')

  SESSION_ID=$(printf '%s' "$START" | jq -er '.sessionId')
  RUN_ID=$(printf '%s' "$START" | jq -er '.runId')
  printf '%s' "$START" | jq -r '.url'

  DEADLINE=$((SECONDS + 300))

  while (( SECONDS < DEADLINE - 10 )); do
    WAIT_SECONDS=$((DEADLINE - SECONDS - 10))
    if (( WAIT_SECONDS > 60 )); then WAIT_SECONDS=60; fi
    WAIT_BODY=$(jq -n --arg sessionId "$SESSION_ID" --arg runId "$RUN_ID" \
      --argjson timeoutSeconds "$WAIT_SECONDS" \
      '{sessionId: $sessionId, runId: $runId, timeoutSeconds: $timeoutSeconds}')
    RESULT=$(curl --fail-with-body --silent --show-error --max-time "$((WAIT_SECONDS + 10))" \
      https://api.krea.ai/agent/wait-for-session \
      -H "Authorization: Bearer $KREA_API_KEY" \
      -H "Content-Type: application/json" \
      -d "$WAIT_BODY")
    printf '%s' "$RESULT" | jq '{status, finished, timedOut, text, media, error, url}'
    if printf '%s' "$RESULT" | jq -e '.finished' > /dev/null; then
      if printf '%s' "$RESULT" | jq -e '.status == "completed"' > /dev/null; then
        exit 0
      fi
      printf '%s' "$RESULT" | jq -r '"Turn ended: \(.status). \(.error // "No error details")"' >&2
      exit 1
    fi
  done

  printf 'Wait budget exhausted; the turn continues. Resume waiting with sessionId=%s runId=%s\n' \
    "$SESSION_ID" "$RUN_ID" >&2
  exit 1
  ```

  ```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
  import json
  import os
  import time
  import requests

  api = "https://api.krea.ai"
  headers = {"Authorization": f"Bearer {os.environ['KREA_API_KEY']}"}

  response = requests.post(
      f"{api}/agent/send-message",
      headers=headers,
      json={
          "prompt": "Create three square product images for a ceramic coffee mug on a neutral studio background. Use no text or logos.",
          "name": "Coffee mug campaign",
      },
      timeout=60,
  )
  response.raise_for_status()
  start = response.json()
  session_id, run_id = start["sessionId"], start["runId"]
  print(start["url"])

  deadline = time.monotonic() + 300
  while True:
      wait_seconds = min(60, int(deadline - time.monotonic()) - 10)
      if wait_seconds < 1:
          raise TimeoutError(
              "Wait budget exhausted; the turn continues. Resume waiting with "
              f"sessionId={session_id} runId={run_id}"
          )
      response = requests.post(
          f"{api}/agent/wait-for-session",
          headers=headers,
          json={
              "sessionId": session_id,
              "runId": run_id,
              "timeoutSeconds": wait_seconds,
          },
          timeout=wait_seconds + 10,
      )
      response.raise_for_status()
      result = response.json()
      print(json.dumps(result, indent=2))
      if result["finished"]:
          if result["status"] != "completed":
              raise RuntimeError(
                  f"Turn ended: {result['status']}. {result.get('error', 'No error details')}"
              )
          break
  ```

  ```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
  import { performance } from "node:perf_hooks";

  const token = process.env.KREA_API_KEY;
  if (!token) throw new Error("Set your Krea API key");
  const api = "https://api.krea.ai";

  async function post(path, body, timeoutMs) {
    const response = await fetch(`${api}${path}`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(timeoutMs),
    });
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }
    return response.json();
  }

  const start = await post("/agent/send-message", {
    prompt: "Create three square product images for a ceramic coffee mug on a neutral studio background. Use no text or logos.",
    name: "Coffee mug campaign",
  }, 60_000);
  const { sessionId, runId } = start;
  console.log(start.url);

  const deadline = performance.now() + 300_000;
  while (true) {
    const timeoutSeconds = Math.min(60, Math.floor((deadline - performance.now()) / 1000) - 10);
    if (timeoutSeconds < 1) {
      throw new Error(
        `Wait budget exhausted; the turn continues. Resume waiting with sessionId=${sessionId} runId=${runId}`,
      );
    }
    const result = await post("/agent/wait-for-session", {
      sessionId,
      runId,
      timeoutSeconds,
    }, (timeoutSeconds + 10) * 1000);
    console.log(JSON.stringify(result, null, 2));
    if (result.finished) {
      if (result.status !== "completed") {
        throw new Error(`Turn ended: ${result.status}. ${result.error ?? "No error details"}`);
      }
      break;
    }
  }
  ```

  ```javascript Node.js (SDK) theme={"theme":{"light":"github-light-default","dark":"vesper"}}
  import { performance } from "node:perf_hooks";
  import { Krea } from "@krea-ai/sdk";

  const token = process.env.KREA_API_KEY;
  if (!token) throw new Error("Set your Krea API key");
  const krea = new Krea({ apiKey: token });

  const start = await krea.requestRaw("/agent/send-message", {
    method: "POST",
    retry: false,
    signal: AbortSignal.timeout(60_000),
    body: {
      prompt: "Create three square product images for a ceramic coffee mug on a neutral studio background. Use no text or logos.",
      name: "Coffee mug campaign",
    },
  });
  const { sessionId, runId } = start;
  console.log(start.url);

  const deadline = performance.now() + 300_000;
  while (true) {
    const timeoutSeconds = Math.min(60, Math.floor((deadline - performance.now()) / 1000) - 15);
    if (timeoutSeconds < 1) {
      throw new Error(
        `Wait budget exhausted; the turn continues. Resume waiting with sessionId=${sessionId} runId=${runId}`,
      );
    }
    const result = await krea.requestRaw("/agent/wait-for-session", {
      method: "POST",
      retry: false,
      signal: AbortSignal.timeout((timeoutSeconds + 15) * 1000),
      body: { sessionId, runId, timeoutSeconds },
    });
    console.log(JSON.stringify(result, null, 2));
    if (result.finished) {
      if (result.status !== "completed") {
        throw new Error(`Turn ended: ${result.status}. ${result.error ?? "No error details"}`);
      }
      break;
    }
  }
  ```
</CodeGroup>

Python の場合は `pip install requests` で `requests` をインストールしてください。Node.js の場合は Node.js 22 以降を使用し、サンプルを `example.mjs` として保存してください。SDK のサンプルには `npm install @krea-ai/sdk` が必要で、HTTP エンドポイントの呼び出しに `requestRaw` を使用します。

これらのサンプルは 1 件のメッセージを送信し、最大 5 分間待機します。HTTP エラー、および失敗またはキャンセルされたターンでは停止します。送信を自動的にリトライすることはありません。送信リクエストがタイムアウトした場合は、再送信する前に Krea でセッションを確認してください。最初のリクエストでターンが開始されている可能性があります。

待機時間の上限に達しても、ターンはバックグラウンドで継続します。出力されたセッション ID と実行 ID を保存しておけば、後で待機を再開できます。

`timeoutSeconds` は `1` から `300` までの整数で、デフォルトは `60` です。HTTP クライアントのタイムアウトは、リクエストする待機時間より長く設定してください。送信後に待機するときは、前のターンの終了ステータスを新しいターンのものと取り違えないよう、常に最新の `runId` を渡してください。

### 待機せずに読み取る

`GET /agent/session/{sessionId}` を使うと、現在のセッションのスナップショットを取得できます。

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl --fail-with-body --silent --show-error \
  "https://api.krea.ai/agent/session/$SESSION_ID" \
  -H "Authorization: Bearer $KREA_API_KEY"
```

### セッションを継続する

ターンが完了したら、その `sessionId` を指定して別のメッセージを送信します。

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
FOLLOW_UP=$(curl --fail-with-body --silent --show-error \
  https://api.krea.ai/agent/send-message \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg sessionId "$SESSION_ID" \
    '{sessionId: $sessionId, prompt: "Make a landscape variation of the first image."}')")

# Use this new runId in the next wait-for-session request.
RUN_ID=$(printf '%s' "$FOLLOW_UP" | jq -er '.runId')
```

1 つのセッションで同時に実行できるターンは 1 つだけです。ターンの実行中に別のメッセージを送信すると、`code: "conflict"` とともに `409` が返されます。

## 入力と添付ファイル

`send-message` は次のフィールドを受け付けます。モデルの enum とスキーマの全体については [リファレンス](/docs/api-reference/agent/send-agent-message) を参照してください。

| フィールド | 動作 |
| - | - |
| `sessionId` | 任意の UUID。新しいセッションの場合は省略し、所有するセッションを継続する場合は指定します。 |
| `prompt` | 最大 100,000 文字の文字列。デフォルトは `""`。空白でないプロンプトか、少なくとも 1 つの添付ファイルが必要です。 |
| `attachments` | 最大 20 件の添付ファイル。デフォルトは `[]`。各項目には `url` が必要で、`name` と `contentType` を含めることもできます。 |
| `model` | 任意の Agent LLM ID。Auto にする場合は省略します。固定するモデルはワークスペースのプランに含まれている必要があります。 |
| `effort` | 任意: `fast`、`default`、`high`、`xhigh`。新しいセッションのデフォルトは `default` です。既存セッションの effort を維持する場合は省略します。 |
| `name` | 任意のセッション名で、新しいセッションでのみ使用できます。前後の空白は除去され、空でない最大 120 文字の文字列である必要があります。 |
| `desktopAppId` | 接続済みのデスクトップアプリを識別する任意の UUID。このターンをそのアプリ内で実行します。アプリは認証された呼び出し元とワークスペースで利用可能である必要があります。 |

添付ファイルの `url` には、アクセス可能な HTTP(S) URL、または `file:550e8400-e29b-41d4-a716-446655440000` のような認可済みの Krea Files URI を指定できます。任意の `name` と `contentType` は、前後の空白が除去された、空でない最大 255 文字の文字列です。呼び出し元のローカルパスや OpenAI の `file_` ID はサポートされていません。先に実際のファイルを転送してください。プロンプトのテキストに ID を書いても、その内容は転送されません。

Agent はアプリケーション側の会話や添付ファイルを引き継ぎません。他の方法ではアクセスできない参照ファイルは添付してください。プロンプト内、既存の Krea コンテキスト、または以前のセッションファイルにある利用可能な URL を繰り返し指定する必要はありません。

## セッションの結果

`send-message` は `sessionId`、`threadId`、`runId`、`status`(常に `"running"`)、`url` を返します。

`GET /agent/session/{sessionId}` と `wait-for-session` は、次のセッションビューを返します。必須の `timedOut` フィールドが追加されるのは `wait-for-session` のみです。

| フィールド | 意味 |
| - | - |
| `sessionId`, `threadId` | セッションとルートスレッドの識別子。 |
| `runId` | 現在のターンの識別子(利用可能な場合)。 |
| `status` | `not_started`、`running`、`completed`、`failed`、`cancelled` のいずれか。 |
| `finished` | ターンが終了状態の場合は `true`。待機時に `runId` を指定した場合、終了したターンがその ID と一致している必要もあります。 |
| `text` | アシスタントの最新メッセージのテキスト。 |
| `media` | セッションで生成されたメディアの配列。順序に意味はありません。 |
| `error` | セッションの任意のエラーテキスト。 |
| `url` | Krea アプリ内のセッションへのリンク。 |
| `timedOut` | 待機のレスポンスのみ: リクエストしたターンが完了する前に期限を過ぎた場合は `true`。 |

各 `media` 項目は、生成物(`jobId` と任意の `mediaKind`: `image`、`video`、`audio`、`3d`)、再ホストされたメディア(`url` と任意の `mimeType`)、または Krea ファイル(`uri`、`name`、`mimeType`)のいずれかを表します。生成物の詳細は `GET /jobs/{jobId}` で取得してください。Krea ファイルの URI は添付ファイルとして再利用できます。また、セッションの `url` を開いてファイルを表示することもできます。メディアはターンの実行中にも表示されることがあります。

## エラー

エンドポイントのエラーは `{ "error": "...", "code": "...", "allowedModels": ["..."] }` の形式です。必須なのは `error` のみです。送信後に失敗したターンは、代わりに成功したセッションレスポンス内で `status: "failed"` として表示されます。

| HTTP ステータス | 意味 |
| - | - |
| `400` | JSON ボディの形式が不正です。 |
| `401` | 認証情報がない、または無効です。 |
| `402` | ワークスペースの compute units 残高が不足しているか(`compute_limit`)、Free プランのメッセージ上限に達しました(`free_message_limit`)。 |
| `403` | 固定したモデルの利用権限がありません(`model_not_entitled`)。`allowedModels` に許可された ID が列挙されます。 |
| `404` | セッションが存在しないかアクセスできません(`not_found`)。または Krea ファイルの添付が存在しないかアクセスできません(`attachment_not_found`)。 |
| `409` | すでにターンが進行中です(`conflict`)。 |
| `422` | 入力が無効か、選択したデスクトップアプリが利用できません。 |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.