| 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 json |
| 8 | import re |
| 9 | import tempfile |
| 10 | |
| 11 | from abc import abstractmethod |
| 12 | from typing import List, Optional |
| 13 | |
| 14 | import requests |
| 15 | from termcolor import cprint |
| 16 | |
| 17 | from .ipython_tool.code_execution import ( |
| 18 | CodeExecutionContext, |
| 19 | CodeExecutionRequest, |
| 20 | CodeExecutor, |
| 21 | TOOLS_ATTACHMENT_KEY_REGEX, |
| 22 | ) |
| 23 | |
| 24 | from llama_stack.apis.inference import * # noqa: F403 |
| 25 | from llama_stack.apis.agents import * # noqa: F403 |
| 26 | |
| 27 | from .base import BaseTool |
| 28 | |
| 29 | |
| 30 | def 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 | |
| 42 | class 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 | |
| 66 | class 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 | |
| 86 | class SearchTool(SingleMessageBuiltinTool): |
| 87 | def __init__(self, engine: SearchEngineType, api_key: str, **kwargs) -> None: |
| 88 | self.api_key = api_key |
| 89 | if engine == SearchEngineType.bing: |
| 90 | self.engine = BingSearch(api_key, **kwargs) |
| 91 | elif engine == SearchEngineType.brave: |
| 92 | self.engine = BraveSearch(api_key, **kwargs) |
| 93 | else: |
| 94 | raise ValueError(f"Unknown search engine: {engine}") |
| 95 | |
| 96 | def get_name(self) -> str: |
| 97 | return BuiltinTool.brave_search.value |
| 98 | |
| 99 | async def run_impl(self, query: str) -> str: |
| 100 | return await self.engine.search(query) |
| 101 | |
| 102 | |
| 103 | class BingSearch: |
| 104 | def __init__(self, api_key: str, top_k: int = 3, **kwargs) -> None: |
| 105 | self.api_key = api_key |
| 106 | self.top_k = top_k |
| 107 | |
| 108 | async def search(self, query: str) -> str: |
| 109 | url = "https://api.bing.microsoft.com/v7.0/search" |
| 110 | headers = { |
| 111 | "Ocp-Apim-Subscription-Key": self.api_key, |
| 112 | } |
| 113 | params = { |
| 114 | "count": self.top_k, |
| 115 | "textDecorations": True, |
| 116 | "textFormat": "HTML", |
| 117 | "q": query, |
| 118 | } |
| 119 | |
| 120 | response = requests.get(url=url, params=params, headers=headers) |
| 121 | response.raise_for_status() |
| 122 | clean = self._clean_response(response.json()) |
| 123 | return json.dumps(clean) |
| 124 | |
| 125 | def _clean_response(self, search_response): |
| 126 | clean_response = [] |
| 127 | query = search_response["queryContext"]["originalQuery"] |
| 128 | if "webPages" in search_response: |
| 129 | pages = search_response["webPages"]["value"] |
| 130 | for p in pages: |
| 131 | selected_keys = {"name", "url", "snippet"} |
| 132 | clean_response.append( |
| 133 | {k: v for k, v in p.items() if k in selected_keys} |
| 134 | ) |
| 135 | if "news" in search_response: |
| 136 | clean_news = [] |
| 137 | news = search_response["news"]["value"] |
| 138 | for n in news: |
| 139 | selected_keys = {"name", "url", "description"} |
| 140 | clean_news.append({k: v for k, v in n.items() if k in selected_keys}) |
| 141 | |
| 142 | clean_response.append(clean_news) |
| 143 | |
| 144 | return {"query": query, "top_k": clean_response} |
| 145 | |
| 146 | |
| 147 | class BraveSearch: |
| 148 | def __init__(self, api_key: str) -> None: |
| 149 | self.api_key = api_key |
| 150 | |
| 151 | async def search(self, query: str) -> str: |
| 152 | url = "https://api.search.brave.com/res/v1/web/search" |
| 153 | headers = { |
| 154 | "X-Subscription-Token": self.api_key, |
| 155 | "Accept-Encoding": "gzip", |
| 156 | "Accept": "application/json", |
| 157 | } |
| 158 | payload = {"q": query} |
| 159 | response = requests.get(url=url, params=payload, headers=headers) |
| 160 | return json.dumps(self._clean_brave_response(response.json())) |
| 161 | |
| 162 | def _clean_brave_response(self, search_response, top_k=3): |
| 163 | query = None |
| 164 | clean_response = [] |
| 165 | if "query" in search_response: |
| 166 | if "original" in search_response["query"]: |
| 167 | query = search_response["query"]["original"] |
| 168 | if "mixed" in search_response: |
| 169 | mixed_results = search_response["mixed"] |
| 170 | for m in mixed_results["main"][:top_k]: |
| 171 | r_type = m["type"] |
| 172 | results = search_response[r_type]["results"] |
| 173 | if r_type == "web": |
| 174 | # For web data - add a single output from the search |
| 175 | idx = m["index"] |
| 176 | selected_keys = [ |
| 177 | "type", |
| 178 | "title", |
| 179 | "url", |
| 180 | "description", |
| 181 | "date", |
| 182 | "extra_snippets", |
| 183 | ] |
| 184 | cleaned = { |
| 185 | k: v for k, v in results[idx].items() if k in selected_keys |
| 186 | } |
| 187 | elif r_type == "faq": |
| 188 | # For faw data - take a list of all the questions & answers |
| 189 | selected_keys = ["type", "question", "answer", "title", "url"] |
| 190 | cleaned = [] |
| 191 | for q in results: |
| 192 | cleaned.append( |
| 193 | {k: v for k, v in q.items() if k in selected_keys} |
| 194 | ) |
| 195 | elif r_type == "infobox": |
| 196 | idx = m["index"] |
| 197 | selected_keys = [ |
| 198 | "type", |
| 199 | "title", |
| 200 | "url", |
| 201 | "description", |
| 202 | "long_desc", |
| 203 | ] |
| 204 | cleaned = { |
| 205 | k: v for k, v in results[idx].items() if k in selected_keys |
| 206 | } |
| 207 | elif r_type == "videos": |
| 208 | selected_keys = [ |
| 209 | "type", |
| 210 | "url", |
| 211 | "title", |
| 212 | "description", |
| 213 | "date", |
| 214 | ] |
| 215 | cleaned = [] |
| 216 | for q in results: |
| 217 | cleaned.append( |
| 218 | {k: v for k, v in q.items() if k in selected_keys} |
| 219 | ) |
| 220 | elif r_type == "locations": |
| 221 | # For faw data - take a list of all the questions & answers |
| 222 | selected_keys = [ |
| 223 | "type", |
| 224 | "title", |
| 225 | "url", |
| 226 | "description", |
| 227 | "coordinates", |
| 228 | "postal_address", |
| 229 | "contact", |
| 230 | "rating", |
| 231 | "distance", |
| 232 | "zoom_level", |
| 233 | ] |
| 234 | cleaned = [] |
| 235 | for q in results: |
| 236 | cleaned.append( |
| 237 | {k: v for k, v in q.items() if k in selected_keys} |
| 238 | ) |
| 239 | elif r_type == "news": |
| 240 | # For faw data - take a list of all the questions & answers |
| 241 | selected_keys = [ |
| 242 | "type", |
| 243 | "title", |
| 244 | "url", |
| 245 | "description", |
| 246 | ] |
| 247 | cleaned = [] |
| 248 | for q in results: |
| 249 | cleaned.append( |
| 250 | {k: v for k, v in q.items() if k in selected_keys} |
| 251 | ) |
| 252 | else: |
| 253 | cleaned = [] |
| 254 | |
| 255 | clean_response.append(cleaned) |
| 256 | |
| 257 | return {"query": query, "top_k": clean_response} |
| 258 | |
| 259 | |
| 260 | class WolframAlphaTool(SingleMessageBuiltinTool): |
| 261 | def __init__(self, api_key: str) -> None: |
| 262 | self.api_key = api_key |
| 263 | self.url = "https://api.wolframalpha.com/v2/query" |
| 264 | |
| 265 | def get_name(self) -> str: |
| 266 | return BuiltinTool.wolfram_alpha.value |
| 267 | |
| 268 | async def run_impl(self, query: str) -> str: |
| 269 | params = { |
| 270 | "input": query, |
| 271 | "appid": self.api_key, |
| 272 | "format": "plaintext", |
| 273 | "output": "json", |
| 274 | } |
| 275 | response = requests.get( |
| 276 | self.url, |
| 277 | params=params, |
| 278 | ) |
| 279 | |
| 280 | return json.dumps(self._clean_wolfram_alpha_response(response.json())) |
| 281 | |
| 282 | def _clean_wolfram_alpha_response(self, wa_response): |
| 283 | remove = { |
| 284 | "queryresult": [ |
| 285 | "datatypes", |
| 286 | "error", |
| 287 | "timedout", |
| 288 | "timedoutpods", |
| 289 | "numpods", |
| 290 | "timing", |
| 291 | "parsetiming", |
| 292 | "parsetimedout", |
| 293 | "recalculate", |
| 294 | "id", |
| 295 | "host", |
| 296 | "server", |
| 297 | "related", |
| 298 | "version", |
| 299 | { |
| 300 | "pods": [ |
| 301 | "scanner", |
| 302 | "id", |
| 303 | "error", |
| 304 | "expressiontypes", |
| 305 | "states", |
| 306 | "infos", |
| 307 | "position", |
| 308 | "numsubpods", |
| 309 | ] |
| 310 | }, |
| 311 | "assumptions", |
| 312 | ], |
| 313 | } |
| 314 | for main_key in remove: |
| 315 | for key_to_remove in remove[main_key]: |
| 316 | try: |
| 317 | if key_to_remove == "assumptions": |
| 318 | if "assumptions" in wa_response[main_key]: |
| 319 | del wa_response[main_key][key_to_remove] |
| 320 | if isinstance(key_to_remove, dict): |
| 321 | for sub_key in key_to_remove: |
| 322 | if sub_key == "pods": |
| 323 | for i in range(len(wa_response[main_key][sub_key])): |
| 324 | if ( |
| 325 | wa_response[main_key][sub_key][i]["title"] |
| 326 | == "Result" |
| 327 | ): |
| 328 | del wa_response[main_key][sub_key][i + 1 :] |
| 329 | break |
| 330 | sub_items = wa_response[main_key][sub_key] |
| 331 | for i in range(len(sub_items)): |
| 332 | for sub_key_to_remove in key_to_remove[sub_key]: |
| 333 | if sub_key_to_remove in sub_items[i]: |
| 334 | del sub_items[i][sub_key_to_remove] |
| 335 | elif key_to_remove in wa_response[main_key]: |
| 336 | del wa_response[main_key][key_to_remove] |
| 337 | except KeyError: |
| 338 | pass |
| 339 | return wa_response |
| 340 | |
| 341 | |
| 342 | class CodeInterpreterTool(BaseTool): |
| 343 | def __init__(self) -> None: |
| 344 | ctx = CodeExecutionContext( |
| 345 | matplotlib_dump_dir=tempfile.mkdtemp(), |
| 346 | ) |
| 347 | self.code_executor = CodeExecutor(ctx) |
| 348 | |
| 349 | def get_name(self) -> str: |
| 350 | return BuiltinTool.code_interpreter.value |
| 351 | |
| 352 | async def run(self, messages: List[CompletionMessage]) -> List[ToolResponseMessage]: |
| 353 | message = messages[0] |
| 354 | assert len(message.tool_calls) == 1, "Expected a single tool call" |
| 355 | |
| 356 | tool_call = messages[0].tool_calls[0] |
| 357 | script = tool_call.arguments["code"] |
| 358 | |
| 359 | req = CodeExecutionRequest(scripts=[script]) |
| 360 | res = self.code_executor.execute(req) |
| 361 | |
| 362 | pieces = [res["process_status"]] |
| 363 | for out_type in ["stdout", "stderr"]: |
| 364 | res_out = res[out_type] |
| 365 | if res_out != "": |
| 366 | pieces.extend([f"[{out_type}]", res_out, f"[/{out_type}]"]) |
| 367 | if out_type == "stderr": |
| 368 | cprint(f"ipython tool error: ↓\n{res_out}", color="red") |
| 369 | |
| 370 | message = ToolResponseMessage( |
| 371 | call_id=tool_call.call_id, |
| 372 | tool_name=tool_call.tool_name, |
| 373 | content="\n".join(pieces), |
| 374 | ) |
| 375 | return [message] |