Agents and Functions Creation using APIs
Introduction
This example provides details on how to create Agents and respective Agent Functions in Agentverse using APIs. We provide a Python script that interacts with Agentverse allowing us to create Agents and Agent Functions.
Prerequisites
-
Before you begin, ensure you have the following:
- Python version greater than 3.9 and less than 3.11.
- The requests library installed. You can install it using
pip install requests
. - Agentverse (opens in a new tab) Credentials.
Steps to get API Tokens
- Go to Profile section in Agentverse (opens in a new tab).
- Click on button
+ New API Key
. - Give name to your API key.
- Click on
write
forAccess to all resources in Agentverse
and click onGenerate API Key
Steps to create agent and respective function
- Open terminal and create a directory
agents
usingmkdir agents
. - Create a python file
agent.py
in this directory and include the following sample script in the Python file.
import requests
from ai_engine import UAgentResponse, UAgentResponseType
class Coordinates(Model):
location: str
location_protocol = Protocol("Location Coordinates")
async def location_coordinates(latitude, longitude):
url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/reversegeocoding"
querystring = {"lat": latitude, "lon": longitude}
headers = {
"X-RapidAPI-Key": "YOUR_API_KEY",
"X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com",
}
response = requests.get(url, headers=headers, params=querystring)
data = response.json()[0]["name"]
return data
@location_protocol.on_message(model=Coordinates, replies=UAgentResponse)
async def location_coordinates_calculator(ctx: Context, sender: str, msg: Coordinates):
ctx.logger.info(msg.location)
latitude, longitude = map(str.strip, msg.location.split(","))
city = location_coordinates(latitude, longitude)
ctx.logger.info(city)
message = city
await ctx.send(
sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
)
agent.include(location_protocol)
- Create a python file with name
agent_create.py
.
Script breakdown
- Importing required libraries and setting up authorization token:
# Importing Required libraries
import time
import requests
# Define access token
token = 'Bearer <Your_access_token>'
- Taking agent Name from user and storing agent address:
# Take name of agent from user
name = input("Please give name of your agent? ")
# Create payload for agent creation request
agent_creation_data = {"name": name}
# Post request to create an agent and store address
response_agent = requests.post(
"https://agentverse.ai/v1/hosting/agents",
json=agent_creation_data,
headers={"Authorization": token},
).json()
address = response_agent["address"]
print(f"Agent Address : {address}")
- Taking code from
agent.py
file and storing it as created agent script:
# Reading code to be placed in agent
with open("agent.py", "r") as file:
code = file.read()
agent_code_data = {"code": code}
# Creating agent.py script for created agent
response_code_update = requests.put(
f"https://agentverse.ai/v1/hosting/agents/{address}/code",
json=agent_code_data,
headers={"Authorization": token},
)
# Starting the agent
requests.post(
f"https://agentverse.ai/v1/hosting/agents/{address}/start",
headers={"Authorization": token},
)
time.sleep(10) # waiting before getting agent's protocol
- Requesting protocol digest for the created Agent:
# Request to get agent protocol digest
response_protcol = requests.get(
f"https://agentverse.ai/v1/almanac/agents/{address}",
headers={"Authorization": token},
)
protocol_digest = response_protcol.json()["protocols"][1]
print(f"Protocol Digest : {protocol_digest}")
time.sleep(10) # Waiting before getting model_digest
# Request to get agent's model details
response_model = requests.get(
f"https://agentverse.ai/v1/almanac/manifests/protocols/{protocol_digest}",
headers={"Authorization": token},
)
model = response_model.json()["models"]
time.sleep(10) # Waiting before storing details to create functions
function_group_ids = requests.get(
"https://agentverse.ai/v1beta1/function-groups/", headers={"Authorization": token}
)
function_group_id = function_group_ids.json()[0]["uuid"]
time.sleep(10)
- Saving all the details required for creating function and creating function on basis of details received:
# Taking inputs from user for details required to create a function
name_service = input("Please give function name: ")
description = input("Please enter function description: ")
field_name = input("Please enter field name: ")
field_description = input("Please enter field description: ")
tasktype = input("Please tell primary or secondary function: ").upper()
# Logging details provided by user
print(
f"Service name: {name_service} \nFunction Description: {description} \nField Name: {field_name}\nField Description: {field_description}\nTask Type: {tasktype}"
)
# Storing model digest and name to be used for function creation
model_digest = response_model.json()["interactions"][0]["request"].replace("model:", "")
print(f"Model Digest : {model_digest}")
model_name = model[0]["schema"]["title"]
print(f"Model Name : {model_name}")
# Creating payload for function creation
data = {
"agent": address,
"name": name_service,
"description": description,
"protocolDigest": protocol_digest,
"modelDigest": model_digest,
"modelName": model_name,
"arguments": [
{
"name": field_name,
"required": True,
"type": "string",
"description": field_description,
}
],
"type": tasktype,
}
# Requesting AI Engine function API to create a function with created payload and storing the response.
response_function = requests.post(
"https://agentverse.ai/v1beta1/functions/",
json=data,
headers={"Authorization": token},
)
# Storing name of function and printing it to check if function was created successfully
name = response_function.json()["name"]
print(f"Function Created with name: {name}")
Whole Script
# Importing Required libraries
import time
import requests
# Decode the refresh token
token = f'Bearer <Your_access_token>'
# Take name of agent from user
name = input("Please give name of your agent? ")
# Create payload for agent creation request
agent_creation_data = {"name": name}
# Post request to create an agent and store address
response_agent = requests.post(
"https://agentverse.ai/v1/hosting/agents",
json=agent_creation_data,
headers={"Authorization": token},
).json()
address = response_agent["address"]
print(f"Agent Address : {address}")
# Reading code to be placed in agent
with open("agent.py", "r") as file:
code = file.read()
agent_code_data = {"code": code}
# Creating agent.py script for created agent
response_code_update = requests.put(
f"https://agentverse.ai/v1/hosting/agents/{address}/code",
json=agent_code_data,
headers={"Authorization": token},
)
# Starting the agent
requests.post(
f"https://agentverse.ai/v1/hosting/agents/{address}/start",
headers={"Authorization": token},
)
time.sleep(10) # waiting before getting agent's protocol
# Request to get agent protocol digest
response_protcol = requests.get(
f"https://agentverse.ai/v1/almanac/agents/{address}",
headers={"Authorization": token},
)
protocol_digest = response_protcol.json()["protocols"][1]
print(f"Protocol Digest : {protocol_digest}")
time.sleep(10) # Waiting before getting model_digest
# Request to get agent's model details
response_model = requests.get(
f"https://agentverse.ai/v1/almanac/manifests/protocols/{protocol_digest}",
headers={"Authorization": token},
)
model = response_model.json()["models"]
time.sleep(10) # Waiting before storing details to create functions
function_group_ids = requests.get(
"https://agentverse.ai/v1beta1/function-groups/", headers={"Authorization": token}
)
function_group_id = function_group_ids.json()[0]["uuid"]
time.sleep(10)
# Taking inputs from user for details required to create a function
name_service = input("Please give function name: ")
description = input("Please enter function description: ")
field_name = input("Please enter field name: ")
field_description = input("Please enter field description: ")
tasktype = input("Please tell primary or secondary function: ").upper()
# Logging details provided by user
print(
f"Service name: {name_service} \nFunction Description: {description} \nField Name: {field_name}\nField Description: {field_description}\nTask Type: {tasktype}"
)
# Storing model digest and name to be used for function creation
model_digest = response_model.json()["interactions"][0]["request"].replace("model:", "")
print(f"Model Digest : {model_digest}")
model_name = model[0]["schema"]["title"]
print(f"Model Name : {model_name}")
# Creating payload for function creation
data = {
"agent": address,
"name": name_service,
"description": description,
"protocolDigest": protocol_digest,
"modelDigest": model_digest,
"modelName": model_name,
"arguments": [
{
"name": field_name,
"required": True,
"type": "string",
"description": field_description,
}
],
"type": tasktype,
}
# Requesting AI Engine function API to create a function with created payload and storing the response.
response_function = requests.post(
"https://agentverse.ai/v1beta1/functions/",
json=data,
headers={"Authorization": token},
)
# Storing name of function and printing it to check if function was created successfully
name = response_function.json()["name"]
print(f"Function Created with name: {name}")
Steps to run the script
- Open terminal and go to directory
agents
created above. - Make sure
agent.py
andagent_create.py
are in this directory. - Open Agentverse (opens in a new tab) and generate API keys .
- Open script in editor and replace
token
. - Run command
python agent_create.py
and enter the required details. - Provide Agent and Fucntion Details as asked and check agent and function on Agentverse.
Expected Output
- Provide all details asked in the script.
abc@xyz-MacBook-Pro agents % python3 agents_create.py
Please give name of your agent? my first API agent
Agent Address : agent1q06l8hekn859e5rtwufewmyhwghe6j9y00g0wc8u7gcx05cjfk98jyf6lte
Protocol Digest : c7a6f160fd8d8b7cb357dad9b5be420510ce466dbb67051c07caf2b860216b01
Please give function name: location finder
Please enter function description: this function helps to find nearest city using coordinates
Please enter field name: location
Please enter field description: this describes the coordinates of the location in string format longitude latitude
Please tell primary or secondary function: primary
Service name: location finder
Function Description: this function helps to find nearest city using coordinates
Field Name: location
Field Description: this describes the coordinates of the location in string format longitude latitude
Task Type: PRIMARY
Model Digest : 10a2f843c4c92955688d5e7f22fabe79623869eabfcd97d97da83527b436d3e2
Model Name : Coordinates
Function Created with name: location finder
- Agent created on Agentverse
- Fucntion created on Agentverse