Skip to main content

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

Metadata

Release files for llm-std-lib 1.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for llm-std-lib 1.0.3
File Size Uploaded
llm_std_lib-1.0.3.tar.gz 110.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for llm-std-lib 1.0.3
File Interpreter ABI Platform
llm_std_lib-1.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 215.1 kB

Release files / llm_std_lib-1.0.3.tar.gz

Download URL llm_std_lib-1.0.3.tar.gz
Size 110.5 kB
Tags Source
SHA-256 checksum
How to use checksums
d4643bfccf6b55884abdce22226f2f9607e5596a4818b475f5e6d90480cef600
BLAKE2b-256 checksum
How to use checksums
b84a03d84a24574139e8e6d49f1232b820d3ab635ef946cf799559e453a1d6bf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 29, 2026.

Transparency log

Release files / llm_std_lib-1.0.3-py3-none-any.whl

Download URL llm_std_lib-1.0.3-py3-none-any.whl
Size 104.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
afe2d2c6b53ece209946bffa422d738d164db1556dda148bf5c7a7a8d72c7e88
BLAKE2b-256 checksum
How to use checksums
0120d768f01b72e7cbb8a5464b79e9298063f9a5aaf6c60dbfebca3c321b6264
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 29, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

1.0.3 This release

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page