Skip to main content

LevelFour Python SDK

CI PyPI PyPI - Python Version License

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 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. While on v0.x, minor versions may include breaking changes. After v1.0.0, breaking changes will only ship in major version bumps.

Contributing

See CONTRIBUTING.md for development setup and guidelines.

Security

To report vulnerabilities, see SECURITY.md.

Changelog

See CHANGELOG.md for release history.

License

Apache-2.0 - see LICENSE.

Metadata

Release files for levelfour 1.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for levelfour 1.2.1
File Size Uploaded Provenance Actions
levelfour-1.2.1.tar.gz 499.7 kB With provenance Details for levelfour-1.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for levelfour 1.2.1
File Interpreter ABI Platform Actions
levelfour-1.2.1-py3-none-any.whl Python 3 none any Details for levelfour-1.2.1-py3-none-any.whl

Total release size: 1.8 MB

Release files / levelfour-1.2.1.tar.gz

Download URL levelfour-1.2.1.tar.gz
Size 499.7 kB
Tags Source
SHA-256 checksum
How to use checksums
4cf8d40ec5ad0ef65defb840e068013ba6140fde4578a9b2d295331a4ec69ceb
BLAKE2b-256 checksum
How to use checksums
c2dee3b81136aaf51beaf2d2f736e0627fd207f691c194d305d99e0ae8b9eed3
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 4, 2026.

Transparency log

Release files / levelfour-1.2.1-py3-none-any.whl

Download URL levelfour-1.2.1-py3-none-any.whl
Size 1.3 MB
Tags Python 3
SHA-256 checksum
How to use checksums
c8d6f94b7d3ac738ff650ad7b5acb9e2bd099f45a117f3a3593b357c7b6fb3b8
BLAKE2b-256 checksum
How to use checksums
662bf504f03a2ad300474989531101e70e7fcb9e77ce9a6e03e0eece3515ec93
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 4, 2026.

Transparency log

Security for levelfour 1.2.1

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.

Select from 2 files

Attestation for levelfour-1.2.1.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 4, 2026.

Transparency log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page