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.1.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.1-py3-none-any.whl (41.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: semanticache-0.1.1.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.1.tar.gz
Algorithm Hash digest
SHA256 97b88392ead03fc47130dea7e1bea6cde41e1bf24b877de78a7089dfc8136854
MD5 fbcb556251d50a0540c46810743c3d7e
BLAKE2b-256 13dd2ac3e83f8a42bf5362749dfeb00e2d8cf5c05b0df338cb1f686cea87eb68

See more details on using hashes here.

File details

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

File metadata

  • Download URL: semanticache-0.1.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c385dbef488436a3ac2d5be572a3b54ca9b7f1a88fc0554e53a9c8ca5684b882
MD5 16583b8e07b5360b615f59a17b0349b4
BLAKE2b-256 dcc229f9b2cd04c3dbb39123ad21097491539c49b3727d83b4200d92080f95ed

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