Elffuss BraidHub

kikocis/llama-stack public

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