• AI Fire
  • Posts
  • ๐Ÿค– Discover AI Agents: Smart Helpers That Turn Your Toughest Tasks into Easy Wins

๐Ÿค– Discover AI Agents: Smart Helpers That Turn Your Toughest Tasks into Easy Wins

Learn how smart AI helpers can do tricky tasks all on their own

How familiar are you with AI agents? ๐Ÿค–

Login or Subscribe to participate in polls.

Introduction

โ€œAI agent workflows will drive massive AI progress this year,โ€ said Andrew Ng.

This quote inspired me to dig deeper into what he calls ai agents. In his recent talk, Andrew Ng discussed these AI agents, which are more advanced than the traditional AI models we're used to. Instead of just responding to a single prompt, these agents can plan, use tools, and work through steps to complete tasks on their own.

In this article, I'll explain what ai agents are in simple terms and show you how to build a basic agentic system from scratch. Whether you're new to AI or looking to understand the latest trends, this guide will help you grasp the concept and potential of ai agents.

I. What is an Agentic Workflow?

An agentic system is a type of advanced AI that doesn't just respond to a single prompt and stop there. Instead, it works through a series of steps to complete tasks on its own. This is a big step up from zero-shot prompting, where you give the AI a prompt and it gives you one answer without any further action.

ai agents have several key features that make them stand out:

  • Reflection: The agent looks at its own outputs and checks for mistakes or areas that need improvement. For example, if it writes a piece of text, it will review it to see if it can make it better.

  • Tool Use: These agents can use various tools to help them complete tasks. Imagine an AI that can access and use a calculator, a search engine, or even other software programs to get the job done more effectively.

  • Planning: Instead of just reacting to a single prompt, an agentic system thinks ahead. It considers different steps and options before deciding on the best course of action. For example, if itโ€™s planning a project, it will outline all the necessary steps and think about potential challenges.

  • Multi-Agent Collaboration: Sometimes, tasks are too complex for one agent to handle alone. In these cases, multiple agents work together, each focusing on a different part of the task. For instance, in building a software application, one agent might handle the coding, another might work on the design, and yet another might focus on testing.

By combining these features, agentic workflows can handle more complex and dynamic tasks, making AI systems more capable and efficient. They can adapt, learn from their actions, and work more autonomously, offering a significant improvement over traditional AI models.

II. Why Agentic Workflows are Better

Agentic workflows are a big step forward in AI technology because they can work on their own and improve over time. Here are a few reasons why they are better:

  • Autonomy: ai agents can plan, use tools, and perform tasks without needing constant guidance. They get high-level instructions and figure out the steps themselves, which makes them much more independent than traditional AI models.

  • Chain-of-Thought Reasoning: These agents break down complex problems into smaller, manageable tasks. Instead of trying to solve a big problem all at once, they handle one piece at a time. This makes it easier for them to find solutions and handle complicated tasks efficiently.

  • Self-Improvement: ai agents learn from their actions. If they make a mistake or find a better way to do something, they adjust and improve. This means they get better over time, recovering from issues and enhancing their performance with each iteration.

Overall, agentic workflows are smarter, more adaptable, and more efficient, making them a powerful tool for tackling a wide range of tasks.

Learn How to Make AI Work For You!

Transform your AI skills with the AI Fire Academy Premium Plan โ€“ FREE for 14 days! Gain instant access to 100+ AI workflows, advanced tutorials, exclusive case studies, and unbeatable discounts. No risks, cancel anytime.

Start Your Free Trial Today >>

III. Key Components of ai agents

ai agents are built with several important features that make them powerful and efficient:

  • Reflection: These agents review their own work to find mistakes or areas for improvement. They can look at what theyโ€™ve done and figure out how to do it better next time.

  • Tool Use: Agents can use different tools to help them complete tasks. For example, they might use a calculator for math problems or a search engine to find information. This ability to use tools makes them more capable and effective.

  • Planning: Instead of just reacting to commands, ai agents think ahead. They plan their actions, consider different options, and make informed decisions about the best way to achieve their goals.

  • Multi-Agent Collaboration: Sometimes, one agent isnโ€™t enough to get the job done. In these cases, multiple agents can work together, each handling a part of the task. For example, in a project, one agent might focus on coding while another works on design, and a third tests the final product. This teamwork allows them to tackle complex problems more effectively.

These components make ai agents smart, flexible, and able to handle a wide range of tasks independently and efficiently.

IV. Agentic vs. Non-Agentic Workflows

Agentic workflows and traditional single-prompt models are very different in how they work:

  • Interaction with Environment: In a traditional single-prompt model, you ask the AI a question, and it gives you one answer. That's it. But in an agentic workflow, the AI interacts with its environment. It asks questions, gets input, asks follow-up questions, and gathers more information. This way, it creates a much richer and more accurate output.

  • Complex Tasks: Traditional models can struggle with complex tasks because they handle everything at once. In contrast, ai agents can break down complex tasks into smaller parts. Multiple agents can work together, each focusing on a specific role or task. For example, in a project, one agent might handle the coding, another works on design, and another on testing. This teamwork makes it easier to manage and complete complex tasks efficiently.

Overall, agentic workflows are more interactive and better suited for handling complicated tasks through collaboration and step-by-step processing.

V. Building an AI Agent from Scratch

1. Setup the Agent

  1. Create an Agent Class: Start by creating a class called Agent. This class will handle the AIโ€™s actions and responses.

class Agent:
    # initialize
    def __init__(self, system=""):
        self.system = system
        self.messages = []
        if self.system:
            self.messages.append({"role": "system", "content": system})
    # call
    def __call__(self, message):
        self.messages.append({"role": "user", "content": message})
        result = self.execute()
        self.messages.append({"role": "assistant", "content": result})
        return result
    #execute
    def execute(self):
        completion =  openai.ChatCompletion.create(
                        model="gpt-4o", 
                        temperature=0,
                        messages=self.messages)
        return completion.choices[0].message.content
  1. Manage Conversations: In the agent class, set up roles for the user and the assistant. This helps the agent know who is speaking and what kind of response is needed.

  2. Initialize Message History: Keep track of the conversation history so the agent remembers what has been said. Add methods to handle messages and execute responses.

2. Set up the React Prompt

  1. Reason and Act (ReAct): The ReAct concept helps the AI think through steps before acting. It involves a loop of thought, action, pause, and observation.

  2. Provide a Detailed Prompt: Create a detailed prompt for the agentโ€™s thought loop. This tells the agent to think about the question, decide on an action, perform the action, and then observe the result before continuing.

    For example:

prompt = """
You run in a loop of Thought, Action, PAUSE, Observation.
At the end of the loop you output an Answer.
Use Thought to describe your thoughts about the question you have been asked.
Use Action together with an input to run one of the actions available to you - then return PAUSE.
Action input should be the Observation from the previous Action.
Observation will be the result of running those actions on those inputs.


Your available actions are:

generate_and_execute_pytrend_code: <key word>
Create the pytrend code to get the related keywords from Google Trends for the given keywords, execute the code returns the data.

analyze_trends_data: <table of top words related to trending topics>
Analyze the trends table data and returns a summary of the insights from the data.

generate_Beehiiv_post_ideas: <trend_summary>
Generates Beehiiv post ideas based on the trend summary.

Example session:

Question: What are the related keywords for the search term "AI agent"?
Thought: I should generate and execute the pytrend code to fetch related topics or keywords for AI agent.
Action: generate_and_execute_pytrend_code: AI agent
PAUSE

Observation: 
 ```
0              Artificial intelligence                   Field of study  100
1                    Intelligent agent                            Topic  90
2                       Software agent                            Topic  70
3                   Multi-agent system             Programming paradigm  65 ```

Thought: I should analyze the trends data to get a summary of the insights.
Action: analyze_trends_data: 
 ```
0              Artificial intelligence                   Field of study  100
1                    Intelligent agent                            Topic  90
2                       Software agent                            Topic  70
3                   Multi-agent system             Programming paradigm  65 ```

PAUSE

Observation: <trend_summary>
Thought: I should generate Beehiiv post ideas based on the trend summary.
Action: generate_Beehiiv_post_ideas: <trend_summary>
PAUSE

Observation: <Beehiiv_post_ideas>
Answer: The trending topics are <trend_summary> and here are some Beehiiv post ideas: <Beehiiv_post_ideas>
""".strip()

3. Create Tools

  1. Define Functions for Actions: Write functions for different actions the agent can take. For example, fetching data from Google Trends, analyzing trends, and generating Beehiiv post ideas.

def generate_and_execute_pytrend_code(keyword):
    def fetch_related_trending_topics(keyword):
        # Initialize pytrends
        pytrends = TrendReq(hl='en-US', tz=360)
        
        # Build the payload with the specified topic
        pytrends.build_payload([keyword], cat=0, timeframe='now 7-d', geo='', gprop='')
        
        # Fetch related topics
        related_topics = pytrends.related_topics()
        
        # Extract top related topics
        if keyword in related_topics and 'top' in related_topics[keyword]:
            top_related_topics = related_topics[keyword]['top']
            return top_related_topics
        else:
            return None
        # usage
    related_trending_topics = fetch_related_trending_topics(keyword)
    return related_trending_topics

def analyze_trends_data(trends_data):
    analysis_prompt = f"""
    You are an AI assistant. 
    Analyze and summarize the following insight: {trends_data}
    """
    
    response = openai.ChatCompletion.create(
        model="gpt-4o",
        messages=[{"role": "system", "content": analysis_prompt}],
        temperature=0
    )
    
    return response.choices[0].message['content']

def generate_Beehiiv_post_ideas(trend_summary):
    analysis_prompt = f"""
    You are a technical content writer. Based on the analysis 
    from the Google trend data for the given keyword and its 
    trend summary, you will generate topic ideas for Beehiiv post.
    The trend_summary is as follows:
    =======
    {trend_summary}
    =======
    
    """
    
    response = openai.ChatCompletion.create(
        model="gpt-4o",
        messages=[{"role": "system", "content": analysis_prompt}],
        temperature=0
    )
    
    return response.choices[0].message['content']
  1. Map Action Names to Functions: Create a dictionary called known_actions that maps action names to the corresponding functions. This allows the agent to call the right function based on the action it decides to take.

# Known actions dictionary that are made available to the agents
known_actions = {
    "generate_and_execute_pytrend_code": generate_and_execute_pytrend_code,
    "analyze_trends_data": analyze_trends_data,
    "generate_Beehiiv_post_ideas": generate_Beehiiv_post_ideas,

4. Automate the Agent

  1. Define the Thought Loop: Set up the thought loop for the agentic workflow. This loop manages how the agent thinks, acts, and learns from its actions.

  2. Implement the Loop: Write the code to handle interactions and execute actions. The agent will go through the thought loop, decide on actions, and use the tools to complete tasks.

# Regex for action selection
action_re = re.compile('^Action: (\w+): (.*)$')

# Function to query and handle actions
def query(question, keyword, max_turns=5):
    # initialize the agent
    i = 0
    bot = Agent(prompt)
    next_prompt = question
    observation = ""
    # run through the loop for max_turn - numbers of times the agent thinks and responds
    while i < max_turns:
        i += 1
        # interaction with the agent, it produces the output
        result = bot(next_prompt)

        # identify actions
        actions = [
            action_re.match(a) 
            for a in result.split('\n') 
            if action_re.match(a)
        ]
        
        if actions:
            # if there is an action to run
            action, action_input = actions[0].groups()
            if action not in known_actions:
                raise Exception(f"Unknown action: {action}")
            if action == "generate_and_execute_pytrend_code":
                observation = known_actions[action](keyword)
            else:
                observation = known_actions[action](action_input)            
            print("Observation:", observation)
            next_prompt = f"Observation: {observation}"
        else:
            return

# usage
keyword = "AI Agent"
question = "Give me some ideas for Beehiiv posts related to the topic 'AI agent'."
query(question, keyword)

Hereโ€™s the full code you can refer:

import openai
import re
import time
from pytrends.request import TrendReq

# Initialize the OpenAI API with your API key
openai.api_key = 'YOUR_OPENAI_API_KEY'

class Agent:
    def __init__(self, system=""):
        self.system = system
        self.messages = []
        if self.system:
            self.messages.append({"role": "system", "content": system})

    def __call__(self, message):
        self.messages.append({"role": "user", "content": message})
        result = self.execute_with_retry()
        self.messages.append({"role": "assistant", "content": result})
        return result

    def execute_with_retry(self, max_retries=5, backoff_factor=2):
        for attempt in range(max_retries):
            try:
                return self.execute()
            except openai.error.RateLimitError:
                if attempt < max_retries - 1:
                    wait_time = backoff_factor ** attempt
                    print(f"Rate limit exceeded. Retrying in {wait_time} seconds...")
                    time.sleep(wait_time)
                else:
                    raise

    def execute(self):
        completion = openai.ChatCompletion.create(
            model="gpt-4",
            temperature=0,
            messages=self.messages
        )
        return completion.choices[0].message['content']

def generate_and_execute_pytrend_code(keyword):
    pytrends = TrendReq(hl='en-US', tz=360)
    pytrends.build_payload([keyword], cat=0, timeframe='now 7-d', geo='', gprop='')
    related_topics = pytrends.related_topics()
    if keyword in related_topics and 'top' in related_topics[keyword]:
        top_related_topics = related_topics[keyword]['top']
        return top_related_topics
    else:
        return None

def analyze_trends_data(trends_data):
    analysis_prompt = f"""
    You are an AI assistant. 
    Analyze and summarize the following insight: {trends_data}
    """
    
    response = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "system", "content": analysis_prompt}],
        temperature=0
    )
    
    return response.choices[0].message['content']

def generate_Beehiiv_post_ideas(trend_summary):
    analysis_prompt = f"""
    You are a technical content writer. Based on the analysis 
    from the Google trend data for the given keyword and its 
    trend summary, you will generate topic ideas for Beehiiv post.
    The trend_summary is as follows:
    =======
    {trend_summary}
    =======
    
    """
    
    response = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "system", "content": analysis_prompt}],
        temperature=0
    )
    
    return response.choices[0].message['content']

known_actions = {
    "generate_and_execute_pytrend_code": generate_and_execute_pytrend_code,
    "analyze_trends_data": analyze_trends_data,
    "generate_Beehiiv_post_ideas": generate_Beehiiv_post_ideas,
}

prompt = """
You run in a loop of Thought, Action, PAUSE, Observation.
At the end of the loop you output an Answer.
Use Thought to describe your thoughts about the question you have been asked.
Use Action together with an input to run one of the actions available to you - then return PAUSE.
Action input should be the Observation from the previous Action.
Observation will be the result of running those actions on those inputs.

Your available actions are:

generate_and_execute_pytrend_code: <key word>
Create the pytrend code to get the related keywords from Google Trends for the given keywords, execute the code returns the data.

analyze_trends_data: <table of top words related to trending topics>
Analyze the trends table data and returns a summary of the insights from the data.

generate_Beehiiv_post_ideas: <trend_summary>
Generates Beehiiv post ideas based on the trend summary.

Example session:

Question: What are the related keywords for the search term "AI agent"?
Thought: I should generate and execute the pytrend code to fetch related topics or keywords for AI agent.
Action: generate_and_execute_pytrend_code: AI agent
PAUSE

Observation:
0              Artificial intelligence                   Field of study  100
1                    Intelligent agent                            Topic  90
2                       Software agent                            Topic  70
3                   Multi-agent system             Programming paradigm  65

Thought: I should analyze the trends data to get a summary of the insights.
Action: analyze_trends_data:
0              Artificial intelligence                   Field of study  100
1                    Intelligent agent                            Topic  90
2                       Software agent                            Topic  70
3                   Multi-agent system             Programming paradigm  65

PAUSE

Observation: <trend_summary>
Thought: I should generate Beehiiv post ideas based on the trend summary.
Action: generate_Beehiiv_post_ideas: <trend_summary>
PAUSE

Observation: <Beehiiv_post_ideas>
Answer: The trending topics are <trend_summary> and here are some Beehiiv post ideas: <Beehiiv_post_ideas>
""".strip()

action_re = re.compile(r'^Action: (\w+): (.*)$')

def query(question, keyword, max_turns=5):
    i = 0
    bot = Agent(prompt)
    next_prompt = question
    observation = ""
    while i < max_turns:
        i += 1
        result = bot(next_prompt)
        actions = [
            action_re.match(a) 
            for a in result.split('\n') 
            if action_re.match(a)
        ]
        
        if actions:
            action, action_input = actions[0].groups()
            if action not in known_actions:
                raise Exception(f"Unknown action: {action}")
            if action == "generate_and_execute_pytrend_code":
                observation = known_actions[action](keyword)
            else:
                observation = known_actions[action](action_input)            
            print("Observation:", observation)
            next_prompt = f"Observation: {observation}"
        else:
            print(result)
            return

# usage
keyword = "AI Agent"
question = "Give me some ideas for Beehiiv posts related to the topic 'AI agent'."
query(question, keyword)

By following these steps, you can create an AI agent that can handle tasks independently, plan its actions, use tools, and improve over time.

VI. Example Workflow

  1. Keyword: โ€œAI Agentโ€

  2. Question: โ€œGive me some ideas for Beehiiv posts related to the topic 'AI agent'.โ€

  3. Process:

    • Fetch related trending topics.

    • Analyze the trends data.

    • Generate Beehiiv post ideas based on the analysis.

ai-agents

Conclusion

In this article, we explored what ai agents are and how they work. We learned that these advanced AI agents can plan, use tools, and work through steps independently, making them much more powerful and efficient than traditional AI models.

We also saw how ai agents can handle complex tasks by breaking them down into smaller parts and even working together with other agents. By building an AI agent from scratch, we demonstrated how to set up, prompt, and automate these agents to complete tasks like fetching and analyzing Google Trends data and generating post ideas.

ai agents represent a big step forward in AI technology, offering smarter, more adaptable, and more efficient workflows. Whether youโ€™re new to AI or looking to stay updated with the latest trends, these systems can help you achieve more.

Try building your own agent and see how it can improve your work. Feel free to share your experiences and any challenges you face. Happy experimenting!

If you are interested in other topics and how AI is transforming different aspects of our lives, or even in making money using AI with more detailed, step-by-step guidance, you can find our other articles here:

*indicates a premium content, if any

Overall, how would you rate the AI Fire 101 Series?

Login or Subscribe to participate in polls.

Reply

or to participate.