Agentverse Hosted Agents

Overview

Hosted Agents are cloud-based Agents managed within the Agentverse, enabling developers to deploy and manage Agents without handling infrastructure. These Agents function as lightweight, efficient tasks, resetting global variables after each call. To maintain state across calls, developers must use Agent Storage for stateful behavior.

Developers can start with blank scripts or use customizable templates for common use cases like retrieving stock prices or finding nearby restaurants. Hosted Agents are highly accessible, requiring no local dependencies, and include an agent.py file from which you can develop them straightforwardly.

Let’s explore the process and insights you need to get started with Hosted Agents on Agentverse!

Create Hosted Agents

On the Agentverse you can create and host any type of Agent you want to create using the My Agents tab.

Let’s start by heading over to the Agentverse: My Agents tab, click on the + New Agent. Here, there are 2 different ways you can start creating your agent. You can either choose to create an Agent:

  1. From a Blank Agent.
  2. From a Skeleton Agent.

Here, click on the + New Agent button and choose Blank Agent.

You will need to provide a name for the Agent you wish to create.

Once you select it, your agent will be ready to be coded and a box will appear in the My Agents page with different data being displayed about the agent you have just created, including the name and the address of the agent.

If you click on your agent box, the code editor will be displayed. This is the Agent Editor; it allows you to create, edit and refine the code for the Agent you have in mind all in one place. The Agent editor provides various basic information about your Agent, including the Agent address and wallet address. For additional information on Agent addresses, have a look at our dedicated documentation here.

The Agent Editor has an integrated agent.py and .env files that allow you to start programming immediately! The Agent Editor offers you the option of structuring your project into several file windows, which are located on the left-hand side of the editor window. All you have to do is enter a name for the new file to be added. An additional feature of the Agent Editor is the Agent Logs; a built-in terminal that displays the output of your script after it has been executed. The Agent Logs provides multiple filters for the different log levels.

The Agent Logs feature is available by clicking the third bottom icon on the left side of the Agent Editor. The first and second buttons enable you to explore Agents Secrets and Agent Storage features.

This way, we aim at making Agents’ development as quick and efficient as possible. This is a great tool to determine if your code runs smoothly and to check if any error arises and solve it immediately!

Documentation and customization for your Agents

Whenever you create an Agent, it is always a good practice to provide a README file, metadata and an Agent’s icon for better reference. The README helps in providing a clear and concise overview of the Agent’s purpose, functionality, and setup instructions. You will be able to see this file within your Agent’s Overview page in Agentverse. On the other hand, the Metadata should serve as a structured summary of your Agent’s configuration, such as its name, description, creator details, and any other specific settings or dependencies. This will help your Agents getting higher score on Agentverse Marketplace, thus increasing their discoverability and usage. Head over to the Agents README Structure guide for guidelines and tips on writing your Agents’ README files. Also, check out the Agent Search Optimization guide for a complete overview on how to enhance the discoverability of Agents across the ecosystem.

Check out the following guide if you have a local Agent which you want to register into the Agentverse using a Mailbox or a Proxy. The guide will help in understanding how to enroll the Agent using these tools, how to possibly set up a README file locally and then publish it on Agentverse for your local Agent.

Additionally, every Agent should have a custom icon (i.e., an Avatar) to visually distinguish it from others. This icon improves the Agent’s identity and usability within the Agentverse. It is possible to customize your agent’s avatar by clicking on your current Agent’s avatar icon and choose either an existing avatar or upload your own! You can do this straightforwardly from the full list of your Hosted Agents or from the Agent Editor when editing information for a particular Agent!

Test network (Testnet) vs Main Network (Mainnet)

We can distinguish between:

  • Testnet: it is a separate blockchain environment that developers and users can use to test new features or applications without risking real tokens. It allows for experimentation in a controlled environment.

  • Mainnet: it is the actual production blockchain where real transactions occur with real tokens. It is the live version of the blockchain.

By setting up and experimenting on a testnet first, developers can ensure that everything works as intended before deploying it on the mainnet. This helps in avoiding potential issues or vulnerabilities in a live environment.

Create your first hosted Agent on the Agentverse!

You are now ready to start using the Agentverse to create and edit your Agents in few minutes! Let’s begin with creating a simple Agent printing “Hello world!” in the Agent Logs on an interval of 3 seconds by using the .on_interval() Agent Handler.

Here’s an example:

To run the agent, simply click on the Run button. You can stop the script by clicking on the Stop button.

The output will be printed in the Agent Logs window:

Within the Agent Editor, you can import and utilize a predefined set of modules to develop your ideas. These pre-approved modules offer a diverse range of functionalities, allowing you to build complex Agents. For further information on modules being available within the Agentverse Editor, have a look at the following resource: Agentverse: allowed imports.

For additional information on Agent Handlers, check out this guide.

Support for Local Agent Code

You can now import the Agent class and create your agent with my_agent = Agent(...). Note that this is simply a wrapper for your pre-loaded agent instance, so any custom configuration you add to the Agent will be ignored. This is because the configuration, seed, name, and address for hosted Agents is already set, and is not allowed to be overwritten.

Additionally, you can now use agent.run() method, but this is also not required. Clicking Run will cause your agent to run whether you include this command or not. The main reason for supporting this is to unify local and hosted Agent code, so that your Agent code can run as either local or hosted without any modifications.

Exceptions:

  • Use of Bureau is not allowed as each Agent project can contain only a single Agent.

    Check out the AVCTL - Agentverse Command Line Interface to better understand how to possibly interact with the Agentverse. AVCTL provides multiple features (e.g., authorization and hosting management) allowing developers to log in, set up projects, and deploy Agents on the Agentverse.

uagents

Build fast and lightweight for decentralized scenarios using the uagents Framework. Check out the Agents documentation:

  • Available classes: Model, Context, Protocol.

    Example:

    copy
    1from uagents import Context, Model
    2
    3class Message(Model):
    4 text: str
    5
    6@agent.on_interval(period=2.0)
    7async def print_message(ctx: Context):
    8 msg = Message(text=f"Hello there my wallet address is {ctx.wallet}.")
    9 print(msg.text)

requests

This package allows you to interact with HTTP requests and responses.

  • Available functions: get, post, put, patch, delete.

    Example:

    copy
    1import requests
    2
    3response = requests.get('https://api.github.com')
    4if response.status_code == 200:
    5 print('Success!')
    6elif response.status_code == 404:
    7 print('Not Found.')
    8
    9print(response.headers)

cosmpy

A Python library for interacting with Cosmos-based blockchains. Checkout the CosmPy documentation:

  • Full access to all functions and features.

    Example:

    copy
    1from cosmpy import aerial
    2
    3# Define network configuration, faucet and ledger
    4network = aerial.client.NetworkConfig.fetchai_stable_testnet()
    5faucet_api = aerial.faucet.FaucetApi(network)
    6ledger = aerial.client.LedgerClient(network)
    7
    8MINIMUM_BALANCE = 100000000000000000
    9
    10@agent.on_interval(period=20.0)
    11async def get_tokens(ctx: Context):
    12
    13 agent_balance = ledger.query_bank_balance(ctx.wallet)
    14
    15 if agent_balance < MINIMUM_BALANCE:
    16 print("Providing wealth to agent...")
    17 faucet_api.get_wealth(ctx.wallet)

pydantic

A package to ensure data validation and settings management. It simplifies the process of defining and validating data models by providing a way to declare and enforce data types, constraints, and validation rules on Python data structures.

  • Full access to all functions and features.

    Example:

    copy
    1from pydantic import BaseModel
    2
    3data = {
    4 "name": "alice",
    5 "age": 21
    6}
    7
    8class User(BaseModel):
    9 name: str
    10 age: int
    11
    12user = User(**data)
    13
    14print(user)

MySQLdb

MySQLdb is a Python library for accessing MySQL databases. It provides a Python interface to MySQL, allowing you to interact with MySQL databases from within your Python code.

  • Full access to all functions and features.

    Example:

    copy
    1import MySQLdb
    2
    3# Connect to the MySQL database
    4connection = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database_name')
    5
    6try:
    7 # Create a cursor object to execute SQL queries
    8 cursor = connection.cursor()
    9
    10 # Example query: Select all rows from a table
    11 cursor.execute("SELECT * FROM your_table")
    12
    13 # Print the fetched rows
    14 for row in cursor.fetchall():
    15 print(row)
    16
    17finally:
    18 # Close the cursor and connection
    19 cursor.close()
    20 connection.close()

pymongo

pymongo allows Python applications to interact with MongoDB databases, making it easy to perform various database operations such as inserting, updating, deleting, and querying documents.

  • Full access to all functions and features.

    Example:

    copy
    1from pymongo import MongoClient
    2
    3# Connect to MongoDB server
    4client = MongoClient('mongodb://localhost:27017/')
    5
    6# Access a specific database
    7db = client['my_database']
    8
    9# Access a specific collection within the database
    10collection = db['my_collection']
    11
    12# Insert a document into the collection
    13document = {'name': 'John', 'age': 30, 'city': 'New York'}
    14collection.insert_one(document)
    15
    16# Query documents from the collection
    17query = {'city': 'New York'}
    18result = collection.find(query)
    19
    20# Print the documents returned by the query
    21for doc in result:
    22 print(doc)
    23
    24# Close the connection to MongoDB
    25client.close()

bs4 (BeautifulSoup)

bs4 make it easy to parse and interact with HTML and XML documents for web scraping or data extraction.

Example:

copy
1from bs4 import BeautifulSoup
2import requests
3
4# Fetch the content of a webpage
5response = requests.get("https://example.com")
6
7# Parse the HTML content
8soup = BeautifulSoup(response.content, "html.parser")
9
10# Extract and print the page title
11print(soup.title.string)

faiss-cpu

faiss-cpu allow you to efficiently perform nearest neighbor search on high-dimensional dense vectors. It is used in machine learning for clustering and similarity search.

Example:

copy
1import faiss
2import numpy as np
3
4# Create a dataset of 128-dimensional vectors
5data = np.random.random((100, 128)).astype('float32')
6
7# Create an index using L2 (Euclidean) distance
8index = faiss.IndexFlatL2(128)
9
10# Add vectors to the index
11index.add(data)
12
13# Perform a search to find the 5 nearest neighbors
14query = np.random.random((1, 128)).astype('float32')
15distances, indices = index.search(query, k=5)
16print(indices)

fetchai-babble

fetchai-babble allows you to interact with the Fetch.ai messaging service (called Memorandum):

Example:

copy
1from babble import Client, Identity
2
3# create a set of agents with random identities
4client1 = Client('agent1.....', Identity.generate())
5client2 = Client('agent1.....', Identity.generate())
6
7# send a message from one client to another
8client1.send(client2.delegate_address, "why hello there")
9
10# receive the messages from the other client
11for msg in client2.receive():
12 print(msg.text)

google-generativeai

google-generativeai allows you to build with the Gemini API. The Gemini API gives you access to Gemini models created by Google DeepMind. Gemini models are built from the ground up to be multimodal, so you can reason seamlessly across text, images, and code:

Example:

copy
1import google.generativeai as genai
2import os
3
4genai.configure(api_key=os.environ["GEMINI_API_KEY"])
5
6model = genai.GenerativeModel('gemini-1.5-flash')
7response = model.generate_content("The opposite of hot is")
8print(response.text)

langchain-anthropic

langchain-anthropic contains the LangChain integration for Anthropic’s generative models:

Example:

copy
1from langchain_anthropic import ChatAnthropic
2from langchain_core.messages import AIMessage, HumanMessage
3
4model = ChatAnthropic(model="claude-3-opus-20240229", temperature=0, max_tokens=1024)
5
6message = HumanMessage(content="What is the capital of France?")
7
8response = model.invoke([message])

langchain-community

langchain-community contains third-party integrations that implement the base interfaces defined in LangChain Core, making them ready-to-use in any LangChain application. It is automatically installed by langchain, but can also be used separately:

Example:

copy
1import bs4
2from langchain_community.document_loaders import WebBaseLoader
3
4# Only keep post title, headers, and content from the full HTML.
5bs4_strainer = bs4.SoupStrainer(class_=("post-title", "post-header", "post-content"))
6loader = WebBaseLoader(
7 web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",),
8 bs_kwargs={"parse_only": bs4_strainer},
9)
10docs = loader.load()
11
12len(docs[0].page_content)

langchain-core

langchain-core contains the base abstractions that power the rest of the LangChain ecosystem:

Example:

copy
1from langchain_core.messages import HumanMessage
2from langchain_google_genai import ChatGoogleGenerativeAI
3
4llm = ChatGoogleGenerativeAI(model="gemini-pro-vision")
5# example
6message = HumanMessage(
7 content=[
8 {
9 "type": "text",
10 "text": "What's in this image?",
11 }, # You can optionally provide text parts
12 {"type": "image_url", "image_url": "https://picsum.photos/seed/picsum/200/300"},
13 ]
14)
15llm.invoke([message])

langchain-google-genai

langchain-google-genai contains the LangChain integrations for Gemini through their generative-ai SDK:

Example:

copy
1from langchain_core.messages import HumanMessage
2from langchain_google_genai import ChatGoogleGenerativeAI
3
4llm = ChatGoogleGenerativeAI(model="gemini-pro-vision")
5# example
6message = HumanMessage(
7 content=[
8 {
9 "type": "text",
10 "text": "What's in this image?",
11 }, # You can optionally provide text parts
12 {"type": "image_url", "image_url": "https://picsum.photos/seed/picsum/200/300"},
13 ]
14)
15llm.invoke([message])

langchain-google-vertexai

langchain-google-vertexai contains the LangChain integrations for Google Cloud generative models:

Example:

copy
1from langchain_core.messages import HumanMessage
2from langchain_google_vertexai import ChatVertexAI
3
4llm = ChatVertexAI(model_name="gemini-pro-vision")
5# example
6message = HumanMessage(
7 content=[
8 {
9 "type": "text",
10 "text": "What's in this image?",
11 }, # You can optionally provide text parts
12 {"type": "image_url", "image_url": {"url": "https://picsum.photos/seed/picsum/200/300"}},
13 ]
14)
15llm.invoke([message])

langchain-openai

langchain-openai contains the LangChain integrations for OpenAI through their openai SDK:

Example:

copy
1from langchain_openai import ChatOpenAI
2
3llm = ChatOpenAI(
4 model="gpt-4o",
5 temperature=0,
6 max_tokens=None,
7 timeout=None,
8 max_retries=2,
9 # api_key="...", # if you prefer to pass api key in directly instaed of using env vars
10 # base_url="...",
11 # organization="...",
12 # other params...
13)

langchain-text-splitters

langchain-text-splitters contains utilities for splitting into chunks a wide variety of text documents:

Example:

copy
1from langchain_text_splitters import RecursiveCharacterTextSplitter
2
3text_splitter = RecursiveCharacterTextSplitter(
4 chunk_size=1000, chunk_overlap=200, add_start_index=True
5)
6all_splits = text_splitter.split_documents(docs)
7
8len(all_splits)

langchain

langchain assists in the development of applications integrating with LLMs:

Example:

copy
1import bs4
2from langchain import hub
3from langchain_chroma import Chroma
4from langchain_community.document_loaders import WebBaseLoader
5from langchain_core.output_parsers import StrOutputParser
6from langchain_core.runnables import RunnablePassthrough
7from langchain_openai import OpenAIEmbeddings
8from langchain_text_splitters import RecursiveCharacterTextSplitter
9
10# Load, chunk and index the contents of the blog.
11loader = WebBaseLoader(
12 web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",),
13 bs_kwargs=dict(
14 parse_only=bs4.SoupStrainer(
15 class_=("post-content", "post-title", "post-header")
16 )
17 ),
18)
19docs = loader.load()
20
21text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
22splits = text_splitter.split_documents(docs)
23vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())
24
25# Retrieve and generate using the relevant snippets of the blog.
26retriever = vectorstore.as_retriever()
27prompt = hub.pull("rlm/rag-prompt")
28
29def format_docs(docs):
30 return "\n\n".join(doc.page_content for doc in docs)
31
32rag_chain = (
33 {"context": retriever | format_docs, "question": RunnablePassthrough()}
34 | prompt
35 | llm
36 | StrOutputParser()
37)
38
39rag_chain.invoke("What is Task Decomposition?")

nltk

nltk is a package for natural language processing.

Example:

copy
1import nltk
2nltk.download('punkt')
3
4from nltk.tokenize import word_tokenize
5
6text = "This is an example sentence, showing off the tokenization process."
7
8tokens = word_tokenize(text)
9
10print(tokens)
11
12# ['This', 'is', 'an', 'example', 'sentence', ',', 'showing', 'off', 'the', 'tokenization', 'process', '.']

openai

openai provides easy access to the OpenAI REST API. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

Example:

copy
1import os
2from openai import OpenAI
3
4client = OpenAI(
5 # This is the default and can be omitted
6 api_key=os.environ.get("OPENAI_API_KEY"),
7)
8
9chat_completion = client.chat.completions.create(
10 messages=[
11 {
12 "role": "user",
13 "content": "Say this is a test",
14 }
15 ],
16 model="gpt-3.5-turbo",
17)

tenacity

tenacity is a general-purpose retrying library to simplify the task of adding retry behavior to just about anything.

Example:

copy
1import random
2from tenacity import retry
3
4@retry
5def do_something_unreliable():
6 if random.randint(0, 10) > 1:
7 raise IOError("Broken sauce, everything is hosed!!!111one")
8 else:
9 return "Awesome sauce!"
10
11print(do_something_unreliable())

unstructured

unstructured is a library for processing and extracting data from unstructured file formats such as PDFs, Word documents, and more.

Example:

copy
1from unstructured.partition.auto import partition
2
3elements = partition(filename="example-docs/fake-email.eml")
4print("\n\n".join([str(el) for el in elements]))

validators

validators is a Python library designed for data validation. It provides simple functions to verify the validity of various types of data:

Example:

copy
1import validators
2print(validators.email('someone@example.com')) # True
3print(validators.email('invalid-email')) # ValidationFailure

web3

web3 is a Python library for interacting with the Ethereum blockchain. It provides functionalities for sending transactions, interacting with smart contracts, and querying blockchain data:

Example:

copy
1from web3 import Web3
2
3w3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"))
4
5print(w3.is_connected()) # True if connected to Ethereum network