-
Notifications
You must be signed in to change notification settings - Fork 757
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
migrate tools and make tool runtime discover
- Loading branch information
Showing
13 changed files
with
1,007 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
llama_stack/providers/inline/tool_runtime/meta_reference/tools/base.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
from abc import ABC, abstractmethod | ||
from typing import Any, Dict, Optional, Type, TypeVar | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
class BaseTool(ABC): | ||
"""Base class for all tools""" | ||
|
||
requires_api_key: bool = False | ||
|
||
def __init__(self, config: Optional[Dict[str, Any]] = None): | ||
self.config = config or {} | ||
|
||
@classmethod | ||
@abstractmethod | ||
def tool_id(cls) -> str: | ||
"""Unique identifier for the tool""" | ||
pass | ||
|
||
@abstractmethod | ||
async def execute(self, **kwargs) -> Any: | ||
"""Execute the tool with given arguments""" | ||
pass | ||
|
||
@classmethod | ||
def get_provider_config_type(cls) -> Optional[Type[T]]: | ||
"""Override to specify a Pydantic model for tool configuration""" | ||
return None |
67 changes: 67 additions & 0 deletions
67
llama_stack/providers/inline/tool_runtime/meta_reference/tools/bing_search.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
import json | ||
from typing import List | ||
|
||
import requests | ||
|
||
from llama_stack.providers.inline.tool_runtime.meta_reference.tools.base import BaseTool | ||
from pydantic import BaseModel | ||
|
||
|
||
class BingSearchConfig(BaseModel): | ||
api_key: str | ||
max_results: int = 5 | ||
|
||
|
||
class BingSearchTool(BaseTool): | ||
requires_api_key: bool = True | ||
|
||
@classmethod | ||
def tool_id(cls) -> str: | ||
return "bing_search" | ||
|
||
@classmethod | ||
def get_provider_config_type(cls): | ||
return BingSearchConfig | ||
|
||
async def execute(self, query: str) -> List[dict]: | ||
config = BingSearchConfig(**self.config) | ||
url = "https://api.bing.microsoft.com/v7.0/search" | ||
headers = { | ||
"Ocp-Apim-Subscription-Key": config.api_key, | ||
} | ||
params = { | ||
"count": config.max_results, | ||
"textDecorations": True, | ||
"textFormat": "HTML", | ||
"q": query, | ||
} | ||
|
||
response = requests.get(url=url, params=params, headers=headers) | ||
response.raise_for_status() | ||
return json.dumps(self._clean_response(response.json())) | ||
|
||
def _clean_response(self, search_response): | ||
clean_response = [] | ||
query = search_response["queryContext"]["originalQuery"] | ||
if "webPages" in search_response: | ||
pages = search_response["webPages"]["value"] | ||
for p in pages: | ||
selected_keys = {"name", "url", "snippet"} | ||
clean_response.append( | ||
{k: v for k, v in p.items() if k in selected_keys} | ||
) | ||
if "news" in search_response: | ||
clean_news = [] | ||
news = search_response["news"]["value"] | ||
for n in news: | ||
selected_keys = {"name", "url", "description"} | ||
clean_news.append({k: v for k, v in n.items() if k in selected_keys}) | ||
clean_response.append(clean_news) | ||
|
||
return {"query": query, "results": clean_response} |
101 changes: 101 additions & 0 deletions
101
llama_stack/providers/inline/tool_runtime/meta_reference/tools/brave_search.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
from typing import List | ||
|
||
import requests | ||
|
||
from llama_stack.providers.inline.tool_runtime.meta_reference.tools.base import BaseTool | ||
from pydantic import BaseModel | ||
|
||
|
||
class BraveSearchConfig(BaseModel): | ||
api_key: str | ||
max_results: int = 3 | ||
|
||
|
||
class BraveSearchTool(BaseTool): | ||
requires_api_key: bool = True | ||
|
||
@classmethod | ||
def tool_id(cls) -> str: | ||
return "brave_search" | ||
|
||
@classmethod | ||
def get_provider_config_type(cls): | ||
return BraveSearchConfig | ||
|
||
async def execute(self, query: str) -> List[dict]: | ||
config = BraveSearchConfig(**self.config) | ||
url = "https://api.search.brave.com/res/v1/web/search" | ||
headers = { | ||
"X-Subscription-Token": config.api_key, | ||
"Accept-Encoding": "gzip", | ||
"Accept": "application/json", | ||
} | ||
payload = {"q": query} | ||
response = requests.get(url=url, params=payload, headers=headers) | ||
response.raise_for_status() | ||
return self._clean_brave_response(response.json(), config.max_results) | ||
|
||
def _clean_brave_response(self, search_response, top_k=3): | ||
query = None | ||
clean_response = [] | ||
if "query" in search_response: | ||
if "original" in search_response["query"]: | ||
query = search_response["query"]["original"] | ||
if "mixed" in search_response: | ||
mixed_results = search_response["mixed"] | ||
for m in mixed_results["main"][:top_k]: | ||
r_type = m["type"] | ||
results = search_response[r_type]["results"] | ||
cleaned = self._clean_result_by_type(r_type, results, m.get("index")) | ||
clean_response.append(cleaned) | ||
|
||
return {"query": query, "results": clean_response} | ||
|
||
def _clean_result_by_type(self, r_type, results, idx=None): | ||
type_cleaners = { | ||
"web": ( | ||
["type", "title", "url", "description", "date", "extra_snippets"], | ||
lambda x: x[idx], | ||
), | ||
"faq": (["type", "question", "answer", "title", "url"], lambda x: x), | ||
"infobox": ( | ||
["type", "title", "url", "description", "long_desc"], | ||
lambda x: x[idx], | ||
), | ||
"videos": (["type", "url", "title", "description", "date"], lambda x: x), | ||
"locations": ( | ||
[ | ||
"type", | ||
"title", | ||
"url", | ||
"description", | ||
"coordinates", | ||
"postal_address", | ||
"contact", | ||
"rating", | ||
"distance", | ||
"zoom_level", | ||
], | ||
lambda x: x, | ||
), | ||
"news": (["type", "title", "url", "description"], lambda x: x), | ||
} | ||
|
||
if r_type not in type_cleaners: | ||
return [] | ||
|
||
selected_keys, result_selector = type_cleaners[r_type] | ||
results = result_selector(results) | ||
|
||
if isinstance(results, list): | ||
return [ | ||
{k: v for k, v in item.items() if k in selected_keys} | ||
for item in results | ||
] | ||
return {k: v for k, v in results.items() if k in selected_keys} |
53 changes: 53 additions & 0 deletions
53
llama_stack/providers/inline/tool_runtime/meta_reference/tools/code_interpreter.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
import tempfile | ||
from typing import Dict | ||
|
||
from llama_stack.providers.inline.tool_runtime.meta_reference.tools.base import BaseTool | ||
from pydantic import BaseModel | ||
|
||
from .ipython_tool.code_execution import ( | ||
CodeExecutionContext, | ||
CodeExecutionRequest, | ||
CodeExecutor, | ||
) | ||
|
||
|
||
class CodeInterpreterConfig(BaseModel): | ||
matplotlib_dump_dir: str = None | ||
|
||
|
||
class CodeInterpreterTool(BaseTool): | ||
|
||
@classmethod | ||
def tool_id(cls) -> str: | ||
return "code_interpreter" | ||
|
||
@classmethod | ||
def get_provider_config_type(cls): | ||
return CodeInterpreterConfig | ||
|
||
async def execute(self, code: str) -> Dict: | ||
config = CodeInterpreterConfig(**self.config) | ||
|
||
ctx = CodeExecutionContext( | ||
matplotlib_dump_dir=config.matplotlib_dump_dir or tempfile.mkdtemp(), | ||
) | ||
executor = CodeExecutor(ctx) | ||
|
||
req = CodeExecutionRequest(scripts=[code]) | ||
result = executor.execute(req) | ||
|
||
response = {"status": result["process_status"], "output": []} | ||
|
||
for out_type in ["stdout", "stderr"]: | ||
if result[out_type]: | ||
response["output"].append( | ||
{"type": out_type, "content": result[out_type]} | ||
) | ||
|
||
return response |
5 changes: 5 additions & 0 deletions
5
llama_stack/providers/inline/tool_runtime/meta_reference/tools/ipython_tool/__init__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. |
Oops, something went wrong.