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

# パターン：ワークフローワーカー

Unitlab の Agent ステージでタスクにラベルを付けるサービス、またはステージ内のタスクを定期的に処理するポーリングワーカーを Python SDK で実行する 2 つの方法を比較して解説します。

独自のコードでタスクを処理する方法は 2 つあります。

| 方式         | タスクの受け取り方                       | 用途                                |
| ---------- | ------------------------------- | --------------------------------- |
| Agent ステージ | Unitlab がタスクごとに署名付き Webhook を送信 | モデルが HTTPS サービスとして動作する場合。ポーリング不要。 |
| ポーリングワーカー  | ジョブがステージのタスクを一覧取得               | バッチジョブやスケジュール実行のスクリプト             |

## Agent ステージ <a href="#agent-stage" id="agent-stage"></a>

アプリでワークフローに Agent ステージを追加し、お使いのサービスを指定します。サービスはイベントを検証し、タスクにラベルを付けて、実行を完了します。[タスクのアノテーションと Agent Webhook](https://docs.unitlab.ai/api-sdk-cli/ja/sdks/task-annotations-and-agent-webhooks.md)を参照してください。

## ポーリングワーカー <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()
```

* 操作の前にクレームし、同じタスクを 2 つのワーカーが処理しないようにします。
* 各実行は短く、冪等に保ちます。残りは次回の実行が引き継ぎます。
* ログにはタスク ID と操作を記録し、メディアや署名付きリンクは記録しないでください。

## 関連情報 <a href="#related" id="related"></a>

[ワークフローステージとタスク](https://docs.unitlab.ai/api-sdk-cli/ja/sdks/workflow-stages-and-tasks.md) · [ワークフローの一括操作](https://docs.unitlab.ai/api-sdk-cli/ja/sdks/bulk-workflow-operations.md) · [Agent ステージ](https://docs.unitlab.ai/documentation/ja/workflows/agent-stage)
