Custom Code
aiXplain allows developers to use custom code as tools within the platform. This guide walks through different techniques for integrating external functionalities, including:
- Adding custom code directly to your agent.
- Onboarding custom code as a utility asset for reuse.
Using Custom Code Directly
You can embed Python code directly into an agent instead of onboarding it as a separate utility model.
Example: Google Maps Directions Utility
The following code snippet fetches driving directions between two locations using the Google Maps API.
def main(start_location: str, end_location: str):
"""
Get driving 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_MAPS_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="driving",
departure_time=now
)
try:
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
Use the code directly in your agent using the create_custom_python_code_tool
method.
from aixplain.factories import AgentFactory
from aixplain.enums import Function, Supplier
ROLE = """You are a chatbot designed to assist tourists in the MENA region.
Your primary goal is to answer questions related to hotels, attractions, transportation, and any other tourism-related inquiries in an ethical and assertive 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."""
agent = AgentFactory.create(
name="MENA Tourist Assistant",
description=ROLE,
tools=[
AgentFactory.create_model_tool(model="6736411cf127849667606689"), # Tavily search
AgentFactory.create_model_tool(model="66f6ac496eb563510e3503d1"), # Google Places API
AgentFactory.create_custom_python_code_tool(code=main),
AgentFactory.create_model_tool(function=Function.TRANSLATION, supplier=Supplier.MICROSOFT), # Translation
]
)
This approach eliminates the need to onboard the function as a separate utility model and allows direct execution within the agent.
Creating and Onboarding a Utility Model
Alternately, utility models allow developers to integrate external services as AI tools for reuse. These models can be created from Python functions and onboarded onto the aiXplain platform for use across agents.
Onboarding the Utility Model
Once the function is defined, you can onboard it as a utility model in aiXplain.
from aixplain.enums import DataType
from aixplain.factories import ModelFactory
from aixplain.modules.model.utility_model import UtilityModelInput
utility_model = ModelFactory.create_utility_model(
name="Google Maps V5",
code=main
)
Now, this model can be executed like any other AI model:
response = utility_model.run({
"start_location": "Riyadh Marriott Hotel",
"end_location": "Sushi Yoshi Riyadh",
})
response
Once created, you can update the utility model and save changes by using the save
method.
utility_model.name = "Google Maps V5 Updated"
utility_model.code = updated_main
utility_model.save()
You can also delete the utility model by using the delete
method.
utility_model.delete()
Adding Utility Models to Agents
Use your utility model as a tool for an agent.
from aixplain.factories import AgentFactory
from aixplain.enums import Function, Supplier
ROLE = """You are a chatbot designed to assist tourists in the MENA region.
Your primary goal is to answer questions related to hotels, attractions, transportation, and any other tourism-related inquiries in an ethical and assertive 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."""
agent = AgentFactory.create(
name="MENA Tourist Assistant",
description=ROLE,
tools=[
AgentFactory.create_model_tool(model="6736411cf127849667606689"), # Tavily search
AgentFactory.create_model_tool(model="66f6ac496eb563510e3503d1"), # Google Places API
AgentFactory.create_model_tool(model=utility_model.id), # Google Maps
AgentFactory.create_model_tool(function=Function.TRANSLATION, supplier=Supplier.MICROSOFT), # Translation
]
)
Formatting the Response
The OutputFormat
enum allows specifying the desired response format when running the agent. It supports:
- OutputFormat.TEXT → Returns plain text output.
- OutputFormat.MARKDOWN → Formats the response in Markdown, allowing structured text elements like headings, bullet points, and emphasis, making it ideal for rich-text displays in chat interfaces, documentation, and web applications.
from aixplain.modules.agent import OutputFormat
response = agent.run("Give me good recommendations of restaurants in Riyadh for steaks. Answer in Arabic", output_format=OutputFormat.MARKDOWN)
print(response["data"]["output"])
Parameters in Custom Code
When adding parameters to custom code, define both required and optional parameters, setting default values where needed. Including clear parameter descriptions improves the readability of function calls and helps agents identify which parameters can be adjusted. Additionally, when documented in the docstring, these parameters can be dynamically modified by inspectors, enhancing flexibility and usability.
def custom_tool(query:str, num_results: int :5) -> str:
"""Searches Google for a given query and returns upto num_results results.
Parameters:
- query (str): The search term.
- num_results (int, optional): The number of search results to return (default 5).
"""
return f"Searching for '{query}' and returning '{num_results}' results..."