> For the complete documentation index, see [llms.txt](https://docs.unitlab.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/task-annotations-and-agent-webhooks.md).

# 任务标注与 Agent Webhook

当任务进入 Agent 阶段时，用你自己的服务完成标注：接收签名 Webhook，通过 Unitlab 任务标注 API 读取和保存标注，并上报运行结果。

**Agent 阶段**把任务交给你的服务处理。每个任务进入该阶段时，Unitlab 会发送一条签名 Webhook。你的服务读取任务的标注、保存新标注并上报运行结果，全程无需轮询。

1. 任务进入 Agent 阶段，Unitlab 发送包含任务 ID 和运行 ID 的 Webhook。
2. 你的服务返回 `2xx`，确认已收到投递。
3. 服务读取任务的标注，保存新标注，然后调用 `complete_agent(run_id)`。
4. 任务沿该阶段的出边继续流转。

## 接收并处理事件 <a href="#receive-and-handle-an-event" id="receive-and-handle-an-event"></a>

```python
from unitlab import AgentWebhook, UnitlabClient

client = UnitlabClient()   # a workspace API key


def handle(body: bytes, headers, secret: str) -> int:
    """Return the HTTP status for the webhook response."""
    event = AgentWebhook.verify(body, headers, secret)   # raises ValueError if invalid
    if event.is_test:                                    # "Test connection" button
        return 204

    ref = event.task
    task = client.get_workflow_task(ref.task_id)
    try:
        for item in task.get_annotations():              # one per Data Group panel
            document = my_model(item.document, item.source_url)
            if document is not None:
                task.save_annotations(item, document)
        task.complete_agent(ref.run_id)
    except Exception as error:
        task.fail_agent(ref.run_id, f"Model error: {error}")
    return 200
```

请把原始请求字节传给 `verify()`。先解析 JSON 再重新编码会改变被签名的内容。如果该阶段没有设置签名密钥，请使用 `AgentWebhook.parse(body)`。

SDK 源码中的 `examples/agent_webhook.py` 提供了一个完整的本地接收端。运行它，用 `cloudflared tunnel --url http://127.0.0.1:8091` 对外暴露，再把 HTTPS 地址填入阶段设置。

## 事件 <a href="#the-event" id="the-event"></a>

请求体是一个 [CloudEvents 1.0](https://cloudevents.io/) JSON 事件，`Content-Type: application/cloudevents+json`。

| `type`                           | 触发时机                         | `data`                                                                          |
| -------------------------------- | ---------------------------- | ------------------------------------------------------------------------------- |
| `ai.unitlab.agent.task.ready.v1` | 任务进入该阶段                      | `project_id`、`workflow_id`、`stage_id`、`task: {task_id, run_id, datasource_ids}` |
| `ai.unitlab.agent.test.v1`       | 在阶段设置中点击 **Test connection** | `test: true`、各 ID（未保存的工作流可能为 `null`）、`task: null`                               |

每个事件只携带一个任务。

## 签名 <a href="#signatures" id="signatures"></a>

事件遵循 [Standard Webhooks](https://www.standardwebhooks.com/) 规范，请求头包括 `webhook-id`、`webhook-timestamp` 和 `webhook-signature`。签名是对 `id.timestamp.body` 计算的 HMAC-SHA256。`verify()` 接受 `v1,<base64>` 格式的签名、明文密钥或 `whsec_` 密钥，允许最多 300 秒的时钟偏差。请保持服务器时钟同步。

## 读取标注 <a href="#read-annotations" id="read-annotations"></a>

`task.get_annotations()` 为每个条目返回一个 `TaskAnnotation`：

| 字段                             | 含义                                 |
| ------------------------------ | ---------------------------------- |
| `datasource_id`、`generic_type` | 对应的条目                              |
| `document`                     | 条目的 UUEF 格式标注，与 UUEF 发布导出的 JSON 相同 |
| `source_url`                   | 带签名的媒体链接。切勿写入日志。                   |
| `revision`                     | 读取的版本                              |
| `format`                       | `uuef`；LiDAR 场景为 `native`          |
| `result`                       | 仅 LiDAR 场景：原生轨迹结果                  |

视频和医学影像条目中的轨迹只列出关键帧。传入 `only_keyframes=False` 可列出所有帧。较大的文档会自动下载。JSON Schema 文件 `uuef.schema.json` 位于每个 UUEF 发布的根目录。

## 保存标注 <a href="#save-annotations" id="save-annotations"></a>

```python
task.save_annotations(item, document)                         # UUEF
task.save_annotations(item, feature_collection, format="geojson")   # geospatial, pathology
task.save_annotations(item, model_reply, format="model")      # images: bboxes, polygons, brush
```

| 规则          | 说明                                       |
| ----------- | ---------------------------------------- |
| 整体覆盖        | 文档中缺失的对象会被删除。保留的每个对象都要保留其 `id`。          |
| 不校验版本       | 你读取之后他人所做的保存会被覆盖                         |
| 作者归属        | 保存的对象记在密钥创建者名下。没有变化时请跳过保存。               |
| 仅限 Agent 阶段 | 管理员把任务移出该阶段后，保存会被拒绝并抛出 `ValidationError` |
| 无效形状        | 自相交的轮廓会被修复，超出边界的形状会被裁剪，面积为零的形状会被跳过       |

LiDAR 场景保存其原生 `result`，只分批发送有变化的轨迹。版本过期时会抛出 `ConflictError`，错误码为 `revision_conflict`；请重新读取后再保存。

## 上报运行结果 <a href="#report-the-run" id="report-the-run"></a>

| 调用                               | 效果                                              |
| -------------------------------- | ----------------------------------------------- |
| `task.complete_agent(run_id)`    | 任务沿该阶段的出边继续流转                                   |
| `task.fail_agent(run_id, error)` | 任务停留在该阶段。管理员可点击 **Retry**，以新的 `run_id` 启动新一次运行。 |

7 天内未完成的运行会被判定为失败。错误文本最多保留 4,000 个字符。

## 生产环境运行 <a href="#run-it-in-production" id="run-it-in-production"></a>

* 只有在事件已持久化存储后才返回 `2xx`，然后异步处理。
* 投递可能重复，请按 `run_id` 去重。
* 使用仅具备 **View labeling interface** 和 **Create labels** 权限的密钥。
* 切勿记录签名密钥、API 密钥、完整请求体或带签名的媒体链接。

## Model 阶段 <a href="#model-stages" id="model-stages"></a>

调用你自有模型服务的 Model 阶段也以同样方式回传结果，结果格式为 GeoJSON：

```python
task.complete_model_run(run_id, feature_collection, model_version="seg-v7")
task.fail_model_run(run_id, "GPU out of memory")
```

## HTTP 路由 <a href="#http-routes" id="http-routes"></a>

所有路由都使用 `Authorization: Api-Key <key>`。

| 调用                                                                       | 请求体 / 响应                                                                        |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
| `GET /api/sdk/workflow-tasks/{task_id}/annotations/?only_keyframes=true` | 包含 `document` 的行，或可不带密钥 GET 的 `document_url`                                    |
| `PUT /api/sdk/workflow-tasks/{task_id}/annotations/`                     | `{"datasource_id", "format", "document"}`，或用 `document_upload_id` 代替 `document` |
| `POST /api/sdk/workflow-tasks/{task_id}/annotations/uploads/`            | `{"datasource_id", "format", "size"}`；然后不带密钥把 JSON PUT 到 `upload_url`           |
| `POST /api/sdk/workflow-tasks/{task_id}/agent-result/`                   | `{"run_id", "status": "complete"}` 或 `{"run_id", "status": "failed", "error"}`  |
| `POST /api/sdk/workflow-tasks/{task_id}/model-result/`                   | `{"run_id", "status", "result" or "results", "model_version"}`                  |

## 相关内容 <a href="#related" id="related"></a>

[Agent 阶段](https://docs.unitlab.ai/documentation/zh/workflows/agent-stage) · [工作流阶段与任务](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/workflow-stages-and-tasks.md) · [模式：工作流 Worker](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/pattern-workflow-worker.md)
