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