> ## 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`。用你保存的批处理ID替换 `YOUR_BATCH_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)。对于抓取，请参见 [抓取](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)
>
> 在一个作业中抓取一个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.