Phidata (Agno) Tutorial: Build Powerful AI Agents with a Simple Framework

# Tutorial Phidata (Agno): Framework AI Agent yang Simpel dan Powerful Membangun AI agent yang cerdas dan otonom kini semakin mudah dengan hadirnya **Phidata** (sekarang dikenal sebagai **Agno**). Fr...

By Ruby Abdullah · · tutorial
PhidataAI AgentLLMAutonomous AgentPython

Phidata (Agno) Tutorial: Build Powerful AI Agents with a Simple Framework

Building intelligent and autonomous AI agents is now easier than ever with Phidata (now known as Agno). This framework offers a simpler approach compared to CrewAI or LangGraph, while remaining powerful enough for various use cases from simple chatbots to complex multi-agent systems.

In this tutorial, we will learn how to build AI agents using Phidata/Agno from scratch, culminating in building a research agent that can search the web and write reports automatically.

What is Phidata/Agno?

Phidata is an open-source framework for building AI agents with Python. It is designed with a simplicity-first philosophy, where you can create a functional agent with just a few lines of code. Phidata recently rebranded to Agno, but the concepts and API remain consistent.

Key advantages of Phidata/Agno:

  • Easy to learn: Intuitive API and comprehensive documentation
  • Built-in tools: Web search, file operations, SQL, and much more
  • Knowledge bases: Integration with vector databases for RAG
  • Memory and storage: Agents that remember conversation context
  • Multi-agent teams: Orchestrate multiple agents simultaneously
  • Structured outputs: Type-safe outputs with Pydantic models
  • Streaming: Real-time streaming response support

Installation and Setup

Package Installation

# Install Phidata/Agno

pip install agno

Or using the legacy name

pip install phidata

Additional dependencies for tools

pip install openai duckduckgo-search sqlalchemy pgvector

API Key Configuration

# Set environment variable for OpenAI

export OPENAIAPIKEY="sk-your-api-key-here"

Or use a .env file

echo 'OPENAIAPIKEY=sk-your-api-key-here' > .env

# Or set directly in Python

import os

os.environ["OPENAIAPIKEY"] = "sk-your-api-key-here"

Creating Your First Agent

Simple Agent

from agno.agent import Agent

from agno.models.openai import OpenAIChat

Create a simple agent

agent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

description="You are a helpful and friendly assistant.",

instructions=[

"Answer clearly and concisely",

"Provide well-structured responses"

],

markdown=True

)

Run the agent

agent.printresponse("Explain what machine learning is in 3 paragraphs")

Agent with Detailed System Prompt

agent = Agent(

model=OpenAIChat(id="gpt-4o"),

description="You are a senior data scientist with 10 years of experience.",

instructions=[

"Provide technical but easy-to-understand answers",

"Include Python code examples when relevant",

"Use analogies to explain complex concepts",

"Always recommend best practices"

],

markdown=True,

showtoolcalls=True

)

response = agent.run("How do I handle imbalanced datasets?")

print(response.content)

Using Tools

Tools are the most powerful feature of Phidata/Agno. Agents can use tools to interact with the outside world such as searching the web, reading files, or querying databases.

Web Search Tool

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.tools.duckduckgo import DuckDuckGoTools

Agent with web search capability

webagent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

tools=[DuckDuckGoTools()],

description="You are a research assistant that can search the internet.",

instructions=[

"Always search for the latest information before answering",

"Include information sources",

"Provide well-structured summaries"

],

showtoolcalls=True,

markdown=True

)

webagent.printresponse("What are the latest AI developments in Southeast Asia in 2026?")

File Operations Tool

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.tools.file import FileTools

Agent that can read and write files

fileagent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

tools=[FileTools(basedir="./output")],

description="You are an assistant that can manage files.",

instructions=[

"Read requested files and provide summaries",

"Write analysis results to new files when asked"

],

showtoolcalls=True

)

fileagent.printresponse("Create a file report.txt with a summary of AI trends in 2026")

SQL Tool

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.tools.sql import SQLTools

Agent that can query databases

sqlagent = Agent(

model=OpenAIChat(id="gpt-4o"),

tools=[SQLTools(

dburl="postgresql://user:password@localhost:5432/mydb"

)],

description="You are a database analyst.",

instructions=[

"Analyze user questions and create appropriate SQL queries",

"Explain query results in easy-to-understand language",

"Never execute DELETE or DROP without confirmation"

],

showtoolcalls=True,

markdown=True

)

sqlagent.printresponse("What are the total sales last month by product category?")

Custom Tools

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.tools import tool

Define custom tools

@tool

def calculatebmi(weightkg: float, heightm: float) -> str:

"""Calculate Body Mass Index (BMI) based on weight and height.

Args:

weightkg: Weight in kilograms

heightm: Height in meters

Returns:

BMI calculation result and category

"""

bmi = weightkg / (heightm * 2)

if bmi < 18.5:

category = "Underweight"

elif bmi < 25:

category = "Normal"

elif bmi < 30:

category = "Overweight"

else:

category = "Obese"

return f"BMI: {bmi:.1f} - Category: {category}"

@tool

def getweather(city: str) -> str:

"""Get weather information for a specific city.

Args:

city: City name

Returns:

Weather information

"""

# Simulated weather data

return f"Weather in {city}: Sunny, 28C, Humidity 65%"

Agent with custom tools

healthagent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

tools=[calculatebmi, getweather],

description="You are a health assistant.",

showtoolcalls=True

)

healthagent.printresponse("Calculate my BMI: weight 70kg, height 1.75m")

Knowledge Bases

Knowledge bases allow agents to access specific data using RAG (Retrieval Augmented Generation) techniques.

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.knowledge.pdf import PDFKnowledgeBase

from agno.vectordb.pgvector import PgVector

Create knowledge base from PDFs

knowledgebase = PDFKnowledgeBase(

path="./documents",

vectordb=PgVector(

tablename="pdfdocuments",

dburl="postgresql+psycopg://user:pass@localhost:5432/ai"

)

)

Load documents into vector database (run once)

knowledgebase.load()

Agent with knowledge base

docagent = Agent(

model=OpenAIChat(id="gpt-4o"),

knowledge=knowledgebase,

description="You are an assistant that answers based on company documents.",

instructions=[

"Answer ONLY based on information from the knowledge base",

"If information is not found, say so honestly",

"Include references to source documents"

],

searchknowledge=True,

markdown=True

)

docagent.printresponse("What is the employee leave policy?")

Knowledge Base from Websites

from agno.knowledge.website import WebsiteKnowledgeBase

from agno.vectordb.pgvector import PgVector

webkb = WebsiteKnowledgeBase(

urls=["https://docs.python.org/3/tutorial/"],

maxdepth=2,

vectordb=PgVector(

tablename="pythondocs",

dburl="postgresql+psycopg://user:pass@localhost:5432/ai"

)

)

webkb.load()

Memory and Storage

Agents can store conversation context and remember previous interactions.

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.memory.db.postgres import PgMemory

from agno.storage.postgres import PostgresStorage

Agent with memory and storage

persistentagent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

# Memory to remember conversations

memory=PgMemory(

tablename="agentmemory",

dburl="postgresql+psycopg://user:pass@localhost:5432/ai"

),

# Storage to save sessions

storage=PostgresStorage(

tablename="agentsessions",

dburl="postgresql+psycopg://user:pass@localhost:5432/ai"

),

description="You are a personal assistant that remembers previous conversations.",

instructions=[

"Remember user preferences and context from previous conversations",

"Personalize answers based on interaction history"

],

# Enable memory features

addhistorytomessages=True,

numhistoryresponses=5,

createusermemories=True,

markdown=True

)

Session 1

persistentagent.printresponse(

"My name is Alex, I'm a data engineer in Singapore",

sessionid="user-alex-001"

)

Session 2 - agent will remember previous context

persistentagent.printresponse(

"Recommend books for my profession",

sessionid="user-alex-001"

)

Multi-Agent Teams

Phidata/Agno allows you to create teams of agents that work together to accomplish complex tasks.

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.tools.duckduckgo import DuckDuckGoTools

from agno.tools.file import FileTools

Researcher Agent

researcher = Agent(

name="Researcher",

model=OpenAIChat(id="gpt-4o"),

tools=[DuckDuckGoTools()],

description="You are a researcher skilled at finding and analyzing information.",

instructions=[

"Search for relevant and up-to-date information",

"Verify facts from multiple sources",

"Provide accurate data and statistics"

]

)

Writer Agent

writer = Agent(

name="Writer",

model=OpenAIChat(id="gpt-4o"),

tools=[FileTools(basedir="./output")],

description="You are a professional content writer.",

instructions=[

"Write engaging and informative content",

"Use clear structure with headings and bullet points",

"Adapt writing style to the target audience"

]

)

Team Leader coordinating agents

teamleader = Agent(

name="Team Leader",

model=OpenAIChat(id="gpt-4o"),

team=[researcher, writer],

description="You are a project manager coordinating the research and writing team.",

instructions=[

"Delegate research tasks to Researcher",

"Delegate writing tasks to Writer",

"Ensure high-quality final output",

"Review and combine results from all agents"

],

showtoolcalls=True,

markdown=True

)

teamleader.printresponse(

"Write an article about generative AI developments in Southeast Asia 2026"

)

Structured Outputs

Phidata/Agno supports structured outputs using Pydantic models to get type-safe and consistent responses.

from pydantic import BaseModel, Field

from typing import List, Optional

from agno.agent import Agent

from agno.models.openai import OpenAIChat

Define output schema

class MovieReview(BaseModel):

title: str = Field(description="Movie title")

genre: List[str] = Field(description="Movie genres")

rating: float = Field(description="Rating 1-10")

summary: str = Field(description="Review summary")

pros: List[str] = Field(description="Movie strengths")

cons: List[str] = Field(description="Movie weaknesses")

recommendation: bool = Field(description="Whether recommended")

Agent with structured output

reviewagent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

description="You are a professional film critic.",

responsemodel=MovieReview

)

Response will be a MovieReview object

response = reviewagent.run("Review the movie The Matrix")

review = response.content

print(f"Movie: {review.title}")

print(f"Rating: {review.rating}/10")

print(f"Recommended: {'Yes' if review.recommendation else 'No'}")

Structured Output for Data Extraction

class CompanyInfo(BaseModel):

name: str

industry: str

foundedyear: Optional[int]

headquarters: Optional[str]

products: List[str]

employeecount: Optional[str]

extractagent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

description="You extract company information from text.",

responsemodel=CompanyInfo

)

text = """

Grab is a Southeast Asian technology company founded in 2012 in Malaysia.

The company provides ride-hailing, food delivery (GrabFood), digital

payments (GrabPay), and logistics services. Grab has more than 8000

employees across the region.

"""

response = extractagent.run(f"Extract company information: {text}")

info = response.content

print(f"Company: {info.name}")

print(f"Products: {', '.join(info.products)}")

Streaming Responses

Streaming allows you to receive responses in real-time, ideal for chatbot applications.

from agno.agent import Agent

from agno.models.openai import OpenAIChat

agent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

description="You are a creative storyteller.",

markdown=True

)

Streaming response

for chunk in agent.run("Tell a story about a robot learning to cook", stream=True):

print(chunk.content, end="", flush=True)

Streaming with Tools

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.tools.duckduckgo import DuckDuckGoTools

agent = Agent(

model=OpenAIChat(id="gpt-4o-mini"),

tools=[DuckDuckGoTools()],

showtoolcalls=True,

markdown=True

)

Stream response including tool calls

responsestream = agent.run(

"Search for the latest news about AI startups in Southeast Asia",

stream=True

)

for chunk in responsestream:

if chunk.content:

print(chunk.content, end="", flush=True)

if chunk.toolcalls:

for toolcall in chunk.toolcalls:

print(f"\n[Calling tool: {toolcall.function.name}]")

Practical Project: Research Agent

Let us build a complete research agent that can search for information on the web, analyze it, and write a structured report.

from agno.agent import Agent

from agno.models.openai import OpenAIChat

from agno.tools.duckduckgo import DuckDuckGoTools

from agno.tools.file import FileTools

from pydantic import BaseModel, Field

from typing import List

from datetime import datetime

Schema for research report

class ResearchSection(BaseModel):

heading: str = Field(description="Section heading")

content: str = Field(description="Section content")

sources: List[str] = Field(description="Reference sources")

class ResearchReport(BaseModel):

title: str = Field(description="Report title")

executivesummary: str = Field(description="Executive summary")

sections: List[ResearchSection] = Field(description="Report sections")

conclusion: str = Field(description="Conclusion")

recommendations: List[str] = Field(description="Recommendations")

Research agent

researchagent = Agent(

name="WebResearcher",

model=OpenAIChat(id="gpt-4o"),

tools=[DuckDuckGoTools()],

description="You are a researcher skilled at finding and gathering information.",

instructions=[

"Search for information from multiple sources",

"Focus on the latest and most reliable data",

"Record all reference sources",

"Provide relevant facts and statistics"

],

showtoolcalls=True

)

Report writing agent

writeragent = Agent(

name="ReportWriter",

model=OpenAIChat(id="gpt-4o"),

tools=[FileTools(basedir="./reports")],

description="You are a professional report writer.",

instructions=[

"Write structured and comprehensive reports",

"Use formal but accessible language",

"Include supporting data and references",

"Create actionable recommendations"

]

)

Team coordinator

researchteam = Agent(

name="ResearchCoordinator",

model=OpenAIChat(id="gpt-4o"),

team=[researchagent, writeragent],

description="You coordinate the research and report writing process.",

instructions=[

"1. Ask WebResearcher to search for information on the topic",

"2. Analyze and synthesize search results",

"3. Ask ReportWriter to write a complete report",

"4. Review and ensure report quality"

],

responsemodel=ResearchReport,

showtoolcalls=True,

markdown=True

)

Run research

topic = "AI implementation in the banking sector in Southeast Asia 2026"

response = researchteam.run(f"Create a research report on: {topic}")

report = response.content

print(f"\n{'='60}")

print(f"REPORT: {report.title}")

print(f"{'='*60}")

print(f"\nExecutive Summary:\n{report.executivesummary}")

for section in report.sections:

print(f"\n## {section.heading}")

print(section.content)

print(f"Sources: {', '.join(section.sources)}")

print(f"\nConclusion:\n{report.conclusion}")

print(f"\nRecommendations:")

for i, rec in enumerate(report.recommendations, 1):

print(f" {i}. {rec}")

Running the Project

# Create project directory

mkdir research-agent && cd research-agent

Setup virtual environment

python -m venv venv

source venv/bin/activate

Install dependencies

pip install agno openai duckduckgo-search

Set API key

export OPENAIAPIKEY="your-key-here"

Run the script

python researchagent.py

Tips and Best Practices

  • Choose the right model: Use gpt-4o-mini for simple tasks and gpt-4o for complex ones. This saves costs without sacrificing quality.
  • Write specific instructions: The more specific your instructions, the better the agent's output. Avoid ambiguous instructions.
  • Use structured outputs: For production applications, always use Pydantic models to ensure consistent output.
  • Limit tool access: Only provide tools that the agent actually needs. Too many tools can confuse the agent.
  • Monitor token usage: Use debug_mode=True to see the number of tokens used per request.
  • Handle errors gracefully: Always wrap agent calls in try-except blocks to handle API errors.
  • try:
    

    response = agent.run("query here")

    except Exception as e:

    print(f"Error: {e}")

    # Implement retry logic or fallback

    Conclusion

    Phidata/Agno is an excellent framework for building AI agents quickly and efficiently. Compared to other frameworks like CrewAI or LangGraph, Phidata offers a lower learning curve without sacrificing flexibility. With features like built-in tools, knowledge bases, memory, and multi-agent teams, you can build complex AI systems with clean and maintainable code.

    Start with a simple agent, add tools as needed, and gradually increase the complexity of your system. Happy building!

    Related Articles

    Browser-Use Tutorial: AI-Powered Browser Automation with LLM Agents

    Tutorial Browser-Use: Automasi Browser dengan AI Agent Pendahuluan Browser-Use adalah library Python open-source yang me...

    CrewAI Tutorial: Building Multi-Agent AI Framework

    CrewAI - Framework AI Multi-Agen Daftar Isi Pendahuluan Prasyarat Instalasi dan Pengaturan Konsep Dasar 5...

    MergeKit Tutorial: Merging LLM Models to Create Custom AI Models

    Tutorial MergeKit: Menggabungkan Model LLM untuk Membuat Model AI Kustom Model bahasa besar (LLM) open-source terus berk...

    Semantic Router Tutorial: Smart Routing for LLM Applications

    Tutorial Semantic Router: Routing Cerdas untuk Aplikasi LLM Semantic Router adalah library Python yang memungkinkan Anda...