> ## 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

> Krea Agent oturumlarını API anahtarınızla HTTP üzerinden yönetin: oturum başlatın, bir turun bitmesini bekleyin, sonuçları okuyun ve takip mesajı gönderin.

Krea Agent'a kendi uygulamanızdan görev vermek için Agent API'yi kullanın. İstekler ve yanıtlar camelCase JSON alanları kullanır. Ajan arka planda çalışırken uygulamanız ilerlemesini ve sonuçlarını okur.

| Uç nokta | Amaç |
| - | - |
| [`POST /agent/send-message`](/docs/api-reference/agent/send-agent-message) | Bir oturum başlatın veya bir takip turu gönderin. |
| [`GET /agent/session/{sessionId}`](/docs/api-reference/agent/get-agent-session) | Mevcut oturumu beklemeden okuyun. |
| [`POST /agent/wait-for-session`](/docs/api-reference/agent/wait-for-agent-session) | Bir turun bitmesini, bir zaman aşımına kadar bekleyin. |

<Warning>
  Ajan arka planda çalışır. Soru sormaz; maliyet ve izin onayları otomatik olarak kabul edilir. Tüm gereksinimleri ve kısıtlamaları isteminize ekleyin. Göndermeden önce görevi gözden geçirin.
</Warning>

## Kimlik doğrulama, erişim ve faturalandırma

`https://api.krea.ai` adresine yapılan her istekte `Authorization: Bearer KREA_API_KEY` gönderin. Kişisel, servis ve eski API anahtarları standart [genel API kimlik doğrulamasını](/docs/tr/developers/api-keys-and-billing) kullanır.

Yalnızca kimliği doğrulanmış çalışma alanında, kimliği doğrulanmış çağırana ait oturumları okuyabilir veya sürdürebilirsiniz. Bir oturum ID'sini bilmek erişim sağlamaz. Krea dosya ekleri de o çalışma alanında o çağıran tarafından erişilebilir olmalıdır.

<Info>
  Ajan turları çalışma alanının hesaplama birimi bakiyesini kullanır. API bakiyesini **kullanmaz**. Agent plan hakları ve Free plan mesaj limitleri yine geçerlidir. [Agent planları, erişim ve krediler](/docs/tr/user-guide/agent/plans-and-credits) sayfasına bakın.
</Info>

Her yanıt, uygun hesap ve çalışma alanı erişimiyle oturumu Krea uygulamasında açabileceğiniz bir `url` içerir.

## Bir oturum başlatın ve sonucunu bekleyin

Önce ortamınızda `KREA_API_KEY` değişkenini ayarlayın. `curl` ve `jq` ile Bash, `requests` ile Python veya yerleşik `fetch` ya da Krea SDK ile Node.js seçin.

<Steps>
  <Step title="İlk turu gönderin">
    Oturum oluşturmak için `sessionId` alanını belirtmeyin. Dönen `sessionId` ve `runId` değerlerini kaydedin. Yanıt `status: "running"` ile hemen döner.
  </Step>

  <Step title="Bu turu bekleyin">
    Her iki ID'yi de `wait-for-session` uç noktasına iletin. `timedOut` değeri `true` ise aynı ID'lerle tekrar çağırın. Zaman aşımı turu iptal etmez.
  </Step>

  <Step title="Sonucu okuyun">
    `finished` değeri `true` olduğunda `status` alanını kontrol edin. `text`, `media` ve varsa `error` alanlarını inceleyin veya dönen `url` adresini açın.
  </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 için `requests` paketini `pip install requests` ile kurun. Node.js için Node.js 22+ kullanın ve örneği `example.mjs` olarak kaydedin. SDK örneği `npm install @krea-ai/sdk` gerektirir ve HTTP uç noktalarını çağırmak için `requestRaw` kullanır.

Bu örnekler tek bir mesaj gönderir ve en fazla beş dakika bekler. HTTP hatalarında ve başarısız ya da iptal edilen turlarda dururlar. Bir gönderimi asla otomatik olarak yeniden denemezler. Bir gönderim isteği zaman aşımına uğrarsa, tekrar göndermeden önce oturumu Krea'da kontrol edin; ilk istek bir tur başlatmış olabilir.

Bekleme süresi dolduğunda tur arka planda devam eder. Beklemeye daha sonra devam etmek için yazdırılan oturum ve çalıştırma ID'lerini kaydedin.

`timeoutSeconds`, `1` ile `300` arasında bir tam sayıdır ve varsayılan değeri `60`'tır. HTTP istemcinizin zaman aşımını istenen bekleme süresinden uzun tutun. Bir gönderimden sonra beklerken her zaman en son `runId` değerini iletin; böylece önceki turun son durumu yeni turun durumu sanılmaz.

### Beklemeden okuma

Mevcut oturumun anlık görüntüsünü almak için `GET /agent/session/{sessionId}` kullanın:

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

### Oturumu sürdürme

Tur bittikten sonra, `sessionId` değeriyle yeni bir mesaj gönderin:

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

Bir oturum aynı anda tek bir tur çalıştırır. Bir tur çalışırken yeni mesaj göndermek `code: "conflict"` ile `409` döndürür.

## Girdiler ve ekler

`send-message` şu alanları kabul eder. Tam model enum'u ve şemalar için [referansa](/docs/api-reference/agent/send-agent-message) bakın.

| Alan | Davranış |
| - | - |
| `sessionId` | İsteğe bağlı UUID. Yeni oturum için belirtmeyin; size ait bir oturumu sürdürmek için ekleyin. |
| `prompt` | En fazla 100.000 karakterlik dize. Varsayılan `""`. Boş olmayan bir istem veya en az bir ek gereklidir. |
| `attachments` | En fazla 20 ek. Varsayılan `[]`. Her biri `url` gerektirir ve `name` ile `contentType` içerebilir. |
| `model` | İsteğe bağlı Agent LLM ID'si. Auto için belirtmeyin. Sabitlenen model çalışma alanı planına dahil olmalıdır. |
| `effort` | İsteğe bağlı: `fast`, `default`, `high` veya `xhigh`. Yeni oturumlarda varsayılan `default`'tur; mevcut bir oturumun effort değerini korumak için belirtmeyin. |
| `name` | İsteğe bağlı oturum adı, yalnızca yeni oturumlar için. Baştaki ve sondaki boşluklar kırpılır; boş olamaz ve en fazla 120 karakter olabilir. |
| `desktopAppId` | Bağlı bir masaüstü uygulamasını tanımlayan isteğe bağlı UUID. Bu turu o uygulamanın içinde çalıştırır. Uygulama, kimliği doğrulanmış çağıran ve çalışma alanı için kullanılabilir olmalıdır. |

Ek `url` alanı, erişilebilir bir HTTP(S) URL'sini veya `file:550e8400-e29b-41d4-a716-446655440000` gibi yetkili bir Krea Files URI'sini kabul eder. İsteğe bağlı `name` ve `contentType`, boşlukları kırpılmış, boş olmayan ve en fazla 255 karakterlik dizelerdir. Çağıranın yerel yolları ve OpenAI `file_` ID'leri desteklenmez. Önce asıl dosyayı aktarın; istem metnindeki bir ID dosyanın içeriğini aktarmaz.

Ajan, uygulamanızın konuşmasını veya eklerini devralmaz. Başka şekilde erişilemeyen referans dosyalarını ekleyin. İstemdeki kullanılabilir URL'leri, mevcut Krea context'ini veya önceki oturum dosyalarını tekrarlamanız gerekmez.

## Oturum sonuçları

`send-message`; `sessionId`, `threadId`, `runId`, `status` (her zaman `"running"`) ve `url` döndürür.

`GET /agent/session/{sessionId}` ve `wait-for-session` aşağıdaki oturum görünümünü döndürür. Zorunlu `timedOut` alanını yalnızca `wait-for-session` ekler.

| Alan | Anlamı |
| - | - |
| `sessionId`, `threadId` | Oturum ve kök thread tanımlayıcıları. |
| `runId` | Mevcut tur tanımlayıcısı (varsa). |
| `status` | `not_started`, `running`, `completed`, `failed` veya `cancelled`. |
| `finished` | Sonlanmış bir tur için `true`. Bir beklemeye `runId` verildiyse, sonlanan turun da o ID ile eşleşmesi gerekir. |
| `text` | En son asistan mesajının metni. |
| `media` | Oturumun ürettiği medya dizisi. Sıralama önemli değildir. |
| `error` | Oturum için isteğe bağlı hata metni. |
| `url` | Krea uygulamasındaki oturumun bağlantısı. |
| `timedOut` | Yalnızca bekleme yanıtlarında: istenen tur bitmeden süre dolduysa `true`. |

Her `media` öğesi bir üretimi (`jobId` ve isteğe bağlı `mediaKind`: `image`, `video`, `audio` veya `3d`), yeniden barındırılan medyayı (`url`, isteğe bağlı `mimeType` ile) veya bir Krea dosyasını (`uri`, `name`, `mimeType`) temsil edebilir. Üretim ayrıntılarını `GET /jobs/{jobId}` ile alın. Bir Krea dosya URI'sini ek olarak yeniden kullanabilir veya dosyalarını görmek için oturumun `url` adresini açabilirsiniz. Medya, tur hâlâ çalışırken görünebilir.

## Hatalar

Uç nokta hataları `{ "error": "...", "code": "...", "allowedModels": ["..."] }` biçimini kullanır. Yalnızca `error` zorunludur. Gönderimden sonra başarısız olan bir tur, bunun yerine başarılı bir oturum yanıtında `status: "failed"` olarak görünür.

| HTTP durumu | Anlamı |
| - | - |
| `400` | Hatalı biçimlendirilmiş JSON gövdesi. |
| `401` | Eksik veya geçersiz kimlik doğrulama. |
| `402` | Çalışma alanında yetersiz hesaplama birimi bakiyesi (`compute_limit`) veya Free plan mesaj limitine ulaşıldı (`free_message_limit`). |
| `403` | Sabitlenen model plana dahil değil (`model_not_entitled`); `allowedModels` izin verilen ID'leri listeler. |
| `404` | Oturum yok veya erişilemiyor (`not_found`) ya da bir Krea dosya eki yok veya erişilemiyor (`attachment_not_found`). |
| `409` | Zaten devam eden bir tur var (`conflict`). |
| `422` | Geçersiz girdi veya seçilen masaüstü uygulaması kullanılamıyor. |


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