Metadata-Version: 2.1
Name: paid-python
Version: 0.0.5a27
Summary: 
Requires-Python: >=3.9,<4.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: anthropic (>=0.57.0)
Requires-Dist: google-genai (>=1.19.0)
Requires-Dist: httpx (>=0.21.0)
Requires-Dist: langchain-core (>=0.1.0)
Requires-Dist: llama-index-core (>=0.13.0)
Requires-Dist: llama-index-llms-openai (>=0.5.0)
Requires-Dist: mistralai (>=1.9.0)
Requires-Dist: mutagen (>=1.47.0)
Requires-Dist: openai (>=1.12.0)
Requires-Dist: openai-agents (>=0.2.0)
Requires-Dist: opentelemetry-api (>=1.23.0)
Requires-Dist: opentelemetry-exporter-otlp-proto-http (>=1.23.0)
Requires-Dist: opentelemetry-sdk (>=1.23.0)
Requires-Dist: pydantic (>=1.9.0)
Requires-Dist: pydantic-core (>=2.18.0)
Requires-Dist: python-dotenv (>=1.0.0)
Requires-Dist: typing_extensions (>=4.0.0)
Description-Content-Type: text/markdown

<div align="center">
    <picture>
        <source media="(prefers-color-scheme: dark)" srcset="./assets/paid_light.svg" width=600>
        <source media="(prefers-color-scheme: light)" srcset="./assets/paid_dark.svg" width=600>
        <img alt="Fallback image description" src="./assets/paid_light.svg" width=600>
    </picture>
</div>

#

<div align="center">
    <a href="https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2FAgentPaid%2Fpaid-python">
        <img src="https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen" alt="fern shield">
    </a>
    <a href="https://pypi.org/project/paid-python">
        <img src="https://img.shields.io/pypi/v/paid-python" alt="pypi shield">
    </a>
</div>

Paid is the all-in-one, drop-in Business Engine for AI Agents that handles your pricing, subscriptions, margins, billing, and renewals with just 5 lines of code.
The Paid Python library provides convenient access to the Paid API from Python applications.

## Documentation

See the full API docs [here](https://paid.docs.buildwithfern.com/api-reference/api-reference/customers/list)

## Installation

You can install the package using pip:

```bash
pip install paid-python
```

## Usage

The client needs to be configured with your account's API key, which is available in the [Paid dashboard](https://app.paid.ai/agent-integration/api-keys).

```python
from paid import Paid

client = Paid(token="API_KEY")

client.customers.create(
    name="name"
)
```

## Request And Response Types

The SDK provides Python classes for all request and response types. These are automatically handled when making API calls.

```python
# Example of creating a customer
response = client.customers.create(
    name="John Doe",
)

# Access response data
print(response.name)
print(response.email)
```

## Exception Handling

When the API returns a non-success status code (4xx or 5xx response), the SDK will raise an appropriate error.

```python
try:
    client.customers.create(...)
except paid.Error as e:
    print(e.status_code)
    print(e.message)
    print(e.body)
    print(e.raw_response)
```

## Logging

Supported log levels are `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL`.

For example, to set the log level to debug, you can set the environment variable:

```bash
export PAID_LOG_LEVEL=DEBUG
```

Defaults to ERROR.

## Cost Tracking via OTEL tracing

### Simple Decorator Method

The easiest way to add cost tracking is using the `@paid_tracing` decorator:

```python
from paid.tracing import paid_tracing

@paid_tracing("<external_customer_id>", "<optional_external_agent_id>")  # add this line
def some_agent_workflow():  # your function
    # Your logic - use any AI providers with Paid wrappers or send signals with Paid.signal().
    # This function is typically an event processor that should lead to AI calls or events emitted as Paid signals
```

- Initializes tracing using your API key you provided to the Paid client, falls back to `PAID_API_KEY` environment variable.
- Handles both sync and async functions
- Gracefully falls back to normal execution if tracing fails

### Using the Paid wrappers

You can track usage costs by using Paid wrappers around your AI provider's SDK.
As of now, the following SDKs' APIs are wrapped:

```
openai
openai-agents
anthropic
langchain (as a callback)
llamaindex
bedrock (boto3)
mistral
gemini (google-genai)
```

Example usage:
```python
from openai import OpenAI
from paid.tracing.wrappers import PaidOpenAI

openAIClient = PaidOpenAI(OpenAI(
    # This is the default and can be omitted
    api_key="<OPENAI_API_KEY>",
))

@paid_tracing("your_external_customer_id", "your_external_agent_id")
def image_generate():
    response = openAIClient.images.generate(
        model="dall-e-3",
        prompt="A sunset over mountains",
        size="1024x1024",
        quality="hd",
        style="vivid",
        n=1
    )
    return response

image_generate()
```

Alternatively, instead of the decorators you can use the paid.trace() function (more control by wrapping with a callback).

```python
from openai import OpenAI
from paid import Paid
from paid.tracing.wrappers import PaidOpenAI

# Initialize Paid SDK
client = Paid(token="PAID_API_KEY")

openAIClient = PaidOpenAI(OpenAI(
    # This is the default and can be omitted
    api_key="<OPENAI_API_KEY>",
))

# Initialize tracing, must be after initializeing Paid SKD
client.initialize_tracing()

def image_generate():
    response = openAIClient.images.generate(
        model="dall-e-3",
        prompt="A sunset over mountains",
        size="1024x1024",
        quality="hd",
        style="vivid",
        n=1
    )
    return response

# Finally, capture the traces!
_ = client.trace(external_customer_id = "<your_external_customer_id>",
                external_agent_id = "<your_external_agent_id>",  # can optionally include external_agent_id to enable agent-level cost tracking
                fn = lambda: image_generate())
```

## Signaling via OTEL tracing

A more reliable and user-friendly way to send signals is to send them from within the traces.
This allows you to send signals with the same customer and agent IDs as the trace, with less arguments and boilerplate.
The interface is `Paid.signal()`, which takes in signal name and optional data.
`Paid.signal()` has to be called within a trace - meaning inside of a callback to `Paid.trace()`.
In contrast to `Paid.usage.record_bulk()`, `Paid.signal()` is using OpenTelemetry to provide reliable delivery.

Here's an example of how to use it:
```python
from paid import Paid

# Initialize Paid SDK
client = Paid(token="PAID_API_KEY")

@paid_tracing("your_external_customer_id", "your_external_agent_id")  # external_agent_id is necessary for sending signals
def do_work():
    # ...do some work...
    client.signal(
        event_name="<your_signal_name>",
        data={ } # optional data (ex. manual cost tracking data)
    )

do_work()
```

Same, but using callback to specify the function to trace:
```python
from paid import Paid

# Initialize Paid SDK
client = Paid(token="PAID_API_KEY")

# Initialize tracing, must be after initializing Paid SDK
client.initialize_tracing()

def do_work():
    # ...do some work...
    client.signal(
        event_name="<your_signal_name>",
        data={ } # optional data (ex. manual cost tracking data)
    )

# Finally, capture the traces!
_ = client.trace(external_customer_id = "<your_external_customer_id>",
                external_agent_id = "<your_external_agent_id>",  # external_agent_id is required for signals
                fn = lambda: do_work())
```

## Manual Cost Tracking

Manual cost tracking allow to insert your own costs to the usage data and
cost traces will be created based on that info.

```python
from paid import Paid, Signal

client = Paid(token="<PAID_API_KEY>")

signal = Signal(
    event_name="<your_signal_name>",
    agent_id="<your_agent_id>",
    customer_id="<your_external_customer_id>",
    data = {
        "costData": {
            "vendor": "<any_vendor_name>", # can be anything
            "cost": {
                "amount": 0.002,
                "currency": "USD"
            },
            "gen_ai.response.model": "<ai_model_name>",
        }
    }
)

_ = client.usage.record_bulk(signals=[signal])
```

## Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.
Additions made directly to this library would have to be moved over to our generation code,
otherwise they would be overwritten upon the next generated release. Feel free to open a PR as
a proof of concept, but know that we will not be able to merge it as-is. We suggest opening
an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!

