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

# Python SDK

> Install and operate the Pylva Python SDK for Python agent runtimes.

The Python SDK installs from PyPI as `pylva-sdk` and imports as `pylva`.

```bash theme={null}
pip install pylva-sdk
```

## Initialize

```python theme={null}
import os
import pylva

pylva.init(api_key=os.environ["PYLVA_API_KEY"])
```

You can pass `endpoint` for self-hosted deployments. Omit it for Pylva Cloud.

## Auto-instrumentation

Importing `pylva` patches supported provider clients in the host process. Current coverage:

* OpenAI.
* Anthropic.

Captured fields include provider, model, tokens in, tokens out, latency, status, `customer_id`, and `step_name` when a tracking context is active.

## Tracking context

```python theme={null}
from pylva import track_context

with track_context(customer_id="acme-corp", step="draft_reply"):
    response = openai_client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
    )
```

`track_context` uses Python context variables so metadata follows async work without manual argument threading.

## LangGraph callback

```bash theme={null}
pip install "pylva-sdk[langchain]"
```

```python theme={null}
import os
from pylva.langchain import PylvaCallbackHandler

handler = PylvaCallbackHandler(api_key=os.environ["PYLVA_API_KEY"])

graph.invoke(
    inputs,
    config={
        "callbacks": [handler],
        "metadata": {"pylva_customer_id": "cust_acme"},
    },
)
```

Use the callback path when LangGraph is the orchestration layer. It preserves
LangGraph run ids and uses `langgraph_node` as the default Pylva step. See
[LangGraph Cost Tracking](/sdks/langgraph).

## Non-LLM usage

```python theme={null}
from pylva import report_usage

report_usage(
    customer_id="acme-corp",
    step="speak_answer",
    metric="characters",
    value=4200,
)
```

Report raw usage, not dollars. Pylva applies pricing on the server.

## Budget hard stops

```python theme={null}
import pylva
from pylva import PylvaBudgetExceeded

pylva.init(api_key=os.environ["PYLVA_API_KEY"])

try:
    response = openai_client.chat.completions.create(...)
except PylvaBudgetExceeded:
    response = cached_or_smaller_response()
```

SDK errors fail open unless an active, cached rule intentionally blocks the call.

## Webhook verification

```python theme={null}
from pylva import verify_webhook

ok = verify_webhook(
    raw_body,
    signature_header,
    webhook_secret,
    timestamp_header,
)
```

The helper accepts raw hex signatures and `sha256=` prefixed signatures.
