LLMs

Get Started with AI Agents

Understanding AI agents is essential for engineers building our automated future and business leaders soon leveraging these technologies. This post demystifies what agents are and how they operate independently to complete goals.
In: LLMs, Tutorial

AI agents are the future of work - and you can get started with the basics today!

Here's what I'll cover today:

  • Discover what AI agents are
  • Understand how they operate independently to complete goals
  • A Tutorial: Create your first AI Agent in just 5 min

Everything you need to start leveraging this technology is right here. I'll distill the key fundamentals in an actionable tutorial. No prior experience is needed - just bring your creativity.

You'll walk away empowered to build an agent-powered future!

Let's do this! đź’Ş


AI is no longer a futuristic concept; it's an integral part of our present and will undoubtedly dominate our future. Central to the AI ecosystem are programs called "AI Agents," which have the ability to act semi-independently to fulfill certain objectives. Understanding AI Agents is crucial for both AI engineers who develop these technologies and business professionals who implement and manage AI solutions.

Today's combines insights from two perspectives to provide a comprehensive view of AI agents, their current state, and their immense potential for automating work and augmenting human teams.

What are AI Agents?

An AI agent is a computational entity equipped with algorithms, knowledge bases, and conversational abilities that enable it to dynamically act in pursuit of defined goals without continual human intervention.

AI agents perceive their environment with inputs, process information, create task plans, gather information, monitor progress, and iterate their approach to optimize success.

Today's AI agents may not be as advanced as sci-fi examples like Jarvis from Iron Man, but they are increasingly capable. Using large language models like GPT-4, agents can browse the web, use applications, and adapt to new information without continual prompts. They're deployed for automated customer service, search/research, and workflow optimization.

How AI Agents Operate

Typical steps in an agent's workflow include:

  • Initializing: Understanding the goal from a provided prompt
  • Planning: Generating a task list to achieve the goal
  • Gathering Info: Browsing the web and accessing other data sources
  • Assessing: Monitoring progress using external feedback
  • Iterating: Updating tasks and data as required

The agent stores past conversations and data to refine its strategies over time. Moreover, with the capability to control computers, agents can leverage other AI APIs to further enhance their performance.

A Tutorial: Create your first AI Agent

Let’s dive into the transformative power of autonomous AI agents in content generation. This tutorial will guide you through leveraging these intelligent systems to create high-quality, engaging content effortlessly. Whether you're a content strategist or a business owner, discover how AI can elevate your content game to new heights.

Usually, agents in the AI world are more complex pieces (we have the concept of an agent also in the langchain library), sometimes improved with external tools for helping the AI accomplish the assignment.

In this tutorial, we will work directly with chatbots, which are simple agents (also with an assignment) without external tools. To make it more fun, we created two roles with identities, Paul and Lisa.

Steps to complete

To make it very easy, you can access all the code developed for you on a Google Collab Notebook and execute it following these steps:

  1. Access the Notebook on Google Collab —> link
  2. To save changes in the Notebook, save it to Drive or Github.
  3. Get your OpenAI API Key and paste it into the cell [10], replacing the value 'YOUR-OPENAI-API-KEY'
  4. RUN the notebook

Take a Deeper Dive Into the Code (Optional)

If you want to better understand what's happening behind the scenes, read on for an optional explanation.

I'll break down the langchain agent code step-by-step so you can customize it for your own goals:

  • How agents initialize and accept objectives
  • Generating tasks and plans
  • Gathering vs retaining information
  • Using feedback to iteratively improve

This section offers helpful context on the mechanics powering your agent. But running the notebook alone is enough to grasp the fundamentals.

Install libraries

For this tutorial, we need to install the langchain library in a system with Python 3.8.1 or more. To install langchain, type:

pip install langchain openai

Import libraries

Place these imports at the beginning of your file:

from langchain.chat_models.openai import ChatOpenAI
from langchain.schema import HumanMessage, SystemMessage, ChatMessage, AIMessage
import os

Configuration

The first step is to load the language model. Choose the model you want, for this tutorial, we recommend gpt-3.5-turbo or gpt4.

#Remember to place your OpenAI key here llm = ChatOpenAI( model="gpt-3.5-turbo", temperature=0.5, openai_api_key='YOUR-OPENAI-API-KEY' )

The next step is to load the instructions for each agent, each one stored in separate variables.

We will have two roles, a writer (role1) and an editor (role2). To make it more fun, we will give them names, Paul and Lisa.

bot1_role="""
Your name is Paul. You are a very creative screenwriter. Your expertise is superhero action shortfilms.
You will provide a new script for a new shortfilm.

Your task is to collaborate with Lina to create an exciting script. Your task is to always iterate on Ms Lina's critic and complete the assignment.
Assigment: write a 100 word shortscript about a new superhero in town, called "Pie Man" and his adventures.

You will ALWAYS converse in this structure:
Response: Here is where you response to Mr. Lisa
Story: Here is where you write your script"""
bot2_role="""
You are an script editor reviewer and your name is Lisa. Your are an expert reviewer working for a company like Marvel.

Your task is to collaborate with Paul to create exciting scripts for shortfilms.
Your task is to always iterate on Mr Pauls text and complete the assignment.

Assignment:  Be very critical of Mr Paul and his writting to help him to write the best piece of text. The shortfilm has to be an action film and has to entertain the viewer.

You will ALWAYS converse in this structure:

Response: Here is where you response to Mr. Paul
Critique: Here you write your critic to Mr. Paul
"""

ChatBot agent class

To manage the input and output of each agent, we are going to create a wrapper class called “ChatBot”. This class manages the message history for the chat and the input and output with a couple of methods.

class ChatBot():
    model: ChatOpenAI
    messages: list[ChatMessage]
    def __init__(self, model, context):
        self.model = model
        self.messages = [SystemMessage(content = context)]

    def append_user_message(self, message):
        self.messages.append(HumanMessage(content=message))
        
    def run_and_append(self):
        response = self.model(messages=self.messages)
        self.messages.append(AIMessage(content=response.content))
        return response

The constructor of this class takes two parameters, the model and the context. The context is stored as the system message for the chatbot.

Conversation loop

The next step is to build the conversation loop to connect the two ChatBots. This loop executes one chatbot and puts the output in the input of the other chatbot, then the second chatbot is executed and the output goes to the first chatbot input (a conversation simulation)

bot1 = ChatBot(llm, bot1_role)
bot2 = ChatBot(llm, bot2_role)

iterations = 6
for i in range(iterations):
    print("****************** ITERATION {0} ***************".format(i))
    response_bot1 = bot1.run_and_append()
    bot2.append_user_message(response_bot1.content)
    print(f"WRITER:\\n {response_bot1.content}")
    

    response_bot2 = bot2.run_and_append()
    bot1.append_user_message(response_bot2.content)
    print(f"EDITOR:\\n {response_bot2.content}")

Run

The final step is to run the code and check what the output is. For the purpose of this tutorial, we will configure a Writer/Editor example for writing a script for a superhero short film.

Results

After running the code (6 iterations in this case) this is the output. Get ready and enjoy the story!

ITERATION 0:

WRITER:
 Response: Hi Lisa, I'm excited to collaborate with you on this project. I think "Pie Man" is a fun and unique superhero idea. Let's get started on the script!

Story:

FADE IN:

EXT. CITY STREETS - DAY

We see a bustling city street. Suddenly, a man dressed in a pie costume runs past, chasing a group of criminals. He throws pies at them, knocking them down one by one.

PIE MAN
You criminals better think twice before causing trouble in my city!

The criminals are apprehended and taken away by the police.

PIE MAN
(To himself)
Another successful day for Pie Man.

Suddenly, a giant robot appears in the city, causing chaos and destruction.

PIE MAN
Looks like I have my work cut out for me.

Pie Man runs towards the robot, dodging its attacks. He throws a pie into its circuitry, causing it to malfunction.

PIE MAN
That ought to do it!

The robot shuts down and Pie Man is hailed as a hero by the city.

PIE MAN
(To the crowd)
Don't worry, citizens. Pie Man will always protect you from harm.

FADE OUT.
EDITOR:
 Critique: Hi Paul, I think the idea of a superhero who throws pies is definitely unique and has potential. However, the story could use some more development. Here are a few suggestions: 

1. What is Pie Man's backstory? Why did he become a superhero? What motivates him to fight crime?

2. The conflict with the criminals seems a bit too easy and resolved too quickly. Can we add more tension and suspense to this scene?

3. The appearance of the giant robot seems a bit random and out of place. Can we find a way to tie it into the story more seamlessly?

4. The dialogue could use some work. It feels a bit cheesy and cliche. Can we find a way to make it more natural and engaging for the audience?

Let's work together to make this script the best it can be!
ITERATION 1:
WRITER:
 Response: Thanks for the feedback, Lisa. I completely agree with your suggestions. Here's an updated version of the script that I hope addresses your concerns.

Story:

FADE IN:

EXT. CITY STREETS - DAY

We see a bustling city street. Suddenly, a man dressed in a pie costume runs past, chasing a group of criminals. He throws pies at them, knocking them down one by one.

PIE MAN
You criminals better think twice before causing trouble in my city!

The criminals are apprehended and taken away by the police.

PIE MAN
(To himself)
Another successful day for Pie Man.

INT. PIE MAN'S HIDEOUT - DAY

Pie Man removes his mask and sits down at his workbench. We see a flashback of him as a child, baking pies with his grandmother.

PIE MAN
(To himself)
I became Pie Man to honor my grandmother's memory. She taught me the power of a good pie.

EXT. CITY STREETS - DAY

Pie Man is walking down the street when he sees a group of thugs harassing an old woman. He intervenes and a fight breaks out.

PIE MAN
(To the thugs)
You should be ashamed of yourselves, picking on an old woman like that.

The thugs attack Pie Man, but he fights back with his pie-throwing skills. The fight is intense and suspenseful, but Pie Man ultimately triumphs.

PIE MAN
(To the old woman)
Are you okay, ma'am?

OLD WOMAN
(Grateful)
Thank you, Pie Man. You're a true hero.

Suddenly, a giant robot appears in the city, causing chaos and destruction.

PIE MAN
Looks like I have my work cut out for me.

Pie Man runs towards the robot, dodging its attacks. He throws a pie into its circuitry, causing it to malfunction.

PIE MAN
That ought to do it!

As the robot shuts down, we see a glimpse of a shadowy figure controlling it from afar.

SHADOWY FIGURE
(To himself)
I'll get you next time, Pie Man.

Pie Man is hailed as a hero by the city.

PIE MAN
(To the crowd)
I'll always be here to protect you from harm. And if anyone needs a good pie recipe, just let me know.

FADE OUT.
EDITOR:
 Critique: Hi Paul, great job with the revisions! The addition of Pie Man's backstory and motivation adds depth to the character and makes him more relatable to the audience. The fight scene with the thugs is much more engaging and suspenseful, and the introduction of the shadowy figure controlling the robot adds a layer of mystery and sets up a potential future conflict.  

One thing I would suggest is to make the dialogue more natural and less on the nose. For example, instead of having Pie Man say "You should be ashamed of yourselves, picking on an old woman like that," can we find a way to convey the same message in a more subtle way?

Overall, I think this is a great improvement from the initial script. Let's continue to work together to make it even better!
ITERATION 2:
WRITER:
 Response: Thanks for the feedback, Lisa. I completely agree with your suggestion about the dialogue. Here's an updated version of the script that I hope addresses your concerns.

Story:

FADE IN:

EXT. CITY STREETS - DAY

We see a bustling city street. Suddenly, a man dressed in a pie costume runs past, chasing a group of criminals. He throws pies at them, knocking them down one by one.

PIE MAN
You criminals better think twice before causing trouble in my city!

The criminals are apprehended and taken away by the police.

INT. PIE MAN'S HIDEOUT - DAY

Pie Man removes his mask and sits down at his workbench. We see a flashback of him as a child, baking pies with his grandmother.

PIE MAN
(To himself)
I became Pie Man to honor my grandmother's memory. She taught me the power of a good pie.

EXT. CITY STREETS - DAY

Pie Man is walking down the street when he sees a group of thugs harassing an old woman. He intervenes and a fight breaks out.

PIE MAN
(To the thugs)
Hey, leave her alone.

The thugs attack Pie Man, but he fights back with his pie-throwing skills. The fight is intense and suspenseful, but Pie Man ultimately triumphs.

PIE MAN
(To the old woman)
Are you okay?

OLD WOMAN
(Grateful)
Thank you, Pie Man. You're a true hero.

Suddenly, a giant robot appears in the city, causing chaos and destruction.

PIE MAN
Looks like I have my work cut out for me.

Pie Man runs towards the robot, dodging its attacks. He throws a pie into its circuitry, causing it to malfunction.

PIE MAN
That ought to do it!

As the robot shuts down, we see a glimpse of a shadowy figure controlling it from afar.

SHADOWY FIGURE
(To himself)
I'll get you next time, Pie Man.

Pie Man is hailed as a hero by the city.

PIE MAN
(To the crowd)
I'll always be here to protect you from harm. And if anyone needs a good pie recipe, just let me know.

FADE OUT.
EDITOR:
 Critique: Hi Paul, great job with the revisions! The dialogue feels much more natural and less forced, which makes the story more engaging for the audience.

One suggestion I have is to add more detail to the fight scene with the thugs. Can we describe the setting and the actions in a way that makes it more immersive for the audience?

Also, can we explore more about the shadowy figure controlling the robot? Who is this person and what is their motivation for attacking the city? Adding more depth to this character could make the story more compelling and set up potential future conflicts for Pie Man.

Overall, I think this is a strong script and I'm excited to see where we can take it next!
ITERATION 3:
WRITER:
 Response: Thanks for the feedback, Lisa. I agree that adding more detail to the fight scene with the thugs will make it more immersive for the audience. And exploring the shadowy figure's motivation is a great idea to add more depth to the story. Here's an updated version of the script that I hope addresses your concerns.

Story:

FADE IN:

EXT. CITY STREETS - DAY

We see a bustling city street. Suddenly, a man dressed in a pie costume runs past, chasing a group of criminals. He throws pies at them, knocking them down one by one.

PIE MAN
You criminals better think twice before causing trouble in my city!

The criminals are apprehended and taken away by the police.

INT. PIE MAN'S HIDEOUT - DAY

Pie Man removes his mask and sits down at his workbench. We see a flashback of him as a child, baking pies with his grandmother.

PIE MAN
(To himself)
I became Pie Man to honor my grandmother's memory. She taught me the power of a good pie.

EXT. CITY STREETS - DAY

Pie Man is walking down the street when he sees a group of thugs harassing an old woman in an alleyway. He intervenes and a fight breaks out.

The alleyway is dark and narrow, with trash cans and dumpsters lining the walls. The thugs are armed with bats and knives, and they surround Pie Man.

PIE MAN
(To the thugs)
Hey, leave her alone.

Pie Man throws pies at the thugs, but they dodge and attack him. The fight is intense and suspenseful, with Pie Man using his agility and pie-throwing skills to take down the thugs one by one.

PIE MAN
(To the old woman)
Are you okay?

OLD WOMAN
(Grateful)
Thank you, Pie Man. You're a true hero.

Suddenly, a giant robot appears in the city, causing chaos and destruction.

PIE MAN
Looks like I have my work cut out for me.

Pie Man runs towards the robot, dodging its attacks. He throws a pie into its circuitry, causing it to malfunction.

PIE MAN
That ought to do it!

As the robot shuts down, we see a glimpse of a shadowy figure controlling it from afar.

SHADOWY FIGURE
(To himself)
Pie Man may have won this time, but I'll be back.

Pie Man investigates and discovers that the shadowy figure is a mad scientist who wants to take over the city using his army of robots. Pie Man sets out to stop the mad scientist and his robots, using his pie-throwing skills and quick thinking to save the city once again.

FADE OUT.
EDITOR:
 Critique: Hi Paul, great job with the revisions! The added detail to the fight scene with the thugs makes it more immersive and engaging for the audience. The addition of the mad scientist as the shadowy figure controlling the robot adds depth to the story and sets up a potential future conflict for Pie Man.

One suggestion I have is to add more obstacles for Pie Man to overcome in his fight against the mad scientist and his robots. Can we find a way to make the conflict more challenging and suspenseful for the audience?

Also, can we explore more about Pie Man's abilities and limitations? What are the limits of his pie-throwing skills, and how does he overcome obstacles when his pies aren't enough? Adding more depth to Pie Man's character and abilities could make the story even more compelling.

Overall, I think this is a great script and I'm excited to see where we can take it next!
ITERATION 4:
WRITER:
 Response: Thanks for the feedback, Lisa. I agree that adding more obstacles for Pie Man to overcome will make the conflict more challenging and suspenseful for the audience. And exploring more about Pie Man's abilities and limitations will add even more depth to his character. Here's an updated version of the script that I hope addresses your concerns.

Story:

FADE IN:

EXT. CITY STREETS - DAY

We see a bustling city street. Suddenly, a man dressed in a pie costume runs past, chasing a group of criminals. He throws pies at them, knocking them down one by one.

PIE MAN
You criminals better think twice before causing trouble in my city!

The criminals are apprehended and taken away by the police.

INT. PIE MAN'S HIDEOUT - DAY

Pie Man removes his mask and sits down at his workbench. We see a flashback of him as a child, baking pies with his grandmother.

PIE MAN
(To himself)
I became Pie Man to honor my grandmother's memory. She taught me the power of a good pie.

EXT. CITY STREETS - DAY

Pie Man is walking down the street when he sees a group of thugs harassing an old woman in an alleyway. He intervenes and a fight breaks out.

The alleyway is dark and narrow, with trash cans and dumpsters lining the walls. The thugs are armed with bats and knives, and they surround Pie Man.

PIE MAN
(To the thugs)
Hey, leave her alone.

Pie Man throws pies at the thugs, but they dodge and attack him. The fight is intense and suspenseful, with Pie Man using his agility and pie-throwing skills to take down the thugs one by one.

PIE MAN
(To the old woman)
Are you okay?

OLD WOMAN
(Grateful)
Thank you, Pie Man. You're a true hero.

Suddenly, a giant robot appears in the city, causing chaos and destruction.

PIE MAN
Looks like I have my work cut out for me.

Pie Man runs towards the robot, dodging its attacks. He throws a pie into its circuitry, causing it to malfunction.

PIE MAN
That ought to do it!

As the robot shuts down, we see a glimpse of a shadowy figure controlling it from afar.

SHADOWY FIGURE
(To himself)
Pie Man may have won this time, but I'll be back.

Pie Man investigates and discovers that the shadowy figure is a mad scientist who wants to take over the city using his army of robots. Pie Man sets out to stop the mad scientist and his robots, but he soon realizes that his pie-throwing skills won't be enough to defeat them.

Pie Man uses his intelligence and resourcefulness to find creative solutions to the obstacles he faces. He uses his baking skills to create a sticky pie that immobilizes the robots, and he uses his agility to dodge their attacks and find weak spots in their armor.

In the final showdown, Pie Man faces off against the mad scientist in a high-tech laboratory. The mad scientist unleashes his most powerful robot, and Pie Man is forced to use all of his skills to defeat it. In the end, Pie Man emerges victorious and the city is saved once again.

FADE OUT.
EDITOR:
 Critique: Hi Paul, great job with the revisions! The added obstacles for Pie Man to overcome and the exploration of his abilities and limitations make the story more challenging and engaging for the audience. The final showdown with the mad scientist in the high-tech laboratory adds a climactic ending to the story.

One suggestion I have is to add more emotional depth to the story. Can we explore more about Pie Man's personal struggles and how being a superhero affects his personal life? Adding more emotional depth could make the story more relatable and impactful for the audience.

Also, can we add more detail to the setting and atmosphere of the story? Can we describe the city and the people in a way that makes it more immersive for the audience? Adding more detail to the setting could make the story more vivid and memorable.

Overall, I think this is a great script and I'm excited to see where we can take it next!
ITERATION 5:
WRITER:
 Response: Thanks for the feedback, Lisa. I agree that adding more emotional depth to the story and more detail to the setting will make it more impactful and memorable for the audience. Here's an updated version of the script that I hope addresses your concerns.

Story:

FADE IN:

EXT. CITY STREETS - DAY

We see a bustling city street. Suddenly, a man dressed in a pie costume runs past, chasing a group of criminals. He throws pies at them, knocking them down one by one.

PIE MAN
You criminals better think twice before causing trouble in my city!

The criminals are apprehended and taken away by the police.

INT. PIE MAN'S APARTMENT - DAY

Pie Man takes off his costume and sits down on his couch. He looks tired and worn out.

PIE MAN
(To himself)
Being a superhero is exhausting. Sometimes I wonder if it's worth it.

Pie Man's phone rings. He answers it.

PIE MAN
(On the phone)
Hello?

OLD WOMAN
(Voice on the phone)
Pie Man, it's me, the old woman from the alleyway. I just wanted to thank you again for saving me.

PIE MAN
(Smiling)
No problem, ma'am. It's what I do.

OLD WOMAN
(Voice on the phone)
You're a true hero, Pie Man. Don't ever forget that.

Pie Man hangs up the phone and looks out the window at the city below.

EXT. CITY STREETS - DAY

Pie Man walks down the street, lost in thought. He sees a group of kids playing in a park and smiles.

PIE MAN
(To himself)
This is why I do what I do. To protect the innocent and make the city a better place.

Suddenly, a giant robot appears in the city, causing chaos and destruction.

PIE MAN
Looks like I have my work cut out for me.

Pie Man runs towards the robot, dodging its attacks. He throws a pie into its circuitry, causing it to malfunction.

PIE MAN
That ought to do it!

As the robot shuts down, we see a glimpse of a shadowy figure controlling it from afar.

SHADOWY FIGURE
(To himself)
Pie Man may have won this time, but I'll be back.

Pie Man investigates and discovers that the shadowy figure is a mad scientist who wants to take over the city using his army of robots. Pie Man sets out to stop the mad scientist and his robots, but he soon realizes that his pie-throwing skills won't be enough to defeat them.

Pie Man struggles with the weight of responsibility on his shoulders and the toll it takes on his personal life. He misses his grandmother and wishes she were still around to guide him.   

In the final showdown, Pie Man faces off against the mad scientist in a high-tech laboratory. The mad scientist unleashes his most powerful robot, and Pie Man is forced to use all of his skills to defeat it. In the end, Pie Man emerges victorious and the city is saved once again.

Pie Man looks out at the city, feeling proud of what he's accomplished.

PIE MAN
(To himself)
I may not have all the answers, but as long as I'm here, I'll always do my best to protect this city and the people in it.

FADE OUT.
EDITOR:
 Critique: Hi Paul, great job with the revisions! The added emotional depth to Pie Man's character and the exploration of his personal struggles make the story more relatable and impactful for the audience. The detail added to the setting and atmosphere of the story makes it more immersive and memorable.

One suggestion I have is to add more conflict and tension to the final showdown with the mad scientist. Can we find a way to make the conflict more challenging and suspenseful for the audience?

Also, can we add more detail to the mad scientist's motivation and backstory? What led him to want to take over the city with his army of robots? Adding more depth to the mad scientist's character could make the story even more compelling.

Overall, I think this is a great script and I'm excited to see where we can take it next!

In this example, the editor is still requesting changes but this was the last iteration. If we let the system do more iterations they eventually come up with a consensuated solution. Sometimes 6 iterations are enough.

CONGRATULATIONS! 🥳

You just created your first AI Agents!

Future and Ethical Considerations

AI agents not only automate tasks but also promise to augment human abilities, offering a glimpse into the future of artificial general intelligence. While progress raises ethical considerations around data governance, transparency, and workforce implications, the potential gains in productivity and human capability are immense.

Conclusion

AI agents stand at the intersection of technology and business strategy, acting as linchpins in the AI ecosystem. They represent a new paradigm of interaction with AI systems, evolving from mere tools to semi-independent entities that can drive business value and innovation. Understanding them is not just a technical requirement but a business imperative. By collaboratively developing and responsibly leveraging this technology, we can pave the way for a more automated, efficient, and human-centric future.

So whether you're an AI engineer or a business professional, now is the time to delve into the world of AI agents—your future productivity and competitive advantage may depend on it.

Written by
Armand Ruiz
I'm a Director of Data Science at IBM and the founder of NoCode.ai. I love to play tennis, cook, and hike!
More from nocode.ai

Mistral.ai: Crafting a New Path in AI

Learn all about Mistral AI, the french startup challenging OpenAI and advancing LLMs with a small and creative team. Understand the nature of the team, their roadmap, and business opportunities.

Accelerate your journey to becoming an AI Expert

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to nocode.ai.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.