Elffuss BraidHub

kikocis/llama-stack public

22356ba7a140 · 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
9import os
10from typing import AsyncGenerator
11
12import fire
13import httpx
14from dotenv import load_dotenv
15
16from pydantic import BaseModel
17from termcolor import cprint
18
19from llama_models.llama3.api.datatypes import * # noqa: F403
20from llama_stack.distribution.datatypes import RemoteProviderConfig
21
22from .agents import * # noqa: F403
23from .event_logger import EventLogger
24
25
26load_dotenv()
27
28
29async def get_client_impl(config: RemoteProviderConfig, _deps):
30 return AgentsClient(config.url)
31
32
33def encodable_dict(d: BaseModel):
34 return json.loads(d.json())
35
36
37class 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
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_agent(agent_config)
108 session_response = await api.create_agent_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_agent_turn(
116 AgentTurnCreateRequest(
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 = AgentsClient(f"http://{host}:{port}")
134
135 tool_definitions = [
136 SearchToolDefinition(
137 engine=SearchEngineType.brave,
138 api_key=os.getenv("BRAVE_SEARCH_API_KEY"),
139 ),
140 WolframAlphaToolDefinition(api_key=os.getenv("WOLFRAM_ALPHA_API_KEY")),
141 CodeInterpreterToolDefinition(),
142 ]
143 tool_definitions += [
144 FunctionCallToolDefinition(
145 function_name="get_boiling_point",
146 description="Get the boiling point of a imaginary liquids (eg. polyjuice)",
147 parameters={
148 "liquid_name": ToolParamDefinition(
149 param_type="str",
150 description="The name of the liquid",
151 required=True,
152 ),
153 "celcius": ToolParamDefinition(
154 param_type="str",
155 description="Whether to return the boiling point in Celcius",
156 required=False,
157 ),
158 },
159 ),
160 ]
161
162 user_prompts = [
163 "Who are you?",
164 "what is the 100th prime number?",
165 "Search web for who was 44th President of USA?",
166 "Write code to check if a number is prime. Use that to check if 7 is prime",
167 "What is the boiling point of polyjuicepotion ?",
168 ]
169 await _run_agent(api, tool_definitions, user_prompts)
170
171
172async def run_rag(host: str, port: int):
173 api = AgentsClient(f"http://{host}:{port}")
174
175 urls = [
176 "memory_optimizations.rst",
177 "chat.rst",
178 "llama3.rst",
179 "datasets.rst",
180 "qat_finetune.rst",
181 "lora_finetune.rst",
182 ]
183 attachments = [
184 Attachment(
185 content=URL(
186 uri=f"https://raw.githubusercontent.com/pytorch/torchtune/main/docs/source/tutorials/{url}"
187 ),
188 mime_type="text/plain",
189 )
190 for i, url in enumerate(urls)
191 ]
192
193 # Alternatively, you can pre-populate the memory bank with documents for example,
194 # using `llama_stack.memory.client`. Then you can grab the bank_id
195 # from the output of that run.
196 tool_definitions = [
197 MemoryToolDefinition(
198 max_tokens_in_context=2048,
199 memory_bank_configs=[],
200 ),
201 ]
202
203 user_prompts = [
204 "How do I use Lora?",
205 "Tell me briefly about llama3 and torchtune",
206 ]
207
208 await _run_agent(api, tool_definitions, user_prompts, attachments)
209
210
211def main(host: str, port: int, rag: bool = False):
212 fn = run_rag if rag else run_main
213 asyncio.run(fn(host, port))
214
215
216if __name__ == "__main__":
217 fire.Fire(main)