Skip to content

Building AI agents, atomically

Update tools to have docstrings + change initializers

KennyVaneetveldeac880aca1d05
diff --git a/atomic_agents/lib/tools/base.py b/atomic_agents/lib/tools/base.py
index 92ee767..1b81d30 100644
--- a/atomic_agents/lib/tools/base.py
+++ b/atomic_agents/lib/tools/base.py
@@ -2,12 +2,40 @@ from typing import Type, Optional
from pydantic import BaseModel
class BaseTool:
+ """
+ Base class for all tools in the Atomic Agents framework.
+
+ Attributes:
+ input_schema (Type[BaseModel]): The schema for the input data.
+ output_schema (Type[BaseModel]): The schema for the output data.
+ tool_name (str): The name of the tool, derived from the input schema's title.
+ tool_description (str): The description of the tool, derived from the input schema's description or overridden by the user.
+ """
+
input_schema: Type[BaseModel]
output_schema: Type[BaseModel]
def __init__(self, tool_description_override: Optional[str] = None):
+ """
+ Initializes the BaseTool with an optional description override.
+
+ Args:
+ tool_description_override (Optional[str]): An optional description to override the default description from the input schema.
+ """
self.tool_name = self.input_schema.Config.title
self.tool_description = tool_description_override or self.input_schema.Config.description
def run(self, params: BaseModel) -> BaseModel:
+ """
+ Runs the tool with the given parameters. This method should be implemented by subclasses.
+
+ Args:
+ params (BaseModel): The input parameters for the tool, adhering to the input schema.
+
+ Returns:
+ BaseModel: The output of the tool, adhering to the output schema.
+
+ Raises:
+ NotImplementedError: If the method is not implemented by a subclass.
+ """
raise NotImplementedError("Subclasses should implement this method")
\ No newline at end of file
diff --git a/atomic_agents/lib/tools/calculator_tool.py b/atomic_agents/lib/tools/calculator_tool.py
index ff85eef..c744ac6 100644
--- a/atomic_agents/lib/tools/calculator_tool.py
+++ b/atomic_agents/lib/tools/calculator_tool.py
@@ -1,10 +1,8 @@
import os
-from typing import Optional
import openai
from pydantic import BaseModel, Field
from sympy import sympify
import instructor
-from openai import OpenAI
from atomic_agents.lib.tools.base import BaseTool
@@ -32,13 +30,39 @@ class CalculatorToolOutputSchema(BaseModel):
# TOOL LOGIC #
################
class CalculatorTool(BaseTool):
+ """
+ Tool for performing calculations based on the provided mathematical expression.
+
+ Attributes:
+ input_schema (CalculatorToolSchema): The schema for the input data.
+ output_schema (CalculatorToolOutputSchema): The schema for the output data.
+ """
input_schema = CalculatorToolSchema
output_schema = CalculatorToolOutputSchema
- def __init__(self, tool_description_override: Optional[str] = None):
- super().__init__(tool_description_override)
+ def __init__(self, *args, **kwargs):
+ """
+ Initializes the CalculatorTool.
+
+ Args:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+ """
+ super().__init__(*args, **kwargs)
def run(self, params: CalculatorToolSchema) -> CalculatorToolOutputSchema:
+ """
+ Runs the CalculatorTool with the given parameters.
+
+ Args:
+ params (CalculatorToolSchema): The input parameters for the tool, adhering to the input schema.
+
+ Returns:
+ CalculatorToolOutputSchema: The output of the tool, adhering to the output schema.
+
+ Raises:
+ ValueError: If there is an error evaluating the expression.
+ """
try:
# Explicitly convert the string form of the expression
parsed_expr = sympify(str(params.expression))
@@ -48,6 +72,7 @@ class CalculatorTool(BaseTool):
except Exception as e:
raise ValueError(f"Error evaluating expression: {e}")
+
#################
# EXAMPLE USAGE #
#################
@@ -69,4 +94,4 @@ if __name__ == "__main__":
)
# Print the result
- print(CalculatorTool().run(result))
\ No newline at end of file
+ print(CalculatorTool(tool_description_override="derp").run(result))
\ No newline at end of file
diff --git a/atomic_agents/lib/tools/searx.py b/atomic_agents/lib/tools/searx.py
index 9de5b69..1fd0ef1 100644
--- a/atomic_agents/lib/tools/searx.py
+++ b/atomic_agents/lib/tools/searx.py
@@ -39,14 +39,44 @@ class SearxNGSearchToolOutputSchema(BaseModel):
# TOOL LOGIC #
##############
class SearxNGSearchTool(BaseTool):
+ """
+ Tool for performing searches on SearxNG based on the provided queries and category.
+
+ Attributes:
+ input_schema (SearxNGSearchToolSchema): The schema for the input data.
+ output_schema (SearxNGSearchToolOutputSchema): The schema for the output data.
+ max_results (int): The maximum number of search results to return.
+ """
input_schema = SearxNGSearchToolSchema
output_schema = SearxNGSearchToolOutputSchema
-
- def __init__(self, tool_description_override: Optional[str] = None, max_results: int = 10):
- super().__init__(tool_description_override)
+
+ def __init__(self, max_results: int = 10, *args, **kwargs):
+ """
+ Initializes the SearxNGSearchTool.
+
+ Args:
+ max_results (int): The maximum number of search results to return.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+ """
+ super().__init__(*args, **kwargs)
self.max_results = max_results
def run(self, params: SearxNGSearchToolSchema, max_results: Optional[int] = None) -> SearxNGSearchToolOutputSchema:
+ """
+ Runs the SearxNGSearchTool with the given parameters.
+
+ Args:
+ params (SearxNGSearchToolSchema): The input parameters for the tool, adhering to the input schema.
+ max_results (Optional[int]): The maximum number of search results to return.
+
+ Returns:
+ SearxNGSearchToolOutputSchema: The output of the tool, adhering to the output schema.
+
+ Raises:
+ ValueError: If the SEARXNG_BASE_URL environment variable is not set.
+ Exception: If the request to SearxNG fails.
+ """
SEARXNG_BASE_URL = os.getenv('SEARXNG_BASE_URL')
if not SEARXNG_BASE_URL:
raise ValueError("SEARXNG_BASE_URL environment variable not set")
@@ -62,7 +92,7 @@ class SearxNGSearchTool(BaseTool):
'language': 'en',
'engines': 'bing,duckduckgo,google,startpage,yandex',
}
-
+
# Add category to query parameters if it is set
if params.category:
query_params['categories'] = params.category
@@ -89,7 +119,7 @@ class SearxNGSearchTool(BaseTool):
if result['url'] not in seen_urls:
unique_results.append(result)
seen_urls.add(result['url'])
-
+
# Filter results to include only those with the correct category if it is set
if params.category:
filtered_results = [result for result in unique_results if result.get('category') == params.category]
@@ -99,14 +129,14 @@ class SearxNGSearchTool(BaseTool):
filtered_results = filtered_results[:max_results or self.max_results]
return SearxNGSearchToolOutputSchema(results=filtered_results)
-
-
+
+
#################
# EXAMPLE USAGE #
#################
if __name__ == "__main__":
rich_console = Console()
-
+
# Initialize the client outside
client = instructor.from_openai(
openai.OpenAI(
@@ -114,16 +144,16 @@ if __name__ == "__main__":
base_url=os.getenv("OPENAI_BASE_URL")
)
)
-
+
# Extract structured data from natural language
result = client.chat.completions.create(
model="gpt-3.5-turbo",
response_model=SearxNGSearchTool.input_schema,
messages=[{"role": "user", "content": "Search for the latest PC gaming news of May 2024 using 3 different queries."}],
)
-
+
rich_console.print(f"Search queries: {result.queries}")
-
+
# Print the result
output = SearxNGSearchTool(max_results=15).run(result)
for i, result in enumerate(output.results):
diff --git a/atomic_agents/lib/tools/user_input_tool.py b/atomic_agents/lib/tools/user_input_tool.py
deleted file mode 100644
index 59d2489..0000000
--- a/atomic_agents/lib/tools/user_input_tool.py
+++ /dev/null
@@ -1,60 +0,0 @@
-import os
-from pydantic import BaseModel, Field
-from typing import Optional
-from rich.console import Console
-import openai
-import instructor
-
-from atomic_agents.lib.tools.base import BaseTool
-
-################
-# INPUT SCHEMA #
-################
-class UserInputToolSchema(BaseModel):
- question: str = Field(..., description="The question to ask the user.")
- context: Optional[str] = Field(None, description="Additional context or information to provide to the user.")
-
- class Config:
- title = "UserInputTool"
- description = "Tool for asking clarifying questions to the user. Use this tool when the AI needs more information or clarification from the user."
- json_schema_extra = {
- "title": title,
- "description": description
- }
-
-####################
-# OUTPUT SCHEMA(S) #
-####################
-class UserInputToolOutputSchema(BaseModel):
- answer: str = Field(..., description="The user's answer to the question.")
-
-##############
-# TOOL LOGIC #
-##############
-class UserInputTool(BaseTool):
- input_schema = UserInputToolSchema
- output_schema = UserInputToolOutputSchema
-
- def __init__(self, tool_description_override: Optional[str] = None):
- super().__init__(tool_description_override)
-
- def run(self, params: UserInputToolSchema) -> UserInputToolOutputSchema:
- print(f"Question: {params.question}")
- if params.context:
- print(f"Context: {params.context}")
- answer = input("Your answer: ")
- return UserInputToolOutputSchema(answer=answer)
-
-#################
-# EXAMPLE USAGE #
-#################
-if __name__ == "__main__":
- rich_console = Console()
-
- question = "What is your favorite color?"
-
- user_input_tool = UserInputTool()
- user_input_params = UserInputToolSchema(question=question)
- user_input_output = user_input_tool.run(user_input_params)
-
- rich_console.print(f"User's answer: {user_input_output.answer}")
\ No newline at end of file
diff --git a/atomic_agents/lib/tools/web_scraping_tool.py b/atomic_agents/lib/tools/web_scraping_tool.py
index bbae0cf..bc769a5 100644
--- a/atomic_agents/lib/tools/web_scraping_tool.py
+++ b/atomic_agents/lib/tools/web_scraping_tool.py
@@ -39,13 +39,36 @@ class WebScrapingToolOutputSchema(BaseModel):
# TOOL LOGIC #
##############
class WebScrapingTool(BaseTool):
+ """
+ Tool for scraping web pages and converting content to markdown.
+
+ Attributes:
+ input_schema (WebScrapingToolSchema): The schema for the input data.
+ output_schema (WebScrapingToolOutputSchema): The schema for the output data.
+ """
input_schema = WebScrapingToolSchema
output_schema = WebScrapingToolOutputSchema
-
- def __init__(self, tool_description_override: Optional[str] = None):
- super().__init__(tool_description_override)
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initializes the WebScrapingTool.
+
+ Args:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+ """
+ super().__init__(*args, **kwargs)
def run(self, params: WebScrapingToolSchema) -> WebScrapingToolOutputSchema:
+ """
+ Runs the WebScrapingTool with the given parameters.
+
+ Args:
+ params (WebScrapingToolSchema): The input parameters for the tool, adhering to the input schema.
+
+ Returns:
+ WebScrapingToolOutputSchema: The output of the tool, adhering to the output schema.
+ """
url = params.url
response = requests.head(url)
content_type = response.headers.get('Content-Type', '')