Elffuss BraidHub

kikocis/llama-stack public

7d178b9d269a · 6.8 KiBRawPermalink
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
7import asyncio
8import json
9from typing import AsyncGenerator
10
11import fire
12
13import httpx
14
15from pydantic import BaseModel
16from termcolor import cprint
17
18from llama_models.llama3.api.datatypes import * # noqa: F403
19from llama_toolchain.core.datatypes import RemoteProviderConfig
20
21from .api import * # noqa: F403
22from .event_logger import EventLogger
23
24
25async def get_client_impl(config: RemoteProviderConfig, _deps):
26 return AgenticSystemClient(config.url)
27
28
29def encodable_dict(d: BaseModel):
30 return json.loads(d.json())
31
32
33class 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={
77 "request": encodable_dict(request),
78 },
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 if "error" in data:
87 cprint(data, "red")
88 continue
89
90 yield AgenticSystemTurnResponseStreamChunk(
91 **json.loads(data)
92 )
93 except Exception as e:
94 print(data)
95 print(f"Error with parsing or validation: {e}")
96
97
98async def _run_agent(api, tool_definitions, user_prompts, attachments=None):
99 agent_config = AgentConfig(
100 model="Meta-Llama3.1-8B-Instruct",
101 instructions="You are a helpful assistant",
102 sampling_params=SamplingParams(temperature=1.0, top_p=0.9),
103 tools=tool_definitions,
104 tool_choice=ToolChoice.auto,
105 tool_prompt_format=ToolPromptFormat.function_tag,
106 )
107
108 create_response = await api.create_agentic_system(agent_config)
109 session_response = await api.create_agentic_system_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_agentic_system_turn(
117 AgenticSystemTurnCreateRequest(
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
133async def run_main(host: str, port: int):
134 api = AgenticSystemClient(f"http://{host}:{port}")
135
136 tool_definitions = [
137 BraveSearchToolDefinition(),
138 WolframAlphaToolDefinition(),
139 CodeInterpreterToolDefinition(),
140 ]
141 tool_definitions += [
142 FunctionCallToolDefinition(
143 function_name="get_boiling_point",
144 description="Get the boiling point of a imaginary liquids (eg. polyjuice)",
145 parameters={
146 "liquid_name": ToolParamDefinition(
147 param_type="str",
148 description="The name of the liquid",
149 required=True,
150 ),
151 "celcius": ToolParamDefinition(
152 param_type="str",
153 description="Whether to return the boiling point in Celcius",
154 required=False,
155 ),
156 },
157 ),
158 ]
159
160 user_prompts = [
161 "Who are you?",
162 "what is the 100th prime number?",
163 "Search web for who was 44th President of USA?",
164 "Write code to check if a number is prime. Use that to check if 7 is prime",
165 "What is the boiling point of polyjuicepotion ?",
166 ]
167 await _run_agent(api, tool_definitions, user_prompts)
168
169
170async def run_rag(host: str, port: int):
171 api = AgenticSystemClient(f"http://{host}:{port}")
172
173 urls = [
174 "memory_optimizations.rst",
175 "chat.rst",
176 "llama3.rst",
177 "datasets.rst",
178 "qat_finetune.rst",
179 "lora_finetune.rst",
180 ]
181 attachments = [
182 Attachment(
183 content=URL(
184 uri=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}"
185 ),
186 mime_type="text/plain",
187 )
188 for i, url in enumerate(urls)
189 ]
190
191 # Alternatively, you can pre-populate the memory bank with documents for example,
192 # using `llama_toolchain.memory.client`. Then you can grab the bank_id
193 # from the output of that run.
194 tool_definitions = [
195 MemoryToolDefinition(
196 max_tokens_in_context=2048,
197 memory_bank_configs=[],
198 ),
199 ]
200
201 user_prompts = [
202 "How do I use Lora?",
203 "Tell me briefly about llama3 and torchtune",
204 ]
205
206 await _run_agent(api, tool_definitions, user_prompts, attachments)
207
208
209def main(host: str, port: int, rag: bool = False):
210 fn = run_rag if rag else run_main
211 asyncio.run(fn(host, port))
212
213
214if __name__ == "__main__":
215 fire.Fire(main)