| 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 | import base64 |
| 7 | import io |
| 8 | import re |
| 9 | from abc import ABC, abstractmethod |
| 10 | from dataclasses import dataclass |
| 11 | from typing import Any, Dict, List, Optional |
| 12 | from urllib.parse import unquote |
| 13 | |
| 14 | import chardet |
| 15 | import httpx |
| 16 | import numpy as np |
| 17 | from numpy.typing import NDArray |
| 18 | from pypdf import PdfReader |
| 19 | from termcolor import cprint |
| 20 | |
| 21 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 22 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 23 | |
| 24 | from llama_stack.apis.memory import * # noqa: F403 |
| 25 | |
| 26 | ALL_MINILM_L6_V2_DIMENSION = 384 |
| 27 | |
| 28 | EMBEDDING_MODELS = {} |
| 29 | |
| 30 | |
| 31 | def get_embedding_model(model: str) -> "SentenceTransformer": |
| 32 | global EMBEDDING_MODELS |
| 33 | |
| 34 | loaded_model = EMBEDDING_MODELS.get(model) |
| 35 | if loaded_model is not None: |
| 36 | return loaded_model |
| 37 | |
| 38 | print(f"Loading sentence transformer for {model}...") |
| 39 | from sentence_transformers import SentenceTransformer |
| 40 | |
| 41 | loaded_model = SentenceTransformer(model) |
| 42 | EMBEDDING_MODELS[model] = loaded_model |
| 43 | return loaded_model |
| 44 | |
| 45 | |
| 46 | def parse_data_url(data_url: str): |
| 47 | data_url_pattern = re.compile( |
| 48 | r"^" |
| 49 | r"data:" |
| 50 | r"(?P<mimetype>[\w/\-+.]+)" |
| 51 | r"(?P<charset>;charset=(?P<encoding>[\w-]+))?" |
| 52 | r"(?P<base64>;base64)?" |
| 53 | r",(?P<data>.*)" |
| 54 | r"$", |
| 55 | re.DOTALL, |
| 56 | ) |
| 57 | match = data_url_pattern.match(data_url) |
| 58 | if not match: |
| 59 | raise ValueError("Invalid Data URL format") |
| 60 | |
| 61 | parts = match.groupdict() |
| 62 | parts["is_base64"] = bool(parts["base64"]) |
| 63 | return parts |
| 64 | |
| 65 | |
| 66 | def content_from_data(data_url: str) -> str: |
| 67 | parts = parse_data_url(data_url) |
| 68 | data = parts["data"] |
| 69 | |
| 70 | if parts["is_base64"]: |
| 71 | data = base64.b64decode(data) |
| 72 | else: |
| 73 | data = unquote(data) |
| 74 | encoding = parts["encoding"] or "utf-8" |
| 75 | data = data.encode(encoding) |
| 76 | |
| 77 | encoding = parts["encoding"] |
| 78 | if not encoding: |
| 79 | detected = chardet.detect(data) |
| 80 | encoding = detected["encoding"] |
| 81 | |
| 82 | mime_type = parts["mimetype"] |
| 83 | mime_category = mime_type.split("/")[0] |
| 84 | if mime_category == "text": |
| 85 | # For text-based files (including CSV, MD) |
| 86 | return data.decode(encoding) |
| 87 | |
| 88 | elif mime_type == "application/pdf": |
| 89 | # For PDF and DOC/DOCX files, we can't reliably convert to string) |
| 90 | pdf_bytes = io.BytesIO(data) |
| 91 | pdf_reader = PdfReader(pdf_bytes) |
| 92 | return "\n".join([page.extract_text() for page in pdf_reader.pages]) |
| 93 | |
| 94 | else: |
| 95 | cprint("Could not extract content from data_url properly.", color="red") |
| 96 | return "" |
| 97 | |
| 98 | |
| 99 | async def content_from_doc(doc: MemoryBankDocument) -> str: |
| 100 | if isinstance(doc.content, URL): |
| 101 | if doc.content.uri.startswith("data:"): |
| 102 | return content_from_data(doc.content.uri) |
| 103 | else: |
| 104 | async with httpx.AsyncClient() as client: |
| 105 | r = await client.get(doc.content.uri) |
| 106 | return r.text |
| 107 | |
| 108 | pattern = re.compile("^(https?://|file://|data:)") |
| 109 | if pattern.match(doc.content): |
| 110 | if doc.content.startswith("data:"): |
| 111 | return content_from_data(doc.content) |
| 112 | else: |
| 113 | async with httpx.AsyncClient() as client: |
| 114 | r = await client.get(doc.content) |
| 115 | return r.text |
| 116 | |
| 117 | return interleaved_text_media_as_str(doc.content) |
| 118 | |
| 119 | |
| 120 | def make_overlapped_chunks( |
| 121 | document_id: str, text: str, window_len: int, overlap_len: int |
| 122 | ) -> List[Chunk]: |
| 123 | tokenizer = Tokenizer.get_instance() |
| 124 | tokens = tokenizer.encode(text, bos=False, eos=False) |
| 125 | |
| 126 | chunks = [] |
| 127 | for i in range(0, len(tokens), window_len - overlap_len): |
| 128 | toks = tokens[i : i + window_len] |
| 129 | chunk = tokenizer.decode(toks) |
| 130 | chunks.append( |
| 131 | Chunk(content=chunk, token_count=len(toks), document_id=document_id) |
| 132 | ) |
| 133 | |
| 134 | return chunks |
| 135 | |
| 136 | |
| 137 | class EmbeddingIndex(ABC): |
| 138 | @abstractmethod |
| 139 | async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): |
| 140 | raise NotImplementedError() |
| 141 | |
| 142 | @abstractmethod |
| 143 | async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse: |
| 144 | raise NotImplementedError() |
| 145 | |
| 146 | |
| 147 | @dataclass |
| 148 | class BankWithIndex: |
| 149 | bank: MemoryBank |
| 150 | index: EmbeddingIndex |
| 151 | |
| 152 | async def insert_documents( |
| 153 | self, |
| 154 | documents: List[MemoryBankDocument], |
| 155 | ) -> None: |
| 156 | model = get_embedding_model(self.bank.config.embedding_model) |
| 157 | for doc in documents: |
| 158 | content = await content_from_doc(doc) |
| 159 | chunks = make_overlapped_chunks( |
| 160 | doc.document_id, |
| 161 | content, |
| 162 | self.bank.config.chunk_size_in_tokens, |
| 163 | self.bank.config.overlap_size_in_tokens |
| 164 | or (self.bank.config.chunk_size_in_tokens // 4), |
| 165 | ) |
| 166 | if not chunks: |
| 167 | continue |
| 168 | embeddings = model.encode([x.content for x in chunks]).astype(np.float32) |
| 169 | |
| 170 | await self.index.add_chunks(chunks, embeddings) |
| 171 | |
| 172 | async def query_documents( |
| 173 | self, |
| 174 | query: InterleavedTextMedia, |
| 175 | params: Optional[Dict[str, Any]] = None, |
| 176 | ) -> QueryDocumentsResponse: |
| 177 | if params is None: |
| 178 | params = {} |
| 179 | k = params.get("max_chunks", 3) |
| 180 | |
| 181 | def _process(c) -> str: |
| 182 | if isinstance(c, str): |
| 183 | return c |
| 184 | else: |
| 185 | return "<media>" |
| 186 | |
| 187 | if isinstance(query, list): |
| 188 | query_str = " ".join([_process(c) for c in query]) |
| 189 | else: |
| 190 | query_str = _process(query) |
| 191 | |
| 192 | model = get_embedding_model(self.bank.config.embedding_model) |
| 193 | query_vector = model.encode([query_str])[0].astype(np.float32) |
| 194 | return await self.index.query(query_vector, k) |