Skip to main content

Python library for standardization, optimization and monitoring of LLM API calls

Project description

llm-std-lib

Python infrastructure library for production-grade LLM API calls.

CI codecov PyPI Python License: MIT

One unified async client for OpenAI, Anthropic, Google, Azure OpenAI, AWS Bedrock, Ollama, Groq, and LM Studio — with semantic caching, model routing, resilience, and Prometheus/OTLP observability built in.


Features

Feature Description
Unified client LLMClient.acomplete() works across 8 providers with one API
Semantic cache Avoid re-paying for similar prompts (Redis, ChromaDB, Qdrant, Pinecone)
Model router Route by complexity, cost, latency, or round-robin
Resilience Retry, circuit breaker, timeout, and provider fallback chains
Middleware PII redaction, cost tracking, rate limiting — all pluggable
Observability Prometheus and OpenTelemetry (OTLP) exporters, Grafana dashboard included
Flexible config YAML/TOML files, environment variables, HashiCorp Vault, AES-256 encryption

Installation

# Core only
pip install llm-std-lib

# With common extras
pip install "llm-std-lib[redis,prometheus]"

# Everything
pip install "llm-std-lib[all]"

Available extras: redis, chroma, qdrant, pinecone, prometheus, otlp, local-embeddings, vault, encryption, all.


Quick start

import asyncio
from llm_std_lib import LLMClient, LLMConfig

config = LLMConfig(
    default_model="openai/gpt-4o-mini",
    providers={"openai": {"api_key": "sk-..."}},
)
client = LLMClient(config)

async def main():
    response = await client.acomplete(
        prompt="Explain semantic caching in one sentence.",
    )
    print(response.text)
    print(f"Cost: ${response.cost_usd:.6f}  |  Latency: {response.latency_ms:.0f}ms")

asyncio.run(main())

Or even shorter — load keys from environment variables:

export OPENAI_API_KEY=sk-...
client = LLMClient.from_env()
response = client.complete("What is the capital of France?")  # sync
print(response.text)  # Paris

Semantic cache

from llm_std_lib import LLMClient, LLMConfig, SemanticCache
from llm_std_lib.cache.backends.redis import RedisBackend
from llm_std_lib.cache.encoders.openai import OpenAIEncoder

cache = SemanticCache(
    backend=RedisBackend(url="redis://localhost:6379"),
    encoder=OpenAIEncoder(api_key="sk-..."),
    similarity_threshold=0.92,
)

config = LLMConfig(
    default_model="openai/gpt-4o-mini",
    providers={"openai": {"api_key": "sk-..."}},
    cache=cache,
)
client = LLMClient(config)

r1 = await client.acomplete(prompt="What is the capital of France?")
r2 = await client.acomplete(prompt="Tell me the capital city of France.")
print(r2.cached)   # True — served from cache

Model router

from llm_std_lib import LLMClient, LLMConfig, ModelRouter

router = ModelRouter.complexity_based(tiers=[
    {"models": ["openai/gpt-4o-mini"],      "max_complexity": 0.3},
    {"models": ["openai/gpt-4o"],           "max_complexity": 0.7},
    {"models": ["anthropic/claude-opus-3"], "max_complexity": 1.0},
])

client = LLMClient(LLMConfig.from_env(), router=router)

# Model is selected automatically based on prompt complexity
r = await client.acomplete(prompt="Hi")                              # → gpt-4o-mini
r = await client.acomplete(prompt="Prove Fermat's Last Theorem")     # → claude-opus-3

Resilience

from llm_std_lib.resilience import ResilienceEngine
from llm_std_lib.resilience.circuit_breaker import CircuitBreaker
from llm_std_lib.resilience.retry import RetryPolicy
from llm_std_lib.resilience.backend import InMemoryBackend

engine = ResilienceEngine(
    breaker=CircuitBreaker(
        backend=InMemoryBackend(),
        key="openai",
        failure_threshold_ratio=0.5,
        recovery_timeout=30.0,
    ),
    retryer=RetryPolicy(max_attempts=3, base_delay=0.5),
)

response = await engine.execute(
    lambda: client.acomplete(prompt="Hello")
)

Observability

from llm_std_lib.metrics import MetricsCollector, PrometheusExporter
from llm_std_lib.types import RequestContext, ResponseContext

exporter  = PrometheusExporter()
collector = MetricsCollector(on_record=exporter.update)
exporter.start_http_server(port=8000)   # scrape at http://localhost:8000/metrics

# Attach manually after each response
ctx = RequestContext(prompt="Hello", model="gpt-4o-mini", provider="openai")
response_ctx = await client._dispatch(ctx)
await collector.post_request(ctx, response_ctx)

Import grafana_dashboard.json (included in the repo) for a ready-made Grafana dashboard.


Supported providers

Provider Model prefix Auth env var
OpenAI openai/ OPENAI_API_KEY
Anthropic anthropic/ ANTHROPIC_API_KEY
Google Gemini google/ GOOGLE_API_KEY
Azure OpenAI azure/ AZURE_OPENAI_API_KEY
AWS Bedrock bedrock/ AWS credential chain
Ollama (local) ollama/
Groq groq/ GROQ_API_KEY
LM Studio (local) lm_studio/ optional

Configuration

From environment variables

from llm_std_lib import LLMClient

client = LLMClient.from_env()

From a YAML file

# config.yaml
default_model: openai/gpt-4o-mini
providers:
  openai:
    api_key: "${OPENAI_API_KEY}"
    timeout_ms: 15000
  anthropic:
    api_key: "${ANTHROPIC_API_KEY}"
from llm_std_lib import LLMConfig

config = LLMConfig.from_file("config.yaml")

From HashiCorp Vault

from llm_std_lib.config import VaultConfig

vault  = VaultConfig(url="https://vault.example.com", secret_path="llm/prod")
config = vault.load()

Documentation


License

MIT

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

llm_std_lib-1.0.3.tar.gz (110.5 kB view details)

Uploaded Source

Built Distribution

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

llm_std_lib-1.0.3-py3-none-any.whl (104.7 kB view details)

Uploaded Python 3

File details

Details for the file llm_std_lib-1.0.3.tar.gz.

File metadata

  • Download URL: llm_std_lib-1.0.3.tar.gz
  • Upload date:
  • Size: 110.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for llm_std_lib-1.0.3.tar.gz
Algorithm Hash digest
SHA256 d4643bfccf6b55884abdce22226f2f9607e5596a4818b475f5e6d90480cef600
MD5 bc5184497ea4b3910d14e1eea114b8d9
BLAKE2b-256 b84a03d84a24574139e8e6d49f1232b820d3ab635ef946cf799559e453a1d6bf

See more details on using hashes here.

Provenance

The following attestation bundles were made for llm_std_lib-1.0.3.tar.gz:

Publisher: release.yml on NutaEnjoyer/llm-std-lib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file llm_std_lib-1.0.3-py3-none-any.whl.

File metadata

  • Download URL: llm_std_lib-1.0.3-py3-none-any.whl
  • Upload date:
  • Size: 104.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for llm_std_lib-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 afe2d2c6b53ece209946bffa422d738d164db1556dda148bf5c7a7a8d72c7e88
MD5 dc85546076564d052b42d69f376e9bfb
BLAKE2b-256 0120d768f01b72e7cbb8a5464b79e9298063f9a5aaf6c60dbfebca3c321b6264

See more details on using hashes here.

Provenance

The following attestation bundles were made for llm_std_lib-1.0.3-py3-none-any.whl:

Publisher: release.yml on NutaEnjoyer/llm-std-lib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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