| 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_stack.apis.memory import * # noqa: F403 |
| 17 | |
| 18 | |
| 19 | from llama_stack.providers.utils.memory.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 | values.append( |
| 84 | ( |
| 85 | f"{chunk.document_id}:chunk-{i}", |
| 86 | Json(chunk.dict()), |
| 87 | embeddings[i].tolist(), |
| 88 | ) |
| 89 | ) |
| 90 | |
| 91 | query = sql.SQL( |
| 92 | f""" |
| 93 | INSERT INTO {self.table_name} (id, document, embedding) |
| 94 | VALUES %s |
| 95 | ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding, document = EXCLUDED.document |
| 96 | """ |
| 97 | ) |
| 98 | execute_values(self.cursor, query, values, template="(%s, %s, %s::vector)") |
| 99 | |
| 100 | async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse: |
| 101 | self.cursor.execute( |
| 102 | f""" |
| 103 | SELECT document, embedding <-> %s::vector AS distance |
| 104 | FROM {self.table_name} |
| 105 | ORDER BY distance |
| 106 | LIMIT %s |
| 107 | """, |
| 108 | (embedding.tolist(), k), |
| 109 | ) |
| 110 | results = self.cursor.fetchall() |
| 111 | |
| 112 | chunks = [] |
| 113 | scores = [] |
| 114 | for doc, dist in results: |
| 115 | chunks.append(Chunk(**doc)) |
| 116 | scores.append(1.0 / float(dist)) |
| 117 | |
| 118 | return QueryDocumentsResponse(chunks=chunks, scores=scores) |
| 119 | |
| 120 | |
| 121 | class PGVectorMemoryAdapter(Memory): |
| 122 | def __init__(self, config: PGVectorConfig) -> None: |
| 123 | print(f"Initializing PGVectorMemoryAdapter -> {config.host}:{config.port}") |
| 124 | self.config = config |
| 125 | self.cursor = None |
| 126 | self.conn = None |
| 127 | self.cache = {} |
| 128 | |
| 129 | async def initialize(self) -> None: |
| 130 | try: |
| 131 | self.conn = psycopg2.connect( |
| 132 | host=self.config.host, |
| 133 | port=self.config.port, |
| 134 | database=self.config.db, |
| 135 | user=self.config.user, |
| 136 | password=self.config.password, |
| 137 | ) |
| 138 | self.cursor = self.conn.cursor() |
| 139 | |
| 140 | version = check_extension_version(self.cursor) |
| 141 | if version: |
| 142 | print(f"Vector extension version: {version}") |
| 143 | else: |
| 144 | raise RuntimeError("Vector extension is not installed.") |
| 145 | |
| 146 | self.cursor.execute( |
| 147 | """ |
| 148 | CREATE TABLE IF NOT EXISTS metadata_store ( |
| 149 | key TEXT PRIMARY KEY, |
| 150 | data JSONB |
| 151 | ) |
| 152 | """ |
| 153 | ) |
| 154 | except Exception as e: |
| 155 | import traceback |
| 156 | |
| 157 | traceback.print_exc() |
| 158 | raise RuntimeError("Could not connect to PGVector database server") from e |
| 159 | |
| 160 | async def shutdown(self) -> None: |
| 161 | pass |
| 162 | |
| 163 | async def create_memory_bank( |
| 164 | self, |
| 165 | name: str, |
| 166 | config: MemoryBankConfig, |
| 167 | url: Optional[URL] = None, |
| 168 | ) -> MemoryBank: |
| 169 | bank_id = str(uuid.uuid4()) |
| 170 | bank = MemoryBank( |
| 171 | bank_id=bank_id, |
| 172 | name=name, |
| 173 | config=config, |
| 174 | url=url, |
| 175 | ) |
| 176 | upsert_models( |
| 177 | self.cursor, |
| 178 | [ |
| 179 | (bank.bank_id, bank), |
| 180 | ], |
| 181 | ) |
| 182 | index = BankWithIndex( |
| 183 | bank=bank, |
| 184 | index=PGVectorIndex(bank, ALL_MINILM_L6_V2_DIMENSION, self.cursor), |
| 185 | ) |
| 186 | self.cache[bank_id] = index |
| 187 | return bank |
| 188 | |
| 189 | async def get_memory_bank(self, bank_id: str) -> Optional[MemoryBank]: |
| 190 | bank_index = await self._get_and_cache_bank_index(bank_id) |
| 191 | if bank_index is None: |
| 192 | return None |
| 193 | return bank_index.bank |
| 194 | |
| 195 | async def _get_and_cache_bank_index(self, bank_id: str) -> Optional[BankWithIndex]: |
| 196 | if bank_id in self.cache: |
| 197 | return self.cache[bank_id] |
| 198 | |
| 199 | banks = load_models(self.cursor, [bank_id], MemoryBank) |
| 200 | if not banks: |
| 201 | return None |
| 202 | |
| 203 | bank = banks[0] |
| 204 | index = BankWithIndex( |
| 205 | bank=bank, |
| 206 | index=PGVectorIndex(bank, ALL_MINILM_L6_V2_DIMENSION, self.cursor), |
| 207 | ) |
| 208 | self.cache[bank_id] = index |
| 209 | return index |
| 210 | |
| 211 | async def insert_documents( |
| 212 | self, |
| 213 | bank_id: str, |
| 214 | documents: List[MemoryBankDocument], |
| 215 | ttl_seconds: Optional[int] = None, |
| 216 | ) -> None: |
| 217 | index = await self._get_and_cache_bank_index(bank_id) |
| 218 | if not index: |
| 219 | raise ValueError(f"Bank {bank_id} not found") |
| 220 | |
| 221 | await index.insert_documents(documents) |
| 222 | |
| 223 | async def query_documents( |
| 224 | self, |
| 225 | bank_id: str, |
| 226 | query: InterleavedTextMedia, |
| 227 | params: Optional[Dict[str, Any]] = None, |
| 228 | ) -> QueryDocumentsResponse: |
| 229 | index = await self._get_and_cache_bank_index(bank_id) |
| 230 | if not index: |
| 231 | raise ValueError(f"Bank {bank_id} not found") |
| 232 | |
| 233 | return await index.query_documents(query, params) |