| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import logging |
| 8 | import uuid |
| 9 | |
| 10 | from typing import Any, Dict, List, Optional |
| 11 | |
| 12 | import faiss |
| 13 | import numpy as np |
| 14 | from numpy.typing import NDArray |
| 15 | |
| 16 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 17 | |
| 18 | from llama_toolchain.memory.api import * # noqa: F403 |
| 19 | from llama_toolchain.memory.common.vector_store import ( |
| 20 | ALL_MINILM_L6_V2_DIMENSION, |
| 21 | BankWithIndex, |
| 22 | EmbeddingIndex, |
| 23 | ) |
| 24 | from llama_toolchain.telemetry import tracing |
| 25 | from .config import FaissImplConfig |
| 26 | |
| 27 | logger = logging.getLogger(__name__) |
| 28 | |
| 29 | |
| 30 | class FaissIndex(EmbeddingIndex): |
| 31 | id_by_index: Dict[int, str] |
| 32 | chunk_by_index: Dict[int, str] |
| 33 | |
| 34 | def __init__(self, dimension: int): |
| 35 | self.index = faiss.IndexFlatL2(dimension) |
| 36 | self.id_by_index = {} |
| 37 | self.chunk_by_index = {} |
| 38 | |
| 39 | @tracing.span(name="add_chunks") |
| 40 | async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): |
| 41 | indexlen = len(self.id_by_index) |
| 42 | for i, chunk in enumerate(chunks): |
| 43 | self.chunk_by_index[indexlen + i] = chunk |
| 44 | logger.info(f"Adding chunk #{indexlen + i} tokens={chunk.token_count}") |
| 45 | self.id_by_index[indexlen + i] = chunk.document_id |
| 46 | |
| 47 | self.index.add(np.array(embeddings).astype(np.float32)) |
| 48 | |
| 49 | async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse: |
| 50 | distances, indices = self.index.search( |
| 51 | embedding.reshape(1, -1).astype(np.float32), k |
| 52 | ) |
| 53 | |
| 54 | chunks = [] |
| 55 | scores = [] |
| 56 | for d, i in zip(distances[0], indices[0]): |
| 57 | if i < 0: |
| 58 | continue |
| 59 | chunks.append(self.chunk_by_index[int(i)]) |
| 60 | scores.append(1.0 / float(d)) |
| 61 | |
| 62 | return QueryDocumentsResponse(chunks=chunks, scores=scores) |
| 63 | |
| 64 | |
| 65 | class FaissMemoryImpl(Memory): |
| 66 | def __init__(self, config: FaissImplConfig) -> None: |
| 67 | self.config = config |
| 68 | self.cache = {} |
| 69 | |
| 70 | async def initialize(self) -> None: ... |
| 71 | |
| 72 | async def shutdown(self) -> None: ... |
| 73 | |
| 74 | async def create_memory_bank( |
| 75 | self, |
| 76 | name: str, |
| 77 | config: MemoryBankConfig, |
| 78 | url: Optional[URL] = None, |
| 79 | ) -> MemoryBank: |
| 80 | assert url is None, "URL is not supported for this implementation" |
| 81 | assert ( |
| 82 | config.type == MemoryBankType.vector.value |
| 83 | ), f"Only vector banks are supported {config.type}" |
| 84 | |
| 85 | bank_id = str(uuid.uuid4()) |
| 86 | bank = MemoryBank( |
| 87 | bank_id=bank_id, |
| 88 | name=name, |
| 89 | config=config, |
| 90 | url=url, |
| 91 | ) |
| 92 | index = BankWithIndex(bank=bank, index=FaissIndex(ALL_MINILM_L6_V2_DIMENSION)) |
| 93 | self.cache[bank_id] = index |
| 94 | return bank |
| 95 | |
| 96 | async def get_memory_bank(self, bank_id: str) -> Optional[MemoryBank]: |
| 97 | index = self.cache.get(bank_id) |
| 98 | if index is None: |
| 99 | return None |
| 100 | return index.bank |
| 101 | |
| 102 | async def insert_documents( |
| 103 | self, |
| 104 | bank_id: str, |
| 105 | documents: List[MemoryBankDocument], |
| 106 | ttl_seconds: Optional[int] = None, |
| 107 | ) -> None: |
| 108 | index = self.cache.get(bank_id) |
| 109 | if index is None: |
| 110 | raise ValueError(f"Bank {bank_id} not found") |
| 111 | |
| 112 | await index.insert_documents(documents) |
| 113 | |
| 114 | async def query_documents( |
| 115 | self, |
| 116 | bank_id: str, |
| 117 | query: InterleavedTextMedia, |
| 118 | params: Optional[Dict[str, Any]] = None, |
| 119 | ) -> QueryDocumentsResponse: |
| 120 | index = self.cache.get(bank_id) |
| 121 | if index is None: |
| 122 | raise ValueError(f"Bank {bank_id} not found") |
| 123 | |
| 124 | return await index.query_documents(query, params) |