|
| 1 | +from typing import Any, Callable |
| 2 | + |
| 3 | +from memstate.constants import Operation |
| 4 | +from memstate.schemas import Fact |
| 5 | + |
| 6 | +try: |
| 7 | + from qdrant_client import QdrantClient, models |
| 8 | +except ImportError: |
| 9 | + raise ImportError("To use QdrantSyncHook, run: pip install qdrant-client") |
| 10 | + |
| 11 | +TextFormatter = Callable[[dict[str, Any]], str] |
| 12 | +MetadataFormatter = Callable[[dict[str, Any]], dict[str, Any]] |
| 13 | +EmbeddingFunction = Callable[[str], list[float]] |
| 14 | + |
| 15 | + |
| 16 | +class FastEmbedEncoder: |
| 17 | + """ |
| 18 | + Default embedding implementation using FastEmbed. |
| 19 | + Used if no custom embedding_fn is provided. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__( |
| 23 | + self, model_name: str = "sentence-transformers/all-MiniLM-L6-v2", options: dict[str, Any] | None = None |
| 24 | + ): |
| 25 | + try: |
| 26 | + from fastembed import TextEmbedding |
| 27 | + except ImportError: |
| 28 | + raise ImportError( |
| 29 | + "FastEmbed is not installed. " "Install it via `pip install fastembed` or pass a custom `embedding_fn`." |
| 30 | + ) |
| 31 | + self.model = TextEmbedding(model_name, **(options or {})) |
| 32 | + |
| 33 | + def __call__(self, text: str) -> list[float]: |
| 34 | + return list(self.model.embed(text))[0].tolist() |
| 35 | + |
| 36 | + |
| 37 | +class QdrantSyncHook: |
| 38 | + """ |
| 39 | + encoder = FastEmbedEncoder( |
| 40 | + model_name="BAAI/bge-small-en-v1.5", |
| 41 | + options={"cuda": True} |
| 42 | + ) |
| 43 | + hook = QdrantSyncHook(client, "memory", embedding_fn=encoder) |
| 44 | +
|
| 45 | + resp = openai.embeddings.create(input=text, model="text-embedding-3-small") |
| 46 | + openai_embedder = resp.data[0].embedding |
| 47 | + hook = QdrantSyncHook(client, "memory", embedding_fn=openai_embedder) |
| 48 | + """ |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + client: QdrantClient, |
| 53 | + collection_name: str, |
| 54 | + embedding_fn: EmbeddingFunction | None = None, |
| 55 | + target_types: set[str] | None = None, |
| 56 | + text_field: str | None = None, |
| 57 | + text_formatter: TextFormatter | None = None, |
| 58 | + metadata_fields: list[str] | None = None, |
| 59 | + metadata_formatter: MetadataFormatter | None = None, |
| 60 | + distance: models.Distance = models.Distance.COSINE, |
| 61 | + ) -> None: |
| 62 | + self.client = client |
| 63 | + self.collection_name = collection_name |
| 64 | + |
| 65 | + self.embedding_fn = embedding_fn or FastEmbedEncoder() |
| 66 | + |
| 67 | + self.target_types = target_types or set() |
| 68 | + self.distance = distance |
| 69 | + |
| 70 | + if text_formatter is not None: |
| 71 | + self._extract_text = text_formatter |
| 72 | + elif text_field: |
| 73 | + self._extract_text = lambda data: str(data.get(text_field, "")) |
| 74 | + else: |
| 75 | + self._extract_text = lambda data: str(data) |
| 76 | + |
| 77 | + self.metadata_fields = metadata_fields or [] |
| 78 | + self.metadata_formatter = metadata_formatter |
| 79 | + |
| 80 | + self._ensure_collection() |
| 81 | + |
| 82 | + def _ensure_collection(self) -> None: |
| 83 | + """ |
| 84 | + Auto-detects vector size by running a dummy embedding |
| 85 | + and ensures the collection exists. |
| 86 | + """ |
| 87 | + try: |
| 88 | + dummy_vec = self.embedding_fn("test") |
| 89 | + vector_size = len(dummy_vec) |
| 90 | + except Exception as e: |
| 91 | + raise RuntimeError(f"Failed to initialize embedding function: {e}") |
| 92 | + |
| 93 | + if not self.client.collection_exists(self.collection_name): |
| 94 | + self.client.create_collection( |
| 95 | + collection_name=self.collection_name, |
| 96 | + vectors_config=models.VectorParams(size=vector_size, distance=self.distance), |
| 97 | + ) |
| 98 | + else: |
| 99 | + coll_info = self.client.get_collection(self.collection_name) |
| 100 | + config = coll_info.config.params.vectors |
| 101 | + |
| 102 | + existing_size = None |
| 103 | + if isinstance(config, models.VectorParams): |
| 104 | + existing_size = config.size |
| 105 | + elif isinstance(config, dict) and "" in config: # Default unnamed vector |
| 106 | + existing_size = config[""].size |
| 107 | + |
| 108 | + if existing_size and existing_size != vector_size: |
| 109 | + raise ValueError( |
| 110 | + f"Collection '{self.collection_name}' expects vector size {existing_size}, " |
| 111 | + f"but your embedding function produces {vector_size}. " |
| 112 | + "Mismatch detected." |
| 113 | + ) |
| 114 | + |
| 115 | + def _get_metadata(self, data: dict[str, Any]) -> dict[str, Any]: |
| 116 | + if self.metadata_formatter is not None: |
| 117 | + return self.metadata_formatter(data) |
| 118 | + |
| 119 | + if self.metadata_fields: |
| 120 | + meta = {} |
| 121 | + for field in self.metadata_fields: |
| 122 | + val = data.get(field) |
| 123 | + if val is not None: |
| 124 | + if isinstance(val, (str, int, float, bool, list)): |
| 125 | + meta[field] = val |
| 126 | + else: |
| 127 | + meta[field] = str(val) |
| 128 | + return meta |
| 129 | + |
| 130 | + return {} |
| 131 | + |
| 132 | + def __call__(self, op: Operation, fact_id: str, data: Fact | None) -> None: |
| 133 | + if op == Operation.DELETE: |
| 134 | + self.client.delete(collection_name=self.collection_name, points_selector=[fact_id]) |
| 135 | + return |
| 136 | + |
| 137 | + if op == Operation.DISCARD_SESSION: |
| 138 | + return |
| 139 | + |
| 140 | + if not data or (self.target_types and data.type not in self.target_types): |
| 141 | + return |
| 142 | + |
| 143 | + if op in (Operation.COMMIT, Operation.UPDATE, Operation.COMMIT_EPHEMERAL, Operation.PROMOTE): |
| 144 | + text = self._extract_text(data.payload) |
| 145 | + if not text.strip(): |
| 146 | + return |
| 147 | + |
| 148 | + vector = self.embedding_fn(text) |
| 149 | + |
| 150 | + meta = {"type": data.type, "source": data.source or "", "ts": str(data.ts), "document": text} |
| 151 | + user_meta = self._get_metadata(data=data.payload) |
| 152 | + meta.update(user_meta) |
| 153 | + |
| 154 | + self.client.upsert( |
| 155 | + collection_name=self.collection_name, |
| 156 | + points=[models.PointStruct(id=fact_id, vector=vector, payload=meta)], |
| 157 | + ) |
0 commit comments