Introduction To Building AI Agents With Phidata And Python

Phidata is a Python framework designed for creating AI assistants that leverage Large Language Models (LLMs), memory, knowledge, and tools. If you’ve ever wanted to create intelligent assistants capable of performing a range of tasks autonomously, you’re in the right place. This article walks through the process of setting up your environment for using Phidata, integrating various tools, and developing AI agents using Python.

What is Phidata?

Phidata is a Python framework designed for creating AI assistants that leverage memory, knowledge, and tools. It allows you to transform large language models (LLMs) into specialized assistants tailored to specific use cases. Phidata integrates seamlessly with various APIs, databases, and other tools, enabling your AI agents to perform complex tasks efficiently.

Why Use Phidata?

There is a growing demand for creating intelligent assistants that can perform complex tasks efficiently. Phidata is an open source tools built for this specific need. It extends the capabilities of general-purpose large language models (LLMs) by integrating essential components like memory, knowledge, and tools. These additions transform LLMs into specialized assistants tailored to specific use cases, making them smarter and more autonomous.

Phidata offers a seamless Python framework for developing AI assistants that can handle long-term interactions by storing chat histories, provide contextual responses by retrieving relevant information from a knowledge base, and perform a wide range of actions through integrated tools. This makes it an invaluable resource for developers looking to build sophisticated AI applications without the hassle of managing multiple disparate systems. Whether you’re developing a customer service bot, a financial advisor, or a research assistant, Phidata’s comprehensive approach simplifies the process and enhances the capabilities of your AI agents.

Phidata extends the capabilities of general-purpose LLMs by adding three critical components:

  • Memory: Stores chat history and contextual information in a database, enabling long-term interactions.
  • Knowledge: Utilizes a vector database to store and retrieve relevant information, providing context to LLMs.
  • Tools: Allows LLMs to execute actions like querying databases, pulling data from APIs, and more.

By combining these elements, Phidata makes your AI agents smarter and more autonomous.

What is an AI Agent?

AI agents are advanced implementations of artificial intelligence designed to autonomously perform tasks, make decisions, and interact with users or systems. They simulate human-like cognitive functions, enabling them to process information, learn from interactions, and adapt to new scenarios without human intervention. Core characteristics include autonomy, learning and adaptation, interaction, and goal-oriented behavior. AI agents automate tasks, enhance efficiency, and can be used in various applications like customer service, data analysis, content generation, and personal assistance. They are pivotal in modern AI development, driving innovation across industries.

Building “AI Assistants” is the way to use this tool to build AI Agents (or Agentic AI solutions) using Python and Phidata.

Setting Up Your Environment

Before diving into building AI agents, you need to set up your development environment. Follow these steps to create a virtual environment and install Phidata.

Step 1: Create a Virtual Environment

Creating a virtual environment ensures that your project dependencies are isolated. This is crucial for maintaining a clean and manageable development setup.

python3 -m venv ai_env
source ai_env/bin/activate

Step 2: Install Phidata

With your virtual environment activated, install Phidata using pip.

pip install -U phidata

Building Your First AI Agent with Phidata

Let’s start by building a simple AI agent that can perform web searches using DuckDuckGo. This example will help you understand the basics of creating and running an assistant with Phidata.

Step 1: Create the Assistant

First, create a file named assistant.py and add the following code:

from phi.assistant import Assistant
from phi.tools.duckduckgo import DuckDuckGo

assistant = Assistant(tools=[DuckDuckGo()], show_tool_calls=True)
assistant.print_response("What's happening in France?", markdown=True)

Step 2: Run the Assistant

Run your assistant by executing the following command:

python assistant.py

Your assistant will now perform a web search and return the latest news from France.

Advanced AI Agent: RAG Assistant

Retrieval-Augmented Generation (RAG) enhances AI responses by providing additional context from a knowledge base. In this section, we’ll create a RAG assistant using Phidata.

Step 1: Create a Knowledge Base

We’ll use a PDF document as our knowledge base. Create a file named rag_assistant.py and add the following code:

from phi.assistant import Assistant
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.pgvector import PgVector2

knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://phidata-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    vector_db=PgVector2(
        collection="recipes",
        db_url="postgresql+psycopg://ai:ai@localhost:5532/ai",
    ),
)
knowledge_base.load(recreate=False)

assistant = Assistant(
    knowledge_base=knowledge_base,
    add_references_to_prompt=True,
)
assistant.print_response("How do I make pad thai?", markdown=True)

Step 2: Run the RAG Assistant

Execute your RAG assistant:

python rag_assistant.py

The assistant will provide detailed instructions on making pad thai, pulling relevant information from the PDF knowledge base.

Building Specialized AI Assistants

Creating a general AI assistant is just the beginning. To truly harness the power of AI, you need to develop specialized assistants tailored to specific tasks and industries. Whether it’s financial analysis, data management, or customer support, Phidata provides the tools and flexibility needed to build AI assistants that meet particular requirements. By integrating various functionalities and customizing the assistants to perform specific actions, you can enhance efficiency and accuracy in their respective fields.

The following examples illustrate the versatility of Phidata and demonstrate how you can leverage its capabilities to build sophisticated, task-oriented AI solutions.

Finance Assistant

Whether you’re managing investments, analyzing market trends, or comparing company performances, having an intelligent assistant can make all the difference. Enter the Finance Assistant—a specialized AI agent designed to streamline financial tasks and provide valuable insights at your fingertips. Using Phidata, you can build a powerful finance assistant that integrates with financial data sources and leverages advanced analytics to deliver up-to-date information and comprehensive reports.

Create an assistant that provides financial information using the YFinance tool.

from phi.assistant import Assistant
from phi.llm.openai import OpenAIChat
from phi.tools.yfinance import YFinanceTools

assistant = Assistant(
    llm=OpenAIChat(model="gpt-4"),
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True, company_news=True)],
    show_tool_calls=True,
    markdown=True,
)
assistant.print_response("What is the stock price of NVDA?")
assistant.print_response("Write a comparison between NVDA and AMD, using all available tools.")

Run the finance assistant:

python finance_assistant.py

Data Analysis Assistant

Whether you’re a data scientist, analyst, or business professional, a specialized AI assistant for data analysis can be a game-changer. With Phidata, you can build a Data Analysis Assistant that automates complex data queries, performs detailed analyses, and presents insights in a clear, actionable format.

Create an assistant that performs data analysis using SQL.

import json
from phi.assistant.duckdb import DuckDbAssistant

duckdb_assistant = DuckDbAssistant(
    semantic_model=json.dumps({
        "tables": [
            {
                "name": "movies",
                "description": "Contains information about movies from IMDB.",
                "path": "https://phidata-public.s3.amazonaws.com/demo_data/IMDB-Movie-Data.csv",
            }
        ]
    }),
)
duckdb_assistant.print_response("What is the average rating of movies? Show me the SQL.", markdown=True)

Run the data analysis assistant:

pip install duckdb
python data_assistant.py

Deploying Your AI Assistant

Once you’ve built and fine-tuned your AI assistant, the next crucial step is deployment. This phase is where your assistant transitions from a development environment to a live application, ready to interact with users and perform tasks in real-time. Effective deployment ensures that your AI assistant is accessible, scalable, and capable of delivering consistent performance.

The following is a simple example using FastApi.

Step 1: Create a FastApi Application

Create a file named app.py and add the following code:

from fastapi import FastAPI
from phi.assistant import Assistant
from phi.tools.duckduckgo import DuckDuckGo

app = FastAPI()

assistant = Assistant(tools=[DuckDuckGo()], show_tool_calls=True)

@app.get("/search")
async def search(query: str):
    response = assistant.print_response(query, markdown=True)
    return {"response": response}

Step 2: Run the FastApi Server

Run your FastApi server:

uvicorn app:app --reload

Visit http://localhost:8000/search?query=What's happening in France? to see your assistant in action.

Conclusion

Building AI agents with Phidata and Python offers a powerful way to create intelligent and autonomous applications. By integrating memory, knowledge, and tools, you can design assistants tailored to various tasks and industries. This guide has provided you with the foundation to start creating your own AI agents. As you continue to explore and innovate, you’ll find even more ways to leverage Phidata’s capabilities to build advanced AI solutions.