| 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 typing import AsyncGenerator |
| 10 | |
| 11 | import fire |
| 12 | |
| 13 | import httpx |
| 14 | |
| 15 | from pydantic import BaseModel |
| 16 | from termcolor import cprint |
| 17 | |
| 18 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 19 | from llama_toolchain.core.datatypes import RemoteProviderConfig |
| 20 | |
| 21 | from .api import * # noqa: F403 |
| 22 | from .event_logger import EventLogger |
| 23 | |
| 24 | |
| 25 | async def get_client_impl(config: RemoteProviderConfig, _deps): |
| 26 | return AgenticSystemClient(config.url) |
| 27 | |
| 28 | |
| 29 | def encodable_dict(d: BaseModel): |
| 30 | return json.loads(d.json()) |
| 31 | |
| 32 | |
| 33 | class AgenticSystemClient(AgenticSystem): |
| 34 | def __init__(self, base_url: str): |
| 35 | self.base_url = base_url |
| 36 | |
| 37 | async def create_agentic_system( |
| 38 | self, agent_config: AgentConfig |
| 39 | ) -> AgenticSystemCreateResponse: |
| 40 | async with httpx.AsyncClient() as client: |
| 41 | response = await client.post( |
| 42 | f"{self.base_url}/agentic_system/create", |
| 43 | json={ |
| 44 | "agent_config": encodable_dict(agent_config), |
| 45 | }, |
| 46 | headers={"Content-Type": "application/json"}, |
| 47 | ) |
| 48 | response.raise_for_status() |
| 49 | return AgenticSystemCreateResponse(**response.json()) |
| 50 | |
| 51 | async def create_agentic_system_session( |
| 52 | self, |
| 53 | agent_id: str, |
| 54 | session_name: str, |
| 55 | ) -> AgenticSystemSessionCreateResponse: |
| 56 | async with httpx.AsyncClient() as client: |
| 57 | response = await client.post( |
| 58 | f"{self.base_url}/agentic_system/session/create", |
| 59 | json={ |
| 60 | "agent_id": agent_id, |
| 61 | "session_name": session_name, |
| 62 | }, |
| 63 | headers={"Content-Type": "application/json"}, |
| 64 | ) |
| 65 | response.raise_for_status() |
| 66 | return AgenticSystemSessionCreateResponse(**response.json()) |
| 67 | |
| 68 | async def create_agentic_system_turn( |
| 69 | self, |
| 70 | request: AgenticSystemTurnCreateRequest, |
| 71 | ) -> AsyncGenerator: |
| 72 | async with httpx.AsyncClient() as client: |
| 73 | async with client.stream( |
| 74 | "POST", |
| 75 | f"{self.base_url}/agentic_system/turn/create", |
| 76 | json=encodable_dict(request), |
| 77 | headers={"Content-Type": "application/json"}, |
| 78 | timeout=20, |
| 79 | ) as response: |
| 80 | async for line in response.aiter_lines(): |
| 81 | if line.startswith("data:"): |
| 82 | data = line[len("data: ") :] |
| 83 | try: |
| 84 | jdata = json.loads(data) |
| 85 | if "error" in jdata: |
| 86 | cprint(data, "red") |
| 87 | continue |
| 88 | |
| 89 | yield AgenticSystemTurnResponseStreamChunk(**jdata) |
| 90 | except Exception as e: |
| 91 | print(data) |
| 92 | print(f"Error with parsing or validation: {e}") |
| 93 | |
| 94 | |
| 95 | async def _run_agent(api, tool_definitions, user_prompts, attachments=None): |
| 96 | agent_config = AgentConfig( |
| 97 | model="Meta-Llama3.1-8B-Instruct", |
| 98 | instructions="You are a helpful assistant", |
| 99 | sampling_params=SamplingParams(temperature=1.0, top_p=0.9), |
| 100 | tools=tool_definitions, |
| 101 | tool_choice=ToolChoice.auto, |
| 102 | tool_prompt_format=ToolPromptFormat.function_tag, |
| 103 | ) |
| 104 | |
| 105 | create_response = await api.create_agentic_system(agent_config) |
| 106 | session_response = await api.create_agentic_system_session( |
| 107 | agent_id=create_response.agent_id, |
| 108 | session_name="test_session", |
| 109 | ) |
| 110 | |
| 111 | for content in user_prompts: |
| 112 | cprint(f"User> {content}", color="white", attrs=["bold"]) |
| 113 | iterator = api.create_agentic_system_turn( |
| 114 | AgenticSystemTurnCreateRequest( |
| 115 | agent_id=create_response.agent_id, |
| 116 | session_id=session_response.session_id, |
| 117 | messages=[ |
| 118 | UserMessage(content=content), |
| 119 | ], |
| 120 | attachments=attachments, |
| 121 | stream=True, |
| 122 | ) |
| 123 | ) |
| 124 | |
| 125 | async for event, log in EventLogger().log(iterator): |
| 126 | if log is not None: |
| 127 | log.print() |
| 128 | |
| 129 | |
| 130 | async def run_main(host: str, port: int): |
| 131 | api = AgenticSystemClient(f"http://{host}:{port}") |
| 132 | |
| 133 | tool_definitions = [ |
| 134 | SearchToolDefinition(engine=SearchEngineType.bing), |
| 135 | WolframAlphaToolDefinition(), |
| 136 | CodeInterpreterToolDefinition(), |
| 137 | ] |
| 138 | tool_definitions += [ |
| 139 | FunctionCallToolDefinition( |
| 140 | function_name="get_boiling_point", |
| 141 | description="Get the boiling point of a imaginary liquids (eg. polyjuice)", |
| 142 | parameters={ |
| 143 | "liquid_name": ToolParamDefinition( |
| 144 | param_type="str", |
| 145 | description="The name of the liquid", |
| 146 | required=True, |
| 147 | ), |
| 148 | "celcius": ToolParamDefinition( |
| 149 | param_type="str", |
| 150 | description="Whether to return the boiling point in Celcius", |
| 151 | required=False, |
| 152 | ), |
| 153 | }, |
| 154 | ), |
| 155 | ] |
| 156 | |
| 157 | user_prompts = [ |
| 158 | "Who are you?", |
| 159 | "what is the 100th prime number?", |
| 160 | "Search web for who was 44th President of USA?", |
| 161 | "Write code to check if a number is prime. Use that to check if 7 is prime", |
| 162 | "What is the boiling point of polyjuicepotion ?", |
| 163 | ] |
| 164 | await _run_agent(api, tool_definitions, user_prompts) |
| 165 | |
| 166 | |
| 167 | async def run_rag(host: str, port: int): |
| 168 | api = AgenticSystemClient(f"http://{host}:{port}") |
| 169 | |
| 170 | urls = [ |
| 171 | "memory_optimizations.rst", |
| 172 | "chat.rst", |
| 173 | "llama3.rst", |
| 174 | "datasets.rst", |
| 175 | "qat_finetune.rst", |
| 176 | "lora_finetune.rst", |
| 177 | ] |
| 178 | attachments = [ |
| 179 | Attachment( |
| 180 | content=URL( |
| 181 | uri=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}" |
| 182 | ), |
| 183 | mime_type="text/plain", |
| 184 | ) |
| 185 | for i, url in enumerate(urls) |
| 186 | ] |
| 187 | |
| 188 | # Alternatively, you can pre-populate the memory bank with documents for example, |
| 189 | # using `llama_toolchain.memory.client`. Then you can grab the bank_id |
| 190 | # from the output of that run. |
| 191 | tool_definitions = [ |
| 192 | MemoryToolDefinition( |
| 193 | max_tokens_in_context=2048, |
| 194 | memory_bank_configs=[], |
| 195 | ), |
| 196 | ] |
| 197 | |
| 198 | user_prompts = [ |
| 199 | "How do I use Lora?", |
| 200 | "Tell me briefly about llama3 and torchtune", |
| 201 | ] |
| 202 | |
| 203 | await _run_agent(api, tool_definitions, user_prompts, attachments) |
| 204 | |
| 205 | |
| 206 | def main(host: str, port: int, rag: bool = False): |
| 207 | fn = run_rag if rag else run_main |
| 208 | asyncio.run(fn(host, port)) |
| 209 | |
| 210 | |
| 211 | if __name__ == "__main__": |
| 212 | fire.Fire(main) |