CrewAI permite la colaboración entre múltiples agentes donde agentes especializados trabajan juntos en tareas complejas. Este tutorial crea un equipo de detección de temas de tendencias con tres agentes: un investigador que busca temas emergentes, un analista que evalúa la fuerza de las tendencias y un redactor que produce resúmenes de contenido. El agente investigador utiliza la API de Scavio para búsquedas en tiempo real, proporcionando datos nuevos a los otros agentes. El equipo detecta temas de tendencia en su nicho y genera resúmenes de contenido procesables.
Requisitos previos
- Python 3.10+ instalado
- pip install crewai solicitudes de herramientas crewai
- Una clave API de Scavio de scavio.dev
- Una clave API de OpenAI para el razonamiento de los agentes
Guia paso a paso
Paso 1: Crea la herramienta de búsqueda Scavio para CrewAI
Cree una herramienta compatible con CrewAI que incluya la API de Scavio. Las herramientas de CrewAI necesitan un nombre, una descripción y un método de ejecución.
import os, requests
from crewai_tools import BaseTool
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
class ScavioSearchTool(BaseTool):
name: str = 'web_search'
description: str = 'Search the web for trending topics, news, and current information. Input should be a search query string.'
def _run(self, query: str) -> str:
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': 'us', 'num_results': 5})
results = resp.json().get('organic_results', [])
return '\n\n'.join(
f'Title: {r["title"]}\nSnippet: {r.get("snippet", "")}\nURL: {r["link"]}'
for r in results
)
search_tool = ScavioSearchTool()
print(search_tool._run('trending AI topics May 2026')[:300])Paso 2: Definir los tres agentes
Cree agentes de investigador, analista y redactor con roles y objetivos especializados. Sólo el Investigador obtiene la herramienta de búsqueda.
from crewai import Agent
researcher = Agent(
role='Trend Researcher',
goal='Find emerging topics and trends in the target niche using web search',
backstory='You are an expert at identifying emerging trends before they peak. You search the web for signals of rising interest.',
tools=[search_tool],
verbose=True
)
analyst = Agent(
role='Trend Analyst',
goal='Evaluate trend strength and predict which topics will grow',
backstory='You analyze search data to determine which trends have staying power versus short-lived spikes.',
verbose=True
)
writer = Agent(
role='Content Brief Writer',
goal='Create actionable content briefs for trending topics',
backstory='You write concise content briefs that content teams can execute immediately.',
verbose=True
)
print('Agents created: Researcher, Analyst, Writer')Paso 3: Definir tareas y dirigir el equipo
Crea tareas para cada agente y reúne a la tripulación. El resultado es una lista de temas de actualidad con resúmenes de contenido.
from crewai import Task, Crew, Process
research_task = Task(
description='Search for 5 trending topics in AI and developer tools for May 2026. For each topic, search for recent articles and note the signals of growth.',
expected_output='A list of 5 trending topics with supporting evidence from search results.',
agent=researcher
)
analysis_task = Task(
description='Analyze the 5 trending topics from the researcher. Rank them by trend strength (1-10) based on recency, volume, and growth signals.',
expected_output='A ranked list of topics with trend strength scores and reasoning.',
agent=analyst
)
brief_task = Task(
description='Create a content brief for the top 3 topics. Include: title, target keywords, outline, and recommended format.',
expected_output='3 content briefs ready for a content team to execute.',
agent=writer
)
crew = Crew(
agents=[researcher, analyst, writer],
tasks=[research_task, analysis_task, brief_task],
process=Process.sequential,
verbose=True
)
result = crew.kickoff()
print('\nCrew Output:')
print(result)Ejemplo en Python
import os, requests
from crewai import Agent, Task, Crew, Process
from crewai_tools import BaseTool
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
class SearchTool(BaseTool):
name: str = 'web_search'
description: str = 'Search the web for current information'
def _run(self, query: str) -> str:
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'},
json={'query': query, 'country_code': 'us', 'num_results': 5})
return '\n'.join(f'{r["title"]}: {r.get("snippet","")}'
for r in resp.json().get('organic_results', []))
researcher = Agent(role='Researcher', goal='Find trending topics',
backstory='Expert trend researcher', tools=[SearchTool()], verbose=True)
analyst = Agent(role='Analyst', goal='Rank trends by strength',
backstory='Data-driven trend analyst', verbose=True)
crew = Crew(
agents=[researcher, analyst],
tasks=[
Task(description='Search for 3 trending AI topics in 2026', expected_output='List of trends', agent=researcher),
Task(description='Rank the trends by strength', expected_output='Ranked list', agent=analyst),
],
process=Process.sequential
)
print(crew.kickoff())Ejemplo en JavaScript
// CrewAI is Python-only; use the Scavio API directly in JS for trend detection
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;
async function detectTrends(niche) {
const queries = [`${niche} trending 2026`, `${niche} emerging trends`, `${niche} latest news`];
const results = [];
for (const q of queries) {
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST',
headers: { 'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ query: q, country_code: 'us', num_results: 3 })
});
const data = await resp.json();
results.push(...(data.organic_results || []));
}
console.log(`Found ${results.length} trend signals for ${niche}`);
results.slice(0, 5).forEach(r => console.log(` ${r.title}`));
}
detectTrends('AI developer tools');Salida esperada
Agent: Trend Researcher
Searching: 'trending AI topics May 2026'
Found 5 results
Searching: 'developer tools trending 2026'
Found 5 results
Agent: Trend Analyst
1. MCP Ecosystem Growth (9/10) - Strong signals across multiple sources
2. Local LLM Tool Integration (8/10) - Rising developer interest
3. AI-Powered Code Review (7/10) - Multiple product launches
Agent: Content Brief Writer
Brief 1: 'The MCP Ecosystem in 2026: A Complete Guide'
Brief 2: 'How to Add Tools to Local LLMs'
Brief 3: 'AI Code Review Tools Compared'