What is phidata?

Phidata is a framework for building agentic systems, use phidata to:

  • Build powerful Agents with memory, knowledge, tools and reasoning. Phidata will manage the agent’s state, memory and knowledge in a database.
  • Run those agents as a software application (with a database, vectordb and api). Phidata will manage your infrastructure, both local and cloud (BYOC).
  • Monitor, evaluate and optimize your agentic system. Phidata will log your sessions and monitor key metrics to help you understand and improve your system.

Let’s start by building some agents.

Setup

1

Create a virtual environment

2

Install libraries

3

Export your OpenAI key

Phidata works with every LLM but for these examples let’s use OpenAI.

You can get an API key from here.

Web Search Agent

Let’s start by building a simple agent that can search the web, create a file web_search.py

1

Create a web search agent

web_search.py
from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.tools.duckduckgo import DuckDuckGo

web_agent = Agent(
    name="Web Agent",
    role="Search the web for information",
    model=OpenAIChat(id="gpt-4o"),
    tools=[DuckDuckGo()],
    markdown=True,
    show_tool_calls=True,
)
web_agent.print_response("Whats happening in France?", stream=True)
2

Run the agent

Install libraries

pip install duckduckgo-search

Run the agent

python web_search.py

Financial Agent

Lets create another agent that can query financial data, create a file finance_agent.py

1

Create a finance agent

finance_agent.py
from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.tools.yfinance import YFinanceTools

finance_agent = Agent(
    name="Finance Agent",
    role="Get financial data",
    model=OpenAIChat(id="gpt-4o"),
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True, company_news=True)],
    instructions=["Always use tables to display data"],
    markdown=True,
    show_tool_calls=True,
)
finance_agent.print_response("Share analyst recommendations for NVDA", stream=True)
2

Run the agent

Install libraries

pip install yfinance

Run the agent

python finance_agent.py

Team of Agents

A team of agents can work together to solve complex problems, create a file agent_team.py

1

Create an agent team

agent_team.py
from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.tools.duckduckgo import DuckDuckGo
from phi.tools.yfinance import YFinanceTools

web_agent = Agent(
    name="Web Agent",
    role="Search the web for information",
    model=OpenAIChat(id="gpt-4o"),
    tools=[DuckDuckGo()],
    markdown=True,
    show_tool_calls=True,
)

finance_agent = Agent(
    name="Finance Agent",
    role="Get financial data",
    model=OpenAIChat(id="gpt-4o"),
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True, company_info=True, company_news=True)],
    instructions=["Always use tables to display data"],
    markdown=True,
    show_tool_calls=True,
)

agent_team = Agent(
    team=[web_agent, finance_agent],
    show_tool_calls=True,
    markdown=True,
)
agent_team.print_response("Research the web for NVDA and share analyst recommendations", stream=True)
2

Run the agent team

Run the agent team

python agent_team.py

Reasoning Agent

Reasoning helps agents work through a problem step-by-step, backtracking and correcting as needed. Let’s give our reasonining agent a simple task that gpt-4o fails at. Create a file reasoning_agent.py

1

Create a reasoning agent

reasoning_agent.py
from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.cli.console import console

regular_agent = Agent(model=OpenAIChat(id="gpt-4o"), markdown=True)
reasoning_agent = Agent(
    model=OpenAIChat(id="gpt-4o-2024-08-06"),
    reasoning=True,
    markdown=True,
    structured_outputs=True,
)

task = "How many 'r' are in the word 'supercalifragilisticexpialidocious'?"

console.rule("[bold green]Regular Agent[/bold green]")
regular_agent.print_response(task, stream=True)
console.rule("[bold yellow]Reasoning Agent[/bold yellow]")
reasoning_agent.print_response(task, stream=True, show_full_reasoning=True)
2

Run the reasoning agent

python reasoning_agent.py

If using tools with reasoning=True, set structured_outputs=False because gpt-4o doesnt support tools with structured outputs.

RAG Agent

Instead of always inserting the “context” into the prompt, the RAG Agent can search its knowledge base (vector db) for the specific information it needs to achieve its task.

This saves tokens and improves response quality. Create a file rag_agent.py

1

Create a RAG agent

rag_agent.py
from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.lancedb import LanceDb, SearchType

db_uri = "tmp/lancedb"
# Create a knowledge base from a PDF
knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://phi-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    # Use LanceDB as the vector database
    vector_db=LanceDb(table_name="recipes", uri=db_uri, search_type=SearchType.vector),
)
# Load the knowledge base: Comment out after first run
knowledge_base.load(upsert=True)

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    # Add the knowledge base to the agent
    knowledge=knowledge_base,
    show_tool_calls=True,
    markdown=True,
)
agent.print_response("How do I make chicken and galangal in coconut milk soup")
2

Run the agent

Install libraries

pip install lancedb tantivy pypdf sqlalchemy pgvector 'psycopg[binary]'

Run the agent

python rag_agent.py

Structured Outputs

Use structured outputs to enforce the structure of the output from an agent and make the agent return a pydantic object. Create a file structured_output.py

1

Create a structured output agent

structured_output.py
from typing import List
from pydantic import BaseModel, Field
from phi.agent import Agent
from phi.model.openai import OpenAIChat

# Define a Pydantic model to enforce the structure of the output
class MovieScript(BaseModel):
    setting: str = Field(..., description="Provide a nice setting for a blockbuster movie.")
    ending: str = Field(..., description="Ending of the movie. If not available, provide a happy ending.")
    genre: str = Field(..., description="Genre of the movie. If not available, select action, thriller or romantic comedy.")
    name: str = Field(..., description="Give a name to this movie")
    characters: List[str] = Field(..., description="Name of characters for this movie.")
    storyline: str = Field(..., description="3 sentence storyline for the movie. Make it exciting!")

# Agent that uses JSON mode
json_mode_agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    description="You write movie scripts.",
    response_model=MovieScript,
)
# Agent that uses structured outputs
structured_output_agent = Agent(
    model=OpenAIChat(id="gpt-4o-2024-08-06"),
    description="You write movie scripts.",
    response_model=MovieScript,
    structured_outputs=True,
)

json_mode_agent.print_response("New York")
structured_output_agent.print_response("New York")
2

Run the agent

python structured_output.py

Ready to build?

Start building your own agents or use a template to build a full-stack agentic system.

Looking for dedicated support?

We’ve helped many companies build AI products, the general workflow is:

  1. Build agents to perform tasks specific to your product.
  2. Serve your agents via an API and connect them to your product.
  3. Monitor, evaluate and improve your AI product.

We provide dedicated support and development, book a call to get started.