Elffuss BraidHub

kikocis/llama-stack public

7d178b9d269a · 10.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 json
8import re
9import tempfile
10
11from abc import abstractmethod
12from typing import List, Optional
13
14import requests
15from termcolor import cprint
16
17from .ipython_tool.code_execution import (
18 CodeExecutionContext,
19 CodeExecutionRequest,
20 CodeExecutor,
21 TOOLS_ATTACHMENT_KEY_REGEX,
22)
23
24from llama_toolchain.inference.api import * # noqa: F403
25from llama_toolchain.agentic_system.api import * # noqa: F403
26
27from .base import BaseTool
28
29
30def interpret_content_as_attachment(content: str) -> Optional[Attachment]:
31 match = re.search(TOOLS_ATTACHMENT_KEY_REGEX, content)
32 if match:
33 snippet = match.group(1)
34 data = json.loads(snippet)
35 return Attachment(
36 content=URL(uri="file://" + data["filepath"]), mime_type=data["mimetype"]
37 )
38
39 return None
40
41
42class SingleMessageBuiltinTool(BaseTool):
43 async def run(self, messages: List[CompletionMessage]) -> List[ToolResponseMessage]:
44 assert len(messages) == 1, f"Expected single message, got {len(messages)}"
45
46 message = messages[0]
47 assert len(message.tool_calls) == 1, "Expected a single tool call"
48
49 tool_call = messages[0].tool_calls[0]
50
51 query = tool_call.arguments["query"]
52 response: str = await self.run_impl(query)
53
54 message = ToolResponseMessage(
55 call_id=tool_call.call_id,
56 tool_name=tool_call.tool_name,
57 content=response,
58 )
59 return [message]
60
61 @abstractmethod
62 async def run_impl(self, query: str) -> str:
63 raise NotImplementedError()
64
65
66class PhotogenTool(SingleMessageBuiltinTool):
67 def __init__(self, dump_dir: str) -> None:
68 self.dump_dir = dump_dir
69
70 def get_name(self) -> str:
71 return BuiltinTool.photogen.value
72
73 async def run_impl(self, query: str) -> str:
74 """
75 Implement this to give the model an ability to generate images.
76
77 Return:
78 info = {
79 "filepath": str(image_filepath),
80 "mimetype": "image/png",
81 }
82 """
83 raise NotImplementedError()
84
85
86class BraveSearchTool(SingleMessageBuiltinTool):
87 def __init__(self, api_key: str) -> None:
88 self.api_key = api_key
89
90 def get_name(self) -> str:
91 return BuiltinTool.brave_search.value
92
93 async def run_impl(self, query: str) -> str:
94 url = "https://api.search.brave.com/res/v1/web/search"
95 headers = {
96 "X-Subscription-Token": self.api_key,
97 "Accept-Encoding": "gzip",
98 "Accept": "application/json",
99 }
100 payload = {"q": query}
101 response = requests.get(url=url, params=payload, headers=headers)
102 return json.dumps(self._clean_brave_response(response.json()))
103
104 def _clean_brave_response(self, search_response, top_k=3):
105 query = None
106 clean_response = []
107 if "query" in search_response:
108 if "original" in search_response["query"]:
109 query = search_response["query"]["original"]
110 if "mixed" in search_response:
111 mixed_results = search_response["mixed"]
112 for m in mixed_results["main"][:top_k]:
113 r_type = m["type"]
114 results = search_response[r_type]["results"]
115 if r_type == "web":
116 # For web data - add a single output from the search
117 idx = m["index"]
118 selected_keys = [
119 "type",
120 "title",
121 "url",
122 "description",
123 "date",
124 "extra_snippets",
125 ]
126 cleaned = {
127 k: v for k, v in results[idx].items() if k in selected_keys
128 }
129 elif r_type == "faq":
130 # For faw data - take a list of all the questions & answers
131 selected_keys = ["type", "question", "answer", "title", "url"]
132 cleaned = []
133 for q in results:
134 cleaned.append(
135 {k: v for k, v in q.items() if k in selected_keys}
136 )
137 elif r_type == "infobox":
138 idx = m["index"]
139 selected_keys = [
140 "type",
141 "title",
142 "url",
143 "description",
144 "long_desc",
145 ]
146 cleaned = {
147 k: v for k, v in results[idx].items() if k in selected_keys
148 }
149 elif r_type == "videos":
150 selected_keys = [
151 "type",
152 "url",
153 "title",
154 "description",
155 "date",
156 ]
157 cleaned = []
158 for q in results:
159 cleaned.append(
160 {k: v for k, v in q.items() if k in selected_keys}
161 )
162 elif r_type == "locations":
163 # For faw data - take a list of all the questions & answers
164 selected_keys = [
165 "type",
166 "title",
167 "url",
168 "description",
169 "coordinates",
170 "postal_address",
171 "contact",
172 "rating",
173 "distance",
174 "zoom_level",
175 ]
176 cleaned = []
177 for q in results:
178 cleaned.append(
179 {k: v for k, v in q.items() if k in selected_keys}
180 )
181 elif r_type == "news":
182 # For faw data - take a list of all the questions & answers
183 selected_keys = [
184 "type",
185 "title",
186 "url",
187 "description",
188 ]
189 cleaned = []
190 for q in results:
191 cleaned.append(
192 {k: v for k, v in q.items() if k in selected_keys}
193 )
194 else:
195 cleaned = []
196
197 clean_response.append(cleaned)
198
199 return {"query": query, "top_k": clean_response}
200
201
202class WolframAlphaTool(SingleMessageBuiltinTool):
203 def __init__(self, api_key: str) -> None:
204 self.api_key = api_key
205 self.url = "https://api.wolframalpha.com/v2/query"
206
207 def get_name(self) -> str:
208 return BuiltinTool.wolfram_alpha.value
209
210 async def run_impl(self, query: str) -> str:
211 params = {
212 "input": query,
213 "appid": self.api_key,
214 "format": "plaintext",
215 "output": "json",
216 }
217 response = requests.get(
218 self.url,
219 params=params,
220 )
221
222 return json.dumps(self._clean_wolfram_alpha_response(response.json()))
223
224 def _clean_wolfram_alpha_response(self, wa_response):
225 remove = {
226 "queryresult": [
227 "datatypes",
228 "error",
229 "timedout",
230 "timedoutpods",
231 "numpods",
232 "timing",
233 "parsetiming",
234 "parsetimedout",
235 "recalculate",
236 "id",
237 "host",
238 "server",
239 "related",
240 "version",
241 {
242 "pods": [
243 "scanner",
244 "id",
245 "error",
246 "expressiontypes",
247 "states",
248 "infos",
249 "position",
250 "numsubpods",
251 ]
252 },
253 "assumptions",
254 ],
255 }
256 for main_key in remove:
257 for key_to_remove in remove[main_key]:
258 try:
259 if key_to_remove == "assumptions":
260 if "assumptions" in wa_response[main_key]:
261 del wa_response[main_key][key_to_remove]
262 if isinstance(key_to_remove, dict):
263 for sub_key in key_to_remove:
264 if sub_key == "pods":
265 for i in range(len(wa_response[main_key][sub_key])):
266 if (
267 wa_response[main_key][sub_key][i]["title"]
268 == "Result"
269 ):
270 del wa_response[main_key][sub_key][i + 1 :]
271 break
272 sub_items = wa_response[main_key][sub_key]
273 for i in range(len(sub_items)):
274 for sub_key_to_remove in key_to_remove[sub_key]:
275 if sub_key_to_remove in sub_items[i]:
276 del sub_items[i][sub_key_to_remove]
277 elif key_to_remove in wa_response[main_key]:
278 del wa_response[main_key][key_to_remove]
279 except KeyError:
280 pass
281 return wa_response
282
283
284class CodeInterpreterTool(BaseTool):
285 def __init__(self) -> None:
286 ctx = CodeExecutionContext(
287 matplotlib_dump_dir=tempfile.mkdtemp(),
288 )
289 self.code_executor = CodeExecutor(ctx)
290
291 def get_name(self) -> str:
292 return BuiltinTool.code_interpreter.value
293
294 async def run(self, messages: List[CompletionMessage]) -> List[ToolResponseMessage]:
295 message = messages[0]
296 assert len(message.tool_calls) == 1, "Expected a single tool call"
297
298 tool_call = messages[0].tool_calls[0]
299 script = tool_call.arguments["code"]
300
301 req = CodeExecutionRequest(scripts=[script])
302 res = self.code_executor.execute(req)
303
304 pieces = [res["process_status"]]
305 for out_type in ["stdout", "stderr"]:
306 res_out = res[out_type]
307 if res_out != "":
308 pieces.extend([f"[{out_type}]", res_out, f"[/{out_type}]"])
309 if out_type == "stderr":
310 cprint(f"ipython tool error: ↓\n{res_out}", color="red")
311
312 message = ToolResponseMessage(
313 call_id=tool_call.call_id,
314 tool_name=tool_call.tool_name,
315 content="\n".join(pieces),
316 )
317 return [message]