kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | fec971db3fc67170a99ab72d12a88611668bd45a4b9257a46a4fa5304c6e94e8 |
|---|---|
| Author | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-06 18:53 -07:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-06 18:53 -07:00 |
| Parents | 0778f181e3a8 |
8 files changed
added llama_toolchain/memory/adapters/chroma/__init__.py +15 −0
| @@ -0,0 +1,15 @@ | ||
| 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 | +from llama_toolchain.core.datatypes import RemoteProviderConfig | |
| 8 | + | |
| 9 | + | |
| 10 | +async def get_adapter_impl(config: RemoteProviderConfig, _deps): | |
| 11 | + from .chroma import ChromaMemoryAdapter | |
| 12 | + | |
| 13 | + impl = ChromaMemoryAdapter(config.url) | |
| 14 | + await impl.initialize() | |
| 15 | + return impl |
added llama_toolchain/memory/adapters/chroma/chroma.py +165 −0
| @@ -0,0 +1,165 @@ | ||
| 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 json | |
| 8 | +import uuid | |
| 9 | +from typing import List | |
| 10 | +from urllib.parse import urlparse | |
| 11 | + | |
| 12 | +import chromadb | |
| 13 | +from numpy.typing import NDArray | |
| 14 | + | |
| 15 | +from llama_toolchain.memory.api import * # noqa: F403 | |
| 16 | + | |
| 17 | + | |
| 18 | +from llama_toolchain.memory.common.vector_store import BankWithIndex, EmbeddingIndex | |
| 19 | + | |
| 20 | + | |
| 21 | +class ChromaIndex(EmbeddingIndex): | |
| 22 | + def __init__(self, client: chromadb.AsyncHttpClient, collection): | |
| 23 | + self.client = client | |
| 24 | + self.collection = collection | |
| 25 | + | |
| 26 | + async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): | |
| 27 | + assert len(chunks) == len( | |
| 28 | + embeddings | |
| 29 | + ), f"Chunk length {len(chunks)} does not match embedding length {len(embeddings)}" | |
| 30 | + | |
| 31 | + for i, chunk in enumerate(chunks): | |
| 32 | + print(f"Adding chunk #{i} tokens={chunk.token_count}") | |
| 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 | + | |
| 68 | +class 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) |
added llama_toolchain/memory/adapters/pgvector/__init__.py +15 −0
| @@ -0,0 +1,15 @@ | ||
| 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 | +from .config import PGVectorConfig | |
| 8 | + | |
| 9 | + | |
| 10 | +async def get_adapter_impl(config: PGVectorConfig, _deps): | |
| 11 | + from .pgvector import PGVectorMemoryAdapter | |
| 12 | + | |
| 13 | + impl = PGVectorMemoryAdapter(config) | |
| 14 | + await impl.initialize() | |
| 15 | + return impl |
added llama_toolchain/memory/adapters/pgvector/config.py +17 −0
| @@ -0,0 +1,17 @@ | ||
| 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 | +from llama_models.schema_utils import json_schema_type | |
| 8 | +from pydantic import BaseModel, Field | |
| 9 | + | |
| 10 | + | |
| 11 | +@json_schema_type | |
| 12 | +class PGVectorConfig(BaseModel): | |
| 13 | + host: str = Field(default="localhost") | |
| 14 | + port: int = Field(default=5432) | |
| 15 | + db: str | |
| 16 | + user: str | |
| 17 | + password: str |
added llama_toolchain/memory/adapters/pgvector/pgvector.py +234 −0
| @@ -0,0 +1,234 @@ | ||
| 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 uuid | |
| 8 | + | |
| 9 | +from typing import List, Tuple | |
| 10 | + | |
| 11 | +import psycopg2 | |
| 12 | +from numpy.typing import NDArray | |
| 13 | +from psycopg2 import sql | |
| 14 | +from psycopg2.extras import execute_values, Json | |
| 15 | +from pydantic import BaseModel | |
| 16 | +from llama_toolchain.memory.api import * # noqa: F403 | |
| 17 | + | |
| 18 | + | |
| 19 | +from llama_toolchain.memory.common.vector_store import ( | |
| 20 | + ALL_MINILM_L6_V2_DIMENSION, | |
| 21 | + BankWithIndex, | |
| 22 | + EmbeddingIndex, | |
| 23 | +) | |
| 24 | + | |
| 25 | +from .config import PGVectorConfig | |
| 26 | + | |
| 27 | + | |
| 28 | +def check_extension_version(cur): | |
| 29 | + cur.execute("SELECT extversion FROM pg_extension WHERE extname = 'vector'") | |
| 30 | + result = cur.fetchone() | |
| 31 | + return result[0] if result else None | |
| 32 | + | |
| 33 | + | |
| 34 | +def upsert_models(cur, keys_models: List[Tuple[str, BaseModel]]): | |
| 35 | + query = sql.SQL( | |
| 36 | + """ | |
| 37 | + INSERT INTO metadata_store (key, data) | |
| 38 | + VALUES %s | |
| 39 | + ON CONFLICT (key) DO UPDATE | |
| 40 | + SET data = EXCLUDED.data | |
| 41 | + """ | |
| 42 | + ) | |
| 43 | + | |
| 44 | + values = [(key, Json(model.dict())) for key, model in keys_models] | |
| 45 | + execute_values(cur, query, values, template="(%s, %s)") | |
| 46 | + | |
| 47 | + | |
| 48 | +def load_models(cur, keys: List[str], cls): | |
| 49 | + query = "SELECT key, data FROM metadata_store" | |
| 50 | + if keys: | |
| 51 | + placeholders = ",".join(["%s"] * len(keys)) | |
| 52 | + query += f" WHERE key IN ({placeholders})" | |
| 53 | + cur.execute(query, keys) | |
| 54 | + else: | |
| 55 | + cur.execute(query) | |
| 56 | + | |
| 57 | + rows = cur.fetchall() | |
| 58 | + return [cls(**row["data"]) for row in rows] | |
| 59 | + | |
| 60 | + | |
| 61 | +class PGVectorIndex(EmbeddingIndex): | |
| 62 | + def __init__(self, bank: MemoryBank, dimension: int, cursor): | |
| 63 | + self.cursor = cursor | |
| 64 | + self.table_name = f"vector_store_{bank.name}" | |
| 65 | + | |
| 66 | + self.cursor.execute( | |
| 67 | + f""" | |
| 68 | + CREATE TABLE IF NOT EXISTS {self.table_name} ( | |
| 69 | + id TEXT PRIMARY KEY, | |
| 70 | + document JSONB, | |
| 71 | + embedding vector({dimension}) | |
| 72 | + ) | |
| 73 | + """ | |
| 74 | + ) | |
| 75 | + | |
| 76 | + async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): | |
| 77 | + assert len(chunks) == len( | |
| 78 | + embeddings | |
| 79 | + ), f"Chunk length {len(chunks)} does not match embedding length {len(embeddings)}" | |
| 80 | + | |
| 81 | + values = [] | |
| 82 | + for i, chunk in enumerate(chunks): | |
| 83 | + print(f"Adding chunk #{i} tokens={chunk.token_count}") | |
| 84 | + values.append( | |
| 85 | + ( | |
| 86 | + f"{chunk.document_id}:chunk-{i}", | |
| 87 | + Json(chunk.dict()), | |
| 88 | + embeddings[i].tolist(), | |
| 89 | + ) | |
| 90 | + ) | |
| 91 | + | |
| 92 | + query = sql.SQL( | |
| 93 | + f""" | |
| 94 | + INSERT INTO {self.table_name} (id, document, embedding) | |
| 95 | + VALUES %s | |
| 96 | + ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding, document = EXCLUDED.document | |
| 97 | + """ | |
| 98 | + ) | |
| 99 | + execute_values(self.cursor, query, values, template="(%s, %s, %s::vector)") | |
| 100 | + | |
| 101 | + async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse: | |
| 102 | + self.cursor.execute( | |
| 103 | + f""" | |
| 104 | + SELECT document, embedding <-> %s::vector AS distance | |
| 105 | + FROM {self.table_name} | |
| 106 | + ORDER BY distance | |
| 107 | + LIMIT %s | |
| 108 | + """, | |
| 109 | + (embedding.tolist(), k), | |
| 110 | + ) | |
| 111 | + results = self.cursor.fetchall() | |
| 112 | + | |
| 113 | + chunks = [] | |
| 114 | + scores = [] | |
| 115 | + for doc, dist in results: | |
| 116 | + chunks.append(Chunk(**doc)) | |
| 117 | + scores.append(1.0 / float(dist)) | |
| 118 | + | |
| 119 | + return QueryDocumentsResponse(chunks=chunks, scores=scores) | |
| 120 | + | |
| 121 | + | |
| 122 | +class PGVectorMemoryAdapter(Memory): | |
| 123 | + def __init__(self, config: PGVectorConfig) -> None: | |
| 124 | + print(f"Initializing PGVectorMemoryAdapter -> {config.host}:{config.port}") | |
| 125 | + self.config = config | |
| 126 | + self.cursor = None | |
| 127 | + self.conn = None | |
| 128 | + self.cache = {} | |
| 129 | + | |
| 130 | + async def initialize(self) -> None: | |
| 131 | + try: | |
| 132 | + self.conn = psycopg2.connect( | |
| 133 | + host=self.config.host, | |
| 134 | + port=self.config.port, | |
| 135 | + database=self.config.db, | |
| 136 | + user=self.config.user, | |
| 137 | + password=self.config.password, | |
| 138 | + ) | |
| 139 | + self.cursor = self.conn.cursor() | |
| 140 | + | |
| 141 | + version = check_extension_version(self.cursor) | |
| 142 | + if version: | |
| 143 | + print(f"Vector extension version: {version}") | |
| 144 | + else: | |
| 145 | + raise RuntimeError("Vector extension is not installed.") | |
| 146 | + | |
| 147 | + self.cursor.execute( | |
| 148 | + """ | |
| 149 | + CREATE TABLE IF NOT EXISTS metadata_store ( | |
| 150 | + key TEXT PRIMARY KEY, | |
| 151 | + data JSONB | |
| 152 | + ) | |
| 153 | + """ | |
| 154 | + ) | |
| 155 | + except Exception as e: | |
| 156 | + import traceback | |
| 157 | + | |
| 158 | + traceback.print_exc() | |
| 159 | + raise RuntimeError("Could not connect to PGVector database server") from e | |
| 160 | + | |
| 161 | + async def shutdown(self) -> None: | |
| 162 | + pass | |
| 163 | + | |
| 164 | + async def create_memory_bank( | |
| 165 | + self, | |
| 166 | + name: str, | |
| 167 | + config: MemoryBankConfig, | |
| 168 | + url: Optional[URL] = None, | |
| 169 | + ) -> MemoryBank: | |
| 170 | + bank_id = str(uuid.uuid4()) | |
| 171 | + bank = MemoryBank( | |
| 172 | + bank_id=bank_id, | |
| 173 | + name=name, | |
| 174 | + config=config, | |
| 175 | + url=url, | |
| 176 | + ) | |
| 177 | + upsert_models( | |
| 178 | + self.cursor, | |
| 179 | + [ | |
| 180 | + (bank.bank_id, bank), | |
| 181 | + ], | |
| 182 | + ) | |
| 183 | + index = BankWithIndex( | |
| 184 | + bank=bank, | |
| 185 | + index=PGVectorIndex(bank, ALL_MINILM_L6_V2_DIMENSION, self.cursor), | |
| 186 | + ) | |
| 187 | + self.cache[bank_id] = index | |
| 188 | + return bank | |
| 189 | + | |
| 190 | + async def get_memory_bank(self, bank_id: str) -> Optional[MemoryBank]: | |
| 191 | + bank_index = await self._get_and_cache_bank_index(bank_id) | |
| 192 | + if bank_index is None: | |
| 193 | + return None | |
| 194 | + return bank_index.bank | |
| 195 | + | |
| 196 | + async def _get_and_cache_bank_index(self, bank_id: str) -> Optional[BankWithIndex]: | |
| 197 | + if bank_id in self.cache: | |
| 198 | + return self.cache[bank_id] | |
| 199 | + | |
| 200 | + banks = load_models(self.cursor, [bank_id], MemoryBank) | |
| 201 | + if not banks: | |
| 202 | + return None | |
| 203 | + | |
| 204 | + bank = banks[0] | |
| 205 | + index = BankWithIndex( | |
| 206 | + bank=bank, | |
| 207 | + index=PGVectorIndex(bank, ALL_MINILM_L6_V2_DIMENSION, self.cursor), | |
| 208 | + ) | |
| 209 | + self.cache[bank_id] = index | |
| 210 | + return index | |
| 211 | + | |
| 212 | + async def insert_documents( | |
| 213 | + self, | |
| 214 | + bank_id: str, | |
| 215 | + documents: List[MemoryBankDocument], | |
| 216 | + ttl_seconds: Optional[int] = None, | |
| 217 | + ) -> None: | |
| 218 | + index = await self._get_and_cache_bank_index(bank_id) | |
| 219 | + if not index: | |
| 220 | + raise ValueError(f"Bank {bank_id} not found") | |
| 221 | + | |
| 222 | + await index.insert_documents(documents) | |
| 223 | + | |
| 224 | + async def query_documents( | |
| 225 | + self, | |
| 226 | + bank_id: str, | |
| 227 | + query: InterleavedTextMedia, | |
| 228 | + params: Optional[Dict[str, Any]] = None, | |
| 229 | + ) -> QueryDocumentsResponse: | |
| 230 | + index = await self._get_and_cache_bank_index(bank_id) | |
| 231 | + if not index: | |
| 232 | + raise ValueError(f"Bank {bank_id} not found") | |
| 233 | + | |
| 234 | + return await index.query_documents(query, params) |
added llama_toolchain/memory/common/vector_store.py +120 −0
| @@ -0,0 +1,120 @@ | ||
| 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 | +from abc import ABC, abstractmethod | |
| 8 | +from dataclasses import dataclass | |
| 9 | +from typing import Any, Dict, List, Optional | |
| 10 | + | |
| 11 | +import httpx | |
| 12 | +import numpy as np | |
| 13 | +from numpy.typing import NDArray | |
| 14 | + | |
| 15 | +from llama_models.llama3.api.datatypes import * # noqa: F403 | |
| 16 | +from llama_models.llama3.api.tokenizer import Tokenizer | |
| 17 | + | |
| 18 | +from llama_toolchain.memory.api import * # noqa: F403 | |
| 19 | + | |
| 20 | + | |
| 21 | +ALL_MINILM_L6_V2_DIMENSION = 384 | |
| 22 | + | |
| 23 | +EMBEDDING_MODEL = None | |
| 24 | + | |
| 25 | + | |
| 26 | +def get_embedding_model() -> "SentenceTransformer": | |
| 27 | + global EMBEDDING_MODEL | |
| 28 | + | |
| 29 | + if EMBEDDING_MODEL is None: | |
| 30 | + print("Loading sentence transformer") | |
| 31 | + | |
| 32 | + from sentence_transformers import SentenceTransformer | |
| 33 | + | |
| 34 | + EMBEDDING_MODEL = SentenceTransformer("all-MiniLM-L6-v2") | |
| 35 | + | |
| 36 | + return EMBEDDING_MODEL | |
| 37 | + | |
| 38 | + | |
| 39 | +async def content_from_doc(doc: MemoryBankDocument) -> str: | |
| 40 | + if isinstance(doc.content, URL): | |
| 41 | + async with httpx.AsyncClient() as client: | |
| 42 | + r = await client.get(doc.content.uri) | |
| 43 | + return r.text | |
| 44 | + | |
| 45 | + return interleaved_text_media_as_str(doc.content) | |
| 46 | + | |
| 47 | + | |
| 48 | +def make_overlapped_chunks( | |
| 49 | + document_id: str, text: str, window_len: int, overlap_len: int | |
| 50 | +) -> List[Chunk]: | |
| 51 | + tokenizer = Tokenizer.get_instance() | |
| 52 | + tokens = tokenizer.encode(text, bos=False, eos=False) | |
| 53 | + | |
| 54 | + chunks = [] | |
| 55 | + for i in range(0, len(tokens), window_len - overlap_len): | |
| 56 | + toks = tokens[i : i + window_len] | |
| 57 | + chunk = tokenizer.decode(toks) | |
| 58 | + chunks.append( | |
| 59 | + Chunk(content=chunk, token_count=len(toks), document_id=document_id) | |
| 60 | + ) | |
| 61 | + | |
| 62 | + return chunks | |
| 63 | + | |
| 64 | + | |
| 65 | +class EmbeddingIndex(ABC): | |
| 66 | + @abstractmethod | |
| 67 | + async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): | |
| 68 | + raise NotImplementedError() | |
| 69 | + | |
| 70 | + @abstractmethod | |
| 71 | + async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse: | |
| 72 | + raise NotImplementedError() | |
| 73 | + | |
| 74 | + | |
| 75 | +@dataclass | |
| 76 | +class BankWithIndex: | |
| 77 | + bank: MemoryBank | |
| 78 | + index: EmbeddingIndex | |
| 79 | + | |
| 80 | + async def insert_documents( | |
| 81 | + self, | |
| 82 | + documents: List[MemoryBankDocument], | |
| 83 | + ) -> None: | |
| 84 | + model = get_embedding_model() | |
| 85 | + for doc in documents: | |
| 86 | + content = await content_from_doc(doc) | |
| 87 | + chunks = make_overlapped_chunks( | |
| 88 | + doc.document_id, | |
| 89 | + content, | |
| 90 | + self.bank.config.chunk_size_in_tokens, | |
| 91 | + self.bank.config.overlap_size_in_tokens | |
| 92 | + or (self.bank.config.chunk_size_in_tokens // 4), | |
| 93 | + ) | |
| 94 | + embeddings = model.encode([x.content for x in chunks]).astype(np.float32) | |
| 95 | + | |
| 96 | + await self.index.add_chunks(chunks, embeddings) | |
| 97 | + | |
| 98 | + async def query_documents( | |
| 99 | + self, | |
| 100 | + query: InterleavedTextMedia, | |
| 101 | + params: Optional[Dict[str, Any]] = None, | |
| 102 | + ) -> QueryDocumentsResponse: | |
| 103 | + if params is None: | |
| 104 | + params = {} | |
| 105 | + k = params.get("max_chunks", 3) | |
| 106 | + | |
| 107 | + def _process(c) -> str: | |
| 108 | + if isinstance(c, str): | |
| 109 | + return c | |
| 110 | + else: | |
| 111 | + return "<media>" | |
| 112 | + | |
| 113 | + if isinstance(query, list): | |
| 114 | + query_str = " ".join([_process(c) for c in query]) | |
| 115 | + else: | |
| 116 | + query_str = _process(query) | |
| 117 | + | |
| 118 | + model = get_embedding_model() | |
| 119 | + query_vector = model.encode([query_str])[0].astype(np.float32) | |
| 120 | + return await self.index.query(query_vector, k) |
modified llama_toolchain/memory/meta_reference/faiss/faiss.py +39 −114
| @@ -5,108 +5,45 @@ | ||
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | 7 | import uuid |
| 8 | -from dataclasses import dataclass, field | |
| 9 | -from typing import Any, Dict, List, Optional, Tuple | |
| 8 | + | |
| 9 | +from typing import Any, Dict, List, Optional | |
| 10 | 10 | |
| 11 | 11 | import faiss |
| 12 | -import httpx | |
| 13 | 12 | import numpy as np |
| 13 | +from numpy.typing import NDArray | |
| 14 | 14 | |
| 15 | 15 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 16 | -from llama_models.llama3.api.tokenizer import Tokenizer | |
| 17 | 16 | |
| 18 | 17 | from llama_toolchain.memory.api import * # noqa: F403 |
| 18 | +from llama_toolchain.memory.common.vector_store import ( | |
| 19 | + ALL_MINILM_L6_V2_DIMENSION, | |
| 20 | + BankWithIndex, | |
| 21 | + EmbeddingIndex, | |
| 22 | +) | |
| 19 | 23 | from .config import FaissImplConfig |
| 20 | 24 | |
| 21 | 25 | |
| 22 | -async def content_from_doc(doc: MemoryBankDocument) -> str: | |
| 23 | - if isinstance(doc.content, URL): | |
| 24 | - async with httpx.AsyncClient() as client: | |
| 25 | - r = await client.get(doc.content.uri) | |
| 26 | - return r.text | |
| 27 | - | |
| 28 | - return interleaved_text_media_as_str(doc.content) | |
| 29 | - | |
| 30 | - | |
| 31 | -def make_overlapped_chunks( | |
| 32 | - text: str, window_len: int, overlap_len: int | |
| 33 | -) -> List[Tuple[str, int]]: | |
| 34 | - tokenizer = Tokenizer.get_instance() | |
| 35 | - tokens = tokenizer.encode(text, bos=False, eos=False) | |
| 36 | - | |
| 37 | - chunks = [] | |
| 38 | - for i in range(0, len(tokens), window_len - overlap_len): | |
| 39 | - toks = tokens[i : i + window_len] | |
| 40 | - chunk = tokenizer.decode(toks) | |
| 41 | - chunks.append((chunk, len(toks))) | |
| 26 | +class FaissIndex(EmbeddingIndex): | |
| 27 | + id_by_index: Dict[int, str] | |
| 28 | + chunk_by_index: Dict[int, str] | |
| 42 | 29 | |
| 43 | - return chunks | |
| 30 | + def __init__(self, dimension: int): | |
| 31 | + self.index = faiss.IndexFlatL2(dimension) | |
| 32 | + self.id_by_index = {} | |
| 33 | + self.chunk_by_index = {} | |
| 44 | 34 | |
| 35 | + async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): | |
| 36 | + indexlen = len(self.id_by_index) | |
| 37 | + for i, chunk in enumerate(chunks): | |
| 38 | + self.chunk_by_index[indexlen + i] = chunk | |
| 39 | + print(f"Adding chunk #{indexlen + i} tokens={chunk.token_count}") | |
| 40 | + self.id_by_index[indexlen + i] = chunk.document_id | |
| 45 | 41 | |
| 46 | -@dataclass | |
| 47 | -class BankState: | |
| 48 | - bank: MemoryBank | |
| 49 | - index: Optional[faiss.IndexFlatL2] = None | |
| 50 | - doc_by_id: Dict[str, MemoryBankDocument] = field(default_factory=dict) | |
| 51 | - id_by_index: Dict[int, str] = field(default_factory=dict) | |
| 52 | - chunk_by_index: Dict[int, str] = field(default_factory=dict) | |
| 53 | - | |
| 54 | - async def insert_documents( | |
| 55 | - self, | |
| 56 | - model: "SentenceTransformer", | |
| 57 | - documents: List[MemoryBankDocument], | |
| 58 | - ) -> None: | |
| 59 | - tokenizer = Tokenizer.get_instance() | |
| 60 | - chunk_size = self.bank.config.chunk_size_in_tokens | |
| 61 | - | |
| 62 | - for doc in documents: | |
| 63 | - indexlen = len(self.id_by_index) | |
| 64 | - self.doc_by_id[doc.document_id] = doc | |
| 65 | - | |
| 66 | - content = await content_from_doc(doc) | |
| 67 | - chunks = make_overlapped_chunks( | |
| 68 | - content, | |
| 69 | - self.bank.config.chunk_size_in_tokens, | |
| 70 | - self.bank.config.overlap_size_in_tokens | |
| 71 | - or (self.bank.config.chunk_size_in_tokens // 4), | |
| 72 | - ) | |
| 73 | - embeddings = model.encode([x[0] for x in chunks]).astype(np.float32) | |
| 74 | - await self._ensure_index(embeddings.shape[1]) | |
| 75 | - | |
| 76 | - self.index.add(embeddings) | |
| 77 | - for i, chunk in enumerate(chunks): | |
| 78 | - self.chunk_by_index[indexlen + i] = Chunk( | |
| 79 | - content=chunk[0], | |
| 80 | - token_count=chunk[1], | |
| 81 | - document_id=doc.document_id, | |
| 82 | - ) | |
| 83 | - print(f"Adding chunk #{indexlen + i} tokens={chunk[1]}") | |
| 84 | - self.id_by_index[indexlen + i] = doc.document_id | |
| 42 | + self.index.add(np.array(embeddings).astype(np.float32)) | |
| 85 | 43 | |
| 86 | - async def query_documents( | |
| 87 | - self, | |
| 88 | - model: "SentenceTransformer", | |
| 89 | - query: InterleavedTextMedia, | |
| 90 | - params: Optional[Dict[str, Any]] = None, | |
| 91 | - ) -> QueryDocumentsResponse: | |
| 92 | - if params is None: | |
| 93 | - params = {} | |
| 94 | - k = params.get("max_chunks", 3) | |
| 95 | - | |
| 96 | - def _process(c) -> str: | |
| 97 | - if isinstance(c, str): | |
| 98 | - return c | |
| 99 | - else: | |
| 100 | - return "<media>" | |
| 101 | - | |
| 102 | - if isinstance(query, list): | |
| 103 | - query_str = " ".join([_process(c) for c in query]) | |
| 104 | - else: | |
| 105 | - query_str = _process(query) | |
| 106 | - | |
| 107 | - query_vector = model.encode([query_str])[0] | |
| 44 | + async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse: | |
| 108 | 45 | distances, indices = self.index.search( |
| 109 | - query_vector.reshape(1, -1).astype(np.float32), k | |
| 46 | + embedding.reshape(1, -1).astype(np.float32), k | |
| 110 | 47 | ) |
| 111 | 48 | |
| 112 | 49 | chunks = [] |
| @@ -119,17 +56,11 @@ | ||
| 119 | 56 | |
| 120 | 57 | return QueryDocumentsResponse(chunks=chunks, scores=scores) |
| 121 | 58 | |
| 122 | - async def _ensure_index(self, dimension: int) -> faiss.IndexFlatL2: | |
| 123 | - if self.index is None: | |
| 124 | - self.index = faiss.IndexFlatL2(dimension) | |
| 125 | - return self.index | |
| 126 | - | |
| 127 | 59 | |
| 128 | 60 | class FaissMemoryImpl(Memory): |
| 129 | 61 | def __init__(self, config: FaissImplConfig) -> None: |
| 130 | 62 | self.config = config |
| 131 | - self.model = None | |
| 132 | - self.states = {} | |
| 63 | + self.cache = {} | |
| 133 | 64 | |
| 134 | 65 | async def initialize(self) -> None: ... |
| 135 | 66 | |
| @@ -153,14 +84,15 @@ | ||
| 153 | 84 | config=config, |
| 154 | 85 | url=url, |
| 155 | 86 | ) |
| 156 | - state = BankState(bank=bank) | |
| 157 | - self.states[bank_id] = state | |
| 87 | + index = BankWithIndex(bank=bank, index=FaissIndex(ALL_MINILM_L6_V2_DIMENSION)) | |
| 88 | + self.cache[bank_id] = index | |
| 158 | 89 | return bank |
| 159 | 90 | |
| 160 | 91 | async def get_memory_bank(self, bank_id: str) -> Optional[MemoryBank]: |
| 161 | - if bank_id not in self.states: | |
| 92 | + index = self.cache.get(bank_id) | |
| 93 | + if index is None: | |
| 162 | 94 | return None |
| 163 | - return self.states[bank_id].bank | |
| 95 | + return index.bank | |
| 164 | 96 | |
| 165 | 97 | async def insert_documents( |
| 166 | 98 | self, |
| @@ -168,10 +100,11 @@ | ||
| 168 | 100 | documents: List[MemoryBankDocument], |
| 169 | 101 | ttl_seconds: Optional[int] = None, |
| 170 | 102 | ) -> None: |
| 171 | - assert bank_id in self.states, f"Bank {bank_id} not found" | |
| 172 | - state = self.states[bank_id] | |
| 103 | + index = self.cache.get(bank_id) | |
| 104 | + if index is None: | |
| 105 | + raise ValueError(f"Bank {bank_id} not found") | |
| 173 | 106 | |
| 174 | - await state.insert_documents(self.get_model(), documents) | |
| 107 | + await index.insert_documents(documents) | |
| 175 | 108 | |
| 176 | 109 | async def query_documents( |
| 177 | 110 | self, |
| @@ -179,16 +112,8 @@ | ||
| 179 | 112 | query: InterleavedTextMedia, |
| 180 | 113 | params: Optional[Dict[str, Any]] = None, |
| 181 | 114 | ) -> QueryDocumentsResponse: |
| 182 | - assert bank_id in self.states, f"Bank {bank_id} not found" | |
| 183 | - state = self.states[bank_id] | |
| 184 | - | |
| 185 | - return await state.query_documents(self.get_model(), query, params) | |
| 186 | - | |
| 187 | - def get_model(self) -> "SentenceTransformer": | |
| 188 | - from sentence_transformers import SentenceTransformer | |
| 189 | - | |
| 190 | - if self.model is None: | |
| 191 | - print("Loading sentence transformer") | |
| 192 | - self.model = SentenceTransformer("all-MiniLM-L6-v2") | |
| 193 | - | |
| 194 | - return self.model | |
| 115 | + index = self.cache.get(bank_id) | |
| 116 | + if index is None: | |
| 117 | + raise ValueError(f"Bank {bank_id} not found") | |
| 118 | + | |
| 119 | + return await index.query_documents(query, params) |
modified llama_toolchain/memory/providers.py +24 −6
| @@ -6,7 +6,12 @@ | ||
| 6 | 6 | |
| 7 | 7 | from typing import List |
| 8 | 8 | |
| 9 | -from llama_toolchain.core.datatypes import Api, InlineProviderSpec, ProviderSpec | |
| 9 | +from llama_toolchain.core.datatypes import * # noqa: F403 | |
| 10 | + | |
| 11 | +EMBEDDING_DEPS = [ | |
| 12 | + "blobfile", | |
| 13 | + "sentence-transformers", | |
| 14 | +] | |
| 10 | 15 | |
| 11 | 16 | |
| 12 | 17 | def available_memory_providers() -> List[ProviderSpec]: |
| @@ -14,12 +19,25 @@ | ||
| 14 | 19 | InlineProviderSpec( |
| 15 | 20 | api=Api.memory, |
| 16 | 21 | provider_id="meta-reference-faiss", |
| 17 | - pip_packages=[ | |
| 18 | - "blobfile", | |
| 19 | - "faiss-cpu", | |
| 20 | - "sentence-transformers", | |
| 21 | - ], | |
| 22 | + pip_packages=EMBEDDING_DEPS + ["faiss-cpu"], | |
| 22 | 23 | module="llama_toolchain.memory.meta_reference.faiss", |
| 23 | 24 | config_class="llama_toolchain.memory.meta_reference.faiss.FaissImplConfig", |
| 24 | 25 | ), |
| 26 | + remote_provider_spec( | |
| 27 | + api=Api.memory, | |
| 28 | + adapter=AdapterSpec( | |
| 29 | + adapter_id="chromadb", | |
| 30 | + pip_packages=EMBEDDING_DEPS + ["chromadb-client"], | |
| 31 | + module="llama_toolchain.memory.adapters.chroma", | |
| 32 | + ), | |
| 33 | + ), | |
| 34 | + remote_provider_spec( | |
| 35 | + api=Api.memory, | |
| 36 | + adapter=AdapterSpec( | |
| 37 | + adapter_id="pgvector", | |
| 38 | + pip_packages=EMBEDDING_DEPS + ["psycopg2-binary"], | |
| 39 | + module="llama_toolchain.memory.adapters.pgvector", | |
| 40 | + config_class="llama_toolchain.memory.adapters.pgvector.PGVectorConfig", | |
| 41 | + ), | |
| 42 | + ), | |
| 25 | 43 | ] |