> 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/pattern-workflow-worker.md).

# 模式：工作流 Worker

用自己的代码处理 Unitlab 工作流任务：通过 Agent 阶段 Webhook 接收任务并自动标注，或用轮询 Worker 定时认领并处理某个阶段的任务。

让自己的代码处理任务有两种方式。

| 方式        | 任务如何到达                      | 适用场景                   |
| --------- | --------------------------- | ---------------------- |
| Agent 阶段  | Unitlab 为每个任务发送一条签名 Webhook | 模型以 HTTPS 服务形式运行，无需轮询。 |
| 轮询 Worker | 你的任务列出某个阶段的任务               | 批处理作业或定时脚本             |

## Agent 阶段 <a href="#agent-stage" id="agent-stage"></a>

在应用中给工作流添加 Agent 阶段，并把它指向你的服务。服务验证事件、标注任务并完成运行。参见 [任务标注与 Agent Webhook](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/task-annotations-and-agent-webhooks.md)。

## 轮询 Worker <a href="#polling-worker" id="polling-worker"></a>

```python
from unitlab import UnitlabClient, ValidationError

client = UnitlabClient()
project = client.projects.get("PROJECT_ID")
stage = project.workflow.get_stage(name="Auto QA")

for task in stage.get_tasks():
    try:
        task.claim()
    except ValidationError:
        continue                     # someone else took it
    if passes_checks(task):
        task.submit()
    else:
        task.release()
client.close()
```

* 先认领再操作，确保两个 Worker 不会处理同一个任务。
* 每次运行保持简短且幂等；剩余的任务由下一次运行接着处理。
* 只记录任务 ID 和执行的操作，不要记录媒体或带签名的链接。

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

[工作流阶段与任务](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/workflow-stages-and-tasks.md) · [批量工作流操作](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/bulk-workflow-operations.md) · [Agent 阶段](https://docs.unitlab.ai/documentation/zh/workflows/agent-stage)
