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

# 后台响应与任务查询

> 查询插件任务响应，区分后台执行与普通上游响应。

`POST /v1/responses` 有普通转发和任务插件两条处理路径。插件需声明支持 `background` 才能使用后台模式；请求输入仍需符合插件对应模型。普通上游返回了 `resp_` ID，不表示本平台能通过 GET 查询它。

## 创建与保存

在支持后台的插件模型请求中设置 `background: true`，保留返回的 `id` 与状态。具体输入沿用该模型已验证的 Responses 请求；不能假设每个媒体插件都接受纯文本聊天。后台提交后通常返回 `queued` 或 `in_progress`，也可能很快完成。`stream` 与 `background` 是不同选项。

不要靠手工给 task ID 改前缀构造 response ID。收到任务 ID 后持久保存它与所属业务请求，防止页面刷新或超时后重复提交。

## 查询已有响应

[`GET /v1/responses/{response_id}`](/zh/api-reference/responses-retrieve)仅查询宿主记录的插件任务响应，按调用用户与项目限制可见性。结果已丢弃、插件不可用或 ID 不属于当前身份都可能返回 404；不存在通用的任意上游响应代理查询。

示例只读取已有响应，最多查询指定次数。按 Python 指南安装依赖后运行：

```sh theme={null}
export API_BASE_URL="https://gateway.example.com/v1"
export API_KEY="YOUR_API_KEY"
export API_RESPONSE_ID="resp_YOUR_EXISTING_RESPONSE_ID"
.venv/bin/python examples/response-status.py --max-attempts 10 --interval 2
```

```python theme={null}
import argparse
import math
import os
import time
from urllib.parse import quote
from openai import OpenAI, APIConnectionError, APIStatusError

parser = argparse.ArgumentParser(description="Poll an existing task-plugin response; never submit a new task.")
parser.add_argument("--max-attempts", type=int, default=10)
parser.add_argument("--interval", type=float, default=2.0)
args = parser.parse_args()
if not 1 <= args.max_attempts <= 60 or not math.isfinite(args.interval) or not 0 <= args.interval <= 60:
    parser.error("Use 1..60 attempts and a finite interval of 0..60 seconds.")
response_id = os.environ["API_RESPONSE_ID"]
if not response_id.startswith("resp_") or len(response_id) <= 5:
    raise SystemExit("API_RESPONSE_ID must be an existing task-plugin response ID.")

with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
            api_key=os.environ["API_KEY"], timeout=30.0, max_retries=0) as client:
    try:
        for attempt in range(args.max_attempts):
            result = client.get(f"/responses/{quote(response_id, safe='')}", cast_to=dict)
            if (not isinstance(result, dict) or result.get("id") != response_id
                    or result.get("object") != "response"):
                raise ValueError("Invalid response identity.")
            status = result.get("status")
            if result.get("error") or status in ("failed", "incomplete", "cancelled"):
                raise ValueError("Response did not complete.")
            if status == "completed":
                output = result.get("output")
                if not isinstance(output, list) or not output or any(not isinstance(item, dict) for item in output):
                    raise ValueError("Missing output.")
                # Lifecycle completion is not a text, image, or safety quality check.
                print(f"completed: {len(output)} output item(s); validate content for your application.")
                break
            if status not in ("queued", "in_progress"):
                raise ValueError("Unknown response status.")
            if attempt + 1 == args.max_attempts:
                raise SystemExit("Polling limit reached. Keep the response ID; the task may still be running.")
            time.sleep(args.interval)
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Keep the response ID; do not resubmit.")
    except APIConnectionError:
        raise SystemExit("Connection failed. Keep the response ID; do not resubmit.")
    except (ValueError, TypeError, AttributeError):
        raise SystemExit("Response is invalid or not complete. Keep the response ID; do not resubmit.")
```

## 状态与业务结果

| 状态 | 应用动作 |
| - | - |
| queued / in\_progress | 等待后查询，受最大次数和业务时限约束 |
| completed | 按实际 output 类型进一步校验并使用结果 |
| failed / incomplete / cancelled | 不当作成功；记录状态并按业务策略处理 |
| 未知状态、无效结构 | 停止本次轮询，保留 ID 供排查 |

当前宿主主要返回 queued、in\_progress、completed、failed；示例也拒绝 incomplete 和 cancelled，避免把非成功终态当作成功。完成输出可能是媒体或其他项，不一定有文本。示例只报告生命周期完成，不下载文件，不将拒答当作文本回答；应用仍需做对应的内容校验。

HTTP 错误或本地轮询次数耗尽不会自动取消任务。需要稍后恢复时继续查询同一 ID。此端点返回 JSON 快照，当前不提供 SSE 续传、`starting_after` 回放或 REST 删除 / 取消能力。

[视频任务](/zh/guides/video-generation)使用独立的视频接口。保存响应、资料和产物的期限需由部署方确认。

[Read in English](/en/guides/background-responses)


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