LevelFour Python SDK
The official Python SDK for the LevelFour 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.
Installation
pip install levelfour
Usage
Set LEVELFOUR_API_KEY in your environment, or pass the key directly:
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
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:
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.
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
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
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():
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:
client = LevelFour(max_retries=0)
Override per-request:
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:
result = client.recommendations.list(
request_options=RequestOptions(timeout_in_seconds=10),
)
Pagination
Paginated endpoints return an iterable:
for item in client.recommendations.list():
print(item)
Collect all results:
items = list(client.recommendations.list())
Async:
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:
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:
from levelfour.webhooks.verifier import WebhookVerifier
verifier = WebhookVerifier("whsec_...")
payload = verifier.verify(request.body, request.headers)
Managing Webhook Endpoints
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
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
# settings.py
LEVELFOUR_API_KEY = "l4_live_..."
# views.py
from levelfour.integrations.django import get_client
client = get_client()
OpenTelemetry
Install the optional telemetry dependency:
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:
import httpx
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
instrumented_client = httpx.Client()
HTTPXClientInstrumentor.instrument_client(instrumented_client)
Stability
The public API surface is:
levelfour.LevelFour/levelfour.AsyncLevelFour: client classeslevelfour.exceptions: error hierarchy (LevelFourError,NotFoundError, etc.)levelfour.types: Pydantic response modelslevelfour.webhooks.verifier: webhook verificationlevelfour.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. After v1.0.0, breaking changes will only ship in major version bumps.
Support
Docs are at docs.levelfour.ai. For help, email support@levelfour.ai.
Security
To report a vulnerability, email security@levelfour.ai.
License
Apache-2.0.
Metadata
Release files for levelfour 1.12.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| levelfour-1.12.0.tar.gz | 592.7 kB | With provenance | Details for levelfour-1.12.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| levelfour-1.12.0-py3-none-any.whl | Python 3 | none | any | Details for levelfour-1.12.0-py3-none-any.whl |
Total release size: 2.1 MB
Release files / levelfour-1.12.0.tar.gz
| Download URL | levelfour-1.12.0.tar.gz |
|---|---|
| Size | 592.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
117c4c4f6164b1d2267e14c10cfe90c1649aed00abef0bf6b254559d47bbd5a9
|
|
BLAKE2b-256 checksum How to use checksums |
92c0fc9e6c07ed0f4fdeb0674a321f4bdb4628bbe461a7ada45156575fdd8ea6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.
Transparency logRelease files / levelfour-1.12.0-py3-none-any.whl
| Download URL | levelfour-1.12.0-py3-none-any.whl |
|---|---|
| Size | 1.5 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c7e033c747a29c56a904dd93335ad3156cee64e9cf459db9ee0dd097367a0f0f
|
|
BLAKE2b-256 checksum How to use checksums |
a28d758165de0d73412581f115c50686c01b44458377f5ccc07084934bcd7d39
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.
Transparency logSecurity for levelfour 1.12.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for levelfour-1.12.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.