How to Begin Building with BafCode and Earn Money

Hello, developers. I hope you're all coding well. In today's tutorial, we will demonstrate how to begin with BafCode and build AI agents that can generate revenue for you as a developer.

Introduction

Let's make one thing clear from the start: suppose you have already built your first AI agent with BafCode. You might be wondering how to earn money from a BafCode AI agent. Well, thanks to BafCloudโ€”a unified platform that offers developers all the necessary tools and features to manage and build AI projects, and is 100% compatible with BafCode. I haven't yet answered your question, but essentially, BafCloud provides a product called Agents APIs, which is a library of ready-to-use AI agent APIs that developers can easily and quickly integrate into their projects through the BafCloud API. To use these AI agents APIs, developers must pay an hourly usage fee. Now, it starts to become clear: if you're interested in building AI agents using BafCode, you can deploy them as AI Agent APIs in BafCloud and begin earning profits from any other developer who uses them. Interesting, right?

Building and Deploying AI Agents

Before we begin, I need to explain what BafCode is and why you should choose BafCode over other AI agent frameworks.

BafCode is an open-source framework designed to assist developers in creating useful AI agents without worrying about the AI automation part. Developers can build AI agents without limitations and connect these agents with any API or library worldwide, focusing solely on creating Agent Tools. Agent Tools are the only aspect you need to understand and develop to construct a useful AI agent using BafCode. Let me explain how Agent Tools actually work.

To understand Agent Tools, it's crucial to comprehend how the BafCode framework operates.

The BafCode Framework Components

The BafCode Framework consists of three core components: the Manager, Master, and Responder.

When you send an API request to a BafCode agent containing the task description in the body, it is first received by the Manager. The Manager reads the task description and generates a task list based on its understanding of the description to achieve the request's goal successfully. One notable feature of the Manager is its ability to review the tools you've created and generate a task list based on those available tools. Thus, the tasks will be accomplished because the Manager always generates a task list that the agent can proceed with and complete using the available tools.

This means that to create a useful agent, you must develop all the tools you believe are necessary to handle various tasks and empower your AI agent.

Manager Component Trick

First, I want to inform you that each core component is guided by a prompt, so the Manager has a prompt with instructions that guide it to generate the task list efficiently.

You can find the prompt in src/prompts/manager_prompt.py:

# Python code snippet for ManagerPrompt
from core import BafLog

# Optionally, import any other required modules or packages

class ManagerPromptPrompt:  # Replace ManagerPrompt with the name of your prompt
    
    def manager_prompt_prompt(task,data):
        from tools import command_mapping
        tools_list = list(command_mapping)
        prompt = """

            Rules: 
            - You can only use the tools listed above.
            - You can use a tool multiple times.
            - Don't generate tasks that are not related to the user's request or input.
            - Don't generate duplicate tasks.
            - Don't generate Tasks that can't be completed by the tools.
            - if tools can't be used to generate tasks, return an empty array.
            - if what the user requested is not clear, return an empty array.
            - if what user request was simple and can

            
            User Input:
            {task}

            Given a user's request or input, provide a list of tasks to be executed in response to the request. Each task should be detailed, clear, and actionable. Please format your response as an array of task objects. Each task object should have the following attributes:

            - `id`: A unique identifier for the task.
            - `description`: A brief description of the task detailing what needs to be done.
            - `status`: Indicate the current status of the task. This can be "pending", "in-progress", or "completed".
            - `results`: A string detailing the results of the task. This should be empty if the task is still pending or in-progress.

            
            For example:

            [
                {{
                    "id": "T001",
                    "description": "Authenticate user credentials",
                    "status": "pending"
                    "results": ""
                }},
                {{
                    "id": "T002",
                    "description": "Query database for user data",
                    "status": "pending"
                    "results": ""
                }}
            ]

            Now, based on the provided input, list out the tasks in the specified format.

            This is the available list of tools that you need to generate tasks based on available tools:
            {tools_list}



        """
        return prompt.format(data=data,tools_list=tools_list)

You can modify this prompt according to your needs. The current version is useful and flexible, but you can incorporate your preferred rules. If you are developing an AI agent designed to perform specific tasks, you can alter the Manager prompt to generate a task list that aligns exclusively with the workflow you specify.

Master Component

Now, let's discuss the Master component. It's quite straightforward: this component simply decides which tool to use for a task received from the Manager, executes it, and returns the results to the Manager. The Manager then stores the results in the Task Object and sends the next task to the Master again.

The Master Component also has a prompt located in the prompts folder. However, I recommend not modifying it because it solely instructs the Master on deciding which tool to use.

Responder Component

Finally, the Responder Component is responsible for returning the final response to the user based on the prompt instructions. By default, the task results are passed to the Responder, and the prompt instructs the component to provide a concise and straightforward summary of the agent's actions.

You can modify the prompt of the Responder in src/prompts/responder_prompt.py:



class ResponderPrompt:
    def generate_final_response(data):
       prompt = """ 
                Role: You are the dedicated component responsible for creating eloquent, accurate, and user-friendly responses for the client side.

                Input: You receive the results of tasks that the manager provides to the agent.

                Objective: Your primary mission is to deeply comprehend these results, ensuring no nuance is lost. Once understood, you will craft a beautiful, coherent, and precise response tailored to the client's needs.

                Key Focus:

                Comprehension: Before responding, ensure that you have a thorough understanding of the results provided by the manager.
                Articulation: It's not just about responding, but doing so in a manner that is clear, engaging, and resonates with the client.
                Accuracy: Every response should reflect the data and results accurately, avoiding potential misunderstandings.
                User-Centric: The ultimate goal is client satisfaction. Thus, every response should be framed in a manner that is relatable and helpful to the client.
                Mission: You are the final bridge between the system and the client, ensuring that every piece of information, no matter how complex, is conveyed beautifully and understandably. You are not just a component; you're the voice of the system to the outside world.
                Rules: Don't say anything about the process between you and the manager,just understand the results and respond to the client like you know the response.
                Input: {data}

           """
       return prompt.format(data=data)

    

Creating Tools with BafCode

Now that we understand how BafCode works and how we can interact with its components, it's time to learn how we can create tools, which are the things that power your agent.

Installing BafCode CLI and Creating a Tool

To create a tool, simply use the following command inside the src folder after you have installed BafCode CLI:

pip install bafcodebafcode make tool <your_tool_name>

Understanding the Created Files

You will notice that three files are created in various folders.The first file is created in src/tools folder which is the actual tool

 
from core import BafLog
from api import ExamplesGetExampleAPI

# Optionally, import any other required modules or packages
# E.g., from api import YourAPI


class ExamplesGetExample:
  def __init__(self):
     self.logger = BafLog

  def execute(self, task,data):
    # Process data here
    response = ExamplesGetExampleAPI.process(data)

    return response
The API File

This is what you will find in the created tool file: a file imported from the API folder, which is actually the second file created by the command, and it looks like this:

 
import requests
from core import BafLog


logger = BafLog

class ExamplesGetExampleAPI:
    def process(task,data):
                
        response = 'Create any logic that will return a string'

        return response
        
The Tool Prompt File

Before i will explain you how to edit these files and start coding the logic of your tools i want to let you know that the third file created by the command is the tool prompt which is placed in prompts folder with a code draft

 
from core import BafLog
# Optionally, import any other required modules or packages

class ExamplesGetExamplePrompt:  # Replace ExamplesGetExample with the name of your prompt
    def examples_get_example_prompt(task,data):
        prompt = """
            Your Prompt Here
            ExamplesGetExample Data:
            {task}
        """
        return prompt.format(data=data)
        

Developing the Tool's Logic

Now, regarding how you can start coding with all of this, essentially, you have the freedom to develop your tool's logic either in the tool file or its API file. The choice is yours because the only requirement is for the executed tool to return a string to the Master, who will then relay it as a result to the manager. If you are an organized person and the tool you're creating performs various tasks to produce the final string, you might use the API file to implement logic that interacts with an external API and returns its response as a string to the tool, which in turn, will pass it on to the Master. Alternatively, you can encapsulate all the logic within the tool file itself.

You might wonder why there's a prompt related to the tool. In that case, let me introduce you to another feature in BafCode, which is LLMS. In the src directory, you will find a folder named llms. By default, it contains an openai.py file that outlines the logic for using OpenAI LLMs, but you can create custom LLM files by using a specific command inside the src directory.

Creating Custom LLM Files

bafcode make llm <your_llm_file>

A file will be created in the llms folder containing a code draft. Actually, you can utilize any LLM inference and attempt to return the LLM response as a string.

Let's return to how you can use the tool-related prompt. Essentially, you just import the LLM class into your tool file or API file, and the LLM Class requires three parameters to be passed, which are data, task, and prompt. The tool-related prompt is utilized in cases where you want to add AI functionality that returns an LLM response during the tool execution. Here is an example of a search tool that uses the Google Search API and LLM functionality:

Example of a Tool Using Google Search API and LLM Functionality

import requests
from core import BafLog
from config import Config

GOOGLE_SEARCH_ENDPOINT = "https://www.googleapis.com/customsearch/v1"
api_key = Config.GOOGLE_API_KEY
search_engine_id = Config.GOOGLE_SEARCH_ENGINE_ID

logger = BafLog

class GoogleSearchAPI:

    @staticmethod
    def process(task, data):
        from llms import LLM
        from prompts import GoogleSearchPrompt

        prompt = GoogleSearchPrompt.google_search_prompt(task)
        generated_query = LLM.llm.process('Generate a query', prompt, task)
        print(f'Generated query: {generated_query}')
        
        params = {
            'q': generated_query,
            'key': api_key,
            'cx': search_engine_id
        }

        response = requests.get(GOOGLE_SEARCH_ENDPOINT, params=params)

        # Handle API response
        if response.status_code != 200:
            logger.error(f"Error fetching GoogleSearch data. API response: {response.text}")
            return "Error fetching GoogleSearch data. Please try again later."

        raw_results = response.json().get('items', [])
        clear_results = []

        # Extracting only the first two results and their essential details
        for item in raw_results[:2]:
            clear_results.append({
                "title": item.get("title", "N/A"),
                "link": item.get("link", "N/A"),
                "description": item.get("snippet", "N/A").strip()
            })

        return clear_results # Response as string

Testing and Deploying Your Agent

This covers everything you need to know to get started with BafCode, but there are many other features to explore. If you require assistance, please don't hesitate to contact us through the BafCode.com website.

Before we conclude, once you have successfully built a useful agent, you can test it locally by executing the 'bafcode start' command in the src directory.

bafcode start or python app.py

Then, send a POST request to the /generate endpoint with the following body:

{  "message":"Your message here",    "mode": "multiple",}

To deploy your agent in BafCloud and start earning profit from any other dev that will use yout Agent API, visit the submission website or contact team@bafcloud.com

There's a huge chance to get your place in one of the first developers that their agents will be offered to BafCloud customers and they may earn higher profit share

Finally thanks for reading the documentation, enjoy coding