Build a Web3 dApp with a Swarm of AI Agents

Imagine building a decentralized application (dApp) based on simple prompts—no manual coding required. In this tutorial, you'll learn how to use SwarmZero.ai to create a swarm of AI agents that collaboratively build a web3 dApp. These agents work together to execute tasks and deliver a functional dApp, demonstrating the power of decentralized AI.

Whether you want to create an NFT minting platform, a DAO, or a simple DeFi to-do application, this agent-driven process simplifies building complex dApps by distributing tasks across multiple agents.

Prerequisites

Before starting, ensure you have the following:

  • Python 3.11 or higher installed

  • Git installed

  • An IDE or text editor (VS Code, PyCharm, etc.)

  • Basic understanding of Python programming

  • API keys from OpenAI, Anthropic, and Mistral

Step-by-Step Tutorial for Building a dApp with Swarm

Below is the step-by-step tutorial to build the swarm which will autonomously create a dApp.

Cloning the Repository

First, clone the repository containing the base code for building your dApp.

Step 1: Open your terminal or command prompt and run the following commands:

git clone https://github.com/hivenetwork-ai/example-agents/
cd dapp_builder

These commands will download the repository and set up the directory to start working on the agent.

Setting Up the Environment

Now, set up the environment required to run the agent.

Step 1: Create a virtual environment:

python -m venv ./venv

Step 2: Activate the virtual environment:

  • On Windows

    • Command Prompt:

      venv\Scripts\activate.bat
    • PowerShell:

      venv\Scripts\Activate.ps1
  • On Linux/Mac:

    venv/bin/activate

Installing Dependencies

With the environment activated, install the required dependencies:

pip install -r requirements.txt

Setting Up Environment Variables

Step 1: Create a new file called .env in the root directory:

touch .env

Step 2: Copy the contents of .env.example into your new .env file.

Step 3: Add your API keys to the .env file:

OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
MISTRAL_API_KEY=your_mistral_api_key

Understanding the Code Structure

The repository contains essential components for running the dApp builder:

  • hive_swarm folder: Houses the agents responsible for various tasks in the dApp environment and helper tools for Hive's ecosystem.

  • swarm.py: The main script orchestrating the swarm agents, and controlling task distribution.

  • main.py: The core driver script where you input prompts and interact with the agents.

  • .env: Stores your API keys and configuration.

  • requirements.txt: Lists dependencies needed to run the agents.

Setting Up the QA Agent

Before creating a swarm, it's essential to set up individual components such as the QA Engineer agent for code review, and utility tools to manage the output generated by swarm. These foundational steps ensure that the multiple agents can perform their tasks efficiently.

Once these are in place, we can move on to creating the swarm. Next, we create the inmain.py, which coordinates the tasks across multiple specialized agents and runs them.

The following code defines a QA agent using the HiveAgent class, tailored to perform code reviews as a Quality Assurance Engineer within the project:

# qa-engineer - agent.py
from hive_agent import HiveAgent
from hive_swarm.agents.instructions import QA_ENGINEER_INSTRUCTION
 
def get_qa_agent(sdk_context):

    sdk_context.add_agent_config("./hive_swarm/agents/qa_engineer/hive_config.toml")

    qa_agent = HiveAgent(
        name="Quality Assurance Engineer Agent",
        description="This agent acts like a QA Engineer on a team and can review code.",
        instruction=QA_ENGINEER_INSTRUCTION,
        role="QA engineer",
        functions=[],
        swarm_mode=True,
        sdk_context=sdk_context,
    )

    return qa_agent

In this example:

  • The agent is named "Quality Assurance Engineer Agent" and its role is set to "QA engineer."

  • The agent uses the instruction set QA_ENGINEER_INSTRUCTION to guide its task as a code reviewer.

  • The agent operates in swarm mode and uses the configuration file hive_config.toml to set its environment.

QA Agent Configuration File

Here’s the configuration file (hive_config.toml) that defines key settings for the QA agent, such as the model, environment, and timeout period:

# qa-engineer - config file
[Quality_Assurance_Engineer_Agent]
model = "mistral-large-latest"
environment = "dev"
timeout = 60

This configuration sets up the QA agent to use the mistral-large-latest model, with a 60-second timeout, and operates in the development environment.


Tools for Managing Code Output

Alongside the QA agent, you should also include utility functions to help save and organize code output generated by the agents. Below is the code for the save_to_file function and its supporting files.

File Saving Function

The core utility for saving the agent's output is found in the files.py module. It ensures that content is saved to a specified file path and handles directory creation if needed:

# tools/files.py
import os

def save_to_file(content: str, file_name: str, file_path: str) -> None:
    """
    Saves the given content to a file at the specified path with the specified file name.

    :param content: The content to be written to the file.
    :param file_name: The name of the file to save the content in.
    :param file_path: The path where the file should be saved.
    """

    # ensure the directory exists
    os.makedirs(file_path, exist_ok=True)

    # construct the full file path
    full_path = os.path.join(file_path, file_name)

    # write the content to the file
    with open(full_path, "w") as file:
        file.write(content)

    print(f"File saved to {full_path}")

This function:

  • Accepts the content, file name, and file path as parameters.

  • Creates the necessary directories if they do not already exist.

  • Writes the content to the specified file and confirms the save operation.

Tools Initialization

The __init__.py file allows importing the save_to_file function from the files.py module:

# tools/__init__.py
from .files import save_to_file

Creating the Swarm

1. Import Required Libraries

First, you need to import the necessary libraries and modules that will be used in building your AI swarm. This includes HiveSwarm for managing the swarm, save_to_file for saving outputs, and SDKContext for context management.

from hive_agent import HiveSwarm
from hive_swarm.tools import save_to_file

from dotenv import load_dotenv
load_dotenv()

from hive_agent.sdk_context import SDKContext
from hive_swarm.agents.qa_engineer.agent import get_qa_agent

2. Load Environment Variables

Use load_dotenv() to load environment variables from a .env file. This is essential for configuring your environment and accessing necessary credentials.

from dotenv import load_dotenv
load_dotenv()

3. Creating the Configuration File

In previous sections, we explored how to configure a single AI agent using a configuration file, setting up essential parameters like the model, environment, and task instructions. However, the configuration file can also be extended to support multiple AI agents, each tailored to specific roles within a software development project.

By assigning distinct models, environments, and task instructions for roles like project management, frontend development, backend development, and Solidity smart contract development, the config file ensures that each agent performs its designated tasks efficiently.

Additionally, the tools for saving outputs in designated folders help keep the workflow organized across all agents.

[model]
model = "gpt-4o"

[environment]
type = "dev"

[timeout]
llm = 60

[Project_Manager_Agent]
model = "gpt-4o"
environment="dev"
timeout = 30
instruction= """
You are a project manager on a software development team and you should provide guidance, \
planning, clarity and instruction on how to build the project.
"""

[Frontend_Developer_Agent]
model = "claude-3-opus-20240229"
environment="dev"
timeout = 60
instruction= """
You are a frontend developer on a team that produces clean, working React code in Typescript. You must \
output all the code to the `./hive-agent-data/output/<users_task_name_goes_here>/frontend` folder \
using the provided tools. Return only code, do not return anything else unless explicitly instructed \
otherwise.
"""
tools=[
    { module = "hive_swarm.tools", name = "save_to_file" }
]

[Backend_Developer_Agent]
model = "claude-3-opus-20240229"
environment="dev"
timeout = 60
instruction= """
You are a backend developer on a team that produces clean, working server code in Express.js. \
You use Typescript as much as possible rather than Javascript. You must output all the code to \
the `./hive-agent-data/output/<users_task_name_goes_here>/backend` folder using the provided \
tools. Return only code, do not return anything else unless explicitly instructed otherwise.
"""
tools=[
    { module = "hive_swarm.tools", name = "save_to_file" }
]

[Solidity_Developer_Agent]
model = "claude-3-opus-20240229"
environment = "dev"
timeout = 60
instruction= """
You are a Solidity smart contract developer on a team that produces clean, working smart contracts \
in Solidity. You must output all the code to the \
`./hive-agent-data/output/<users_task_name_goes_here>/contracts` folder using the provided tools. \
Return only code, do not return anything else unless explicitly instructed otherwise.
"""
tools=[
    { module = "hive_swarm.tools", name = "save_to_file" }
]

4. Create an SDK Context

Define the path to your configuration file (hive_config.toml) and create an SDKContext instance. This context will manage the configuration settings for the swarm.

config_path = "./hive_swarm/hive_config.toml"
sdk_context = SDKContext(config_path=config_path)

5. Initialize the HiveSwarm

Create an instance of HiveSwarm. Set its name, description, and instructions on how it should operate. Provide the functions it will use (e.g., save_to_file) and pass the previously created SDKContext.

dapp_swarm = HiveSwarm(
    name="DeFi Startup",
    description="A swarm of agents that collaborate as members of a DeFi (Decentralized Finance) startup.",
    instruction="You are a DeFi Startup whose goal is to create new DeFi products for your customers. You are to "
    "output working code that satisfies the user's needs. You must output all the code to the "
    "`./hive-agent-data/output/<users_task_name_goes_here>/<code_type_name_goes_here>` folder using the provided tools.",
    functions=[save_to_file],
    sdk_context=sdk_context, # We created sdkcontext to pass context to another agent.
    #config_path=config_path, # If you don't want to add agent you can pass config_path and remove sdkcontext to swarm it will create sdkcontext for you.
)

6. Add the QA Agent

Use get_qa_agent() to create a QA agent with the SDKContext. Add this QA agent to the swarm to enable quality assurance functionalities.

qa_agent = get_qa_agent(sdk_context)
dapp_swarm.add_agent(qa_agent)

If needed, you can remove the QA agent from the swarm. This is optional and can be done if you no longer require the QA functionalities.

# dapp_swarm.remove_agent(qa_agent)

Creating main.pyto run the Swarm

Step 1: Import Necessary Libraries

Open main.py and ensure the following libraries are imported:

import asyncio
from dotenv import load_dotenv
from hive_swarm import dapp_swarm

Step 2: Load Environment Variables

Load the environment variables from the .env file containing your API keys:

load_dotenv()

Step 3: Define the Agent and Process Prompts

The agent listens for user prompts, fetches related tasks, and returns a response.

async def main():
    print("Welcome to the dApp Builder Swarm!\nVisit https://swarmzero.ai to learn more.\nType 'exit' to quit.\n")
    while True:
        prompt = input("\n\nEnter your prompt: \n\n")
        if prompt.lower() == "exit":
            break
        response = await dapp_swarm.chat(prompt)
        print(response)

Step 4: Run the Agent

In the same script, execute the main function that runs the agent:

if __name__ == "__main__":
    asyncio.run(main())

Running the Agent

Now that everything is set up, let's run the dApp builder.

Step 1: Run the agent:

(venv) python main.py

Step 2: Input your prompt:

Build a dApp for an NFT collection where each NFT represents a unique LLM

The agents will process the task and generate the code, which will be stored in hive-agent-data/output.

Output

Once you’ve input a prompt, the swarm of AI agents will collaboratively work to build the requested dApp. You can check the generated code in the output folder. Additionally, explore the functionality further by testing the generated dApp.

Wrap Up

Congratulations! You've successfully built a decentralized application using SwarmZero.ai and its AI-driven agents. The next step is exploring more complex prompts, refining the agents' capabilities, and diving deeper into decentralized AI-powered development.

By using SwarmZero, you're tapping into a powerful ecosystem where AI agents collaborate to achieve real-world tasks, including building web3 applications!

Last updated