Les agents CrewAI sont plus efficaces lorsqu'ils ont accès à des données web actualisées pour leurs tâches de recherche. Sans outils de recherche, ils se fient uniquement à leurs données d'apprentissage et hallucinent lorsqu'on les interroge sur des événements récents, des prix ou des informations concurrentielles. Ajouter un outil de recherche à CrewAI est simple : créer une classe d'outil qui appelle une API de recherche, l'enregistrer auprès de votre agent et lui attribuer des tâches de recherche qui l'exploitent. Ce tutoriel montre comment ajouter une base de recherche à n'importe quel crew CrewAI en utilisant l'API Scavio à 0,005 $ par recherche.
Prérequis
- Python 3.10+ installé
- Paquet crewai installé (pip install crewai)
- Une clé API Scavio depuis scavio.dev
- Une clé API OpenAI ou Anthropic pour le backend LLM
Parcours
Étape 1: Créer la classe d'outil de recherche
Les outils CrewAI étendent la classe BaseTool. Créez un outil de recherche qui encapsule l'API Scavio et renvoie des résultats formatés.
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()Étape 2: Créer un outil de recherche TikTok pour la recherche sociale
Ajoutez un deuxième outil pour la recherche TikTok. Cela donne à l'agent un accès aux données des réseaux sociaux en complément de la recherche 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()Étape 3: Définir des agents avec des outils de recherche
Créez des agents CrewAI et assignez-leur les outils de recherche. Un agent chercheur obtient la recherche web, un analyste social obtient la recherche 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]}')Étape 4: Créer des tâches et exécuter le crew
Définissez des tâches nécessitant une recherche et assemblez le crew. Les agents décideront de manière autonome quand utiliser leurs outils de recherche.
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)Exemple 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())Exemple 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);Sortie attendue
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