| 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 asyncio |
| 8 | import json |
| 9 | from pathlib import Path |
| 10 | |
| 11 | from typing import Any, Dict, List, Optional |
| 12 | |
| 13 | import fire |
| 14 | import httpx |
| 15 | from termcolor import cprint |
| 16 | |
| 17 | from llama_toolchain.core.datatypes import RemoteProviderConfig |
| 18 | |
| 19 | from .api import * # noqa: F403 |
| 20 | from .common.file_utils import data_url_from_file |
| 21 | |
| 22 | |
| 23 | async def get_client_impl(config: RemoteProviderConfig, _deps: Any) -> Memory: |
| 24 | return MemoryClient(config.url) |
| 25 | |
| 26 | |
| 27 | class MemoryClient(Memory): |
| 28 | def __init__(self, base_url: str): |
| 29 | self.base_url = base_url |
| 30 | |
| 31 | async def initialize(self) -> None: |
| 32 | pass |
| 33 | |
| 34 | async def shutdown(self) -> None: |
| 35 | pass |
| 36 | |
| 37 | async def get_memory_bank(self, bank_id: str) -> Optional[MemoryBank]: |
| 38 | async with httpx.AsyncClient() as client: |
| 39 | r = await client.get( |
| 40 | f"{self.base_url}/memory_banks/get", |
| 41 | params={ |
| 42 | "bank_id": bank_id, |
| 43 | }, |
| 44 | headers={"Content-Type": "application/json"}, |
| 45 | timeout=20, |
| 46 | ) |
| 47 | r.raise_for_status() |
| 48 | d = r.json() |
| 49 | if not d: |
| 50 | return None |
| 51 | return MemoryBank(**d) |
| 52 | |
| 53 | async def create_memory_bank( |
| 54 | self, |
| 55 | name: str, |
| 56 | config: MemoryBankConfig, |
| 57 | url: Optional[URL] = None, |
| 58 | ) -> MemoryBank: |
| 59 | async with httpx.AsyncClient() as client: |
| 60 | r = await client.post( |
| 61 | f"{self.base_url}/memory_banks/create", |
| 62 | json={ |
| 63 | "name": name, |
| 64 | "config": config.dict(), |
| 65 | "url": url, |
| 66 | }, |
| 67 | headers={"Content-Type": "application/json"}, |
| 68 | timeout=20, |
| 69 | ) |
| 70 | r.raise_for_status() |
| 71 | d = r.json() |
| 72 | if not d: |
| 73 | return None |
| 74 | return MemoryBank(**d) |
| 75 | |
| 76 | async def insert_documents( |
| 77 | self, |
| 78 | bank_id: str, |
| 79 | documents: List[MemoryBankDocument], |
| 80 | ) -> None: |
| 81 | async with httpx.AsyncClient() as client: |
| 82 | r = await client.post( |
| 83 | f"{self.base_url}/memory_bank/insert", |
| 84 | json={ |
| 85 | "bank_id": bank_id, |
| 86 | "documents": [d.dict() for d in documents], |
| 87 | }, |
| 88 | headers={"Content-Type": "application/json"}, |
| 89 | timeout=20, |
| 90 | ) |
| 91 | r.raise_for_status() |
| 92 | |
| 93 | async def query_documents( |
| 94 | self, |
| 95 | bank_id: str, |
| 96 | query: InterleavedTextMedia, |
| 97 | params: Optional[Dict[str, Any]] = None, |
| 98 | ) -> QueryDocumentsResponse: |
| 99 | async with httpx.AsyncClient() as client: |
| 100 | r = await client.post( |
| 101 | f"{self.base_url}/memory_bank/query", |
| 102 | json={ |
| 103 | "bank_id": bank_id, |
| 104 | "query": query, |
| 105 | "params": params, |
| 106 | }, |
| 107 | headers={"Content-Type": "application/json"}, |
| 108 | timeout=20, |
| 109 | ) |
| 110 | r.raise_for_status() |
| 111 | return QueryDocumentsResponse(**r.json()) |
| 112 | |
| 113 | |
| 114 | async def run_main(host: str, port: int, stream: bool): |
| 115 | client = MemoryClient(f"http://{host}:{port}") |
| 116 | |
| 117 | # create a memory bank |
| 118 | bank = await client.create_memory_bank( |
| 119 | name="test_bank", |
| 120 | config=VectorMemoryBankConfig( |
| 121 | bank_id="test_bank", |
| 122 | embedding_model="dragon-roberta-query-2", |
| 123 | chunk_size_in_tokens=512, |
| 124 | overlap_size_in_tokens=64, |
| 125 | ), |
| 126 | ) |
| 127 | cprint(json.dumps(bank.dict(), indent=4), "green") |
| 128 | |
| 129 | retrieved_bank = await client.get_memory_bank(bank.bank_id) |
| 130 | assert retrieved_bank is not None |
| 131 | assert retrieved_bank.config.embedding_model == "dragon-roberta-query-2" |
| 132 | |
| 133 | urls = [ |
| 134 | "memory_optimizations.rst", |
| 135 | "chat.rst", |
| 136 | "llama3.rst", |
| 137 | "datasets.rst", |
| 138 | "qat_finetune.rst", |
| 139 | "lora_finetune.rst", |
| 140 | ] |
| 141 | documents = [ |
| 142 | MemoryBankDocument( |
| 143 | document_id=f"num-{i}", |
| 144 | content=URL( |
| 145 | uri=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}" |
| 146 | ), |
| 147 | mime_type="text/plain", |
| 148 | ) |
| 149 | for i, url in enumerate(urls) |
| 150 | ] |
| 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 | |
| 162 | # insert some documents |
| 163 | await client.insert_documents( |
| 164 | bank_id=bank.bank_id, |
| 165 | documents=documents, |
| 166 | ) |
| 167 | |
| 168 | # query the documents |
| 169 | response = await client.query_documents( |
| 170 | bank_id=bank.bank_id, |
| 171 | query=[ |
| 172 | "How do I use Lora?", |
| 173 | ], |
| 174 | ) |
| 175 | for chunk, score in zip(response.chunks, response.scores): |
| 176 | print(f"Score: {score}") |
| 177 | print(f"Chunk:\n========\n{chunk}\n========\n") |
| 178 | |
| 179 | response = await client.query_documents( |
| 180 | bank_id=bank.bank_id, |
| 181 | query=[ |
| 182 | "Tell me more about llama3 and torchtune", |
| 183 | ], |
| 184 | ) |
| 185 | for chunk, score in zip(response.chunks, response.scores): |
| 186 | print(f"Score: {score}") |
| 187 | print(f"Chunk:\n========\n{chunk}\n========\n") |
| 188 | |
| 189 | |
| 190 | def main(host: str, port: int, stream: bool = True): |
| 191 | asyncio.run(run_main(host, port, stream)) |
| 192 | |
| 193 | |
| 194 | if __name__ == "__main__": |
| 195 | fire.Fire(main) |