kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | 63314e75ef83cbb069d9be88324680f9a1c25e65856554e6c1bf55e12bdfe2de |
|---|---|
| Author | Hardik Shah <hjshah@meta.com> · 2024-09-12 13:00 -07:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-12 13:00 -07:00 |
| Parents | 401d6bad2f7e |
6 files changed
modified llama_toolchain/agentic_system/client.py +3 −4
| @@ -83,13 +83,12 @@ | ||
| 83 | 83 | if line.startswith("data:"): |
| 84 | 84 | data = line[len("data: ") :] |
| 85 | 85 | try: |
| 86 | - if "error" in data: | |
| 86 | + jdata = json.loads(data) | |
| 87 | + if "error" in jdata: | |
| 87 | 88 | cprint(data, "red") |
| 88 | 89 | continue |
| 89 | 90 | |
| 90 | - yield AgenticSystemTurnResponseStreamChunk( | |
| 91 | - **json.loads(data) | |
| 92 | - ) | |
| 91 | + yield AgenticSystemTurnResponseStreamChunk(**jdata) | |
| 93 | 92 | except Exception as e: |
| 94 | 93 | print(data) |
| 95 | 94 | print(f"Error with parsing or validation: {e}") |
modified llama_toolchain/memory/api/api.py +1 −2
| @@ -8,7 +8,6 @@ | ||
| 8 | 8 | # |
| 9 | 9 | # This source code is licensed under the terms described in the LICENSE file in |
| 10 | 10 | # the root directory of this source tree. |
| 11 | - | |
| 12 | 11 | from typing import List, Optional, Protocol |
| 13 | 12 | |
| 14 | 13 | from llama_models.schema_utils import json_schema_type, webmethod |
| @@ -23,7 +22,7 @@ | ||
| 23 | 22 | class MemoryBankDocument(BaseModel): |
| 24 | 23 | document_id: str |
| 25 | 24 | content: InterleavedTextMedia | URL |
| 26 | - mime_type: str | |
| 25 | + mime_type: str | None = None | |
| 27 | 26 | metadata: Dict[str, Any] = Field(default_factory=dict) |
| 28 | 27 | |
| 29 | 28 |
modified llama_toolchain/memory/client.py +15 −1
| @@ -5,15 +5,19 @@ | ||
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | 7 | import asyncio |
| 8 | +import json | |
| 9 | +from pathlib import Path | |
| 8 | 10 | |
| 9 | 11 | from typing import Any, Dict, List, Optional |
| 10 | 12 | |
| 11 | 13 | import fire |
| 12 | 14 | import httpx |
| 15 | +from termcolor import cprint | |
| 13 | 16 | |
| 14 | 17 | from llama_toolchain.core.datatypes import RemoteProviderConfig |
| 15 | 18 | |
| 16 | 19 | from .api import * # noqa: F403 |
| 20 | +from .common.file_utils import data_url_from_file | |
| 17 | 21 | |
| 18 | 22 | |
| 19 | 23 | async def get_client_impl(config: RemoteProviderConfig, _deps: Any) -> Memory: |
| @@ -120,7 +124,7 @@ | ||
| 120 | 124 | overlap_size_in_tokens=64, |
| 121 | 125 | ), |
| 122 | 126 | ) |
| 123 | - print(bank) | |
| 127 | + cprint(json.dumps(bank.dict(), indent=4), "green") | |
| 124 | 128 | |
| 125 | 129 | retrieved_bank = await client.get_memory_bank(bank.bank_id) |
| 126 | 130 | assert retrieved_bank is not None |
| @@ -145,6 +149,16 @@ | ||
| 145 | 149 | for i, url in enumerate(urls) |
| 146 | 150 | ] |
| 147 | 151 | |
| 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 | + | |
| 148 | 162 | # insert some documents |
| 149 | 163 | await client.insert_documents( |
| 150 | 164 | 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 @@ | ||
| 3 | 3 | # |
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | - | |
| 6 | +import base64 | |
| 7 | +import io | |
| 8 | +import re | |
| 7 | 9 | from abc import ABC, abstractmethod |
| 8 | 10 | from dataclasses import dataclass |
| 9 | 11 | from typing import Any, Dict, List, Optional |
| 12 | +from urllib.parse import unquote | |
| 10 | 13 | |
| 14 | +import chardet | |
| 11 | 15 | import httpx |
| 12 | 16 | import numpy as np |
| 13 | 17 | from numpy.typing import NDArray |
| 18 | +from pypdf import PdfReader | |
| 14 | 19 | |
| 15 | 20 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 16 | 21 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 17 | 22 | |
| 18 | 23 | from llama_toolchain.memory.api import * # noqa: F403 |
| 19 | 24 | |
| 20 | - | |
| 21 | 25 | ALL_MINILM_L6_V2_DIMENSION = 384 |
| 22 | 26 | |
| 23 | 27 | EMBEDDING_MODEL = None |
| @@ -36,11 +40,67 @@ | ||
| 36 | 40 | return EMBEDDING_MODEL |
| 37 | 41 | |
| 38 | 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 | + | |
| 39 | 96 | async def content_from_doc(doc: MemoryBankDocument) -> str: |
| 40 | 97 | 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 | |
| 44 | 104 | |
| 45 | 105 | return interleaved_text_media_as_str(doc.content) |
| 46 | 106 |
modified llama_toolchain/memory/providers.py +2 −0
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | |
| 11 | 11 | EMBEDDING_DEPS = [ |
| 12 | 12 | "blobfile", |
| 13 | + "chardet", | |
| 14 | + "PdfReader", | |
| 13 | 15 | "sentence-transformers", |
| 14 | 16 | ] |
| 15 | 17 |