Metadata-Version: 2.4
Name: levelfour
Version: 1.6.0
Summary: The official Python SDK for the LevelFour API
Author-email: LevelFour <support@levelfour.ai>
License-Expression: Apache-2.0
Project-URL: Homepage, https://levelfour.ai
Project-URL: Documentation, https://docs.levelfour.ai/sdks/python
Keywords: levelfour,cloud,cost-optimization,finops,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.24.0
Requires-Dist: pydantic<3,>=2.0
Provides-Extra: telemetry
Requires-Dist: opentelemetry-api>=1.20.0; extra == "telemetry"
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == "fastapi"
Provides-Extra: django
Requires-Dist: django>=4.0; extra == "django"
Dynamic: license-file

# LevelFour Python SDK

[![PyPI](https://img.shields.io/pypi/v/levelfour)](https://pypi.org/project/levelfour/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/levelfour)](https://pypi.org/project/levelfour/)

The official Python SDK for the [LevelFour](https://levelfour.ai) API.

## Requirements

Python 3.9 or later.

> **Note:** Python 3.9 reached end-of-life in October 2025. We will continue supporting it until a future major release.

## Documentation

API reference and package details are available at [levelfour.ai/docs](https://levelfour.ai/docs).

## Installation

```bash
pip install levelfour
```

## Usage

Set `LEVELFOUR_API_KEY` in your environment, or pass the key directly:

```python
from levelfour import LevelFour

client = LevelFour(api_key="l4_live_...")
# Or use LEVELFOUR_API_KEY env var:
client = LevelFour()

summary = client.recommendations.get_savings_by_provider()
print(summary)
```

### Async

```python
from levelfour import AsyncLevelFour

client = AsyncLevelFour(api_key="l4_live_...")
summary = await client.recommendations.get_savings_by_provider()
```

### Managing Resources

Both clients support context managers for proper resource cleanup:

```python
with LevelFour() as client:
    summary = client.recommendations.get_savings_by_provider()

async with AsyncLevelFour() as client:
    summary = await client.recommendations.get_savings_by_provider()
```

## Cost alerts

`client.cost_alerts` creates, changes, pauses and deletes the alerts that watch an account or a saved cost view. It ships in 0.2.0, and writes need a read-write key.

```python
from levelfour import LevelFour
from levelfour.cost_alerts import CreateAlertRequestParams_Budget, UpdateAlertRequestParams_Budget
from levelfour.types import AlertRecipient, BudgetRuleInput

client = LevelFour()
monthly = dict(reset="monthly", rules=[BudgetRuleInput(amount=80, unit="percent")])

alert = client.cost_alerts.create_alert(
    name="Production budget",
    source_id="123456789012",  # an id from client.cost_alerts.list_sources()
    params=CreateAlertRequestParams_Budget(budget=40000, **monthly),
    recipients=[AlertRecipient(name="Ana", email="ana@example.com", member=True)],
)
alert_id = alert.data.id

# Only the arguments you pass change. params replaces the whole rule, so send it back with the new figure.
client.cost_alerts.update_alert(alert_id, params=UpdateAlertRequestParams_Budget(budget=50000, **monthly))

client.cost_alerts.update_alert(alert_id, enabled=False)  # pause
client.cost_alerts.update_alert(alert_id, enabled=True)  # resume

# Deleting takes the alert's history with it. Pausing keeps it.
client.cost_alerts.delete_alert(alert_id)
```

## Error Handling

```python
from levelfour import LevelFour
from levelfour.exceptions import (
    LevelFourError,
    LevelFourConnectionError,
    LevelFourTimeoutError,
    NotFoundError,
    RateLimitError,
)

client = LevelFour()
try:
    rec = client.recommendations.get(recommendation_id="abc")
except NotFoundError:
    print("Recommendation not found")
except RateLimitError as e:
    print(f"Rate limited, retry after: {e.retry_after}")
except LevelFourTimeoutError:
    print("Request timed out")
except LevelFourConnectionError:
    print("Network error")
except LevelFourError as e:
    print(f"{e.status_code} {e.code}: {e.message}")
```

Available exceptions: `BadRequestError` (400), `AuthenticationError` (401), `AuthorizationError` (403), `NotFoundError` (404), `ConflictError` (409), `ValidationError` (422), `RateLimitError` (429), `InternalServerError` (500), `LevelFourConnectionError` (network failure), `LevelFourTimeoutError` (timeout), `WebhookVerificationError` (webhook signature/payload error).

All exceptions inherit from `LevelFourError`. Always import from `levelfour` or `levelfour.exceptions`: the `levelfour.errors` package is generated infrastructure and should not be imported directly.

## Configuration

```python
client = LevelFour(
    api_key="l4_live_...",
    base_url="https://custom.api.com",
    timeout=60.0,
    max_retries=5,
    headers={"X-Custom-Header": "value"},
)
```

| Option | Default | Description |
|--------|---------|-------------|
| `api_key` | `LEVELFOUR_API_KEY` env var | API key (`l4_live_*` for production, `l4_test_*` for testing) |
| `base_url` | `https://api.levelfour.ai` | API base URL |
| `timeout` | `30.0` | Request timeout in seconds |
| `max_retries` | `2` | Retry attempts for transient errors |
| `http_client` | `None` | Custom `httpx.Client` (for proxy, mTLS, etc.) |
| `headers` | `None` | Additional default headers |

### Cloning Clients

Create a modified copy of a client with `with_options()`:

```python
admin_client = client.with_options(
    headers={"X-Admin": "1"},
    timeout=120.0,
)
```

## Retries

The client retries failed requests on `5xx`, `429`, `408`, and `409` responses using exponential backoff with jitter. The default retry count is `2`. Disable retries with `max_retries=0`:

```python
client = LevelFour(max_retries=0)
```

Override per-request:

```python
from levelfour.core.request_options import RequestOptions

result = client.recommendations.list(
    request_options=RequestOptions(max_retries=5),
)
```

## Timeouts

The default request timeout is 30 seconds. Override at construction time or per-request:

```python
result = client.recommendations.list(
    request_options=RequestOptions(timeout_in_seconds=10),
)
```

## Pagination

Paginated endpoints return an iterable:

```python
for item in client.recommendations.list():
    print(item)
```

Collect all results:

```python
items = list(client.recommendations.list())
```

Async:

```python
async for item in client.recommendations.list():
    print(item)
```

## Raw Response Access

Use `.with_raw_response` on any sub-client to access HTTP headers and status codes:

```python
response = client.api_keys.with_raw_response.list()
print(response.status_code)
print(dict(response.headers))
keys = response.data
```

## Webhooks

Verify incoming webhook events using HMAC-SHA256:

```python
from levelfour.webhooks.verifier import WebhookVerifier

verifier = WebhookVerifier("whsec_...")
payload = verifier.verify(request.body, request.headers)
```

### Managing Webhook Endpoints

```python
endpoints = client.webhooks.list()

new_endpoint = client.webhooks.register(
    url="https://example.com/webhooks",
    event_types=["recommendation.created"],
)

client.webhooks.delete(endpoint_id="ep_...")
```

## Framework Integrations

### FastAPI

```python
from fastapi import Depends, FastAPI
from levelfour.integrations.fastapi import LevelFourMiddleware, get_levelfour

app = FastAPI()
app.add_middleware(LevelFourMiddleware, api_key="l4_live_...")


@app.get("/savings")
async def get_savings(client=Depends(get_levelfour)):
    return await client.recommendations.get_savings_by_provider()
```

### Django

```python
# settings.py
LEVELFOUR_API_KEY = "l4_live_..."

# views.py
from levelfour.integrations.django import get_client

client = get_client()
```

<details>
<summary>OpenTelemetry</summary>

Install the optional telemetry dependency:

```bash
pip install levelfour[telemetry]
```

When `opentelemetry-api` is installed, the SDK automatically instruments all HTTP requests with spans and metrics. Alternatively, pass a custom `httpx.Client` with your own transport:

```python
import httpx
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

instrumented_client = httpx.Client()
HTTPXClientInstrumentor.instrument_client(instrumented_client)
```

</details>

## Stability

The public API surface is:

- `levelfour.LevelFour` / `levelfour.AsyncLevelFour`: client classes
- `levelfour.exceptions`: error hierarchy (`LevelFourError`, `NotFoundError`, etc.)
- `levelfour.types`: Pydantic response models
- `levelfour.webhooks.verifier`: webhook verification
- `levelfour.integrations`: framework helpers (FastAPI, Django, OpenTelemetry)

The `levelfour.core` and `levelfour.errors` packages are generated infrastructure. They may change without notice between versions and should not be imported directly.

## Versioning

This SDK follows [Semantic Versioning](https://semver.org/). After `v1.0.0`, breaking changes will only ship in major version bumps.

## Support

Docs are at [docs.levelfour.ai](https://docs.levelfour.ai). For help, email support@levelfour.ai.

## Security

To report a vulnerability, email security@levelfour.ai.

## License

Apache-2.0.
