Elffuss BraidHub

kikocis/llama-stack public

main · 5.0 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 json
8import uuid
9from typing import List
10from urllib.parse import urlparse
11
12import chromadb
13from numpy.typing import NDArray
14
15from llama_stack.apis.memory import * # noqa: F403
16
17
18from llama_stack.providers.utils.memory.vector_store import (
19 BankWithIndex,
20 EmbeddingIndex,
21)
22
23
24class ChromaIndex(EmbeddingIndex):
25 def __init__(self, client: chromadb.AsyncHttpClient, collection):
26 self.client = client
27 self.collection = collection
28
29 async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray):
30 assert len(chunks) == len(
31 embeddings
32 ), f"Chunk length {len(chunks)} does not match embedding length {len(embeddings)}"
33
34 await self.collection.add(
35 documents=[chunk.json() for chunk in chunks],
36 embeddings=embeddings,
37 ids=[f"{c.document_id}:chunk-{i}" for i, c in enumerate(chunks)],
38 )
39
40 async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse:
41 results = await self.collection.query(
42 query_embeddings=[embedding.tolist()],
43 n_results=k,
44 include=["documents", "distances"],
45 )
46 distances = results["distances"][0]
47 documents = results["documents"][0]
48
49 chunks = []
50 scores = []
51 for dist, doc in zip(distances, documents):
52 try:
53 doc = json.loads(doc)
54 chunk = Chunk(**doc)
55 except Exception:
56 import traceback
57
58 traceback.print_exc()
59 print(f"Failed to parse document: {doc}")
60 continue
61
62 chunks.append(chunk)
63 scores.append(1.0 / float(dist))
64
65 return QueryDocumentsResponse(chunks=chunks, scores=scores)
66
67
68class ChromaMemoryAdapter(Memory):
69 def __init__(self, url: str) -> None:
70 print(f"Initializing ChromaMemoryAdapter with url: {url}")
71 url = url.rstrip("/")
72 parsed = urlparse(url)
73
74 if parsed.path and parsed.path != "/":
75 raise ValueError("URL should not contain a path")
76
77 self.host = parsed.hostname
78 self.port = parsed.port
79
80 self.client = None
81 self.cache = {}
82
83 async def initialize(self) -> None:
84 try:
85 print(f"Connecting to Chroma server at: {self.host}:{self.port}")
86 self.client = await chromadb.AsyncHttpClient(host=self.host, port=self.port)
87 except Exception as e:
88 import traceback
89
90 traceback.print_exc()
91 raise RuntimeError("Could not connect to Chroma server") from e
92
93 async def shutdown(self) -> None:
94 pass
95
96 async def create_memory_bank(
97 self,
98 name: str,
99 config: MemoryBankConfig,
100 url: Optional[URL] = None,
101 ) -> MemoryBank:
102 bank_id = str(uuid.uuid4())
103 bank = MemoryBank(
104 bank_id=bank_id,
105 name=name,
106 config=config,
107 url=url,
108 )
109 collection = await self.client.create_collection(
110 name=bank_id,
111 metadata={"bank": bank.json()},
112 )
113 bank_index = BankWithIndex(
114 bank=bank, index=ChromaIndex(self.client, collection)
115 )
116 self.cache[bank_id] = bank_index
117 return bank
118
119 async def get_memory_bank(self, bank_id: str) -> Optional[MemoryBank]:
120 bank_index = await self._get_and_cache_bank_index(bank_id)
121 if bank_index is None:
122 return None
123 return bank_index.bank
124
125 async def _get_and_cache_bank_index(self, bank_id: str) -> Optional[BankWithIndex]:
126 if bank_id in self.cache:
127 return self.cache[bank_id]
128
129 collections = await self.client.list_collections()
130 for collection in collections:
131 if collection.name == bank_id:
132 print(collection.metadata)
133 bank = MemoryBank(**json.loads(collection.metadata["bank"]))
134 index = BankWithIndex(
135 bank=bank,
136 index=ChromaIndex(self.client, collection),
137 )
138 self.cache[bank_id] = index
139 return index
140
141 return None
142
143 async def insert_documents(
144 self,
145 bank_id: str,
146 documents: List[MemoryBankDocument],
147 ttl_seconds: Optional[int] = None,
148 ) -> None:
149 index = await self._get_and_cache_bank_index(bank_id)
150 if not index:
151 raise ValueError(f"Bank {bank_id} not found")
152
153 await index.insert_documents(documents)
154
155 async def query_documents(
156 self,
157 bank_id: str,
158 query: InterleavedTextMedia,
159 params: Optional[Dict[str, Any]] = None,
160 ) -> QueryDocumentsResponse:
161 index = await self._get_and_cache_bank_index(bank_id)
162 if not index:
163 raise ValueError(f"Bank {bank_id} not found")
164
165 return await index.query_documents(query, params)