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

# 非同期ジョブ

> バッチとクロールはバックグラウンドで実行されます。ジョブを時間制限付きで待機する方法と、ジョブIDで後から結果を取得する方法を学びましょう。

スクレイプ、検索、回答、マップはレスポンスで結果を返します。バッチとクロールは異なります。これらはバックグラウンドで実行され、作成リクエストはすぐにジョブの`id`を返します。

## 非同期ジョブの仕組み

1. **ジョブを作成**するには`POST /v1/batches`または`POST /v1/crawls`を使用します。レスポンスから`id`を保存します。
2. **ジョブを待機します。** `GET /v1/batches/{batch_id}`または`GET /v1/crawls/{crawl_id}`をチェックし、`status`が`completed`になるまで待ちます。
3. **結果を取得します。** バッチのアイテムまたはクロールのページをリストします。その後、各結果の`retrieve_id`でコンテンツを取得します。

ステップ2と3では保存したジョブIDを使用します。プログラムが停止した場合、そのIDを使用してステータスを確認し、結果を取得します。新しい作成リクエストは作業を繰り返し、より多くのクレジットを使用する可能性があります。

## `completed`の意味

`status`が`completed`になったら、ジョブのステータスを確認するのをやめて結果をリストします。バッチのコンテンツは読み取り可能になるまでに時間がかかることがあります。APIが`failed`を返した場合、待機をやめてサポートのためにジョブIDを保持してください。

`completed`はすべてのURLが成功したことを意味しません：

* **バッチ:** 完了したバッチには失敗したURLが含まれることがあります。`GET /v1/batches/{batch_id}/items?status=failed`でリストします。
* **クロール:** クロールは0ページで完了することがあります。`pages_count`を確認します。ページのレスポンスは`metadata.failed_urls`に失敗したURLをリストします。
* **コンテンツ:** `GET /v1/retrieve`のレスポンスで`size_exceeded`が`true`の場合、`markdown_hosted_url`からMarkdownを取得します。バッチが完了した直後に`markdown_content`と`markdown_hosted_url`の両方が空の場合、後で同じ`retrieve_id`を再試行してください。

## 時間制限付きで待機

以下のヘルパーはチェックの間に10秒待機します。30分後には新しいチェックを開始しません。また、HTTPエラー（例：`401`または`429`）で停止します。停止してもジョブはキャンセルされません：後でIDで再確認できます。

Python 3.9以降またはNode.js 18以降を使用してください。Pythonの場合、`python -m pip install requests`でRequestsをインストールします。サンプルを実行する前に`OLOSTEP_API_KEY`環境変数を設定してください。

```python wait_for_job.py theme={null}
import os
import time

import requests

API_KEY = os.environ["OLOSTEP_API_KEY"]
API_URL = "https://api.olostep.com/v1"


def wait_for_job(path, timeout_s=1800, interval_s=10):
    """Check GET /v1/<path> until the job is completed or failed.

    Wait interval_s seconds between checks. Start no new check after
    timeout_s seconds. Stopping does not cancel the job.
    """
    deadline = time.monotonic() + timeout_s
    while time.monotonic() < deadline:
        response = requests.get(
            f"{API_URL}/{path}",
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=30,
        )
        response.raise_for_status()  # Stop on an HTTP error, for example 401 or 429
        job = response.json()
        if not isinstance(job.get("status"), str):
            raise ValueError(f"{path}: no status in the response")
        print("Status:", job["status"])
        if job["status"] == "completed":
            return job
        if job["status"] == "failed":
            raise RuntimeError(f"{path} failed")
        time.sleep(interval_s)
    raise TimeoutError(f"{path} is not complete after {timeout_s} seconds")
```

```javascript waitForJob.mjs theme={null}
import { setTimeout as sleep } from 'node:timers/promises'

const API_URL = 'https://api.olostep.com/v1'

export async function waitForJob(path, timeoutMs = 30 * 60 * 1000, intervalMs = 10_000) {
  // Check GET /v1/<path> until the job is completed or failed.
  // Wait intervalMs between checks. Start no new check after timeoutMs.
  // Stopping does not cancel the job.
  const deadline = performance.now() + timeoutMs
  while (performance.now() < deadline) {
    const res = await fetch(`${API_URL}/${path}`, {
      headers: { Authorization: `Bearer ${process.env.OLOSTEP_API_KEY}` },
      signal: AbortSignal.timeout(30_000),
    })
    // Stop on an HTTP error, for example 401 or 429
    if (!res.ok) throw new Error(`${path}: HTTP ${res.status} ${await res.text()}`)
    const job = await res.json()
    if (typeof job.status !== 'string') throw new Error(`${path}: no status in the response`)
    console.log('Status:', job.status)
    if (job.status === 'completed') return job
    if (job.status === 'failed') throw new Error(`${path} failed`)
    await sleep(intervalMs)
  }
  throw new Error(`${path} is not complete after ${timeoutMs / 1000} seconds`)
}
```

ヘルパーにジョブのパスを指定します：`batches/<batch_id>`または`crawls/<crawl_id>`。

ターミナルからステータスを一度確認するには：

```bash theme={null}
curl --max-time 30 "https://api.olostep.com/v1/batches/YOUR_BATCH_ID" \
  -H "Authorization: Bearer $OLOSTEP_API_KEY"
```

## ジョブIDで後から結果を取得

この例では保存されたバッチIDを使用します。バッチが完了するまで待機します。その後、完了したアイテムと失敗したアイテムをリストします。各リストは1,000ページ以上の最後のページがない場合にエラーで停止します。これはサンプルの制限であり、APIの制限ではありません。

Pythonブロックを同じフォルダに`wait_for_job.py`と`get_results.py`として保存します。Node.jsの場合、`waitForJob.mjs`と`getResults.mjs`を使用します。`YOUR_BATCH_ID`を保存したバッチIDに置き換えます。

```python get_results.py theme={null}
import requests

from wait_for_job import API_KEY, API_URL, wait_for_job

BATCH_ID = "YOUR_BATCH_ID"  # Saved when you created the batch


def list_items(batch_id, status, max_pages=1000):
    """Get all items with this status. Follow the cursor until the last page."""
    items = []
    cursor = None  # The first request has no cursor
    seen = set()  # Cursors from the API, to stop if one repeats
    for _ in range(max_pages):
        response = requests.get(
            f"{API_URL}/batches/{batch_id}/items",
            headers={"Authorization": f"Bearer {API_KEY}"},
            params={"status": status, "cursor": cursor},
            timeout=30,
        )
        response.raise_for_status()  # Stop on an HTTP error, for example 401 or 429
        page = response.json()
        items.extend(page["items"])
        cursor = page.get("cursor")
        if cursor is None:  # No cursor: this was the last page
            return items
        if cursor in seen:
            raise RuntimeError(f"Pagination stopped: cursor {cursor} repeated")
        seen.add(cursor)
    raise RuntimeError(f"Pagination stopped after {max_pages} pages")


wait_for_job(f"batches/{BATCH_ID}")
completed = list_items(BATCH_ID, "completed")
failed = list_items(BATCH_ID, "failed")
print(f"{len(completed)} completed, {len(failed)} failed")
for item in completed:
    print(item["url"], item["retrieve_id"])
for item in failed:
    print("Failed:", item["url"])
```

```javascript getResults.mjs theme={null}
import { waitForJob } from './waitForJob.mjs'

const API_URL = 'https://api.olostep.com/v1'
const batchId = 'YOUR_BATCH_ID' // Saved when you created the batch

async function listItems(batchId, status, maxPages = 1000) {
  // Get all items with this status. Follow the cursor until the last page.
  const items = []
  let cursor = null // The first request has no cursor
  const seen = new Set() // Cursors from the API, to stop if one repeats
  for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {
    const params = new URLSearchParams({ status })
    if (cursor !== null) params.set('cursor', String(cursor))
    const res = await fetch(`${API_URL}/batches/${batchId}/items?${params}`, {
      headers: { Authorization: `Bearer ${process.env.OLOSTEP_API_KEY}` },
      signal: AbortSignal.timeout(30_000),
    })
    // Stop on an HTTP error, for example 401 or 429
    if (!res.ok) throw new Error(`HTTP ${res.status} ${await res.text()}`)
    const page = await res.json()
    items.push(...page.items)
    cursor = page.cursor ?? null
    if (cursor === null) return items // No cursor: this was the last page
    if (seen.has(cursor)) throw new Error(`Pagination stopped: cursor ${cursor} repeated`)
    seen.add(cursor)
  }
  throw new Error(`Pagination stopped after ${maxPages} pages`)
}

await waitForJob(`batches/${batchId}`)
const completed = await listItems(batchId, 'completed')
const failed = await listItems(batchId, 'failed')
console.log(`${completed.length} completed, ${failed.length} failed`)
for (const item of completed) console.log(item.url, item.retrieve_id)
for (const item of failed) console.log('Failed:', item.url)
```

サンプルを実行するには、`python get_results.py`または`node getResults.mjs`を使用します。各結果のコンテンツを取得するには、その`retrieve_id`を[`GET /v1/retrieve`](https://docs.olostep.com/api-reference/retrieve)に送信します。クロールの場合は、[Crawls](https://docs.olostep.com/features/crawls.md)を参照してください。

ポーリングの代わりに、ジョブを作成する際に`webhook`を設定することもできます。[Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md)を参照してください。

## 次のステップ

> [card] [バッチ](https://docs.olostep.com/features/batches.md)
>
> 1つのジョブでURLのリストをスクレイプします。

> [card] [クロール](https://docs.olostep.com/features/crawls.md)
>
> サイト全体のページを取得します。

> [card] [コンテンツを取得](https://docs.olostep.com/api-reference/retrieve.md)
>
> 結果の`retrieve_id`でコンテンツを取得します。

> [card] [Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md)
>
> ジョブが完了したときにリクエストを受け取ります。


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