CrewAI permite construir sistemas multiagente donde agentes especializados colaboran en tareas complejas. Agregar búsqueda web en vivo a un agente de CrewAI le brinda acceso a información actual más allá del límite de capacitación de su LLM. Este tutorial crea una herramienta CrewAI personalizada que envuelve la API de Scavio, la registra con un agente de investigación y ejecuta una canalización de múltiples agentes donde un agente busca y otro sintetiza los hallazgos.
Requisitos previos
- Python 3.10 o superior
- solicitudes de equipo de instalación de pip
- Una clave API de Scavio
- Una clave API de OpenAI o un LLM compatible
Guia paso a paso
Paso 1: Crear la herramienta de búsqueda Scavio
Subclase BaseTool de CrewAI para crear una ScavioSearchTool personalizada. Defina el nombre, la descripción y el método _run.
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
import requests
class ScavioSearchInput(BaseModel):
query: str = Field(description="The search query")
class ScavioSearchTool(BaseTool):
name: str = "scavio_search"
description: str = "Search Google for current information. Input: search query string."
args_schema: type[BaseModel] = ScavioSearchInput
def _run(self, query: str) -> str:
r = requests.post("https://api.scavio.dev/api/v1/search",
headers={"x-api-key": "your_scavio_api_key"},
json={"query": query, "country_code": "us"})
r.raise_for_status()
results = r.json().get("organic_results", [])[:5]
return "\n".join(f"{i['title']}: {i.get('snippet', '')}" for i in results)Paso 2: Definir el agente de investigación
Cree un agente CrewAI con ScavioSearchTool. Este agente se encargará de todas las tareas de búsqueda web.
from crewai import Agent
from langchain_openai import ChatOpenAI
search_tool = ScavioSearchTool()
researcher = Agent(
role="Web Researcher",
goal="Find accurate and current information on any topic",
backstory="Expert researcher who uses web search to gather facts.",
tools=[search_tool],
llm=ChatOpenAI(model="gpt-4o", temperature=0),
verbose=True
)Paso 3: Definir el agente de síntesis
Cree un segundo agente que reciba los hallazgos del investigador y escriba un resumen pulido.
from langchain_openai import ChatOpenAI
writer = Agent(
role="Technical Writer",
goal="Write clear, accurate summaries of research findings",
backstory="Technical writer who turns raw research into clear explanations.",
llm=ChatOpenAI(model="gpt-4o", temperature=0.3),
verbose=True
)Paso 4: Ejecute el equipo de múltiples agentes
Crea tareas para cada agente y dirige el equipo. El investigador busca, el escritor sintetiza.
from crewai import Crew, Task
research_task = Task(description="Research the latest AI agent frameworks released in 2026", agent=researcher, expected_output="List of frameworks with descriptions")
write_task = Task(description="Write a concise summary of the research findings", agent=writer, expected_output="200-word summary")
crew = Crew(agents=[researcher, writer], tasks=[research_task, write_task], verbose=True)
result = crew.kickoff()
print(result)Ejemplo en Python
import os
import requests
from crewai import Agent, Task, Crew
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = "your_openai_key"
class ScavioSearchInput(BaseModel):
query: str = Field(description="Search query")
class ScavioTool(BaseTool):
name: str = "web_search"
description: str = "Search the web for current information."
args_schema: type[BaseModel] = ScavioSearchInput
def _run(self, query: str) -> str:
r = requests.post("https://api.scavio.dev/api/v1/search",
headers={"x-api-key": os.environ["SCAVIO_API_KEY"]},
json={"query": query, "country_code": "us"})
r.raise_for_status()
results = r.json().get("organic_results", [])[:5]
return "\n".join(f"{r['title']}: {r.get('snippet', '')}" for r in results)
llm = ChatOpenAI(model="gpt-4o", temperature=0)
researcher = Agent(role="Researcher", goal="Find current info", backstory="Expert researcher", tools=[ScavioTool()], llm=llm)
task = Task(description="Research top AI agent frameworks in 2026", agent=researcher, expected_output="Bulleted list")
crew = Crew(agents=[researcher], tasks=[task])
if __name__ == "__main__":
print(crew.kickoff())Ejemplo en JavaScript
// CrewAI is Python-only. JS equivalent using fetch-based agent loop:
const API_KEY = process.env.SCAVIO_API_KEY || "your_scavio_api_key";
async function search(query) {
const res = 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 res.json();
return (data.organic_results || []).slice(0, 5).map(r => `${r.title}: ${r.snippet || ""}`).join("\n");
}
// Researcher agent step
async function researcherAgent(topic) {
const results = await search(`${topic} 2026`);
console.log("Researcher found:\n", results);
return results;
}
researcherAgent("AI agent frameworks").catch(console.error);Salida esperada
Researcher Agent: Searching for 'AI agent frameworks 2026'...
Found 5 results.
Writer Agent: Synthesizing research...
Final Output:
In 2026, the leading AI agent frameworks include LangGraph for stateful agents,
CrewAI for multi-agent coordination, AutoGen for conversational agents,
and Haystack for production RAG. LangChain remains the most widely adopted
foundation layer across all these frameworks.