For advanced control, manually instantiate a Cache object and pass it to init_similar_cache. This allows you to define custom embedding, data_manager, evaluation, and post_func components.
Important: When using a custom cache_obj, you MUST pass it as a parameter to the LLM adapter method (e.g., openai.ChatCompletion.create(..., cache_obj=your_cache_instance)).
from gptcache import Cache, Config
from gptcache.adapter import openai
from gptcache.adapter.api import init_similar_cache
from gptcache.embedding import Onnx
from gptcache.manager import manager_factory
from gptcache.processor.post import random_one
from gptcache.processor.pre import last_content
from gptcache.similarity_evaluation import OnnxModelEvaluation
# 1. Create Cache object
openai_complete_cache = Cache()
# 2. Setup Encoder
encoder = Onnx()
# 3. Setup Data Manager
sqlite_faiss_data_manager = manager_factory(
"sqlite,faiss",
data_dir="openai_complete_cache",
scalar_params={
"sql_url": "sqlite:///./openai_complete_cache.db",
"table_name": "openai_chat",
},
vector_params={
"dimension": encoder.dimension,
"index_file_path": "./openai_chat_faiss.index",
},
)
# 4. Setup Evaluation and Config
onnx_evaluation = OnnxModelEvaluation()
cache_config = Config(similarity_threshold=0.75)
# 5. Initialize
init_similar_cache(
cache_obj=openai_complete_cache,
pre_func=last_content,
embedding=encoder,
data_manager=sqlite_faiss_data_manager,
evaluation=onnx_evaluation,
post_func=random_one,
config=cache_config,
)
# 6. Use with cache_obj parameter
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "what's github"}],
cache_obj=openai_complete_cache,
)