Build an agent to talk to your APIs
This tutorial helps you make an agent with a custom utility allowing you to run API calls through your agent.
Create Custom Utility Models
Create Google Maps Function
- Set up an account on Google Maps to get your API key
- For custom function, we need to write a function to be later used in the
ModelFactory.create_utility_model
. To learn more about how to write this function, please refer to this guide.
def main(start_location: str, end_location: str):
"""
Get public transport directions from start_location to end_location
"""
import os
try:
import googlemaps
except:
os.system("pip install googlemaps")
import googlemaps
import json
from datetime import datetime
# Set up your Google Maps API key
API_KEY = 'YOUR_GOOGLE_API_KEY' # Replace with your actual API key
# Initialize the Google Maps client
gmaps = googlemaps.Client(key=API_KEY)
# Request directions
now = datetime.now()
directions_result = gmaps.directions(
start_location,
end_location,
mode="transit", # Use "transit" for public transport
departure_time=now
)
try:
directions = []
# Output the directions
for step in directions_result[0]['legs'][0]['steps']:
directions.append({
"instructions": step['html_instructions'],
"duration": step['duration']['text'],
"distance": step['distance']['text']
})
directions = json.dumps(directions)
except:
directions = "No directions found. Please check your input."
return directions
Create Yelp Search Function
Sign up on Yelp if you want to use Yelp Search for your agent.
def main(location: str, term: str):
"""
Get restaurant/coffee shop recommendation in any USA city
"""
import os
import requests
import json
# Set up your Yelp API key
api_key = 'YELP_API_KEY'
# Construct the URL with query parameters
url = f"https://api.yelp.com/v3/businesses/search?location={location}&term={term}&sort_by=best_match&limit=2"
# Set the headers, including the Authorization header
headers = {
"accept": "application/json",
"Authorization": f"Bearer {api_key}"
}
#headers = {"accept": "application/json"}
# Make the GET request to the Yelp API
response = requests.get(url, headers=headers)
# Print the response text
if response.status_code == 200:
#print(response.json()) # Print the JSON response if successful
data = response.json() # Get the JSON response
# Post-process the data to remove unwanted fields
for business in data.get('businesses', []):
# Remove unwanted fields from coordinates
business['coordinates'].pop('longitude', None)
business['coordinates'].pop('latitude', None)
# Remove unwanted fields from location
business['location'].pop('country', None)
business['location'].pop('state', None)
# Remove longitude and latitude from region center
# Remove the entire region dictionary
data.pop('region', None)
return data # Return the modified data
else:
print(f"Error fetching recommendations: {response.status_code} - {response.text}")
return None
Onboard Utility Models
Use the functions defined to create utility models.
from aixplain.enums import DataType
from aixplain.factories import ModelFactory
from aixplain.modules.model.utility_model import UtilityModelInput
utility_model_yelp = ModelFactory.create_utility_model(
name = "Yelp Search",
code = main,
output_examples="This is an example"
)
utility_model_google_maps = ModelFactory.create_utility_model(
name = "Google Maps 2",
code = main,
output_examples="This is an example version"
)
Run the Utility Models
- The output from response will show all the details that come with the API you use for your utility model.
- In this case, Yelp API lets you access the geographical, pricing, menu and other such details. For this tutorial, the focus is on restaurants and cafes in any given location.
response = utility_model_yelp.run({
"location": "San Francisco",
"term": "coffee shop",
})
response
Build an Agent
Create an agent with the custom utilities as tools. This agent uses the Llama 4 Scout Instruct (Basic) model as the llm_id
.
For more details on how to create an agent, refer to this guide.
from aixplain.factories import AgentFactory
from aixplain.enums import Function, Supplier
ROLE = """ You are a chatbot designed to assist people in finding coffee shops, restaurants, and rooftop bars in any city in the USA.
Your primary goal is to answer questions related to restaurants, cafes, coffee shops, and any other food or drinks-related inquiries in an ethical and assertive manner.
When responding, utilize the available tools (Yelp and Google Maps) to provide accurate and relevant recommendations. If the user asks for specific types of establishments or has particular preferences, use the tools to gather data and present it in a clear, concise manner.
If you are unable to provide an answer or require more information, please ask the user for further details or let them know that you are unable to provide the information they seek. Always aim to enhance the user experience by being informative and engaging.
"""
agent = AgentFactory.create(
name="Food and Coffee Recommendation Assistant",
description=ROLE,
tools=[
AgentFactory.create_model_tool(model = utility_model_yelp.id), # Yelp Search
AgentFactory.create_model_tool(model=utility_model_google_maps.id) # Google Maps
],
llm_id="67f3fd7f5014ab221273856f" #Llama 4 Scout Instruct (Basic) Fireworks AI
)
Run your Agent
response = agent.run("What are good coffee shops in San Francisco?")
print(response.data.output)
Deploy your Agent
By default, agents are saved as drafts available for 24 hours. Once you are happy with your agent's responses, deploy
your agent.
agent.deploy()