Metadata-Version: 2.5
Name: fluxmeter
Version: 2.0.2
Summary: Real-time AI token metering and pre-request budget enforcement. Self-hostable, synchronous admission checks (latency is deployment-dependent), Apache 2.0.
Project-URL: Homepage, https://fluxmeter.dev
Project-URL: Documentation, https://github.com/10kshuaizhang/fluxmeter/blob/main/docs/api-reference.md
Project-URL: Repository, https://github.com/10kshuaizhang/fluxmeter
Author-email: FluxMeter <hello@fluxmeter.dev>
License-Expression: Apache-2.0
Keywords: agents,ai,billing,budget,flink,kafka,llm,openai,self-hosted,token-metering
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.20; extra == 'anthropic'
Provides-Extra: dev
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-asyncio; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Provides-Extra: openai
Requires-Dist: openai>=1.0; extra == 'openai'
Description-Content-Type: text/markdown

# FluxMeter Python SDK

HTTP-only Python SDK for [FluxMeter](https://fluxmeter.dev) token metering and budget enforcement.

Budget checks are synchronous Redis reads. Latency is **deployment-dependent** (load, Redis, and network).

Python SDK **2.0.2** is versioned separately from engine/API **4.8.5** and JS SDK
**2.0.0**. Repository version does not confirm package-index publication.

## Install

Requires **2.0.2 or newer**. PyPI 1.5.0 does not export `DeliveryError`;
`from fluxmeter import DeliveryError` fails on that release.

```bash
pip install "fluxmeter>=2.0.2"
# or pin:
pip install fluxmeter==2.0.2
```

From a clone of this repository (before 2.0.2 is on PyPI, or to test a checkout):

```bash
pip install ./sdk/python
```

## Usage

```python
from fluxmeter import DeliveryError, FluxMeter

meter = FluxMeter(
    api_url="http://localhost:8000",
    api_key="fm_live_...",
    environment="production",
)

try:
    event_id = meter.track(
        customer_id="cust_123",
        model_id="gpt-4o",
        input_tokens=500,
        output_tokens=150,
        parent_span_id="span_agent_42",
        session_id="session_7",
    )
except DeliveryError as error:
    # The exception preserves the stable event ID used across bounded retries.
    print(error.event_id)
```

`track_openai`, `track_anthropic`, and `track_google` extract usage from provider responses and send the same HTTP event contract. Direct `track*` calls raise typed delivery errors after bounded retries. FluxMeter returns acceptance only after Kafka acknowledgement and identity finalization; this is not settled billing. A quarantine receipt is not billable usage.

Direct Kafka configuration and the former local WAL were removed in 2.0.0. Kafka is an internal transport; applications should use `/ingest` or `/ingest/batch`.

See the [API reference](../../../docs/api-reference.md) and [v4 migration guide](../../../docs/migration-4.0.md).


## OpenAI wrapper: observe metering failures

```python
import logging
from fluxmeter import wrap

logger = logging.getLogger(__name__)

def metering_failed(error):
    # Send to your application's durable recovery/alerting path.
    # DeliveryError preserves the event_id; retain provider usage in your app.
    logger.error("Metering failure: %s, event_id=%s",
                 type(error).__name__, getattr(error, "event_id", None))

client = wrap(openai_client, meter, customer_id="cust_123",
              fail_open=False, on_metering_error=metering_failed)
```

The callback receives the original exception on non-streaming tracking failures
and stream tracking failures. A warning is always logged. For compatibility, the
provider result remains available and callback exceptions are logged rather than
replacing that result. Do not retry a provider call just because its metering
failed: recover delivery of the original usage.
`fail_open` controls admission failure behavior only. `wrap()` reserves before
every call (streaming and not) and attaches `reservationId` on track so Flink
releases the hold at settlement. Do not call `reconcile` immediately after
`/ingest`. Unused holds (provider failure) are released immediately.
