Tutorial

How to Add Search to a CrewAI Agent

Add live web search capability to CrewAI agents. Build a search tool, register it with your crew, and ground agent research with real data.

CrewAI agents work best when they have access to current web data for research tasks. Without search tools, agents rely solely on their training data and hallucinate when asked about recent events, pricing, or competitive intelligence. Adding a search tool to CrewAI is straightforward: create a tool class that calls a search API, register it with your agent, and assign research tasks that leverage it. This tutorial shows how to add search grounding to any CrewAI crew using the Scavio API at $0.005 per search.

Prerequisites

  • Python 3.10+ installed
  • crewai package installed (pip install crewai)
  • A Scavio API key from scavio.dev
  • An OpenAI or Anthropic API key for the LLM backend

Walkthrough

Step 1: Create the search tool class

CrewAI tools extend the BaseTool class. Create a search tool that wraps the Scavio API and returns formatted results.

Python
from crewai.tools import BaseTool
import requests, os
from typing import Type
from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(description='Search query')

class WebSearchTool(BaseTool):
    name: str = 'web_search'
    description: str = 'Search the web for current information about any topic.'
    args_schema: Type[BaseModel] = SearchInput

    def _run(self, query: str) -> str:
        api_key = os.environ['SCAVIO_API_KEY']
        resp = requests.post('https://api.scavio.dev/api/v1/search',
            headers={'x-api-key': api_key, 'Content-Type': 'application/json'},
            json={'query': query, 'country_code': 'us'})
        results = resp.json().get('organic_results', [])[:5]
        if not results:
            return 'No results found.'
        return '\n\n'.join(
            f'Title: {r["title"]}\nURL: {r["link"]}\nSnippet: {r.get("snippet", "")}'
            for r in results
        )

search_tool = WebSearchTool()

Step 2: Create a TikTok search tool for social research

Add a second tool for TikTok research. This gives the agent access to social media data alongside web search.

Python
class TikTokInput(BaseModel):
    keyword: str = Field(description='TikTok search keyword')

class TikTokSearchTool(BaseTool):
    name: str = 'tiktok_search'
    description: str = 'Search TikTok for videos about a topic. Returns video titles, creators, and play counts.'
    args_schema: Type[BaseModel] = TikTokInput

    def _run(self, keyword: str) -> str:
        api_key = os.environ['SCAVIO_API_KEY']
        resp = requests.post('https://api.scavio.dev/api/v1/tiktok/search/videos',
            headers={'Authorization': f'Bearer {api_key}',
                     'Content-Type': 'application/json'},
            json={'keyword': keyword, 'count': 10, 'cursor': 0})
        videos = resp.json().get('data', {}).get('videos', [])
        if not videos:
            return 'No TikTok videos found.'
        return '\n'.join(
            f'@{v.get("author", {}).get("uniqueId", "")} - '
            f'{v.get("stats", {}).get("playCount", 0):,} plays: '
            f'{v.get("desc", "")[:80]}'
            for v in videos
        )

tiktok_tool = TikTokSearchTool()

Step 3: Define agents with search tools

Create CrewAI agents and assign them the search tools. A researcher agent gets web search, a social analyst gets TikTok search.

Python
from crewai import Agent

researcher = Agent(
    role='Market Researcher',
    goal='Find current, accurate market data and competitive intelligence.',
    backstory='You are a senior market researcher who always uses web search to verify facts.',
    tools=[search_tool],
    verbose=True
)

social_analyst = Agent(
    role='Social Media Analyst',
    goal='Analyze social media trends and influencer activity.',
    backstory='You are a social media expert who uses TikTok data to identify trends.',
    tools=[tiktok_tool, search_tool],  # both tools available
    verbose=True
)

print(f'Researcher tools: {[t.name for t in researcher.tools]}')
print(f'Social analyst tools: {[t.name for t in social_analyst.tools]}')

Step 4: Create tasks and run the crew

Define tasks that require search and assemble the crew. The agents will autonomously decide when to use their search tools.

Python
from crewai import Task, Crew, Process

market_research = Task(
    description='Research the current CRM software market in 2026. Include top products, pricing, and market trends.',
    expected_output='A structured market report with product names, prices, and key trends.',
    agent=researcher
)

social_analysis = Task(
    description='Find trending TikTok content about CRM tools and productivity software. Identify top creators.',
    expected_output='A list of trending videos and creators in the CRM/productivity niche on TikTok.',
    agent=social_analyst
)

crew = Crew(
    agents=[researcher, social_analyst],
    tasks=[market_research, social_analysis],
    process=Process.sequential,
    verbose=True
)

result = crew.kickoff()
print(result)

Python Example

Python
from crewai import Agent, Task, Crew, Process
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
import requests, os
from typing import Type

class SearchInput(BaseModel):
    query: str = Field(description='Search query')

class WebSearchTool(BaseTool):
    name: str = 'web_search'
    description: str = 'Search the web for current information.'
    args_schema: Type[BaseModel] = SearchInput
    def _run(self, query: str) -> str:
        resp = requests.post('https://api.scavio.dev/api/v1/search',
            headers={'x-api-key': os.environ['SCAVIO_API_KEY'], 'Content-Type': 'application/json'},
            json={'query': query, 'country_code': 'us'})
        return '\n'.join(f'{r["title"]}: {r.get("snippet", "")}'
            for r in resp.json().get('organic_results', [])[:5])

researcher = Agent(role='Researcher', goal='Find accurate current data.',
    backstory='Senior researcher.', tools=[WebSearchTool()])
task = Task(description='Research top CRM tools 2026 with pricing.',
    expected_output='Market report.', agent=researcher)
crew = Crew(agents=[researcher], tasks=[task], process=Process.sequential)
print(crew.kickoff())

JavaScript Example

JavaScript
// CrewAI is Python-only; this JS shows the equivalent search pattern
const API_KEY = process.env.SCAVIO_API_KEY;

async function webSearch(query) {
  const resp = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST',
    headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, country_code: 'us' })
  });
  const data = await resp.json();
  return (data.organic_results || []).slice(0, 5)
    .map(r => `${r.title}: ${r.snippet || ''}`);
}

async function main() {
  const results = await webSearch('top CRM tools 2026 pricing');
  console.log('Research results:');
  results.forEach(r => console.log(`  ${r}`));
}

main().catch(console.error);

Expected Output

JSON
Researcher tools: ['web_search']
Social analyst tools: ['tiktok_search', 'web_search']

[Researcher] Using tool: web_search
  Query: CRM software market 2026 pricing comparison
  Found 5 results

[Social Analyst] Using tool: tiktok_search
  Keyword: CRM software tips
  Found 10 videos

Market Report:
1. HubSpot CRM - Free to $1,200/mo
2. Salesforce - $25-300/user/mo
3. Pipedrive - $14.90-99/user/mo
...

Cost: ~4 search calls = $0.02

Related Tutorials

Frequently Asked Questions

Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

Python 3.10+ installed. crewai package installed (pip install crewai). A Scavio API key from scavio.dev. An OpenAI or Anthropic API key for the LLM backend. A Scavio API key gives you 250 free credits per month.

Yes. The free tier includes 250 credits per month, which is more than enough to complete this tutorial and prototype a working solution.

Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

Start Building

Add live web search capability to CrewAI agents. Build a search tool, register it with your crew, and ground agent research with real data.