# Python SDK

The HQ API for Python, with retries, idempotency, a resumable event stream and webhook verification built in.



<Callout title="Not published yet">
  The package is not on PyPI yet; this page shows how it will work. Until it is, call the API as in
  the [quickstart](/docs/api/quickstart/).
</Callout>

`aiworkforceone-hq` runs on Python 3.9+ and uses the standard library only.

```bash
pip install aiworkforceone-hq
```

## Authenticate [#authenticate]

```python
from aiworkforceone_hq import HQ

hq = HQ()  # reads HQ_API_KEY; or HQ(api_key="hq_live_…")
```

`api_key` takes an [API key](/docs/api/authentication/) or an [OAuth app](/docs/api/oauth/)'s access
token.

## Send a prompt and stream the reply [#send-a-prompt-and-stream-the-reply]

```python
s = hq.sessions.create("team_3kQ9…", engine="claude", run_with="team_key")
hq.sessions.messages.create(s.id, content=[{"type": "text", "text": "Summarise open PRs in /data/repo"}])
for ev in hq.sessions.stream(s.id):
    if ev.type == "session.message.completed":
        print(ev.data)
    if ev.type == "session.turn.completed":
        break
```

Objects are dicts you can also read by attribute: `s.id` or `s["id"]`.

## What it does for you [#what-it-does-for-you]

**Retries.** A `429`, a `5xx` or a dropped connection is retried with backoff (`max_retries`,
default 2), honouring `Retry-After`. A `421` is retried once at once. Any other `4xx` raises at once.

**Idempotency.** Every write carries an `Idempotency-Key`, the same one across its own retries.
Pass `idempotency_key=` to use yours.

**Errors.** A refusal raises `HQError` with the stable [`code`](/docs/api/errors/), `status`,
`detail` and `request_id`:

```python
from aiworkforceone_hq import HQError

try:
    hq.sessions.create("team_3kQ9…", run_with="team_key")
except HQError as err:
    if err.code != "permission_denied":
        raise
    print(err.permission)
```

**Streaming.** `sessions.stream(id)` yields each [event](/docs/api/streaming/) once, resumes with
`Last-Event-ID` across `stream.rotate` and dropped connections, and yields `stream.reset` when you
should re-list the session's items.

**Operations.** `operations.wait(op)` polls an [operation](/docs/api/operations/) until it settles:

```python
op = hq.computer.resize("team_3kQ9…", tier="boost")
if op.get("object") == "operation":
    hq.operations.wait(op)
```

**Pagination.** `teams.list()` and `sessions.list()` iterate every page.

**Webhooks.** Verify a delivery with the raw body:

```python
event = HQ.webhooks.verify(request.body, request.headers, os.environ["HQ_WEBHOOK_SECRET"])
```

**Everything else.** `hq.call("operationId", {"path_param": "…"}, query=..., body=...)` reaches any
endpoint in the [reference](/docs/api/reference/).
