How to Build a Web Search Agent with Phidata: A Step-by-Step Guide - Incentius Blog Home - Incentius - Enable Digital Transformation  

[![Logo](/img_astro/incentius-logo.svg)](/)

Solutions

About

[Case Studies](/portfolio/)

[Blogs](/blog-posts/)

[Career](http://aurochs.freshteam.com/jobs)

Open main menu ![Menu icon](/img_astro/menu1.png)  

[Get In Touch](/contact/)

Solutions

 [![](/img_astro/generative-black.svg) ![](/img_astro/brain-green.svg)

Voice AI](/voice-ai/)

 [![](/img_astro/product-development-black.svg) ![](/img_astro/product-development.svg)

Product Development](/product-engineering/)

 [![](/img_astro/generative-black.svg) ![](/img_astro/brain-green.svg)

Generative AI](/generative-ai/)

 [![](/img_astro/data-black.svg) ![](/img_astro/database-green.svg)

Data Engineering](/data-engineering/)

 [![](/img_astro/mvp-black.svg) ![](/img_astro/rocket-green.svg)

Data & Analytics](/data-analytics/)

 [![](/img_astro/cloud-black.svg) ![](/img_astro/computing-green.svg)

DevOps & CloudOps](/devops-and-cloudops/)

About Us

  [![](/img_astro/product-black.svg)  ![](/img_astro/product-green.svg)

About Us](/about-us/)

  [![](/img_astro/team_black.svg)  ![](/img_astro/team_green.svg)

Team](/team/)

Solutions ![](/img_astro/dropdown-arr.svg) 

[

![](/img_astro/generative-black.svg)

Voice AI



](/voice-ai/)[

![](/img_astro/product-development-black.svg)

Product Development



](/product-engineering/)[

![](/img_astro/generative-black.svg)

Generative AI



](/generative-ai/)[

![](/img_astro/data-black.svg)

Data Engineering



](/data-engineering/)[

![](/img_astro/mvp-black.svg)

Data & Analytics



](/data-analytics/)[

![](/img_astro/cloud-black.svg)

DevOps & CloudOps



](/devops-and-cloudops/)

[Blogs](/blog-posts/) About ![](/img_astro/dropdown-arr.svg) 

[

![](/img_astro/product-black.svg)

About Us



](/about-us/)[

![](/img_astro/team_black.svg)

Team



](/team/)

[Case Studies](/portfolio/) [Career](http://aurochs.freshteam.com/jobs)

[Get In Touch](/contact/)

How to Build a Web Search Agent with Phidata: A Step-by-Step Guide

Kartik Puri

1.  Apr 02, 2025
2.  4 min read

![](/_astro/Screenshot_2025-04-02_at_12.09.33_PM.width-1000_ZyU6y1.webp)

Phidata is an **open-source framework** for building AI agents with capabilities like memory, tool use, and reasoning​ It’s model-agnostic and supports various large language models (LLMs), allowing developers to turn any LLM (like OpenAI GPT or local models) into a functional **search agent**. In this tutorial, we’ll walk through creating a web search agent using Phidata. The agent will be able to query the web (via a search API) and return answers with source citations. We’ll cover the setup, code structure, an example implementation, and tips for optimizing performance.

## **Overview of Phidata for Web Search Agents**

Phidata simplifies the creation of AI agents by providing abstractions for **models** (LLMs), **tools** (for actions like web search), **memory**, and **knowledge integration**​.For web search use cases, Phidata comes with pre-built toolkits such as DuckDuckGo, Google Search, SerpAPI, etc., enabling agents to retrieve real-time information from the web​

## **Why Phidata?**

Phidata is model-agnostic, so it supports different LLM providers (including OpenAI, local models, etc.). It also comes with built-in tools for common tasks like searching the web, extracting website content, or reading PDFs. By simply configuring your agent to use these tools, you can give it the power to find and summarize real-time information.

## **Setting Up the Environment and Dependencies**

Before writing code, ensure your development environment is ready:

1.  **Python Environment:** Make sure you have Python 3 installed. It’s recommended to use a virtual environment for isolation. For example, on macOS/Linux you can create one with:

```

python3 -m venv aienv
source aienv/bin/activate
```

1.  **Install Phidata and Tools:** Phidata is available on PyPI. You’ll also need the OpenAI client library (if using OpenAI’s model) and a search toolkit. For a DuckDuckGo-based web agent, install the following:  
    **pip install phidata openai duckduckgo-search**  
    This installs Phidata, OpenAI’s Python SDK, and the DuckDuckGo search toolkit​  
    [github.com](https://github.com/agno-agi/phidata#:%7E:text=Install%20libraries%2C%20export%20your%20,and%20run%20the%20Agent)
2.  **Set API Keys:** If you plan to use OpenAI’s GPT model, set your OpenAI API key as an environment variable. For example: **export OPENAI\_API\_KEY=sk-<your\_openai\_key>**  
    Phidata will use this key when calling OpenAI’s API​  
    [github.com](https://github.com/agno-agi/phidata#:%7E:text=Install%20libraries%2C%20export%20your%20,and%20run%20the%20Agent)
3.  **Optional Dependencies:** Depending on customizations, you might install other toolkits. For instance, Phidata’s Google Search tool requires **googlesearch-python** and **pycountry**​

For this tutorial, DuckDuckGo’s library is sufficient, which we already installed. With the environment ready and dependencies installed, we can proceed to build the agent.

## **Writing the Phidata Web Search Agent Code**

Now, let’s create the search agent script. Open a text editor and create a file (e.g., **web\_search.py**). Add the following code to define a web search agent:

```

from phi.agent import Agent
from phi.model.openai import OpenAIChat
from phi.tools.duckduckgo import DuckDuckG


#### Initialize the language model (OpenAI GPT-4 in this case)

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

#### Initialize the web search agent with the DuckDuckGo tool

    web_agent = Agent(
        name="Web Search Agent",
        model=model,
        tools=[DuckDuckGo()],
        instructions=["Always include sources"],
        show_tool_calls=True,
        markdown=True,
    )
```

**Ask the agent a sample question and print the response**

```

query = "Tell me about OpenAI Sora?"
web_agent.print_response(query, stream=True)
```

Let’s break down this code and explain the key components:

*   **Imports:** We import **Agent** from **phi.agent**, the OpenAI chat model wrapper, and the DuckDuckGo tool class. These are provided by Phidata’s library​
*   **Model Setup:** **OpenAIChat(id="gpt-4o")** creates an LLM instance for the agent​

Here we chose an OpenAI GPT-4 model (denoted by \`"gpt-4o"\` in Phidata). You could switch this to a different model if needed (e.g., GPT-3.5 or a local model via Ollama as in the Dev example​

*   **Agent Initialization:** We create an Agent with several parameters​

```

`name`: A human-friendly name for the agent (optional, used for logging or UI).
`model`: The LLM to use (the `OpenAIChat` instance we created).
`tools`: A list of tools the agent can use. Here we pass `[DuckDuckGo()]`, enabling web search capability​
    
  . The DuckDuckGo tool allows the agent to perform web queries and fetch news via DuckDuckGo’s API​
   
`instructions`: A list of guidelines for the agent. We include `"Always include sources"` to prompt the agent to add source references in its answers​
   
    These instructions are incorporated into the agent’s system prompt, influencing its behavior​
```

*   **Using the Agent:** Finally, we use **web\_agent.print\_response(query, stream=True)** to run the agent on a query and print the answer​  
      
    The **stream=True** option streams the response tokens as they are generated, which is handy for interactive use. You can set **stream=False** to wait and get the full response at once (the default is False if not specified).

## **Step 3: Run Your Agent**

Simply execute:

**python web\_search.py**

When prompted, the agent will search DuckDuckGo for the latest information on France, then generate a summarized answer. If you watch the console, you’ll notice output indicating when the agent makes a search call. Finally, you’ll get a response with a brief summary along with any relevant sources.

## **Best Practices for Optimizing Search Performance**

Building a search agent is powerful, but to make it efficient and reliable, consider the following best practices:

*   **Limit Search Results:** By default, the DuckDuckGo toolkit will return a number of results (the exact number can vary). If you only need the top few hits, set the **fixed\_max\_results** parameter for the DuckDuckGo tool. For example, **DuckDuckGo(fixed\_max\_results=5)** will limit to 5 results​  
    [docs.phidata.com](https://docs.phidata.com/tools/duckduckgo#:%7E:text=,be%20sent%20with%20HTTP%20requests)  
    *   This can speed up the search and reduce noise. Similarly, other search tools like GoogleSearch have parameters like **max\_results**​
    *   [docs.phidata.com](https://docs.phidata.com/tools/googlesearch#:%7E:text=Function%20Description%20,as%20a%20JSON%20formatted%20string)
*   **Use Caching for Repeated Queries:** If your agent will handle recurring queries or is part of a larger workflow, caching results can improve performance. Phidata supports caching via its storage mechanism. For instance, you could store search results in a local SQLite database and reuse them to avoid calling the search API repeatedly​  
    [docs.phidata.com](https://docs.phidata.com/workflows#:%7E:text=pip%20install%20phidata%20openai%20duckduckgo,sqlalchemy)  
    This is especially useful for expensive operations or when running in batch workflows.
*   **Optimize Tool Usage:** Ensure your agent’s instructions are clear so it only calls the search tool when necessary. Ambiguous prompts might lead the LLM to make redundant searches or take irrelevant actions. During development, use **show\_tool\_calls=True** and even **debug\_mode=True** (which prints raw logs) to understand the agent’s decision-making and refine its prompt or tools​
*   **Choose the Right Search Toolkit:** Phidata offers multiple web search integrations. DuckDuckGo is handy for general use (no API key required), but you might consider alternatives:  
    *   _GoogleSearch:_ for more comprehensive results or news from Google’s index​
    *   _SerpAPI or SearxNG:_ if you need more control or a different search engine with an API​
    *   _BaiduSearch:_ if you need results from a different region/language (e.g., Chinese web).  
        Each toolkit may have its own strengths, rate limits, or requirements, so pick one that fits your use case.

You can find the full code in this [gist](https://gist.github.com/kartikpuri95/ebf0b5503f23480d89ed568e2d4eba63)

## **Conclusion**

Building a simple web search agent with Phidata only takes a few lines of code. By pairing a language model (like GPT-4 or GPT-3.5) with a search toolkit (DuckDuckGo in this case), you can quickly produce an agent that provides up-to-date information—complete with source citations. From here, you can extend its functionality by adding more tools or hooking up other models. Phidata’s flexibility and ease of use let you mix and match capabilities as your project grows.

Feel free to experiment with different instructions, additional data sources, or custom tools. Your search agent can evolve into a powerful assistant that tackles everything from quick fact checks to in-depth research.

About Author

![](/_astro/Kartik_Puri.width-300_1YNCyp.webp)

Kartik Puri

![](/img_astro/thumb.png)

### See What Our Clients Say

![](/img_astro/left-chevron_1.svg)

![](/img_astro/left-chevron_2.svg)

![](/img_astro/mind-gap-crop.svg)

Mindgap

Incentius has been a fantastic partner for us. Their strong expertise in technology helped deliver some complex solutions for our customers within challenging timelines. Specific call out to Sujeet and his team who developed custom sales analytics dashboards in SFDC for a SoCal based healthcare diagnostics client of ours. Their professionalism, expertise, and flexibility to adjust to client needs were greatly appreciated. MindGap is excited to continue to work with Incentius and add value to our customers.

Samik Banerjee

Founder & CEO

![](/img_astro/trusted-by-businesses/worldatwork_coloured.webp)

World at Work

Having worked so closely for half a year on our website project, I wanted to thank Incentius for all your fantastic work and efforts that helped us deliver a truly valuable experience to our WorldatWork members. I am in awe of the skills, passion, patience, and above all, the ownership that you brought to this project every day! I do not say this lightly, but we would not have been able to deliver a flawless product, but for you. I am sure you'll help many organizations and projects as your skills and professionalism are truly amazing.

Shantanu Bayaskar

Senior Project Manager

![](/img_astro/trusted-by-businesses/gogla_coloured.webp)

Gogla

It was a pleasure working with Incentius to build a data collection platform for the off-grid solar sector in India. It is rare to find a team with a combination of good understanding of business as well as great technological know-how. Incentius team has this perfect combination, especially their technical expertise is much appreciated. We had a fantastic time working with their expert team, especially with Amit.

Viraj gada

Gogla

![](/img_astro/trusted-by-businesses/humblex_coloured.webp)

Humblx

Choosing Incentius to work with is one of the decisions we are extremely happy with. It's been a pleasure working with their team. They have been tremendously helpful and efficient through the intense development cycle that we went through recently. The team at Incentius is truly agile and open to a discussion in regards to making tweaks and adding features that may add value to the overall solution. We found them willing to go the extra mile for us and it felt like working with someone who rooted for us to win.

Samir Dayal Singh

CEO Humblx

![](/img_astro/mind-gap-crop.svg)

Transportation & Logistics Consulting Organization

Incentius is very flexible and accommodating to our specific needs as an organization. In a world where approaches and strategies are constantly changing, it is invaluable to have an outsourcer who is able to adjust quickly to shifts in the business environment.

Transportation & Logistics Consulting Organization

Consultant

![](</img_astro/trusted-by-businesses/Mudraksh & McShaw.png>)

Mudraksh & McShaw

Incentius was instrumental in bringing the visualization aspect into our investment and trading business. They helped us organize our trading algorithms processing framework, review our backtests and analyze results in an efficient, visual manner.

Priyank Dutt Dwivedi

Mudraksh & McShaw Advisory

![](/img_astro/mind-gap-crop.svg)

Leading Healthcare Consulting Organization

The Incentius resource was highly motivated and developed a complex forecasting model with minimal supervision. He was thorough with quality checks and kept on top of multiple changes.

Leading Healthcare Consulting Organization

Sr. Principal

![](/img_astro/mind-gap-crop.svg)

US Fortune 100 Telecommunications Company

The Incentius resource was highly motivated and developed a complex forecasting model with minimal supervision. He was thorough with quality checks and kept on top of multiple changes.

Incentive Compensation

Sr. Director

Most Read

[

![](/_astro/ChatGPT_Image_Apr_2_2025_12_06_35_PM.width-1000_ZUChn3.webp)

Optimizing Large-Scale Data Exports: FastAPI, GraphQL, and AWS S3

Struggling with slow, inefficient file downloads in your application? Generating and handling large file downloads can be a nightmare—UI freezing, server overload, and endless waiting.

![](/_astro/Vinay_Chaudhari.width-300_1QPJnB.webp)

Vinay Chaudhari

1.  Apr 08, 2025
2.  4 min read









](/blog-posts/optimizing-large-scale-data-exports-fastapi-graphql-and-aws-s3/)[

![](/_astro/Screenshot_2025-04-02_at_12.09.33_PM.width-1000_ZyU6y1.webp)

How to Build a Web Search Agent with Phidata: A Step-by-Step Guide

Phidata is an **open-source framework** for building AI agents with capabilities like memory, tool use, and reasoning​ It’s model-agnostic and supports various large language models (LLMs), allowing developers to turn any LLM (like OpenAI GPT or local models) into a functional **search agent**.

![](/_astro/Kartik_Puri.width-300_1YNCyp.webp)

Kartik Puri

1.  Apr 02, 2025
2.  4 min read









](/blog-posts/how-to-build-a-web-search-agent-with-phidata-a-step-by-step-guide/)[

![](/_astro/e20f5335-cbf6-414c-a096-7d2849109cff.width-1000_15DfBS.webp)

Migrating to Soketi: Improving Our Real- Time Communication Architecture

Our journey with real-time data communication has evolved significantly. Initially using

Flask-SocketIO with Vue, we faced several challenges that led us to seek a more robust

solution.

![](/_astro/pratik.width-300_Z2vB9eu.webp)

Pratik Patel

1.  Mar 17, 2025
2.  4 min read









](/blog-posts/migrating-to-soketi-improving-our-real-time-communication-architecture/)[

![](/_astro/startup-employee-looking-business-charts-usin.width-1000_2knrAp.webp)

Understanding AI Agents: A Comprehensive Guide to AI Agentic Workflows

In the rapidly evolving landscape of artificial intelligence, AI Agents have emerged as a transformative technology that represents far more than just industry jargon.

![](/_astro/chetan_piucv.width-300_ZK3Vor.webp)

Chetan Patel

1.  Feb 28, 2025
2.  4 min read









](/blog-posts/understanding-ai-agents-a-comprehensive-guide-to-ai-agentic-workflows/)

## We use cookies

We use cookies to improve site. Some cookies are necessary for our website and services to function properly. Other cookies are optional and help personalize your experience, including advertising and analytics.You can consent to all cookies or decline all optional cookies. Without a selection, our default cookie settings will apply.

I agree I decline

[![logo](/img_astro/logo.svg)](/)

Incentius is a technology and professional services company providing analytics, operations and product engineering services.

 [![facebook](/img_astro/facebook.svg)](https://www.facebook.com/Incentius/)[![twitter](/img_astro/twitter.svg) ](https://x.com/incentius/)[![linkedin](/img_astro/linkedin.svg)](https://www.linkedin.com/company/incentius/posts/?feedView=all)

![location](/img_astro/pin.svg)

Office No.201B, 2nd Floor, Beta-1, Giga Space IT Park, Viman Nagar, Pune - 411014, Maharashtra, India

![email](/img_astro/message-icon.svg)

info@incentius.com

![phone](/img_astro/telephone.svg)

+1 (302) 415 3208

![](/img_astro/secure-footer.svg) ![](/img_astro/secure-footer-mobile.svg)

*   Solutions
*   [Voice AI](/voice-ai/)
*   [Generative AI](/generative-ai/)
*   [Data Engineering](/data-engineering/)
*   [Product Development](/product-engineering/)
*   [Data & Analytics](/data-analytics/)
*   [DevOps & CloudOps](/devops-and-cloudops/)
*   [UI/UX Design](/ui-ux-design/)

*   Recent Blog
*   [Medallion Architecture in Practice: Six Layers, One Source of Truth](/blog-posts/medallion-architecture-in-practice-six-layers-one-source-of-truth/)
*   ["Document later" is how teams say "document never"](/blog-posts/document-later-is-how-teams-say-document-never/)
*   [Your Business & AI - What It Actually Means for You](/blog-posts/your-business-ai-what-it-actually-means-for-you/)
*   [How Internal Agent-Built Software Reduced Our SaaS Dependency](/blog-posts/how-internal-agent-built-software-reduced-our-saas-dependency/)
*   [MarkItDown: A Powerful Utility for File Conversion to Markdown](/blog-posts/markitdown-a-powerful-utility-for-file-conversion-to-markdown/)
*   [Python 3.14: A Game-Changing Release for Modern Development](/blog-posts/python-314-a-game-changing-release-for-modern-development/)
*   [Building a RESTful Blog API with Flask and Swagger: A Complete Guide to Streamlined API Development](/blog-posts/building-a-restful-blog-api-with-flask-and-swagger-a-complete-guide-to-streamlined-api-development/)
*   [Tailwind CSS 4.0 vs 3.x: What Changed and How We Implemented It](/blog-posts/tailwind-css-40-vs-3x-what-changed-and-how-we-implemented-it/)
*   [The Future of AI: What to Expect in the Next 5 Years](/blog-posts/the-future-of-ai-what-to-expect-in-the-next-5-years/)

*   Menu
*   [About](/about-us/)
*   [Blog](/blog-posts/)
*   [Career](http://aurochs.freshteam.com/jobs)
*   [Case Studies](/portfolio/)
*   [For Startups](/startups/)
*   [Let's Talk](/contact/)

© Copyright 2025 Incentius

[Request Site](/)  
  
[Terms and Conditions](/)  
  
[Privacy Policy](/privacy-policy/)