Elffuss BraidHub

kikocis/llama-stack public

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