| 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(api, tool_definitions, user_prompts, attachments=None): |
| 98 | agent_config = AgentConfig( |
| 99 | model="Meta-Llama3.1-8B-Instruct", |
| 100 | instructions="You are a helpful assistant", |
| 101 | sampling_params=SamplingParams(temperature=1.0, top_p=0.9), |
| 102 | tools=tool_definitions, |
| 103 | tool_choice=ToolChoice.auto, |
| 104 | tool_prompt_format=ToolPromptFormat.function_tag, |
| 105 | enable_session_persistence=False, |
| 106 | ) |
| 107 | |
| 108 | create_response = await api.create_agent(agent_config) |
| 109 | session_response = await api.create_agent_session( |
| 110 | agent_id=create_response.agent_id, |
| 111 | session_name="test_session", |
| 112 | ) |
| 113 | |
| 114 | for content in user_prompts: |
| 115 | cprint(f"User> {content}", color="white", attrs=["bold"]) |
| 116 | iterator = api.create_agent_turn( |
| 117 | AgentTurnCreateRequest( |
| 118 | agent_id=create_response.agent_id, |
| 119 | session_id=session_response.session_id, |
| 120 | messages=[ |
| 121 | UserMessage(content=content), |
| 122 | ], |
| 123 | attachments=attachments, |
| 124 | stream=True, |
| 125 | ) |
| 126 | ) |
| 127 | |
| 128 | async for event, log in EventLogger().log(iterator): |
| 129 | if log is not None: |
| 130 | log.print() |
| 131 | |
| 132 | |
| 133 | async def run_main(host: str, port: int): |
| 134 | api = AgentsClient(f"http://{host}:{port}") |
| 135 | |
| 136 | tool_definitions = [ |
| 137 | SearchToolDefinition( |
| 138 | engine=SearchEngineType.brave, |
| 139 | api_key=os.getenv("BRAVE_SEARCH_API_KEY"), |
| 140 | ), |
| 141 | WolframAlphaToolDefinition(api_key=os.getenv("WOLFRAM_ALPHA_API_KEY")), |
| 142 | CodeInterpreterToolDefinition(), |
| 143 | ] |
| 144 | tool_definitions += [ |
| 145 | FunctionCallToolDefinition( |
| 146 | function_name="get_boiling_point", |
| 147 | description="Get the boiling point of a imaginary liquids (eg. polyjuice)", |
| 148 | parameters={ |
| 149 | "liquid_name": ToolParamDefinition( |
| 150 | param_type="str", |
| 151 | description="The name of the liquid", |
| 152 | required=True, |
| 153 | ), |
| 154 | "celcius": ToolParamDefinition( |
| 155 | param_type="str", |
| 156 | description="Whether to return the boiling point in Celcius", |
| 157 | required=False, |
| 158 | ), |
| 159 | }, |
| 160 | ), |
| 161 | ] |
| 162 | |
| 163 | user_prompts = [ |
| 164 | "Who are you?", |
| 165 | "what is the 100th prime number?", |
| 166 | "Search web for who was 44th President of USA?", |
| 167 | "Write code to check if a number is prime. Use that to check if 7 is prime", |
| 168 | "What is the boiling point of polyjuicepotion ?", |
| 169 | ] |
| 170 | await _run_agent(api, tool_definitions, user_prompts) |
| 171 | |
| 172 | |
| 173 | async def run_rag(host: str, port: int): |
| 174 | api = AgentsClient(f"http://{host}:{port}") |
| 175 | |
| 176 | urls = [ |
| 177 | "memory_optimizations.rst", |
| 178 | "chat.rst", |
| 179 | "llama3.rst", |
| 180 | "datasets.rst", |
| 181 | "qat_finetune.rst", |
| 182 | "lora_finetune.rst", |
| 183 | ] |
| 184 | attachments = [ |
| 185 | Attachment( |
| 186 | content=URL( |
| 187 | uri=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}" |
| 188 | ), |
| 189 | mime_type="text/plain", |
| 190 | ) |
| 191 | for i, url in enumerate(urls) |
| 192 | ] |
| 193 | |
| 194 | # Alternatively, you can pre-populate the memory bank with documents for example, |
| 195 | # using `llama_stack.memory.client`. Then you can grab the bank_id |
| 196 | # from the output of that run. |
| 197 | tool_definitions = [ |
| 198 | MemoryToolDefinition( |
| 199 | max_tokens_in_context=2048, |
| 200 | memory_bank_configs=[], |
| 201 | ), |
| 202 | ] |
| 203 | |
| 204 | user_prompts = [ |
| 205 | "How do I use Lora?", |
| 206 | "Tell me briefly about llama3 and torchtune", |
| 207 | ] |
| 208 | |
| 209 | await _run_agent(api, tool_definitions, user_prompts, attachments) |
| 210 | |
| 211 | |
| 212 | def main(host: str, port: int, rag: bool = False): |
| 213 | fn = run_rag if rag else run_main |
| 214 | asyncio.run(fn(host, port)) |
| 215 | |
| 216 | |
| 217 | if __name__ == "__main__": |
| 218 | fire.Fire(main) |