Elffuss BraidHub

kikocis/llama-stack public

33277250c87b · 3.6 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 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
65class 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)