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