CrewAI permet une collaboration multi-agent où des agents spécialisés travaillent ensemble sur des tâches complexes. Ce tutoriel construit une équipe de détection de tendances avec trois agents : un Chercheur qui recherche des sujets émergents, un Analyste qui évalue la force des tendances, et un Rédacteur qui produit des briefs de contenu. L'agent Chercheur utilise l'API Scavio pour des recherches en temps réel, alimentant les autres agents avec des données fraîches. L'équipe détecte les tendances dans votre niche et produit des briefs de contenu exploitables.
Prérequis
- Python 3.10+ installé
- pip install crewai crewai-tools requests
- Une clé API Scavio provenant de scavio.dev
- Une clé API OpenAI pour le raisonnement des agents
Parcours
Étape 1: Créer l'outil de recherche Scavio pour CrewAI
Construire un outil compatible CrewAI qui encapsule l'API Scavio. Les outils CrewAI nécessitent un nom, une description et une méthode run.
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])Étape 2: Définir les trois agents
Créer les agents Chercheur, Analyste et Rédacteur avec des rôles et objectifs spécialisés. Seul le Chercheur reçoit l'outil de recherche.
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')Étape 3: Définir les tâches et exécuter l'équipe
Créer des tâches pour chaque agent et assembler l'équipe. Le résultat est une liste de sujets tendance avec des briefs de contenu.
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)Exemple 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())Exemple 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');Sortie attendue
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'