ScavioScavio
ProductoPreciosDocumentación
Iniciar sesionComenzar
  1. Inicio
  2. Tutoriales
  3. Cómo agregar búsqueda a un agente de CrewAI
Tutorial

Cómo agregar búsqueda a un agente de CrewAI

Agregue capacidad de búsqueda web en vivo a los agentes de CrewAI. Cree una herramienta de búsqueda, regístrela con su equipo e investigue agentes terrestres con datos reales.

Obtener clave API gratisDocumentacion API

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.

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()

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.

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()

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.

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]}')

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.

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)

Ejemplo en Python

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

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

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

Tutoriales relacionados

  • Cómo agregar una base de búsqueda a cualquier agente Python
  • Cómo crear un agente multiherramienta MCP en 2026
  • Cómo consolidar las herramientas de búsqueda de agentes en una sola API

Preguntas frecuentes

La mayoria de los desarrolladores completan este tutorial en 15 a 30 minutos. Necesitaras una clave API de Scavio (el plan gratuito funciona) y un entorno de Python o JavaScript.

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. Una clave API de Scavio te da 50 creditos gratuitos al registrarte.

Si. El plan gratuito incluye 50 creditos al registrarte, mas que suficiente para completar este tutorial y crear un prototipo funcional.

Scavio tiene un paquete nativo de LangChain (langchain-scavio), un servidor MCP y una API REST simple que funciona con cualquier cliente HTTP. Este tutorial usa the raw REST API, pero puedes adaptarlo al framework que prefieras.

Recursos relacionados

Best Of

La mejor API de búsqueda para agentes de CrewAI en 2026

Read more
Best Of

Las mejores API de búsqueda después de los cambios en el modo AI de Google I/O 2026

Read more
Use Case

Acceso web de IA de código abierto 2026

Read more
Glossary

Panorama de proveedores de API de búsqueda (2026)

Read more
Glossary

Buscar Era del muro de pago (2026)

Read more
Comparison

Search APIs (Scavio, Tavily, SerpAPI) vs Headless Browser (Playwright, Puppeteer, Browserbase)

Read more

Empieza a construir

Agregue capacidad de búsqueda web en vivo a los agentes de CrewAI. Cree una herramienta de búsqueda, regístrela con su equipo e investigue agentes terrestres con datos reales.

Obtener clave API gratuitaLeer la documentacion
ScavioScavio

API de busqueda en tiempo real para agentes de IA. Busca en todas las plataformas, no solo en Google.

Producto

  • Funciones
  • Precios
  • Panel
  • Afiliados

Desarrolladores

  • Documentacion
  • Referencia de API
  • Inicio rapido
  • Integracion MCP
  • Python SDK

Alternativas

  • Alternativa a Tavily
  • Alternativa a SerpAPI
  • Alternativa a Firecrawl
  • Alternativa a Exa

Herramientas

  • Formateador JSON
  • cURL a codigo
  • Contador de tokens
  • Todas las herramientas

© 2026 Scavio. Todos los derechos reservados.

Featured on TAAFT
Terminos de servicioPolitica de privacidad