Agents and Functions Creation using APIs
Introduction
This guide shows how to create Agents and Agent Functions in Agentverse using APIs. With this guide, we set up a Python script that interacts with the Agentverse and help us creating Agents and Agent Functions. Before you begin, it is necessary that you satisfy the following requirements:
- Python version greater than 3.9 and less than 3.11.
- The
requests
library is installed. You can install it using:pip install requests
. - Agentverse (opens in a new tab) credentials.
How to get Agentverse API Tokens
- Log in to your Agentverse (opens in a new tab) account and go to the Profile section.
- 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
How to create Agents and respective Functions
- Open terminal and create a directory
agents
using:mkdir agents
. - Create two Python files,
agent.py
andagent_create.py
, in this directory and include the following sample scripts within them. You can do this using:
windowsecho. > agent.py
windowsecho. > agent_create.py
- Fill in the scripts with the code presented here below for each one of them:
Script 1: agent.py
agent.pyimport requests import json 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(',')) message = location_coordinates(latitude, longitude) ctx.logger.info(f"Location found: {message}") await ctx.send(sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)) agent.include(location_protocol)
Script 2: agent_create.py
This script interacts with the Agentverse API to achieve the Agent and Function creation tasks.
Let's get started!
-
Import the required libraries and set up the authorization token:
# Importing Required libraries import time import requests # Define access token token = 'Bearer <Your_access_token>'
-
Take the agent name from user and store the agent's 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}')
-
Take code from
agent.py
file. Then, store it in a dedicated script for the created agent:# 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
Model
digest and name using Almanac APIs:# 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
-
Now, save all the required details to create the Agent Function. Then, create the Agent Function on the basis of the details received:
# Taking inputs from user for details required to create a function name_function = 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"Function name: {name_function} \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_function, "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}")
Complete Script
agent_create.py# 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 simple_function.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 # Taking inputs from user for details required to create a function name_function = 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"Function name: {name_function} \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_function, "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. - Head over to the Agentverse (opens in a new tab) and generate API keys .
- Open script in editor and replace
token
field. - Run command
python agent_create.py
and enter the required details. - Provide Agent and Function details as asked, then, 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 Function 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:
- Function created on Agentverse: