> ## Documentation Index
> Fetch the complete documentation index at: https://docs.truagents.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Official first-party Python client for the TruAgents public API. Handles OAuth, retries, and rate limits so you focus on business logic.

The `truagents` package is the first-party Python client for the TruAgents public API. It handles OAuth 2.0 token acquisition and refresh, retries with `Retry-After` awareness, and typed exceptions — so you skip hand-rolling the flow and focus on your integration logic. Under the hood it wraps the OpenAPI spec with a typed HTTP client and an exception hierarchy over the RFC 6749 error taxonomy.

## Install

```bash theme={null}
pip install truagents
```

Requires Python 3.11 or later. Distributed under Apache 2.0.

## Quickstart

Use `Client` for synchronous code:

```python theme={null}
from truagents import Client

with Client(client_id="<client_id>", client_secret="tru_cs_<client_secret>") as client:
    resp = client.list_email_unsubscribes()
    for record in resp.data:
        print(record.email, record.unsubscribed)
```

Use `AsyncClient` inside an async framework:

```python theme={null}
import asyncio
from truagents import AsyncClient

async def main() -> None:
    async with AsyncClient(client_id="<client_id>", client_secret="tru_cs_<client_secret>") as client:
        resp = await client.list_email_unsubscribes()
        for record in resp.data:
            print(record.email, record.unsubscribed)

asyncio.run(main())
```

Provision `client_id` and `client_secret` under **Settings → API Keys**. See [Authentication](/developers/authentication) for the full flow, environments, and rotation policy.

## What the SDK handles for you

* **OAuth tokens.** Access tokens are acquired on demand, cached in memory, and refreshed before expiry. If the refresh token is revoked mid-flight, the SDK mints a fresh session via `client_credentials` automatically. Concurrent callers deduplicate onto a single in-flight token request.
* **Retries and rate limits.** Transient network errors and 5xx responses retry with exponential backoff. `429 Too Many Requests` responses honor the `Retry-After` header. Other 4xx failures do not retry.
* **Typed exceptions.** All errors inherit from `TruAgentsError`. Catch `AuthError`, `RateLimited`, `NotFound`, `InvalidRequest`, `ServerError`, or `NetworkError` on the specific concern that matters instead of parsing error strings.
* **Observability hooks.** Register `on_request`, `on_response`, and `on_error` callbacks to route SDK activity into your existing logging and metrics pipelines.
* **Sync and async parity.** `Client` and `AsyncClient` expose the same surface; choose based on your host framework.

## Custom retry policy

Override the default retry behavior by passing a `RetryPolicy`:

```python theme={null}
from truagents import Client, RetryPolicy

policy = RetryPolicy(max_attempts=5, base_delay=0.1, retry_after_cap=30.0)
client = Client(
    client_id="<client_id>",
    client_secret="tru_cs_<client_secret>",
    retry=policy,
)
```

## Observability hooks

Route SDK activity into your logging or metrics pipeline by registering hook callbacks:

```python theme={null}
from truagents import Client, Hooks, Request, Response

def log_request(req: Request) -> None:
    print(f"-> {req.method} {req.url}")

def log_response(resp: Response, elapsed_ms: float) -> None:
    print(f"<- {resp.status_code} ({elapsed_ms:.0f}ms)")

hooks = Hooks(on_request=log_request, on_response=log_response)
client = Client(
    client_id="<client_id>",
    client_secret="tru_cs_<client_secret>",
    hooks=hooks,
)
```

## Development vs. production

Point the SDK at the development environment by overriding `base_url`:

```python theme={null}
from truagents import Client

with Client(
    client_id="<client_id>",
    client_secret="tru_cs_<client_secret>",
    base_url="https://api.dev-truagents.com",
) as client:
    resp = client.list_email_unsubscribes()
```

Development credentials are separate from production. See [Authentication → Endpoints](/developers/authentication#endpoints) for both environment URLs.

## SDK resources

* **PyPI:** [pypi.org/project/truagents](https://pypi.org/project/truagents/)
* **Source:** [github.com/ablt-ai/truagents-sdk](https://github.com/ablt-ai/truagents-sdk)
* **Issues:** [github.com/ablt-ai/truagents-sdk/issues](https://github.com/ablt-ai/truagents-sdk/issues)

## Related pages

* [Authentication](/developers/authentication)
* [OpenAPI specification](/developers/openapi-or-endpoint-reference)
* [Unsubscribe API](/integrations/unsubscribe-api)
