🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
Semantic Cache Phase 1 (#3790)
Yug Borana27bde5020f5a
diff --git a/camel/caches/__init__.py b/camel/caches/__init__.pynew file mode 100644index 000000000..ae387cf9f--- /dev/null+++ b/camel/caches/__init__.py@@ -0,0 +1,22 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++from .base import BaseCache, CacheRecord+from .semantic_cache import SemanticCache++__all__ = [+ "BaseCache",+ "CacheRecord",+ "SemanticCache",+]diff --git a/camel/caches/base.py b/camel/caches/base.pynew file mode 100644index 000000000..3a01f08f9--- /dev/null+++ b/camel/caches/base.py@@ -0,0 +1,119 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from datetime import datetime+from typing import Any, Dict, Optional+++@dataclass+class CacheRecord:+ r"""Represents a cached query-response pair with metadata.++ Attributes:+ query (str): The original query text.+ response (str): The cached response for the query.+ query_id (str): Unique identifier for this cache entry.+ created_at (datetime): Timestamp when the entry was created.+ metadata (Dict[str, Any]): Additional metadata about the cache entry.+ """++ query: str+ response: str+ query_id: str+ created_at: datetime = field(default_factory=datetime.now)+ metadata: Dict[str, Any] = field(default_factory=dict)+++class BaseCache(ABC):+ r"""An abstract base class for cache systems.++ This class defines the interface for caching mechanisms that can store+ and retrieve query-response pairs. Implementations may use various+ strategies including exact match, semantic similarity, or hybrid.+ """++ @abstractmethod+ def get(self, query: str) -> Optional[str]:+ r"""Retrieve a cached response for the given query.++ Args:+ query (str): The query to look up in the cache.++ Returns:+ Optional[str]: The cached response if found, None otherwise.+ """+ pass++ @abstractmethod+ def set(self, query: str, response: str, **kwargs: Any) -> Optional[str]:+ r"""Store a query-response pair in the cache.++ Args:+ query (str): The query text.+ response (str): The response to cache.+ **kwargs (Any): Additional arguments for the cache entry.++ Returns:+ Optional[str]: The unique ID of the cache entry, or None.+ """+ pass++ @abstractmethod+ def delete(self, entry_id: str) -> bool:+ r"""Delete a specific cache entry by its ID.++ Args:+ entry_id (str): The unique ID of the entry to delete.++ Returns:+ bool: True if the entry was deleted, False otherwise.+ """+ pass++ @abstractmethod+ def clear(self) -> None:+ r"""Remove all entries from the cache."""+ pass++ @property+ @abstractmethod+ def size(self) -> int:+ r"""Returns the number of entries in the cache.++ Returns:+ int: The number of cached entries.+ """+ pass++ @property+ @abstractmethod+ def enabled(self) -> bool:+ r"""Returns whether the cache is enabled.++ Returns:+ bool: True if cache is enabled, False otherwise.+ """+ pass++ @enabled.setter+ @abstractmethod+ def enabled(self, value: bool) -> None:+ r"""Enable or disable the cache.++ Args:+ value (bool): True to enable, False to disable.+ """+ passdiff --git a/camel/caches/semantic_cache.py b/camel/caches/semantic_cache.pynew file mode 100644index 000000000..5a38ed149--- /dev/null+++ b/camel/caches/semantic_cache.py@@ -0,0 +1,496 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++import json+from datetime import datetime+from threading import Lock+from typing import Any, Dict, List, Optional+from uuid import uuid4++from camel.caches.base import BaseCache, CacheRecord+from camel.embeddings.base import BaseEmbedding+from camel.logger import get_logger+from camel.storages.vectordb_storages import (+ BaseVectorStorage,+ VectorDBQuery,+ VectorRecord,+)++logger = get_logger(__name__)+++class SemanticCache(BaseCache):+ r"""A semantic cache implementation that uses vector similarity to find+ cached responses for semantically similar queries.++ This cache generates embeddings for queries and stores them in a vector+ database. When looking up a query, it finds the most similar cached query+ using vector similarity search and returns the corresponding response if+ the similarity exceeds the threshold.++ Args:+ embedding_model (BaseEmbedding): The embedding model to use for+ generating query embeddings.+ vector_storage (BaseVectorStorage): The vector storage backend for+ storing and searching query embeddings.+ similarity_threshold (float): The minimum similarity score (0.0-1.0)+ required for a cache hit. Higher values require closer matches.+ (default: :obj:`0.85`)+ cache_enabled (bool): Whether the cache is enabled.+ (default: :obj:`True`)++ """++ # Payload keys for storing cache data+ _QUERY_KEY = "query"+ _RESPONSE_KEY = "response"+ _CREATED_AT_KEY = "created_at"+ _METADATA_KEY = "metadata"++ def __init__(+ self,+ embedding_model: BaseEmbedding,+ vector_storage: BaseVectorStorage,+ similarity_threshold: float = 0.85,+ cache_enabled: bool = True,+ ) -> None:+ r"""Initialize the semantic cache.++ Args:+ embedding_model (BaseEmbedding): The embedding model for queries.+ vector_storage (BaseVectorStorage): The vector storage backend.+ similarity_threshold (float): Minimum similarity for cache hit.+ cache_enabled (bool): Whether the cache is enabled initially.+ """+ if not 0.0 <= similarity_threshold <= 1.0:+ raise ValueError(+ f"similarity_threshold must be between 0.0 and 1.0, "+ f"got {similarity_threshold}"+ )++ self._embedding_model = embedding_model+ self._vector_storage = vector_storage+ self._similarity_threshold = similarity_threshold+ self._cache_enabled = cache_enabled+ self._cache_hits = 0+ self._cache_misses = 0+ self._stats_lock = Lock()++ logger.info(+ f"SemanticCache initialized with threshold={similarity_threshold}"+ )++ @property+ def similarity_threshold(self) -> float:+ r"""Returns the similarity threshold for cache hits.++ Returns:+ float: The similarity threshold (0.0-1.0).+ """+ return self._similarity_threshold++ @similarity_threshold.setter+ def similarity_threshold(self, value: float) -> None:+ r"""Set the similarity threshold for cache hits.++ Args:+ value (float): The new threshold value (0.0-1.0).++ Raises:+ ValueError: If value is not between 0.0 and 1.0.+ """+ if not 0.0 <= value <= 1.0:+ raise ValueError(+ f"similarity_threshold must be between 0.0 and 1.0, "+ f"got {value}"+ )+ self._similarity_threshold = value++ @property+ def enabled(self) -> bool:+ r"""Returns whether the cache is enabled.++ Returns:+ bool: True if cache is enabled.+ """+ return self._cache_enabled++ @enabled.setter+ def enabled(self, value: bool) -> None:+ r"""Enable or disable the cache.++ Args:+ value (bool): True to enable, False to disable.+ """+ self._cache_enabled = value++ @property+ def size(self) -> int:+ r"""Returns the number of entries in the cache.++ Returns:+ int: The number of cached entries.+ """+ return self._vector_storage.status().vector_count++ @property+ def hit_rate(self) -> float:+ r"""Returns the cache hit rate.++ Returns:+ float: Cache hit rate (0.0-1.0), or 0.0 if no lookups yet.+ """+ with self._stats_lock:+ total = self._cache_hits + self._cache_misses+ if total == 0:+ return 0.0+ return self._cache_hits / total++ @property+ def stats(self) -> Dict[str, Any]:+ r"""Returns cache statistics.++ Returns:+ Dict[str, Any]: Dictionary containing cache statistics including+ hits, misses, hit rate, and size.+ """+ with self._stats_lock:+ return {+ "hits": self._cache_hits,+ "misses": self._cache_misses,+ "hit_rate": (+ self._cache_hits / (self._cache_hits + self._cache_misses)+ if (self._cache_hits + self._cache_misses) > 0+ else 0.0+ ),+ "size": self.size,+ "enabled": self.enabled,+ "similarity_threshold": self._similarity_threshold,+ }++ def _query_similar(self, query: str, top_k: int = 1) -> Optional[List]:+ r"""Internal helper to query vector storage for similar entries.++ This consolidates the common logic of embedding generation and+ vector storage querying used by get, get_with_score, and find_similar.++ Args:+ query (str): The query to search for.+ top_k (int): Number of results to return. (default: :obj:`1`)++ Returns:+ Optional[List]: List of query results from vector storage,+ or None if query fails or is empty.+ """+ if not query or not query.strip():+ return None++ # Generate embedding for the query+ try:+ query_embedding = self._embedding_model.embed(query)+ except Exception as e:+ logger.warning(f"Failed to generate embedding for query: {e}")+ return None++ # Search for similar queries+ try:+ results = self._vector_storage.query(+ VectorDBQuery(query_vector=query_embedding, top_k=top_k)+ )+ return results if results else None+ except Exception as e:+ logger.warning(f"Failed to query vector storage: {e}")+ return None++ def _result_to_cache_record(self, result) -> CacheRecord:+ r"""Convert a vector storage result to a CacheRecord.++ Args:+ result: A query result from vector storage.++ Returns:+ CacheRecord: The converted cache record.+ """+ payload = result.record.payload or {}+ # Deserialize metadata from JSON string (stored as JSON for+ # compatibility with storage backends that don't support nested dicts)+ metadata_raw = payload.get(self._METADATA_KEY, "{}")+ if isinstance(metadata_raw, str):+ try:+ metadata = json.loads(metadata_raw)+ except json.JSONDecodeError:+ metadata = {}+ else:+ metadata = metadata_raw if isinstance(metadata_raw, dict) else {}+ return CacheRecord(+ query=payload.get(self._QUERY_KEY, ""),+ response=payload.get(self._RESPONSE_KEY, ""),+ query_id=result.record.id,+ created_at=datetime.fromisoformat(+ payload.get(self._CREATED_AT_KEY, datetime.now().isoformat())+ ),+ metadata=metadata,+ )++ def _normalize_similarity(self, score: float) -> float:+ r"""Normalize similarity score to 0.0-1.0 range.++ Different vector storage backends may return similarity scores in+ different ranges. This method ensures consistent behavior by clamping+ scores to the expected 0.0-1.0 range.++ Args:+ score (float): Raw similarity score from storage backend.++ Returns:+ float: Normalized similarity score between 0.0 and 1.0.+ """+ return max(0.0, min(1.0, score))++ def get(self, query: str) -> Optional[str]:+ r"""Retrieve a cached response for a semantically similar query.++ Generates an embedding for the query and searches the vector storage+ for similar cached queries. Returns the cached response if a match+ is found with similarity >= threshold.++ Args:+ query (str): The query to look up in the cache.++ Returns:+ Optional[str]: The cached response if a similar query is found+ with sufficient similarity, None otherwise.+ """+ if not self._cache_enabled:+ return None++ results = self._query_similar(query, top_k=1)+ if not results:+ with self._stats_lock:+ self._cache_misses += 1+ logger.debug("Cache miss: no results found for query")+ return None++ # Check if the best match exceeds the threshold+ best_match = results[0]+ similarity = self._normalize_similarity(best_match.similarity)+ if similarity >= self._similarity_threshold:+ with self._stats_lock:+ self._cache_hits += 1+ payload = best_match.record.payload or {}+ response = payload.get(self._RESPONSE_KEY)+ logger.debug(+ f"Cache hit: similarity={similarity:.4f}, "+ f"threshold={self._similarity_threshold}"+ )+ return response++ with self._stats_lock:+ self._cache_misses += 1+ logger.debug(+ f"Cache miss: similarity={similarity:.4f} < "+ f"threshold={self._similarity_threshold}"+ )+ return None++ def get_with_score(+ self, query: str+ ) -> Optional[tuple[str, float, CacheRecord]]:+ r"""Retrieve cached response with similarity score and full record.++ Similar to get(), but returns additional information about the match.++ Args:+ query (str): The query to look up in the cache.++ Returns:+ Optional[tuple[str, float, CacheRecord]]: A tuple of+ (response, similarity_score, cache_record) if found,+ None otherwise.+ """+ if not self._cache_enabled:+ return None++ results = self._query_similar(query, top_k=1)+ if not results:+ with self._stats_lock:+ self._cache_misses += 1+ return None++ # Check if the best match exceeds the threshold+ best_match = results[0]+ similarity = self._normalize_similarity(best_match.similarity)+ if similarity >= self._similarity_threshold:+ with self._stats_lock:+ self._cache_hits += 1+ record = self._result_to_cache_record(best_match)+ return (record.response, similarity, record)++ with self._stats_lock:+ self._cache_misses += 1+ return None++ def set(+ self,+ query: str,+ response: str,+ **kwargs: Any,+ ) -> Optional[str]:+ r"""Store a query-response pair in the cache.++ Generates an embedding for the query and stores it along with the+ response in the vector storage. If a semantically similar query+ already exists (above the similarity threshold), the old entry is+ deleted and replaced with the new one.++ Args:+ query (str): The query text.+ response (str): The response to cache.+ **kwargs (Any): Additional arguments. Supports:+ - metadata (Dict[str, Any]): Additional metadata to store.++ Returns:+ Optional[str]: The unique ID assigned to this cache entry,+ or None if cache is disabled.++ Raises:+ ValueError: If query or response is empty.+ """+ if not self._cache_enabled:+ return None++ if not query or not query.strip():+ raise ValueError("Query cannot be empty")+ if not response:+ raise ValueError("Response cannot be empty")++ # Extract metadata from kwargs+ metadata: Optional[Dict[str, Any]] = kwargs.get("metadata")++ # Generate embedding for the query+ query_embedding = self._embedding_model.embed(query)++ # Check for existing similar entry to avoid duplicates+ try:+ existing = self._vector_storage.query(+ VectorDBQuery(+ query_vector=query_embedding,+ top_k=1,+ )+ )+ if existing:+ best = existing[0]+ sim = self._normalize_similarity(best.similarity)+ if sim >= self._similarity_threshold:+ old_id = best.record.id+ try:+ self._vector_storage.delete([old_id])+ logger.debug(+ f"Deleted duplicate entry "+ f"id={old_id} "+ f"(similarity={sim:.4f})"+ )+ except Exception as e:+ logger.debug(f"Could not delete old entry: {e}")+ except Exception as e:+ logger.debug(f"Duplicate check skipped: {e}")++ # Create unique ID for this entry+ entry_id = str(uuid4())+ created_at = datetime.now()++ # Prepare payload with cache data+ # Serialize metadata to JSON string for storage backends that+ # don't support nested dicts (e.g., ChromaDB)+ payload = {+ self._QUERY_KEY: query,+ self._RESPONSE_KEY: response,+ self._CREATED_AT_KEY: created_at.isoformat(),+ self._METADATA_KEY: json.dumps(metadata or {}),+ }++ # Create vector record+ record = VectorRecord(+ vector=query_embedding,+ id=entry_id,+ payload=payload,+ )++ # Store in vector storage+ self._vector_storage.add([record])++ logger.debug(f"Cached entry with id={entry_id}")+ return entry_id++ def delete(self, entry_id: str) -> bool:+ r"""Delete a specific cache entry by its ID.++ Args:+ entry_id (str): The unique ID of the cache entry to delete.++ Returns:+ bool: True if the entry was deleted, False if not found.+ """+ try:+ self._vector_storage.delete([entry_id])+ logger.debug(f"Deleted cache entry with id={entry_id}")+ return True+ except Exception as e:+ logger.warning(f"Failed to delete cache entry {entry_id}: {e}")+ return False++ def clear(self) -> None:+ r"""Remove all entries from the cache."""+ self._vector_storage.clear()+ with self._stats_lock:+ self._cache_hits = 0+ self._cache_misses = 0+ logger.info("Cache cleared")++ def find_similar(+ self, query: str, top_k: int = 5+ ) -> List[tuple[CacheRecord, float]]:+ r"""Find the top-k most similar cached queries.++ This method returns similar entries regardless of whether they+ meet the similarity threshold.++ Args:+ query (str): The query to search for.+ top_k (int): Number of results to return. (default: :obj:`5`)++ Returns:+ List[tuple[CacheRecord, float]]: List of (record, similarity)+ tuples sorted by similarity in descending order.+ """+ results = self._query_similar(query, top_k=top_k)+ if not results:+ return []++ # Convert results to CacheRecords using helper+ return [+ (+ self._result_to_cache_record(result),+ self._normalize_similarity(result.similarity),+ )+ for result in results+ ]++ def __repr__(self) -> str:+ return (+ f"SemanticCache("+ f"threshold={self._similarity_threshold}, "+ f"size={self.size}, "+ f"enabled={self._cache_enabled})"+ )diff --git a/camel/storages/vectordb_storages/faiss.py b/camel/storages/vectordb_storages/faiss.pyindex a376b6e2e..20f1c1604 100644--- a/camel/storages/vectordb_storages/faiss.py+++ b/camel/storages/vectordb_storages/faiss.py@@ -458,8 +458,11 @@ class FaissStorage(BaseVectorStorage):if not ids_to_delete:return- # Check if the index supports removal- if hasattr(self._index, 'remove_ids'):+ # Check if the index supports direct removal.+ # Note: We only use remove_ids for Flat indexes because it compacts+ # positions predictably. Other index types might leave gaps or not+ # shift IDs, leading to collisions or mapping errors.+ if self.index_type == 'Flat' and hasattr(self._index, 'remove_ids'):# Convert IDs to indicesindices_to_remove = np.array([@@ -471,18 +474,15 @@ class FaissStorage(BaseVectorStorage):)if len(indices_to_remove) > 0:- # Create a selector where 1 means "remove"- selector = np.zeros(self._index.ntotal, dtype=bool)- selector[indices_to_remove] = True-try:- # Remove from FAISS index- id_selector = faiss.IDSelectorArray(- len(indices_to_remove), indices_to_remove- )+ # NOTE: Pass only the array (1 arg) so FAISS's+ # Python wrapper auto-converts via swig_ptr().+ # Passing 2 args (len, array) bypasses the+ # wrapper and fails on some platforms.+ id_selector = faiss.IDSelectorArray(indices_to_remove)self._index.remove_ids(id_selector)- # Update mappings and storage+ # Update storagefor id in ids_to_delete:if id in self._id_to_index:idx = self._id_to_index[id]@@ -493,6 +493,18 @@ class FaissStorage(BaseVectorStorage):if id in self._vectors:del self._vectors[id]+ # FAISS remove_ids() compacts the index (for Flat indexes),+ # shifting positions down. We must rebuild _id_to_index and+ # _index_to_id to match the new dense positions.+ remaining_items = sorted(+ self._id_to_index.items(), key=lambda x: x[1]+ )+ self._id_to_index.clear()+ self._index_to_id.clear()+ for new_idx, (id, _old_idx) in enumerate(remaining_items):+ self._id_to_index[id] = new_idx+ self._index_to_id[new_idx] = id+# Save to disk if storage path is providedself._save_to_disk()except Exception as e:@@ -500,7 +512,7 @@ class FaissStorage(BaseVectorStorage):f"Failed to remove vectors from FAISS index: {e}")else:- # Index doesn't support removal, need to rebuild+ # Index doesn't support removal or needs rebuild for safetylogger.warning("This FAISS index type doesn't support direct removal. ""Rebuilding entire index (may be slow for large datasets)."diff --git a/camel/storages/vectordb_storages/pgvector.py b/camel/storages/vectordb_storages/pgvector.pyindex 1aacc2d5a..bf95c1cea 100644--- a/camel/storages/vectordb_storages/pgvector.py+++ b/camel/storages/vectordb_storages/pgvector.py@@ -226,7 +226,6 @@ class PgVectorStorage(BaseVectorStorage):try:with self._conn.cursor() as cur:- # Fix distance metric mappingmetric_info = {VectorDistance.COSINE: ('<=>', 'ASC'), # Cosine distanceVectorDistance.EUCLIDEAN: (@@ -235,8 +234,8 @@ class PgVectorStorage(BaseVectorStorage):), # Euclidean distanceVectorDistance.DOT: ('<#>',- 'DESC',- ), # Negative dot product (higher is better)+ 'ASC',+ ), # Negative inner product, lower is more similar}if self.distance not in metric_info:@@ -246,27 +245,27 @@ class PgVectorStorage(BaseVectorStorage):metric, order = metric_info[self.distance]- from psycopg.sql import SQL, Identifier, Literal+ from psycopg.sql import SQL, Identifierquery_sql = SQL("""- SELECT id, vector, payload, (vector {} %s::vector)- AS similarity+ SELECT id, vector, payload, (vector {} %s::vector) AS scoreFROM {}- ORDER BY similarity {}+ ORDER BY score {}LIMIT %s""").format(- Literal(metric),+ SQL(metric),Identifier(self.table_name),- Literal(order),+ SQL(order),)cur.execute(query_sql, (query.query_vector, query.top_k))results = []for row in cur.fetchall():- id, vector, payload, similarity = row+ id, vector, payload, score = row+ similarity = self._score_to_similarity(float(score))results.append(VectorDBQueryResult.create(- similarity=float(similarity),+ similarity=similarity,vector=list(vector),id=id,payload=payload,@@ -277,6 +276,16 @@ class PgVectorStorage(BaseVectorStorage):logger.error(f"Failed to query vectors: {e}")raise+ def _score_to_similarity(self, score: float) -> float:+ r"""Convert a pgvector operator result to high-is-better similarity."""+ if self.distance == VectorDistance.COSINE:+ return max(0.0, min(1.0, 1.0 - score))+ if self.distance == VectorDistance.EUCLIDEAN:+ return 1.0 / (1.0 + max(0.0, score))+ if self.distance == VectorDistance.DOT:+ return -score+ raise ValueError(f"Unsupported distance metric: {self.distance}")+def status(self, **kwargs: Any) -> VectorDBStatus:r"""Get the status of the vector database, including vectordimension and count.diff --git a/camel/storages/vectordb_storages/surreal.py b/camel/storages/vectordb_storages/surreal.pyindex 11753daba..15767f744 100644--- a/camel/storages/vectordb_storages/surreal.py+++ b/camel/storages/vectordb_storages/surreal.py@@ -262,9 +262,7 @@ class SurrealStorage(BaseVectorStorage):# SurrealDB RecordID has an 'id' attribute for the actual IDactual_id = record_id.id if hasattr(record_id, 'id') else record_iddist = float(row["dist"])- similarity = (- 1.0 - dist if self.distance == VectorDistance.COSINE else -dist- )+ similarity = self._distance_to_similarity(dist)results.append(VectorDBQueryResult(record=VectorRecord(@@ -277,6 +275,13 @@ class SurrealStorage(BaseVectorStorage):)return results+ def _distance_to_similarity(self, distance: float) -> float:+ r"""Convert a SurrealDB distance value to high-is-better similarity."""+ distance = max(0.0, distance)+ if self.distance == VectorDistance.COSINE:+ return max(0.0, min(1.0, 1.0 - distance))+ return 1.0 / (1.0 + distance)+def add(self, records: List[VectorRecord], **kwargs) -> None:r"""Insert validated vector records into the SurrealDB table.diff --git a/examples/caches/semantic_cache_example.py b/examples/caches/semantic_cache_example.pynew file mode 100644index 000000000..36d13138f--- /dev/null+++ b/examples/caches/semantic_cache_example.py@@ -0,0 +1,208 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++"""+Semantic Cache Example+======================++This example demonstrates how to use the SemanticCache to cache LLM responses+and retrieve them based on semantic similarity of queries.++The semantic cache uses vector embeddings to find similar queries, allowing+cache hits even when the exact wording differs from the original query.++This example supports both:+ 1. OpenAI (requires OPENAI_API_KEY environment variable)+ 2. Sentence Transformers (fully local, no API key required)++Prerequisites:+ - faiss-cpu or faiss-gpu installed for vector storage+ - sentence-transformers (optional, for local embeddings)++Usage:+ python examples/caches/semantic_cache_example.py+"""++import os+import time++from camel.caches import SemanticCache+from camel.embeddings import OpenAIEmbedding, SentenceTransformerEncoder+from camel.storages import FaissStorage+from camel.types import VectorDistance+++def main():+ """Demonstrate semantic cache functionality."""++ print("=" * 60)+ print("Semantic Cache Example")+ print("=" * 60)++ # Step 1: Initialize the embedding model+ # Prefer local Sentence Transformers if no API key is found+ print("\n1. Initializing embedding model...")+ if os.environ.get("OPENAI_API_KEY"):+ print(" Using OpenAIEmbedding (requires internet)")+ embedding_model = OpenAIEmbedding()+ else:+ print(" OPENAI_API_KEY not found. Using local SentenceTransformer.")+ embedding_model = SentenceTransformerEncoder(+ model_name="all-MiniLM-L6-v2"+ )++ vector_dim = embedding_model.get_output_dim()+ print(f" Embedding dimension: {vector_dim}")++ # Step 2: Initialize vector storage (in-memory FAISS)+ print("\n2. Initializing vector storage...")+ vector_storage = FaissStorage(+ vector_dim=vector_dim,+ distance=VectorDistance.COSINE,+ )+ print(" Using FAISS with cosine similarity")++ # Step 3: Create the semantic cache+ print("\n3. Creating semantic cache...")+ cache = SemanticCache(+ embedding_model=embedding_model,+ vector_storage=vector_storage,+ similarity_threshold=0.85, # 85% similarity required for cache hit+ )+ print(f" Similarity threshold: {cache.similarity_threshold}")++ # Step 4: Populate the cache with some responses+ print("\n4. Populating cache with sample responses...")++ sample_data = [+ {+ "query": "What is the capital of France?",+ "response": (+ "The capital of France is Paris. Paris is known for "+ "landmarks like the Eiffel Tower and the Louvre Museum."+ ),+ },+ {+ "query": "Explain machine learning in simple terms.",+ "response": (+ "Machine learning is a type of artificial intelligence "+ "that enables computers to learn from data and improve "+ "their performance without being explicitly programmed."+ ),+ },+ {+ "query": "What is Python programming language?",+ "response": (+ "Python is a high-level, interpreted programming language "+ "known for its clear syntax and readability. It's widely "+ "used for web development, data science, and automation."+ ),+ },+ ]++ for item in sample_data:+ cache_id = cache.set(+ query=item["query"],+ response=item["response"],+ metadata={"source": "example"},+ )+ print(f" Cached: '{item['query'][:40]}...' (id: {cache_id[:8]}...)")++ print(f" Cache size: {cache.size} entries")++ # Step 5: Test cache lookups with similar queries+ print("\n5. Testing cache lookups with similar queries...")++ test_queries = [+ # Should hit - semantically similar+ "What's the capital city of France?",+ "Tell me about machine learning",+ "What is the Python programming language used for?",+ # Should miss - different topics+ "What is the weather like today?",+ "How do I cook pasta?",+ ]++ print("\n" + "-" * 60)+ for query in test_queries:+ start_time = time.time()+ result = cache.get_with_score(query)+ lookup_time = (time.time() - start_time) * 1000 # ms++ if result:+ response, similarity, record = result+ print(f" Query: '{query}'")+ print(f" ✓ CACHE HIT (similarity: {similarity:.2%})")+ print(f" Response: '{response[:60]}...'")+ print(f" Lookup time: {lookup_time:.2f}ms\n")+ else:+ print(f" Query: '{query}'")+ print(" ✗ CACHE MISS")+ print(f" Lookup time: {lookup_time:.2f}ms\n")+ print("-" * 60)++ # Step 6: Demonstrate deduplication (Replacement)+ print("\n6. Demonstrating deduplication (automatic replacement)...")+ print(f" Current cache size: {cache.size}")++ updated_query = "What is Python?"+ updated_response = "Python is a versatile and popular scripting language!"+ print(f" Setting updated response for similar query: '{updated_query}'")++ cache.set(updated_query, updated_response)+ print(f" Cache size after update: {cache.size} (should still be 3)")++ # Verify the update+ res = cache.get(updated_query)+ print(f" Verified response: '{res}'")++ # Step 7: Show cache statistics+ print("\n7. Cache Statistics:")+ stats = cache.stats+ print(f" Total entries: {stats['size']}")+ print(f" Cache hits: {stats['hits']}")+ print(f" Cache misses: {stats['misses']}")+ print(f" Hit rate: {stats['hit_rate']:.2%}")++ # Step 8: Demonstrate find_similar+ print("\n8. Finding similar cached queries (threshold-agnostic)...")+ query = "How does ML work?"+ similar = cache.find_similar(query, top_k=3)+ print(f" Query: '{query}'")+ for i, (record, similarity) in enumerate(similar, 1):+ print(+ f" {i}. '{record.query[:50]}...' (similarity: {similarity:.2%})"+ )++ # Step 9: Demonstrate cache management+ print("\n9. Cache management operations...")++ # Disable cache+ cache.enabled = False+ print(+ f" Cache disabled. Lookup for 'What is Python?': "+ f"{cache.get('What is Python?')}"+ )++ # Clear cache+ cache.clear()+ print(f" Cache cleared. Size: {cache.size}")++ print("\n" + "=" * 60)+ print("Example completed successfully!")+ print("=" * 60)+++if __name__ == "__main__":+ main()diff --git a/test/caches/test_semantic_cache.py b/test/caches/test_semantic_cache.pynew file mode 100644index 000000000..3966d1322--- /dev/null+++ b/test/caches/test_semantic_cache.py@@ -0,0 +1,425 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++from unittest.mock import MagicMock++import pytest++from camel.caches import CacheRecord, SemanticCache+++class TestCacheRecord:+ """Tests for the CacheRecord dataclass."""++ def test_cache_record_creation(self):+ """Test that CacheRecord can be created with required fields."""+ record = CacheRecord(+ query="test query",+ response="test response",+ query_id="test-id-123",+ )+ assert record.query == "test query"+ assert record.response == "test response"+ assert record.query_id == "test-id-123"+ assert record.metadata == {}+ assert record.created_at is not None++ def test_cache_record_with_metadata(self):+ """Test CacheRecord with custom metadata."""+ metadata = {"source": "test", "version": 1}+ record = CacheRecord(+ query="test query",+ response="test response",+ query_id="test-id-123",+ metadata=metadata,+ )+ assert record.metadata == metadata+++class TestSemanticCache:+ """Tests for the SemanticCache implementation."""++ @pytest.fixture+ def mock_embedding_model(self):+ """Create a mock embedding model."""+ mock = MagicMock()+ mock.embed.return_value = [0.1, 0.2, 0.3, 0.4, 0.5]+ mock.get_output_dim.return_value = 5+ return mock++ @pytest.fixture+ def mock_vector_storage(self):+ """Create a mock vector storage."""+ mock = MagicMock()+ mock.status.return_value = MagicMock(vector_count=0)+ mock.query.return_value = []+ return mock++ @pytest.fixture+ def cache(self, mock_embedding_model, mock_vector_storage):+ """Create a SemanticCache instance with mocks."""+ return SemanticCache(+ embedding_model=mock_embedding_model,+ vector_storage=mock_vector_storage,+ similarity_threshold=0.85,+ )++ def test_cache_initialization(self, cache):+ """Test that cache initializes with default values."""+ assert cache.similarity_threshold == 0.85+ assert cache.enabled is True+ assert cache.size == 0+ assert cache.hit_rate == 0.0++ def test_cache_initialization_invalid_threshold(+ self, mock_embedding_model, mock_vector_storage+ ):+ """Test that invalid threshold raises ValueError."""+ with pytest.raises(ValueError, match="similarity_threshold must be"):+ SemanticCache(+ embedding_model=mock_embedding_model,+ vector_storage=mock_vector_storage,+ similarity_threshold=1.5,+ )++ with pytest.raises(ValueError, match="similarity_threshold must be"):+ SemanticCache(+ embedding_model=mock_embedding_model,+ vector_storage=mock_vector_storage,+ similarity_threshold=-0.1,+ )++ def test_set_stores_entry(self, cache, mock_vector_storage):+ """Test that set() stores the query-response pair."""+ entry_id = cache.set("What is Python?", "A programming language.")++ assert entry_id is not None+ mock_vector_storage.add.assert_called_once()++ # Check the stored record+ call_args = mock_vector_storage.add.call_args[0][0]+ assert len(call_args) == 1+ record = call_args[0]+ assert record.payload["query"] == "What is Python?"+ assert record.payload["response"] == "A programming language."++ def test_set_with_metadata(self, cache, mock_vector_storage):+ """Test that set() stores metadata correctly."""+ import json++ metadata = {"source": "test", "model": "gpt-4"}+ cache.set("Query", "Response", metadata=metadata)++ call_args = mock_vector_storage.add.call_args[0][0]+ record = call_args[0]+ # Metadata is stored as JSON string for storage backend compatibility+ assert json.loads(record.payload["metadata"]) == metadata++ def test_set_empty_query_raises(self, cache):+ """Test that empty query raises ValueError."""+ with pytest.raises(ValueError, match="Query cannot be empty"):+ cache.set("", "Some response")++ with pytest.raises(ValueError, match="Query cannot be empty"):+ cache.set(" ", "Some response")++ def test_set_empty_response_raises(self, cache):+ """Test that empty response raises ValueError."""+ with pytest.raises(ValueError, match="Response cannot be empty"):+ cache.set("Some query", "")++ def test_get_cache_hit(+ self, cache, mock_vector_storage, mock_embedding_model+ ):+ """Test cache hit when similarity exceeds threshold."""+ # Mock a similar query result+ mock_result = MagicMock()+ mock_result.similarity = 0.95 # Above threshold+ mock_result.record.payload = {+ "query": "What is Python?",+ "response": "A programming language.",+ "created_at": "2026-01-01T00:00:00",+ "metadata": {},+ }+ mock_result.record.id = "test-id"+ mock_vector_storage.query.return_value = [mock_result]++ response = cache.get("What's Python?")++ assert response == "A programming language."+ assert cache.stats["hits"] == 1+ assert cache.stats["misses"] == 0++ def test_get_cache_miss_below_threshold(+ self, cache, mock_vector_storage, mock_embedding_model+ ):+ """Test cache miss when similarity is below threshold."""+ # Mock a query result below threshold+ mock_result = MagicMock()+ mock_result.similarity = 0.5 # Below threshold+ mock_result.record.payload = {+ "query": "Unrelated query",+ "response": "Unrelated response",+ }+ mock_vector_storage.query.return_value = [mock_result]++ response = cache.get("What is Python?")++ assert response is None+ assert cache.stats["hits"] == 0+ assert cache.stats["misses"] == 1++ def test_get_cache_miss_empty_results(self, cache, mock_vector_storage):+ """Test cache miss when no results found."""+ mock_vector_storage.query.return_value = []++ response = cache.get("Some query")++ assert response is None+ assert cache.stats["misses"] == 1++ def test_get_disabled_cache(self, cache):+ """Test that get returns None when cache is disabled."""+ cache.enabled = False+ response = cache.get("Any query")+ assert response is None++ def test_get_empty_query(self, cache):+ """Test that empty query returns None."""+ assert cache.get("") is None+ assert cache.get(" ") is None++ def test_clear_resets_cache(self, cache, mock_vector_storage):+ """Test that clear removes all entries and resets stats."""+ # Simulate some hits and misses+ cache._cache_hits = 5+ cache._cache_misses = 3++ cache.clear()++ mock_vector_storage.clear.assert_called_once()+ assert cache.stats["hits"] == 0+ assert cache.stats["misses"] == 0++ def test_hit_rate_calculation(self, cache):+ """Test hit rate calculation."""+ cache._cache_hits = 3+ cache._cache_misses = 7++ assert cache.hit_rate == 0.3 # 3 / (3 + 7) = 0.3++ def test_hit_rate_no_lookups(self, cache):+ """Test hit rate is 0.0 when no lookups have been made."""+ assert cache.hit_rate == 0.0++ def test_similarity_threshold_setter(self, cache):+ """Test setting similarity threshold."""+ cache.similarity_threshold = 0.9+ assert cache.similarity_threshold == 0.9++ with pytest.raises(ValueError):+ cache.similarity_threshold = 1.5++ with pytest.raises(ValueError):+ cache.similarity_threshold = -0.1++ def test_enabled_property(self, cache):+ """Test enabling and disabling cache."""+ assert cache.enabled is True+ cache.enabled = False+ assert cache.enabled is False+ cache.enabled = True+ assert cache.enabled is True++ def test_stats_property(self, cache):+ """Test stats property returns correct structure."""+ cache._cache_hits = 10+ cache._cache_misses = 5++ stats = cache.stats++ assert "hits" in stats+ assert "misses" in stats+ assert "hit_rate" in stats+ assert "size" in stats+ assert "enabled" in stats+ assert "similarity_threshold" in stats+ assert stats["hits"] == 10+ assert stats["misses"] == 5++ def test_find_similar(+ self, cache, mock_vector_storage, mock_embedding_model+ ):+ """Test finding similar cached queries."""+ # Mock multiple results+ mock_results = []+ for i, sim in enumerate([0.95, 0.85, 0.75]):+ result = MagicMock()+ result.similarity = sim+ result.record.id = f"id-{i}"+ result.record.payload = {+ "query": f"Query {i}",+ "response": f"Response {i}",+ "created_at": "2026-01-01T00:00:00",+ "metadata": {},+ }+ mock_results.append(result)++ mock_vector_storage.query.return_value = mock_results++ results = cache.find_similar("test query", top_k=3)++ assert len(results) == 3+ assert results[0][1] == 0.95 # Highest similarity first+ assert results[0][0].query == "Query 0"++ def test_delete(self, cache, mock_vector_storage):+ """Test deleting a cache entry."""+ result = cache.delete("test-id")++ assert result is True+ mock_vector_storage.delete.assert_called_once_with(["test-id"])++ def test_delete_failure(self, cache, mock_vector_storage):+ """Test delete returns False on error."""+ mock_vector_storage.delete.side_effect = Exception("Delete failed")++ result = cache.delete("test-id")++ assert result is False++ def test_get_with_score(+ self, cache, mock_vector_storage, mock_embedding_model+ ):+ """Test get_with_score returns response with similarity."""+ mock_result = MagicMock()+ mock_result.similarity = 0.92+ mock_result.record.id = "test-id"+ mock_result.record.payload = {+ "query": "Original query",+ "response": "Cached response",+ "created_at": "2026-01-01T00:00:00",+ "metadata": {"source": "test"},+ }+ mock_vector_storage.query.return_value = [mock_result]++ result = cache.get_with_score("Similar query")++ assert result is not None+ response, score, record = result+ assert response == "Cached response"+ assert score == 0.92+ assert record.query == "Original query"+ assert record.metadata == {"source": "test"}++ def test_repr(self, cache):+ """Test string representation."""+ repr_str = repr(cache)+ assert "SemanticCache" in repr_str+ assert "threshold=0.85" in repr_str+ assert "enabled=True" in repr_str++ def test_set_stores_new_entry(+ self, cache, mock_vector_storage, mock_embedding_model+ ):+ """Test that set() stores a new entry."""+ mock_vector_storage.query.return_value = []++ new_id = cache.set("What is Python?", "A programming language.")++ # New entry should be added+ mock_vector_storage.add.assert_called_once()+ assert new_id is not None++ def test_set_replaces_duplicate(+ self, cache, mock_vector_storage, mock_embedding_model+ ):+ """Test that set() deletes existing entry for similar query."""+ # Mock: vector storage finds an existing similar entry+ mock_existing = MagicMock()+ mock_existing.similarity = 0.95 # Above threshold+ mock_existing.record.id = "old-entry-id"+ mock_vector_storage.query.return_value = [mock_existing]++ new_id = cache.set("What is Python?", "Updated answer.")++ # Old entry should be deleted from vector storage+ mock_vector_storage.delete.assert_called_once_with(["old-entry-id"])+ # New entry should be added+ mock_vector_storage.add.assert_called_once()+ assert new_id is not None+ assert new_id != "old-entry-id"++ def test_set_no_replace_below_threshold(+ self, cache, mock_vector_storage, mock_embedding_model+ ):+ """Test that set() does not replace when similarity is below+ threshold.+ """+ mock_existing = MagicMock()+ mock_existing.similarity = 0.5 # Below threshold+ mock_vector_storage.query.return_value = [mock_existing]++ cache.set("What is Python?", "A programming language.")++ # Old entry should NOT be deleted+ mock_vector_storage.delete.assert_not_called()+ # New entry should still be added+ mock_vector_storage.add.assert_called_once()++ def test_normalize_similarity_clamps_score(self, cache):+ """Test that similarity scores are clamped to the expected range."""+ assert cache._normalize_similarity(-0.5) == 0.0+ assert cache._normalize_similarity(0.25) == 0.25+ assert cache._normalize_similarity(1.5) == 1.0++ def test_storage_normalized_distance_score_hits_cache(+ self, cache, mock_vector_storage+ ):+ """Test cache hit with storage-normalized similarity."""+ mock_result = MagicMock()+ mock_result.similarity = 1.0+ mock_result.record.payload = {+ "query": "What is Python?",+ "response": "A programming language.",+ "created_at": "2026-01-01T00:00:00",+ "metadata": {},+ }+ mock_result.record.id = "test-id"+ mock_vector_storage.query.return_value = [mock_result]++ response = cache.get("What is Python?")++ assert response == "A programming language."+ assert cache.stats["hits"] == 1++ def test_raw_distance_score_misses_without_storage_normalization(+ self, cache, mock_vector_storage+ ):+ """Test raw distance scores are not interpreted in cache layer."""+ mock_result = MagicMock()+ mock_result.similarity = 0.0+ mock_result.record.payload = {+ "query": "What is Python?",+ "response": "A programming language.",+ "created_at": "2026-01-01T00:00:00",+ "metadata": {},+ }+ mock_result.record.id = "test-id"+ mock_vector_storage.query.return_value = [mock_result]++ response = cache.get("What is Python?")++ assert response is None+ assert cache.stats["misses"] == 1diff --git a/test/storages/vector_storages/test_pgvector.py b/test/storages/vector_storages/test_pgvector.pyindex 392403f7d..b96c2410d 100644--- a/test/storages/vector_storages/test_pgvector.py+++ b/test/storages/vector_storages/test_pgvector.py@@ -84,7 +84,30 @@ def test_pgvector_query(mock_pgvector_conn):assert results[0].record.id == "1"assert results[0].record.vector == [0.1, 0.2, 0.3, 0.4]assert results[0].record.payload == {"a": 1}- assert results[0].similarity == 0.01+ assert results[0].similarity == pytest.approx(0.99)+++ ("distance", "score", "expected_similarity"),+ [+ (VectorDistance.COSINE, 0.0, 1.0),+ (VectorDistance.COSINE, 0.25, 0.75),+ (VectorDistance.EUCLIDEAN, 1.0, 0.5),+ (VectorDistance.DOT, -0.8, 0.8),+ ],+)+def test_pgvector_score_to_similarity(+ mock_pgvector_conn, distance, score, expected_similarity+):+ mock_conn, _ = mock_pgvector_conn+ with (+ patch("psycopg.connect", return_value=mock_conn),+ patch("pgvector.psycopg.register_vector"),+ ):+ storage = PgVectorStorage(4, {"host": "localhost"}, distance=distance)+ assert storage._score_to_similarity(score) == pytest.approx(+ expected_similarity+ )def test_pgvector_delete(mock_pgvector_conn):diff --git a/test/storages/vector_storages/test_surreal.py b/test/storages/vector_storages/test_surreal.pyindex 1df15ca6c..c99e74798 100644--- a/test/storages/vector_storages/test_surreal.py+++ b/test/storages/vector_storages/test_surreal.py@@ -24,6 +24,7 @@ from camel.storages.vectordb_storages.surreal import (VectorDBStatus,VectorRecord,)+from camel.types import VectorDistance# Mock the module if surrealdb is not installedsys.modules['surrealdb'] = MagicMock()@@ -92,6 +93,26 @@ def test_query(storage):assert len(results) == 2+ ("distance", "raw_distance", "expected_similarity"),+ [+ (VectorDistance.COSINE, 0.0, 1.0),+ (VectorDistance.COSINE, 0.25, 0.75),+ (VectorDistance.EUCLIDEAN, 0.0, 1.0),+ (VectorDistance.EUCLIDEAN, 1.0, 0.5),+ ],+)+def test_distance_to_similarity(+ storage, distance, raw_distance, expected_similarity+):+ storage_instance, _ = storage+ storage_instance.distance = distance++ assert storage_instance._distance_to_similarity(+ raw_distance+ ) == pytest.approx(expected_similarity)++def test_status(storage):storage_instance, mock_db = storage