Skip to main content

Semantic caching library for LLM apps

Project description

Coverage

SemantiCache

SemantiCache is a semantic caching library that enables efficient storage and retrieval of query-response pairs using FAISS and vector embeddings. It supports cache expiration, trimming strategies, and query similarity search.

Features

  • Vector-based caching using FAISS and HuggingFace embeddings
  • Query similarity search for retrieving semantically relevant responses
  • Automatic cache management with size and TTL-based trimming
  • Leaderboard tracking for frequently accessed queries
  • Persistent storage for cache state management

Installation

pip install semanticache

Usage

Full Documentation

Read the docs


Initializing SemantiCache

from semanticache import SemantiCache

cache = SemantiCache(
    trim_by_size=True,
    cache_path="./sem_cache",
    config_path="./sem_config",
    cache_size=100,
    ttl=3600,
    threshold=0.1,
    leaderboard_top_n=5,
    log_level="INFO"
)

Storing a Query-Response Pair

cache.set("What is the capital of France?", "Paris")

Retrieving a Cached Response

response = cache.get("What is the capital of France?")
print(response)  # Output: Paris

Clearing the Cache

cache.clear(clear_files=True)  # Clears all cache entries and files

Reading the Leaderboard

leaderboard = cache.read_leaderboard()
print(leaderboard)  # Outputs most frequently accessed queries

Configuration

SemantiCache stores configuration parameters in ./sem_config/sem_config.yaml. These include:

cache:
  path: ./sem_cache
  name: sem_cache_index
  cache_size: 100
  ttl: 3600
  threshold: 0.1
  trim_by_size: True
  leaderboard_top_n: 5

Example: Using the Cache with an LLM

This example demonstrates how to check the cache before querying an LLM and how to store responses when needed.

from semanticache import SemantiCache

def call_llm(query):
    """Simulate an LLM call (replace with actual API call)."""
    return f"Response for: {query}"

# Initialize the cache
cache = SemantiCache()

# Example query
query = "What is the capital of France?"

# Check if the response is already cached
cached_response = cache.get(query)

if cached_response:
    print(f"Cache Hit: {cached_response}")
else:
    print("Cache Miss: Querying LLM...")
    response = call_llm(query)
    cache.set(query, response)
    print(f"Stored in cache: {response}")

Advanced Settings

Cache Trimming

  • By Size: Keeps the most accessed entries up to cache_size

  • By Time (TTL): Removes entries older than ttl seconds

    This is toggled by setting trim_by_size to True or False in config file or during initialization in script

Similarity Threshold

  • Determines when a query matches an existing cache entry
  • A lower threshold increases exact matches, while a higher one allows more flexible retrieval

Dependencies

  • FAISS for vector similarity search
  • HuggingFace from Langchain Community for embedding generation
  • yaml, numpy, json, and pickle for serialization

Help

Feel free to reach out to me or create a new issue if you encounter any problems using SemantiCache

Contribution: Possible Improvements/Ideas

  • More unit tests
  • Less dependence on other libraries
  • Support for alternate vector index engines like ChromaDB, Milvus, etc.
  • More optimized logic where possible
  • Implement more sophisticated ranking and pruning algorithms.
  • Support additional embedding models for improved semantic search.

Authors

Contributors names and contact info

Abraham Audu

Version History

Acknowledgments

  • This library was built on top of FAISS, HuggingFace and LangChain

License

This project is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.

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

semanticache-0.1.0.tar.gz (49.9 kB view details)

Uploaded Source

Built Distribution

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

semanticache-0.1.0-py3-none-any.whl (41.5 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for semanticache-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a68a1656004bedf6d8319698f939fabf17d4245584cf60be0f1b933ca719e2d4
MD5 328a63990b76bd90f02fdea277633116
BLAKE2b-256 079878422d125d71c83e502d255b87a2badb6490ec5aa12a2c1bd85d681540fd

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for semanticache-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0af81acae7d63bf7913006b96244b5ef735c3487b55f87ac3421d7f57411506e
MD5 fd5c787ad8d432f70c1fb7add6c12d1f
BLAKE2b-256 d28e8fd81582e56d845d4187d195cafcdbebd1705e77943c0c6308b32ede4c3b

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