Skip to main content

SpendLil SDK — drop-in AI proxy wrapper for cost tracking, compliance, and rate limiting

Project description

SpendLil Python SDK

Drop-in wrapper for OpenAI, Anthropic, Google, and Mistral that routes all AI calls through your SpendLil proxy — giving you cost tracking, compliance controls, PII detection, rate limiting, and audit logs with minimal code changes.

Install

pip install spendlil
# or with optional provider packages:
pip install "spendlil[openai]"
pip install "spendlil[anthropic]"
pip install "spendlil[all]"

Quick start

import os
from spendlil import SpendLil, SpendLilError

sl = SpendLil(
    agent_id="your-agent-id",           # from SpendLil dashboard
    base_url="https://spendlil.yourco.com/api",
)

# ── OpenAI (drop-in replacement) ─────────────────────────
openai = sl.openai(api_key=os.environ["OPENAI_API_KEY"])

response = openai.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
)

print(response["choices"][0]["message"]["content"])
print(response["_spendlil"].tier)        # 'frontier'
print(response["_spendlil"].model)       # 'gpt-4o'

# ── Anthropic (drop-in replacement) ──────────────────────
anthropic = sl.anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

msg = anthropic.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Summarise this..."}],
)

print(msg["content"][0]["text"])

# ── Auto-routing (SpendLil picks the best model) ─────────
auto = openai.chat.completions.auto_create(
    messages=[{"role": "user", "content": "Write a haiku about Python"}],
)
print(auto["_spendlil"].model)   # e.g. 'gpt-4o-mini' — SpendLil chose

# ── Async ─────────────────────────────────────────────────
import asyncio

async def main():
    response = await openai.chat.completions.async_create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello async!"}],
    )
    print(response["choices"][0]["message"]["content"])

asyncio.run(main())

# ── Async streaming ───────────────────────────────────────
async def stream():
    async for chunk in openai.chat.completions.async_stream(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Count to 5"}],
    ):
        delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
        print(delta, end="", flush=True)

asyncio.run(stream())

# ── Session / context management ─────────────────────────
session_sl = sl.with_session("user-session-abc123")
session_openai = session_sl.openai(api_key=os.environ["OPENAI_API_KEY"])
# All requests with this client share context in SpendLil (STICKY/POOL mode)

Error handling

from spendlil import SpendLilError

try:
    response = openai.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello"}],
    )
except SpendLilError as e:
    print(f"HTTP {e.status_code}: {e.message}")
    if e.meta and e.meta.quota_exceeded:
        print("Agent quota exceeded — try again later")

SpendLil metadata

Every response includes a _spendlil key with a SpendLilMeta dataclass:

Attribute Type Description
tracked bool Request was logged by SpendLil
model str Model actually used
provider str Provider used
tier str economy / standard / frontier
fallback bool Fallback model was used
escalated bool Request was auto-escalated
escalated_from str Original model before escalation
translated bool Cross-provider format translation applied
session_key str Active session key
context_mode str none / sticky / pool
quota_exceeded bool Agent quota was exceeded

Batch / deferred processing

response = openai.chat.completions.create(
    model="gpt-4o",
    messages=[...],
    priority="batch",   # deferred to SpendLil batch queue
)
# Returns 202 with batch job ID

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spendlil-0.1.0.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spendlil-0.1.0-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

Details for the file spendlil-0.1.0.tar.gz.

File metadata

  • Download URL: spendlil-0.1.0.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for spendlil-0.1.0.tar.gz
Algorithm Hash digest
SHA256 06b7e053ee1d18159ba624b0583e80d8b938784fbb10a7601f405a5e69ba7c4e
MD5 4df030daf8fec9b1eb67a54a95ed36e4
BLAKE2b-256 707e5aa98c3cb16684ae1fb0007a2b5e0c50f4d2a4b9cbacdd31c88efe8315e1

See more details on using hashes here.

File details

Details for the file spendlil-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: spendlil-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for spendlil-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3d75cf38e0199526fc63f79c6f180aea69122f92eeb9b29b22fa4acf90b1c41a
MD5 104ba8fef7999f5e20ed3188cebb7a39
BLAKE2b-256 8489d580bb3313c7a25b6df0e614355369e9bb0723b72d547270ef5352d23a79

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page