Elffuss BraidHub

kikocis/llama-stack public

Support `data:` in URL for memory. Add ootb support for pdfs (#67)

* support data: in URL for memory. Add ootb support for pdfs

* moved utility to common and updated data_url parsing logic

---------

Co-authored-by: Hardik Shah <hjshah@fb.com>
Changeset63314e75ef83cbb069d9be88324680f9a1c25e65856554e6c1bf55e12bdfe2de
AuthorHardik Shah <hjshah@meta.com> · 2024-09-12 13:00 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-12 13:00 -07:00
Parents401d6bad2f7e

Browse the files at this changeset

6 files changed

modified llama_toolchain/agentic_system/client.py +3 −4
@@ -83,13 +83,12 @@
8383 if line.startswith("data:"):
8484 data = line[len("data: ") :]
8585 try:
86- if "error" in data:
86+ jdata = json.loads(data)
87+ if "error" in jdata:
8788 cprint(data, "red")
8889 continue
8990
90- yield AgenticSystemTurnResponseStreamChunk(
91- **json.loads(data)
92- )
91+ yield AgenticSystemTurnResponseStreamChunk(**jdata)
9392 except Exception as e:
9493 print(data)
9594 print(f"Error with parsing or validation: {e}")
modified llama_toolchain/memory/api/api.py +1 −2
@@ -8,7 +8,6 @@
88 #
99 # This source code is licensed under the terms described in the LICENSE file in
1010 # the root directory of this source tree.
11-
1211 from typing import List, Optional, Protocol
1312
1413 from llama_models.schema_utils import json_schema_type, webmethod
@@ -23,7 +22,7 @@
2322 class MemoryBankDocument(BaseModel):
2423 document_id: str
2524 content: InterleavedTextMedia | URL
26- mime_type: str
25+ mime_type: str | None = None
2726 metadata: Dict[str, Any] = Field(default_factory=dict)
2827
2928
modified llama_toolchain/memory/client.py +15 −1
@@ -5,15 +5,19 @@
55 # the root directory of this source tree.
66
77 import asyncio
8+import json
9+from pathlib import Path
810
911 from typing import Any, Dict, List, Optional
1012
1113 import fire
1214 import httpx
15+from termcolor import cprint
1316
1417 from llama_toolchain.core.datatypes import RemoteProviderConfig
1518
1619 from .api import * # noqa: F403
20+from .common.file_utils import data_url_from_file
1721
1822
1923 async def get_client_impl(config: RemoteProviderConfig, _deps: Any) -> Memory:
@@ -120,7 +124,7 @@
120124 overlap_size_in_tokens=64,
121125 ),
122126 )
123- print(bank)
127+ cprint(json.dumps(bank.dict(), indent=4), "green")
124128
125129 retrieved_bank = await client.get_memory_bank(bank.bank_id)
126130 assert retrieved_bank is not None
@@ -145,6 +149,16 @@
145149 for i, url in enumerate(urls)
146150 ]
147151
152+ this_dir = os.path.dirname(__file__)
153+ files = [Path(this_dir).parent.parent / "CONTRIBUTING.md"]
154+ documents += [
155+ MemoryBankDocument(
156+ document_id=f"num-{i}",
157+ content=data_url_from_file(path),
158+ )
159+ for i, path in enumerate(files)
160+ ]
161+
148162 # insert some documents
149163 await client.insert_documents(
150164 bank_id=bank.bank_id,
added llama_toolchain/memory/common/file_utils.py +26 −0
@@ -0,0 +1,26 @@
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 base64
8+import mimetypes
9+import os
10+
11+from llama_models.llama3.api.datatypes import URL
12+
13+
14+def data_url_from_file(file_path: str) -> URL:
15+ if not os.path.exists(file_path):
16+ raise FileNotFoundError(f"File not found: {file_path}")
17+
18+ with open(file_path, "rb") as file:
19+ file_content = file.read()
20+
21+ base64_content = base64.b64encode(file_content).decode("utf-8")
22+ mime_type, _ = mimetypes.guess_type(file_path)
23+
24+ data_url = f"data:{mime_type};base64,{base64_content}"
25+
26+ return URL(uri=data_url)
modified llama_toolchain/memory/common/vector_store.py +65 −5
@@ -3,21 +3,25 @@
33 #
44 # This source code is licensed under the terms described in the LICENSE file in
55 # the root directory of this source tree.
6-
6+import base64
7+import io
8+import re
79 from abc import ABC, abstractmethod
810 from dataclasses import dataclass
911 from typing import Any, Dict, List, Optional
12+from urllib.parse import unquote
1013
14+import chardet
1115 import httpx
1216 import numpy as np
1317 from numpy.typing import NDArray
18+from pypdf import PdfReader
1419
1520 from llama_models.llama3.api.datatypes import * # noqa: F403
1621 from llama_models.llama3.api.tokenizer import Tokenizer
1722
1823 from llama_toolchain.memory.api import * # noqa: F403
1924
20-
2125 ALL_MINILM_L6_V2_DIMENSION = 384
2226
2327 EMBEDDING_MODEL = None
@@ -36,11 +40,67 @@
3640 return EMBEDDING_MODEL
3741
3842
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+
3996 async def content_from_doc(doc: MemoryBankDocument) -> str:
4097 if isinstance(doc.content, URL):
41- async with httpx.AsyncClient() as client:
42- r = await client.get(doc.content.uri)
43- return r.text
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
44104
45105 return interleaved_text_media_as_str(doc.content)
46106
modified llama_toolchain/memory/providers.py +2 −0
@@ -10,6 +10,8 @@
1010
1111 EMBEDDING_DEPS = [
1212 "blobfile",
13+ "chardet",
14+ "PdfReader",
1315 "sentence-transformers",
1416 ]
1517