Skip to main content

Official Python API for CacheAI - Semantic Caching for Large Language Models

Project description

CacheAI Python API

Official Python API for CacheAI - Semantic Caching for Large Language Models

PyPI version Python Support License: MIT

Features

  • OpenAI Compatible: Drop-in replacement for OpenAI Python SDK
  • Semantic Caching: Automatic caching of similar queries using advanced semantic similarity
  • Multiple LLM Backends: Support for OpenAI, Anthropic, Google AI, and more
  • Streaming Support: Full support for streaming responses
  • Type-Safe: Complete type hints for better IDE support
  • Easy Integration: Minimal code changes required

Installation

pip install cacheai

Quick Start

Basic Usage

from cacheai import Client

# Initialize client
client = Client(
    api_key="your-cacheai-api-key",
    base_url="https://api.cacheai.tech/v1"  # Optional, this is the default
)

# Create a chat completion
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Hello, how are you?"}
    ]
)

print(response.choices[0].message.content)

With Environment Variables

import os
from cacheai import Client

# Set environment variables
os.environ["CACHEAI_API_KEY"] = "your-cacheai-api-key"
os.environ["CACHEAI_BACKEND_PROVIDER"] = "openai"
os.environ["CACHEAI_BACKEND_API_KEY"] = "your-openai-api-key"

# Initialize client (reads from environment)
client = Client()

response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "What is Python?"}]
)

print(response.choices[0].message.content)

Streaming

from cacheai import Client

client = Client(api_key="your-cacheai-api-key")

stream = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Configuration

Backend LLM Configuration

CacheAI acts as a caching layer in front of your preferred LLM provider. Configure the backend:

from cacheai import Client

client = Client(
    api_key="your-cacheai-api-key",
    backend_provider="openai",        # "openai", "anthropic", "google", etc.
    backend_api_key="your-openai-key",  # Backend LLM API key
)

# Or use environment variables:
# CACHEAI_BACKEND_PROVIDER=openai
# CACHEAI_BACKEND_API_KEY=sk-...

Cache Control

from cacheai import Client

# Disable caching (for debugging/testing)
client = Client(
    api_key="your-cacheai-api-key",
    enable_cache=False
)

# Or via environment variable:
# CACHEAI_ENABLE_CACHE=false

Advanced Usage

Context Manager

from cacheai import Client

with Client(api_key="your-api-key") as client:
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(response.choices[0].message.content)
# Connection is automatically closed

Custom Timeout and Retries

from cacheai import Client

client = Client(
    api_key="your-api-key",
    timeout=30.0,      # Request timeout in seconds
    max_retries=3      # Maximum retry attempts
)

Error Handling

from cacheai import Client, CacheAIError, AuthenticationError, RateLimitError

client = Client(api_key="your-api-key")

try:
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Hello!"}]
    )
except AuthenticationError as e:
    print(f"Invalid API key: {e}")
except RateLimitError as e:
    print(f"Rate limit exceeded: {e}")
except CacheAIError as e:
    print(f"API error: {e}")

API Reference

Client

Client(
    api_key: Optional[str] = None,           # CacheAI API key
    base_url: Optional[str] = None,          # API base URL
    timeout: float = 60.0,                   # Request timeout
    max_retries: int = 2,                    # Max retry attempts
    enable_cache: bool = True,               # Enable semantic caching
    backend_provider: Optional[str] = None,  # Backend LLM provider
    backend_api_key: Optional[str] = None,   # Backend API key
    backend_base_url: Optional[str] = None   # Custom backend URL
)

Chat Completions

client.chat.completions.create(
    model: str,                              # Model ID
    messages: List[Dict[str, str]],          # Conversation messages
    temperature: Optional[float] = None,     # Sampling temperature (0-2)
    max_tokens: Optional[int] = None,        # Max tokens to generate
    top_p: Optional[float] = None,           # Nucleus sampling
    frequency_penalty: Optional[float] = None,  # Frequency penalty
    presence_penalty: Optional[float] = None,   # Presence penalty
    stop: Optional[Union[str, List[str]]] = None,  # Stop sequences
    stream: bool = False                     # Enable streaming
) -> ChatCompletion

Environment Variables

Variable Description Default
CACHEAI_API_KEY CacheAI API key (required)
CACHEAI_BASE_URL API base URL https://api.cacheai.tech/v1
CACHEAI_ENABLE_CACHE Enable semantic caching true
CACHEAI_BACKEND_PROVIDER Backend LLM provider (optional)
CACHEAI_BACKEND_API_KEY Backend LLM API key (optional)
CACHEAI_BACKEND_BASE_URL Custom backend URL (optional)

Migration from OpenAI

CacheAI is designed to be a drop-in replacement for OpenAI:

# Before (OpenAI)
from openai import OpenAI
client = OpenAI(api_key="sk-...")
response = client.chat.completions.create(...)

# After (CacheAI)
from cacheai import Client
client = Client(api_key="ca-...", backend_provider="openai", backend_api_key="sk-...")
response = client.chat.completions.create(...)

Examples

See the examples directory for more usage examples:

Development

Install Development Dependencies

pip install -e ".[dev]"

Run Tests

pytest

Type Checking

mypy cacheai

Code Formatting

black cacheai
ruff cacheai

Support

License

MIT License - see LICENSE file for details.

Links

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

cacheai-0.1.0.tar.gz (15.7 kB view details)

Uploaded Source

Built Distribution

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

cacheai-0.1.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: cacheai-0.1.0.tar.gz
  • Upload date:
  • Size: 15.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for cacheai-0.1.0.tar.gz
Algorithm Hash digest
SHA256 93178d1ea8f2f64fbaf4fffc974c251cfef0149e61066f6e160ad534097f066d
MD5 f317a0f102186103bfb6d4c06dc14ebe
BLAKE2b-256 5c9c3b8ee9d26101774daf50e2642a6a94d51d6bb5c5e0a31ed85cdb77be8899

See more details on using hashes here.

File details

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

File metadata

  • Download URL: cacheai-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for cacheai-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2af96f814ebcfd0752137f596efeef9692b86d4521a8ed55b13e84ddc33e08f5
MD5 c18477736ea0d2f40e362922599b0aab
BLAKE2b-256 062f8f82dbb05df99aa11457b6bc19761ef6d22f55005943b80e5d28bb49d2dc

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