Elffuss BraidHub

kikocis/llama-stack public

63314e75ef83 · 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 jdata = json.loads(data)
87 if "error" in jdata:
88 cprint(data, "red")
89 continue
90
91 yield AgenticSystemTurnResponseStreamChunk(**jdata)
92 except Exception as e:
93 print(data)
94 print(f"Error with parsing or validation: {e}")
95
96
97async 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 )
106
107 create_response = await api.create_agentic_system(agent_config)
108 session_response = await api.create_agentic_system_session(
109 agent_id=create_response.agent_id,
110 session_name="test_session",
111 )
112
113 for content in user_prompts:
114 cprint(f"User> {content}", color="white", attrs=["bold"])
115 iterator = api.create_agentic_system_turn(
116 AgenticSystemTurnCreateRequest(
117 agent_id=create_response.agent_id,
118 session_id=session_response.session_id,
119 messages=[
120 UserMessage(content=content),
121 ],
122 attachments=attachments,
123 stream=True,
124 )
125 )
126
127 async for event, log in EventLogger().log(iterator):
128 if log is not None:
129 log.print()
130
131
132async def run_main(host: str, port: int):
133 api = AgenticSystemClient(f"http://{host}:{port}")
134
135 tool_definitions = [
136 SearchToolDefinition(engine=SearchEngineType.bing),
137 WolframAlphaToolDefinition(),
138 CodeInterpreterToolDefinition(),
139 ]
140 tool_definitions += [
141 FunctionCallToolDefinition(
142 function_name="get_boiling_point",
143 description="Get the boiling point of a imaginary liquids (eg. polyjuice)",
144 parameters={
145 "liquid_name": ToolParamDefinition(
146 param_type="str",
147 description="The name of the liquid",
148 required=True,
149 ),
150 "celcius": ToolParamDefinition(
151 param_type="str",
152 description="Whether to return the boiling point in Celcius",
153 required=False,
154 ),
155 },
156 ),
157 ]
158
159 user_prompts = [
160 "Who are you?",
161 "what is the 100th prime number?",
162 "Search web for who was 44th President of USA?",
163 "Write code to check if a number is prime. Use that to check if 7 is prime",
164 "What is the boiling point of polyjuicepotion ?",
165 ]
166 await _run_agent(api, tool_definitions, user_prompts)
167
168
169async def run_rag(host: str, port: int):
170 api = AgenticSystemClient(f"http://{host}:{port}")
171
172 urls = [
173 "memory_optimizations.rst",
174 "chat.rst",
175 "llama3.rst",
176 "datasets.rst",
177 "qat_finetune.rst",
178 "lora_finetune.rst",
179 ]
180 attachments = [
181 Attachment(
182 content=URL(
183 uri=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}"
184 ),
185 mime_type="text/plain",
186 )
187 for i, url in enumerate(urls)
188 ]
189
190 # Alternatively, you can pre-populate the memory bank with documents for example,
191 # using `llama_toolchain.memory.client`. Then you can grab the bank_id
192 # from the output of that run.
193 tool_definitions = [
194 MemoryToolDefinition(
195 max_tokens_in_context=2048,
196 memory_bank_configs=[],
197 ),
198 ]
199
200 user_prompts = [
201 "How do I use Lora?",
202 "Tell me briefly about llama3 and torchtune",
203 ]
204
205 await _run_agent(api, tool_definitions, user_prompts, attachments)
206
207
208def main(host: str, port: int, rag: bool = False):
209 fn = run_rag if rag else run_main
210 asyncio.run(fn(host, port))
211
212
213if __name__ == "__main__":
214 fire.Fire(main)