fetch-logo
ConceptsConceptsGuidesGuidesExamplesExamplesReferencesReferencesAPIsAPIs
GitHub (opens in a new tab)
  • Guides
      • Quickstart
        • What's an Agent?
        • uAgents Framework installation
        • Create your first agent
        • Agents address
        • Communicating with other agents
        • Agent Handlers (on_...)
        • Agents storage functions
        • Public and private Agents
        • Send tokens with Agents
        • Agents Mailboxes
        • Agent Functions
        • Make agents AI Engine compatible
        • Multi-file agent pipeline for AI Engine: Hugging face API to create a multi agent pipeline
        • Options for running local agents
        • Hosted agent
        • Introducing dialogues
        • Almanac Contract
        • Verify messages with Agents
        • Multi-file agent pipeline for AI Engine: Network of Primary and Secondary functions in Agentverse
        • Localwallet
        • Agentverse: Hosted Agents
        • Agentverse: Dice Roll agent
        • Agentverse: Allowed Imports
        • Agentverse: Mailbox
        • Register Agentverse Functions
        • Agentverse Functions: coin toss agent
        • Field descriptions for DeltaV
        • Agentverse Command Line Interface (AVCTL)
        • AVCTL Hosting commands
      • Agents and Functions creation APIs
      • Secret Management APIs
      • How to convert native FET to and from ERC-20 FET
      • How to stake FET tokens
      • Different ways of staking FET
      • Re-delegating staked FET token
      • Reconciliation service
      • How to setup a Multisig Wallet
        • Getting started
        • How to use the Fetch wallet
        • How to stake and claim rewards
        • Address book
        • Connections
        • Fetch Wallet Hardware Connection Guide
        • Installation
        • Connecting to a blockchain
        • Querying balances
        • Wallets and private keys
        • Sending funds
        • Staking
        • Smart contracts
          • Stake auto-compounder
          • Stake optimizer
          • Oracles
          • Wallet top-up
          • Liquidity pool
          • Swap automation
        • Installation️
        • Getting started
        • Keys
          • How to add profiles
          • How to add contract templates
          • How to compile contracts
          • How to deploy contracts
          • Contract interaction
        • Installation
        • How to use chain state snapshots
        • State-synchronization (state-sync)
        • How to set up a validator node
        • How to join a testnet
        • How to run a single node test network
        • Governance
        • How to get testnet tokens via the Token Faucet
          • CLI - Introduction
          • CLI - Managing keys
          • CLI - Managing tokens
          • CLI - Multisig keys
          • CLI - Delegation
          • Governance proposals
      • Agents 101
      • Agents 101 for AI Engine
  • Guides
      • Quickstart
        • What's an Agent?
        • uAgents Framework installation
        • Create your first agent
        • Agents address
        • Communicating with other agents
        • Agent Handlers (on_...)
        • Agents storage functions
        • Public and private Agents
        • Send tokens with Agents
        • Agents Mailboxes
        • Agent Functions
        • Make agents AI Engine compatible
        • Multi-file agent pipeline for AI Engine: Hugging face API to create a multi agent pipeline
        • Options for running local agents
        • Hosted agent
        • Introducing dialogues
        • Almanac Contract
        • Verify messages with Agents
        • Multi-file agent pipeline for AI Engine: Network of Primary and Secondary functions in Agentverse
        • Localwallet
        • Agentverse: Hosted Agents
        • Agentverse: Dice Roll agent
        • Agentverse: Allowed Imports
        • Agentverse: Mailbox
        • Register Agentverse Functions
        • Agentverse Functions: coin toss agent
        • Field descriptions for DeltaV
        • Agentverse Command Line Interface (AVCTL)
        • AVCTL Hosting commands
      • Agents and Functions creation APIs
        • Introduction
        • How to get Agentverse API Tokens
        • How to create Agents and respective Functions
        • Steps to run the script
        • Expected Output
      • Secret Management APIs
      • How to convert native FET to and from ERC-20 FET
      • How to stake FET tokens
      • Different ways of staking FET
      • Re-delegating staked FET token
      • Reconciliation service
      • How to setup a Multisig Wallet
        • Getting started
        • How to use the Fetch wallet
        • How to stake and claim rewards
        • Address book
        • Connections
        • Fetch Wallet Hardware Connection Guide
        • Installation
        • Connecting to a blockchain
        • Querying balances
        • Wallets and private keys
        • Sending funds
        • Staking
        • Smart contracts
          • Stake auto-compounder
          • Stake optimizer
          • Oracles
          • Wallet top-up
          • Liquidity pool
          • Swap automation
        • Installation️
        • Getting started
        • Keys
          • How to add profiles
          • How to add contract templates
          • How to compile contracts
          • How to deploy contracts
          • Contract interaction
        • Installation
        • How to use chain state snapshots
        • State-synchronization (state-sync)
        • How to set up a validator node
        • How to join a testnet
        • How to run a single node test network
        • Governance
        • How to get testnet tokens via the Token Faucet
          • CLI - Introduction
          • CLI - Managing keys
          • CLI - Managing tokens
          • CLI - Multisig keys
          • CLI - Delegation
          • Governance proposals
      • Agents 101
      • Agents 101 for AI Engine
Guides
APIs
Agents and Functions creation APIs

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

  • 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 for Access to all resources in Agentverse and click on Generate API Key

How to create Agents and respective Functions

  1. Open terminal and create a directory agents using: mkdir agents.
  2. Create two Python files, agent.py and agent_create.py, in this directory and include the following sample scripts within them. You can do this using: touch agent.py and touch agent_create.py.
  3. Fill in the scripts with the code presented here below for each one of them:

Script 1: agent.py

import 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(','))
    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)

Script 2: agent_create.py

This script interacts with the Agentverse API to achieve the Agent and Function creation tasks.

Let's get started!

  1. 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>'
  2. 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}')
  3. 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
  4. 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
  5. 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
  6. 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

# 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
 
# 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

  1. Open terminal and go to directory agents created above.
  2. Make sure agent.py and agent_create.py are in this directory.
  3. Head over to the Agentverse ↗️ (opens in a new tab) and generate API keys ↗️.
  4. Open script in editor and replace token field.
  5. Run command python agent_create.py and enter the required details.
  6. 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:

Was this page helpful?

AVCTL Hosting commandsSecret Management APIs
footer-logo

Main website

Integrations

Events

We’re hiring!

Twitter (opens in a new tab)Telegram (opens in a new tab)Discord (opens in a new tab)GitHub (opens in a new tab)Youtube (opens in a new tab)LinkedIn (opens in a new tab)Reddit (opens in a new tab)
Sign up for developer updates