Los agentes de CrewAI funcionan mejor cuando tienen acceso a datos web actuales para tareas de investigación. Sin herramientas de búsqueda, los agentes dependen únicamente de sus datos de capacitación y alucinan cuando se les pregunta sobre eventos recientes, precios o inteligencia competitiva. Agregar una herramienta de búsqueda a CrewAI es sencillo: cree una clase de herramienta que llame a una API de búsqueda, regístrela con su agente y asigne tareas de investigación que la aprovechen. Este tutorial muestra cómo agregar bases de búsqueda a cualquier equipo de CrewAI usando la API de Scavio a $0.005 por búsqueda.
Requisitos previos
- Python 3.10+ instalado
- Paquete crewai instalado (pip install crewai)
- Una clave API de Scavio de scavio.dev
- Una clave OpenAI o Anthropic API para el backend de LLM
Guia paso a paso
Paso 1: Crear la clase de herramienta de búsqueda
Las herramientas CrewAI amplían la clase BaseTool. Cree una herramienta de búsqueda que incluya la API de Scavio y devuelva resultados formateados.
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()Paso 2: Crea una herramienta de búsqueda de TikTok para investigaciones sociales
Agregue una segunda herramienta para la investigación de TikTok. Esto le da al agente acceso a datos de redes sociales junto con la búsqueda web.
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()Paso 3: Definir agentes con herramientas de búsqueda
Crea agentes de CrewAI y asígnales las herramientas de búsqueda. Un agente investigador realiza búsquedas en la web, un analista social obtiene búsquedas en TikTok.
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]}')Paso 4: Crea tareas y dirige el equipo
Definir tareas que requieran buscar y reunir la tripulación. Los agentes decidirán de forma autónoma cuándo utilizar sus herramientas de búsqueda.
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)Ejemplo en 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())Ejemplo en 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);Salida esperada
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