Machine Learning

Agentic AI 101: Starting your Construction Agents

The criminal criminal industry moves quickly. It's amazing and too often.

I've been reading, reading, and building my base in this data science world because I believe the future of data is strongly related to the development of Anni productivity.

It was another day when I built my first AI agent, and a few weeks after this, there was a few Python packages to choose, can tell the code options very well, such as n8n.

From “Mere” models can talk to us in tsunami Ai lawyers everywhere, they are searching for files, and do all data science projects (from EDA until modeling and testing), everything has happened in a few years.

What?

Seeing all that, my thought is: “I need to get on the board as soon as possible”. After all, it is best to use a wave rather than swallowing it.

For that reason, I have decided to start this post series when planning from the platforms to build our first AI, until the complex concepts.

Sufficient speech, let's get in.

The Foundations of Agents

AID agent is created when we give the llm to communicate with tools and do practical actions for us. So, instead of just Chatbot, now they can set up appointments, select Our Calendar, search internet, list the posts of social media, and list continues …

Agents AI can do some helpful things, not just to talk.

But how can we give that power to the LLM?

A simple answer to use API to contact the llm. There are several packages of Python in those days. If you follow my blog, you will see that I have tried a few packages to create agents: Langchain, Agno (formerly phidata), and Creewai, for example. In this series, I will stick with Agno [1].

First, set visible nature using uvAnaconda, or the work of your favorite environment. Next, enter packages.

# Agno AI
pip install agno

# module to interact with Gemini
pip install google-generativeai

# Install these other packages that will be needed throughout the tutorial
 pip install agno groq lancedb sentence-transformers tantivy youtube-transcript-api

A quick note before we continue. Don't forget to get Google Gemini Veni [2].

Creating a simple agir is very simple. All packages are very similar. They have class Agent Or the same thing that allows us to choose the model and start connecting with our choice. Here are the best parts of this section:

  • model: Communication with llm. Here we will choose between Openai, Gemini, Llama, Deepseek etc.
  • description: This dispute allows us to explain the performance of the agent. This is added to system_messagewhich is the same conflict.
  • instructions: I would like to think about an agent like a worker or the administrative assistant. For employment, we must provide the orders of what you need to be done. This is where you can do that.
  • expected_output: Here we can provide instructions about expected issues.
  • tools: This is what makes a galaxy of the agent, providing the actual work environment using these tools.

Now, let's create a simple agent without tools, but it will work to create our sense around the formation of the code.

# Imports
from agno.agent import Agent
from agno.models.google import Gemini
import os

# Create agent
agent = Agent(
    model= Gemini(id="gemini-1.5-flash",
                  api_key = os.environ.get("GEMINI_API_KEY")),
    description= "An assistant agent",
    instructions= ["Be sucint. Answer in a maximum of 2 sentences."],
    markdown= True
    )

# Run agent
response = agent.run("What's the weather like in NYC in May?")

# Print response
print(response.content)
########### OUTPUT ###############
Expect mild temperatures in NYC during May, typically ranging from the low 50s 
to the mid-70s Fahrenheit.  
There's a chance of rain, so packing layers and an umbrella is advisable.

That's good. We use Gemini model 1.5. Note how it means based on the information that is trained. If we ask us to tell the weather today, we will see the answer that you cannot access the Internet.

Let's examine instructions including expected_output The issues. Now we want a table with the moon, season and temperatures between NYC.

# Imports
from agno.agent import Agent
from agno.models.google import Gemini
import os

# Create agent
agent = Agent(
    model= Gemini(id="gemini-1.5-flash",
                  api_key = os.environ.get("GEMINI_API_KEY")),
    description= "An assistant agent",
    instructions= ["Be sucint. Return a markdown table"],
    expected_output= "A table with month, season and average temperature",	
    markdown= True
    )

# Run agent
response = agent.run("What's the weather like in NYC for each month of the year?")

# Print response
print(response.content)

And there is a result.

Month Season Average temperature (° F)
January Winter 32
February Winter 35
Walk Spring 44
April Spring 54
Maybe Spring 63
June Summer 72
July Summer 77
August Summer 76
September Autumn Which is 70
October Autumn 58
November Autumn 48
December Winter 37

Tools

The previous answers are good. But we do not naturally use the powerful models like llms to play with Chatbot or tell us old stories, don't you?

We want to be a bridge to take place, product, and knowledge. Therefore, Tools It will add skills to our Agents to AI, the building, therefore, a bridge with a real world. Common examples of agents tools are: Search web, move SQL, sending an email or driving the APIs.

But more than that, we can build custom skills for our agents through any Python work as a tool.

Tools It is the work that agent can run to achieve tasks.

According to the code, add a tool to the agent is just a matter of using an argument tools in Agent category.

Consider the soloprenur (one person's company) in a living organism in a living organism that wants to change their generations of content. This person sends tips about healthy habits every day. I know about the fact that the content of the content is not correct as it looks. It wants to be intelligence, research, and writing skills. Therefore, if this can work, or at least part of it, that is the time saved.

We therefore write this code to create a very simple agir that can produce easy-simple Instagram posts and save from the Markdown file for the review. We have reduced the process in thinking> Research> To write> Review> Sending to Review> Sending.

# Imports
import os
from agno.agent import Agent
from agno.models.google import Gemini
from agno.tools.file import FileTools

# Create agent
agent = Agent(
    model= Gemini(id="gemini-1.5-flash",
                  api_key = os.environ.get("GEMINI_API_KEY")),
                  description= "You are a social media marketer specialized in creating engaging content.",
                  tools=[FileTools(
                      read_files=True, 
                      save_files=True
                      )],
                  show_tool_calls=True)


# Writing and saving a file
agent.print_response("""Write a short post for instagram with tips and tricks
                        that positions me as an authority in healthy eating 
                        and save it to a file named 'post.txt'.""",
                     markdown=True)

As a result, we have the next.

Unlock Your Best Self Through Healthy Eating:

1. Prioritize whole foods: Load up on fruits, vegetables, lean proteins, and whole
 grains.  They're packed with nutrients and keep you feeling full and energized.
2. Mindful eating:  Pay attention to your body's hunger and fullness cues. 
Avoid distractions while eating.
3. Hydrate, hydrate, hydrate: Water is crucial for digestion, energy levels, 
and overall health.
4. Don't deprive yourself:  Allow for occasional treats.  
Deprivation can lead to overeating later.  Enjoy everything in moderation!
5. Plan ahead:  Prep your meals or snacks in advance to avoid unhealthy 
impulse decisions.

#healthyeating #healthylifestyle #nutrition #foodie 
#wellbeing #healthytips #eatclean #weightloss #healthyrecipes 
#nutritiontips #instahealth #healthyfood #mindfuleating #wellnessjourney 
#healthcoach

Certainly, we can make it very easy to create a group with other agents to search the list of content, investment and individual production of postal image. But I believe you have a common idea how to add a tool in Agent.

Another type of tool that can be accepted is the operate tool. We can use the Python work to serve as a LLM tool. Just don't forget to add directions for type as video_id:strSo the model knows what to use as a worksheet. Besides, you can see the error.

Let's take a brief look at how that works.

Now we want our agent to get the video given to it and summarize. To do such a job, we simply create video text work from YT and transfer the summary model.

# Imports
import os
from agno.agent import Agent
from agno.models.google import Gemini
from youtube_transcript_api import YouTubeTranscriptApi

# Get YT transcript
def get_yt_transcript(video_id:str) -> str:
      
    """
    Use this function to get the transcript from a YouTube video using the video id.

    Parameters
    ----------
    video_id : str
        The id of the YouTube video.
    Returns
    -------
    str
        The transcript of the video.
    """

    # Instantiate
    ytt_api = YouTubeTranscriptApi()
    # Fetch
    yt = ytt_api.fetch(video_id)
    # Return
    return ''.join([line.text for line in yt])


# Create agent
agent = Agent(
    model= Gemini(id="gemini-1.5-flash",
                  api_key = os.environ.get("GEMINI_API_KEY")),
                  description= "You are an assistant that summarizes YouTube videos.",
                  tools=[get_yt_transcript],
                  expected_output= "A summary of the video with the 5 main points and 2 questions for me to test my understanding.",
                  markdown=True,
                  show_tool_calls=True)


# Run agent
agent.print_response("""Summarize the text of the video with the id 'hrZSfMly_Ck' """,
                     markdown=True)

And then you have a result.

The result of the requested summary. Photo by author.

Agents that have consultation

Another cool option in the AGNO packet allows us to easily create agents that can analyze the situation before answering the question. It is a consultation tool.

We will build a consulting agent with Alaba's QWEN-QWQ-32b. Note that the only difference here, without model, is adding a tool ReasoningTools().

This page adding_instructions=True It means providing detailed instructions in the agent, which improves the integrity and accuracy of the use of its tools, while setting this False Icend that agent depends on their thinking, which is inclined to mistakes.

# Imports
import os
from agno.agent import Agent
from agno.models.groq import Groq
from agno.tools.reasoning import ReasoningTools


# Create agent with reasoning
agent = Agent(
    model= Groq(id="qwen-qwq-32b",
                  api_key = os.environ.get("GROQ_API_KEY")),
                  description= "You are an experienced math teacher.",
                  tools=[ReasoningTools(add_instructions=True)],
                  show_tool_calls=True)


# Writing and saving a file
agent.print_response("""Explain the concept of sin and cosine in simple terms.""",
                     stream=True,
                     show_full_reasoning=True,
                     markdown=True)

Following the result.

Effect of a consulting model. Photo by author.

Agent with information

This tool is an easy way to me to create a rebirth generation (RAG). For this feature, you can point to a agent on a website or website list, and will add content to the Vector database. Then, it is searching. Ever asked, the agent can use the content as part of the answer.

In this simple example, I added one page of my website and I asked the agel what books were counted there.

# Imports
import os
from agno.agent import Agent
from agno.models.google import Gemini
from agno.knowledge.url import UrlKnowledge
from agno.vectordb.lancedb import LanceDb, SearchType
from agno.embedder.sentence_transformer import SentenceTransformerEmbedder

# Load webpage to the knowledge base
agent_knowledge = UrlKnowledge(
    urls=["
    vector_db=LanceDb(
        uri="tmp/lancedb",
        table_name="projects",
        search_type=SearchType.hybrid,
        # Use Sentence Transformer for embeddings
        embedder=SentenceTransformerEmbedder(),
    ),
)

# Create agent
agent = Agent(
    model=Gemini(id="gemini-2.0-flash", api_key=os.environ.get("GEMINI_API_KEY")),
    instructions=[
        "Use tables to display data.",
        "Search your knowledge before answering the question.",
        "Only inlcude the content from the agent_knowledge base table 'projects'",
        "Only include the output in your response. No other text.",
    ],
    knowledge=agent_knowledge,
    add_datetime_to_instructions=True,
    markdown=True,
)

if __name__ == "__main__":
    # Load the knowledge base, you can comment out after first run
    # Set recreate to True to recreate the knowledge base if needed
    agent.knowledge.load(recreate=False)
    agent.print_response(
        "What are the two books listed in the 'agent_knowledge'",
        stream=True,
        show_full_reasoning=True,
        stream_intermediate_steps=True,
    )
Feedback from an agent after searching the basis of knowledge. Photo by author.

Agent with memory

The last kind of falling in this post is a agent with memory.

This agent can save and retrieve information about the users from previous communication, allowing a user reader and customizing its answers.

Let's look at this example when I will tell a few things on the agent and ask for recommendations based on that partners.

# imports
import os
from agno.agent import Agent
from agno.memory.v2.db.sqlite import SqliteMemoryDb
from agno.memory.v2.memory import Memory
from agno.models.google import Gemini
from rich.pretty import pprint

# User Name
user_id = "data_scientist"

# Creating a memory database
memory = Memory(
    db=SqliteMemoryDb(table_name="memory", 
                      db_file="tmp/memory.db"),
    model=Gemini(id="gemini-2.0-flash", 
                 api_key=os.environ.get("GEMINI_API_KEY"))
                 )

# Clear the memory before start
memory.clear()

# Create the agent
agent = Agent(
    model=Gemini(id="gemini-2.0-flash", api_key=os.environ.get("GEMINI_API_KEY")),
    user_id=user_id,
    memory=memory,
    # Enable the Agent to dynamically create and manage user memories
    enable_agentic_memory=True,
    add_datetime_to_instructions=True,
    markdown=True,
)


# Run the code
if __name__ == "__main__":
    agent.print_response("My name is Gustavo and I am a Data Scientist learning about AI Agents.")
    memories = memory.get_user_memories(user_id=user_id)
    print(f"Memories about {user_id}:")
    pprint(memories)
    agent.print_response("What topic should I study about?")
    agent.print_response("I write articles for Towards Data Science.")
    print(f"Memories about {user_id}:")
    pprint(memories)
    agent.print_response("Where should I post my next article?")
An example of AI agent with memory. Photo by author.

And here we finish this first text about agents AI.

Before you go

There is a lot of content on this post. We have increased the first step in this day of reading about agents AI. I know, amazing. There are so many details when it is more difficult to know where you can start and what to read.

My suggestion is to take the same road I take. One step at a time, selecting only a few packages like AGNO, crewai, and deeply on those, how to make how hard agents always create.

In this case, we started from the beginning, we learn that we can simply meet the llm to create agents with memory, or even to build a simple AI rag.

Obviously, there is more to do with one agent. Check Reference [4].

With these simple skills, be sure that you are in front of many people, and there is much to do. Just use art and (why not?) Ask for llm help to build something cool!

In the next post, we will learn a lot about agents and explore. Stay tuned!

GitHub Repository

Communication and availability of internet

If you have loved this content, find out some of my activities and social media on my website:

Progress

[1]

[2]

[3]

[4]

[5] / agents # or information

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button