| 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 typing import AsyncGenerator |
| 11 | |
| 12 | import fire |
| 13 | import httpx |
| 14 | from dotenv import load_dotenv |
| 15 | |
| 16 | from pydantic import BaseModel |
| 17 | from termcolor import cprint |
| 18 | |
| 19 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 20 | from llama_stack.distribution.datatypes import RemoteProviderConfig |
| 21 | |
| 22 | from .agents import * # noqa: F403 |
| 23 | from .event_logger import EventLogger |
| 24 | |
| 25 | |
| 26 | load_dotenv() |
| 27 | |
| 28 | |
| 29 | async def get_client_impl(config: RemoteProviderConfig, _deps): |
| 30 | return AgentsClient(config.url) |
| 31 | |
| 32 | |
| 33 | def encodable_dict(d: BaseModel): |
| 34 | return json.loads(d.json()) |
| 35 | |
| 36 | |
| 37 | class AgentsClient(Agents): |
| 38 | def __init__(self, base_url: str): |
| 39 | self.base_url = base_url |
| 40 | |
| 41 | async def create_agent(self, agent_config: AgentConfig) -> AgentCreateResponse: |
| 42 | async with httpx.AsyncClient() as client: |
| 43 | response = await client.post( |
| 44 | f"{self.base_url}/agents/create", |
| 45 | json={ |
| 46 | "agent_config": encodable_dict(agent_config), |
| 47 | }, |
| 48 | headers={"Content-Type": "application/json"}, |
| 49 | ) |
| 50 | response.raise_for_status() |
| 51 | return AgentCreateResponse(**response.json()) |
| 52 | |
| 53 | async def create_agent_session( |
| 54 | self, |
| 55 | agent_id: str, |
| 56 | session_name: str, |
| 57 | ) -> AgentSessionCreateResponse: |
| 58 | async with httpx.AsyncClient() as client: |
| 59 | response = await client.post( |
| 60 | f"{self.base_url}/agents/session/create", |
| 61 | json={ |
| 62 | "agent_id": agent_id, |
| 63 | "session_name": session_name, |
| 64 | }, |
| 65 | headers={"Content-Type": "application/json"}, |
| 66 | ) |
| 67 | response.raise_for_status() |
| 68 | return AgentSessionCreateResponse(**response.json()) |
| 69 | |
| 70 | async def create_agent_turn( |
| 71 | self, |
| 72 | request: AgentTurnCreateRequest, |
| 73 | ) -> AsyncGenerator: |
| 74 | async with httpx.AsyncClient() as client: |
| 75 | async with client.stream( |
| 76 | "POST", |
| 77 | f"{self.base_url}/agents/turn/create", |
| 78 | json=encodable_dict(request), |
| 79 | headers={"Content-Type": "application/json"}, |
| 80 | timeout=20, |
| 81 | ) as response: |
| 82 | async for line in response.aiter_lines(): |
| 83 | if line.startswith("data:"): |
| 84 | data = line[len("data: ") :] |
| 85 | try: |
| 86 | jdata = json.loads(data) |
| 87 | if "error" in jdata: |
| 88 | cprint(data, "red") |
| 89 | continue |
| 90 | |
| 91 | yield AgentTurnResponseStreamChunk(**jdata) |
| 92 | except Exception as e: |
| 93 | print(data) |
| 94 | print(f"Error with parsing or validation: {e}") |
| 95 | |
| 96 | |
| 97 | async def _run_agent( |
| 98 | api, model, tool_definitions, tool_prompt_format, user_prompts, attachments=None |
| 99 | ): |
| 100 | agent_config = AgentConfig( |
| 101 | model=model, |
| 102 | instructions="You are a helpful assistant", |
| 103 | sampling_params=SamplingParams(temperature=0.6, top_p=0.9), |
| 104 | tools=tool_definitions, |
| 105 | tool_choice=ToolChoice.auto, |
| 106 | tool_prompt_format=tool_prompt_format, |
| 107 | enable_session_persistence=False, |
| 108 | ) |
| 109 | |
| 110 | create_response = await api.create_agent(agent_config) |
| 111 | session_response = await api.create_agent_session( |
| 112 | agent_id=create_response.agent_id, |
| 113 | session_name="test_session", |
| 114 | ) |
| 115 | |
| 116 | for content in user_prompts: |
| 117 | cprint(f"User> {content}", color="white", attrs=["bold"]) |
| 118 | iterator = api.create_agent_turn( |
| 119 | AgentTurnCreateRequest( |
| 120 | agent_id=create_response.agent_id, |
| 121 | session_id=session_response.session_id, |
| 122 | messages=[ |
| 123 | UserMessage(content=content), |
| 124 | ], |
| 125 | attachments=attachments, |
| 126 | stream=True, |
| 127 | ) |
| 128 | ) |
| 129 | |
| 130 | async for event, log in EventLogger().log(iterator): |
| 131 | if log is not None: |
| 132 | log.print() |
| 133 | |
| 134 | |
| 135 | async def run_llama_3_1(host: str, port: int): |
| 136 | model = "Llama3.1-8B-Instruct" |
| 137 | api = AgentsClient(f"http://{host}:{port}") |
| 138 | |
| 139 | tool_definitions = [ |
| 140 | SearchToolDefinition( |
| 141 | engine=SearchEngineType.brave, |
| 142 | api_key=os.getenv("BRAVE_SEARCH_API_KEY"), |
| 143 | ), |
| 144 | WolframAlphaToolDefinition(api_key=os.getenv("WOLFRAM_ALPHA_API_KEY")), |
| 145 | CodeInterpreterToolDefinition(), |
| 146 | ] |
| 147 | tool_definitions += [ |
| 148 | FunctionCallToolDefinition( |
| 149 | function_name="get_boiling_point", |
| 150 | description="Get the boiling point of a imaginary liquids (eg. polyjuice)", |
| 151 | parameters={ |
| 152 | "liquid_name": ToolParamDefinition( |
| 153 | param_type="str", |
| 154 | description="The name of the liquid", |
| 155 | required=True, |
| 156 | ), |
| 157 | "celcius": ToolParamDefinition( |
| 158 | param_type="str", |
| 159 | description="Whether to return the boiling point in Celcius", |
| 160 | required=False, |
| 161 | ), |
| 162 | }, |
| 163 | ), |
| 164 | ] |
| 165 | |
| 166 | user_prompts = [ |
| 167 | "Who are you?", |
| 168 | "what is the 100th prime number?", |
| 169 | "Search web for who was 44th President of USA?", |
| 170 | "Write code to check if a number is prime. Use that to check if 7 is prime", |
| 171 | "What is the boiling point of polyjuicepotion ?", |
| 172 | ] |
| 173 | await _run_agent(api, model, tool_definitions, ToolPromptFormat.json, user_prompts) |
| 174 | |
| 175 | |
| 176 | async def run_llama_3_2_rag(host: str, port: int): |
| 177 | model = "Llama3.2-3B-Instruct" |
| 178 | api = AgentsClient(f"http://{host}:{port}") |
| 179 | |
| 180 | urls = [ |
| 181 | "memory_optimizations.rst", |
| 182 | "chat.rst", |
| 183 | "llama3.rst", |
| 184 | "datasets.rst", |
| 185 | "qat_finetune.rst", |
| 186 | "lora_finetune.rst", |
| 187 | ] |
| 188 | attachments = [ |
| 189 | Attachment( |
| 190 | content=URL( |
| 191 | uri=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}" |
| 192 | ), |
| 193 | mime_type="text/plain", |
| 194 | ) |
| 195 | for i, url in enumerate(urls) |
| 196 | ] |
| 197 | |
| 198 | # Alternatively, you can pre-populate the memory bank with documents for example, |
| 199 | # using `llama_stack.memory.client`. Then you can grab the bank_id |
| 200 | # from the output of that run. |
| 201 | tool_definitions = [ |
| 202 | MemoryToolDefinition( |
| 203 | max_tokens_in_context=2048, |
| 204 | memory_bank_configs=[], |
| 205 | ), |
| 206 | ] |
| 207 | |
| 208 | user_prompts = [ |
| 209 | "How do I use Lora?", |
| 210 | "Tell me briefly about llama3 and torchtune", |
| 211 | ] |
| 212 | |
| 213 | await _run_agent( |
| 214 | api, model, tool_definitions, ToolPromptFormat.json, user_prompts, attachments |
| 215 | ) |
| 216 | |
| 217 | |
| 218 | async def run_llama_3_2(host: str, port: int): |
| 219 | model = "Llama3.2-3B-Instruct" |
| 220 | api = AgentsClient(f"http://{host}:{port}") |
| 221 | |
| 222 | # zero shot tools for llama3.2 text models |
| 223 | tool_definitions = [ |
| 224 | FunctionCallToolDefinition( |
| 225 | function_name="get_boiling_point", |
| 226 | description="Get the boiling point of a imaginary liquids (eg. polyjuice)", |
| 227 | parameters={ |
| 228 | "liquid_name": ToolParamDefinition( |
| 229 | param_type="str", |
| 230 | description="The name of the liquid", |
| 231 | required=True, |
| 232 | ), |
| 233 | "celcius": ToolParamDefinition( |
| 234 | param_type="bool", |
| 235 | description="Whether to return the boiling point in Celcius", |
| 236 | required=False, |
| 237 | ), |
| 238 | }, |
| 239 | ), |
| 240 | FunctionCallToolDefinition( |
| 241 | function_name="make_web_search", |
| 242 | description="Search the web / internet for more realtime information", |
| 243 | parameters={ |
| 244 | "query": ToolParamDefinition( |
| 245 | param_type="str", |
| 246 | description="the query to search for", |
| 247 | required=True, |
| 248 | ), |
| 249 | }, |
| 250 | ), |
| 251 | ] |
| 252 | |
| 253 | user_prompts = [ |
| 254 | "Who are you?", |
| 255 | "what is the 100th prime number?", |
| 256 | "Who was 44th President of USA?", |
| 257 | # multiple tool calls in a single prompt |
| 258 | "What is the boiling point of polyjuicepotion and pinkponklyjuice?", |
| 259 | ] |
| 260 | await _run_agent( |
| 261 | api, model, tool_definitions, ToolPromptFormat.python_list, user_prompts |
| 262 | ) |
| 263 | |
| 264 | |
| 265 | def main(host: str, port: int, run_type: str): |
| 266 | assert run_type in [ |
| 267 | "tools_llama_3_1", |
| 268 | "tools_llama_3_2", |
| 269 | "rag_llama_3_2", |
| 270 | ], f"Invalid run type {run_type}, must be one of tools_llama_3_1, tools_llama_3_2, rag_llama_3_2" |
| 271 | |
| 272 | fn = { |
| 273 | "tools_llama_3_1": run_llama_3_1, |
| 274 | "tools_llama_3_2": run_llama_3_2, |
| 275 | "rag_llama_3_2": run_llama_3_2_rag, |
| 276 | } |
| 277 | asyncio.run(fn[run_type](host, port)) |
| 278 | |
| 279 | |
| 280 | if __name__ == "__main__": |
| 281 | fire.Fire(main) |