Skip to content

Building AI agents, atomically

playing around with a yelp restaurant finder example

KennyVaneetvelde26b9712464a5
diff --git a/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py b/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py
new file mode 100644
index 0000000..1bd10fe
--- /dev/null
+++ b/atomic_agents/lib/tools/yelp_restaurant_finder_tool.py
@@ -0,0 +1,199 @@
+import os
+import requests
+from pydantic import BaseModel, Field
+from typing import List, Optional
+from rich.console import Console
+from rich.table import Table
+from enum import Enum
+
+from atomic_agents.lib.tools.base import BaseTool, BaseToolConfig
+
+################
+# INPUT SCHEMA #
+################
+class YelpCategory(Enum):
+ ITALIAN = "italian"
+ MEXICAN = "mexican"
+ PIZZA = "pizza"
+ SUSHI = "sushi"
+ CHINESE = "chinese"
+ INDIAN = "indian"
+ THAI = "thai"
+ FRENCH = "french"
+ GREEK = "greek"
+ JAPANESE = "japanese"
+ KOREAN = "korean"
+ VIETNAMESE = "vietnamese"
+ AMERICAN = "american"
+ BBQ = "bbq"
+ BURGERS = "burgers"
+ SEAFOOD = "seafood"
+ STEAKHOUSES = "steakhouses"
+ VEGAN = "vegan"
+ VEGETARIAN = "vegetarian"
+
+class PriceRange(Enum):
+ ONE = "1"
+ TWO = "2"
+ THREE = "3"
+ FOUR = "4"
+
+class YelpSearchToolSchema(BaseModel):
+ location: str = Field(..., description="Location to search for food.")
+ term: Optional[str] = Field(None, description="Search term (e.g., 'pizza', 'sushi').")
+ categories: Optional[List[YelpCategory]] = Field(None, description="Categories to filter by (e.g., 'italian, mexican').")
+ price: Optional[List[PriceRange]] = Field(None, description="Price range to filter by (e.g., '1', '2', '3', '4').")
+ open_now: Optional[bool] = Field(False, description="Filter for businesses that are open now.")
+ sort_by: Optional[str] = Field("best_match", description="Sort by criteria (e.g., 'best_match', 'rating', 'review_count', 'distance').")
+ limit: Optional[int] = Field(10, description="Number of results to return.")
+
+ class Config:
+ title = "YelpSearchTool"
+ description = "Tool for searching for food using the Yelp API. Returns a list of businesses with details such as name, rating, and address."
+ json_schema_extra = {
+ "title": title,
+ "description": description
+ }
+
+####################
+# OUTPUT SCHEMA(S) #
+####################
+class YelpSearchResultSchema(BaseModel):
+ name: str
+ url: str
+ rating: float
+ review_count: int
+ address: str
+ phone: Optional[str] = None
+ categories: List[str]
+
+class YelpSearchToolOutputSchema(BaseModel):
+ results: List[YelpSearchResultSchema]
+
+##############
+# TOOL LOGIC #
+##############
+class YelpSearchToolConfig(BaseToolConfig):
+ api_key: str = ""
+ max_results: int = 10
+
+class YelpSearchTool(BaseTool):
+ """
+ Tool for performing searches using the Yelp API based on the provided queries.
+
+ Attributes:
+ input_schema (YelpSearchToolSchema): The schema for the input data.
+ output_schema (YelpSearchToolOutputSchema): The schema for the output data.
+ api_key (str): The API key for the Yelp API.
+ max_results (int): The maximum number of search results to return.
+ """
+ input_schema = YelpSearchToolSchema
+ output_schema = YelpSearchToolOutputSchema
+
+ def __init__(self, config: YelpSearchToolConfig = YelpSearchToolConfig()):
+ """
+ Initializes the YelpSearchTool.
+
+ Args:
+ config (YelpSearchToolConfig): Configuration for the tool, including API key, max results, and optional title and description overrides.
+ """
+ super().__init__(config)
+ self.api_key = config.api_key
+ self.max_results = config.max_results
+
+ def run(self, params: YelpSearchToolSchema) -> YelpSearchToolOutputSchema:
+ """
+ Runs the YelpSearchTool with the given parameters.
+
+ Args:
+ params (YelpSearchToolSchema): The input parameters for the tool, adhering to the input schema.
+ max_results (Optional[int]): The maximum number of search results to return.
+
+ Returns:
+ YelpSearchToolOutputSchema: The output of the tool, adhering to the output schema.
+
+ Raises:
+ ValueError: If the API key is not provided.
+ Exception: If the request to Yelp API fails.
+ """
+ if not self.api_key:
+ raise ValueError("API key is required to use the Yelp API.")
+
+ # Prepare the query parameters
+ query_params = {
+ "location": params.location,
+ "term": params.term,
+ "categories": ",".join([category.value for category in params.categories]) if params.categories else None,
+ "price": ",".join([price.value for price in params.price]) if params.price else None,
+ "sort_by": params.sort_by,
+ "limit": self.max_results
+ }
+
+ # Make the GET request
+ headers = {
+ 'Authorization': f'Bearer {self.api_key}'
+ }
+ response = requests.get("https://api.yelp.com/v3/businesses/search", headers=headers, params=query_params)
+
+ # Check if the request was successful
+ if response.status_code != 200:
+ raise Exception(f"Failed to fetch search results: {response.status_code} {response.reason}")
+
+ results = response.json().get('businesses', [])
+
+ # Convert to output schema format
+ output_results = [
+ YelpSearchResultSchema(
+ name=result['name'],
+ url=result['url'].split('?')[0],
+ rating=result['rating'],
+ review_count=result['review_count'],
+ address=", ".join(result['location']['display_address']),
+ phone=result.get('display_phone'),
+ categories=[category['title'] for category in result['categories']]
+ )
+ for result in results
+ ]
+
+ return YelpSearchToolOutputSchema(results=output_results)
+
+#################
+# EXAMPLE USAGE #
+#################
+if __name__ == "__main__":
+ rich_console = Console()
+ search_tool_instance = YelpSearchTool(config=YelpSearchToolConfig(api_key=os.getenv('YELP_API_KEY'), max_results=10))
+
+ search_input = YelpSearchTool.input_schema(
+ location="Diepenbeek, Belgium",
+ term="",
+ categories=[YelpCategory.PIZZA],
+ price=[PriceRange.ONE, PriceRange.TWO, PriceRange.THREE, PriceRange.FOUR],
+ sort_by="best_match"
+ )
+
+ output = search_tool_instance.run(search_input)
+
+ # Create a table to display the results
+ table = Table(title="Yelp Search Results")
+
+ table.add_column("Name", style="cyan", no_wrap=True)
+ table.add_column("Rating", style="magenta")
+ table.add_column("Review Count", style="magenta")
+ table.add_column("Address", style="green")
+ table.add_column("URL", style="blue")
+ table.add_column("Phone", style="yellow")
+ table.add_column("Categories", style="red")
+
+ for result in output.results:
+ table.add_row(
+ result.name,
+ str(result.rating),
+ str(result.review_count),
+ result.address,
+ result.url,
+ result.phone or "N/A",
+ ", ".join(result.categories)
+ )
+
+ rich_console.print(table)
diff --git a/examples/yelp_restaurant_finder.py b/examples/yelp_restaurant_finder.py
new file mode 100644
index 0000000..5239865
--- /dev/null
+++ b/examples/yelp_restaurant_finder.py
@@ -0,0 +1,102 @@
+import os
+import logging
+from typing import Union
+from pydantic import BaseModel, Field
+import instructor
+import openai
+from rich.console import Console
+
+from atomic_agents.lib.components.chat_memory import ChatMemory
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo
+from atomic_agents.agents.base_chat_agent import BaseChatAgent, BaseChatAgentResponse
+from atomic_agents.lib.tools.yelp_restaurant_finder_tool import YelpSearchTool, YelpSearchToolConfig, YelpSearchToolSchema
+
+# Configure logging
+logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+logger = logging.getLogger(__name__)
+
+# Define system prompt information including background, steps, and output instructions
+system_prompt = SystemPromptInfo(
+ background=[
+ 'This assistant is a restaurant finder AI designed to help users find the best restaurants based on their preferences by asking clarifying questions.',
+ ],
+ steps=[
+ 'Greet the user and introduce yourself as a restaurant finder assistant.',
+ 'Inspect the required Yelp schema and identify the necessary filters.',
+ 'Ask the user questions to gather information for each filter until all required information is clear.',
+ 'Use the chat responses to gather all necessary information from the user.',
+ 'Once all required information is gathered, use the YelpSearchTool schema to search Yelp for restaurants.',
+ ],
+ output_instructions=[
+ 'Provide helpful and relevant information to assist the user.',
+ 'Be friendly and respectful in all interactions.',
+ 'Ensure that the chat responses are used to ask clarifying questions and gather information, and the Yelp schema is used to perform the actual search.'
+ ]
+)
+
+
+# Initialize the system prompt generator with the defined system prompt and dynamic info providers
+system_prompt_generator = SystemPromptGenerator(system_prompt)
+
+# Initialize chat memory to store conversation history
+memory = ChatMemory()
+# Define initial memory with a greeting message from the assistant
+initial_memory = [
+ {'role': 'assistant', 'content': 'Hello, can I help you find a restaurant?'}
+]
+# Load the initial memory into the chat memory
+memory.load(initial_memory)
+
+console = Console()
+
+# Initialize the client
+# For all supported clients such as Anthropic & Gemini, have a look at the `instructor` library documentation.
+client = instructor.from_openai(openai.OpenAI())
+
+# Initialize the YelpSearchTool
+yelp_tool = YelpSearchTool(YelpSearchToolConfig(api_key=os.getenv('YELP_API_KEY'), max_results=10))
+
+# Define a custom response schema that can handle both chat responses and Yelp search tool responses
+class ResponseSchema(BaseModel):
+ chosen_schema: Union[BaseChatAgentResponse, YelpSearchToolSchema] = Field(..., description='The response from the chat agent.')
+
+ class Config:
+ title = 'ResponseSchema'
+ description = 'The response schema for the chat agent.'
+ json_schema_extra = {
+ 'title': title,
+ 'description': description,
+ }
+
+# Create a chat agent with the specified model, system prompt generator, and memory
+agent = BaseChatAgent(
+ client=client,
+ system_prompt_generator=system_prompt_generator,
+ model='gpt-3.5-turbo',
+ memory=memory,
+ output_schema=ResponseSchema
+)
+
+console.print("BaseChatAgent with YelpSearchTool is ready.")
+console.print(f'Agent: {initial_memory[0]["content"]}')
+
+while True:
+ user_input = input('You: ')
+ if user_input.lower() in ['exit', 'quit']:
+ print('Exiting chat...')
+ break
+
+ response = agent.run(user_input)
+
+ # Log the chosen schema
+ logger.info(f'Chosen schema: {response.chosen_schema}')
+
+ # Check the type of the response schema
+ if isinstance(response.chosen_schema, YelpSearchToolSchema):
+ output = yelp_tool.run(response.chosen_schema)
+ agent.memory.add_message('assistant', f'INTERNAL THOUGHT: I have found the following information: {output.results}\n\n I will now summarize the results for the user.')
+ output = agent.run().chosen_schema.response
+ else:
+ output = response.chosen_schema.response
+
+ console.print(f'Agent: {output}')
\ No newline at end of file