> 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/ko/sdks/task-annotations-and-agent-webhooks.md).

# 작업 어노테이션과 Agent 웹훅

Agent 단계에 도달한 작업을 자체 서비스에서 라벨링하는 방법을 설명합니다. 서명된 웹훅 검증, Python SDK와 HTTP API를 통한 작업 어노테이션 읽기·저장, 실행 결과 보고를 다룹니다.

**Agent 단계**는 작업을 사용자의 서비스로 넘깁니다. 작업이 단계에 들어올 때마다 Unitlab은 작업당 서명된 웹훅을 하나씩 보냅니다. 서비스는 작업의 어노테이션을 읽고, 새 어노테이션을 저장한 뒤 실행 결과를 보고합니다. 폴링은 필요하지 않습니다.

1. 작업이 Agent 단계에 들어옵니다. Unitlab이 작업 ID와 실행 ID가 담긴 웹훅을 보냅니다.
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>

본문은 `Content-Type: application/cloudevents+json`을 가진 [CloudEvents 1.0](https://cloudevents.io/) 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`를 저장합니다. 변경된 트랙만 분할하여 전송됩니다. 리비전이 오래되면 코드 `revision_conflict`인 `ConflictError`가 발생하므로, 다시 읽고 다시 저장하세요.

## 실행 결과 보고 <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` 대신 `document_upload_id` |
| `POST /api/sdk/workflow-tasks/{task_id}/annotations/uploads/`            | `{"datasource_id", "format", "size"}`. 이후 키 없이 `upload_url`에 JSON을 PUT합니다        |
| `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/ko/workflows/agent-stage) · [워크플로 단계와 작업](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/workflow-stages-and-tasks.md) · [패턴: 워크플로 워커](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/pattern-workflow-worker.md)
