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