CrewAI permet de construire des systèmes multi-agents où des agents spécialisés collaborent sur des tâches complexes. Ajouter une recherche web en direct à un agent CrewAI lui donne accès à des informations actuelles au-delà de la date limite d’entraînement de son LLM. Ce tutoriel construit un outil CrewAI personnalisé enveloppant l’API Scavio, l’enregistre avec un agent de recherche, et exécute un pipeline multi-agents où un agent cherche et un autre synthétise les résultats.
Prérequis
- Python 3.10 ou supérieur
- pip install crewai requests
- Une clé API Scavio
- Une clé API OpenAI ou un LLM compatible
Parcours
Étape 1: Créer l’outil de recherche Scavio
Sous-classez BaseTool de CrewAI pour créer un ScavioSearchTool personnalisé. Définissez le nom, la description et la méthode _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)Étape 2: Définir l’agent de recherche
Créez un agent CrewAI avec le ScavioSearchTool. Cet agent gérera toutes les tâches de recherche 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
)Étape 3: Définir l’agent de synthèse
Créez un deuxième agent qui reçoit les résultats du chercheur et rédige un résumé soigné.
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
)Étape 4: Exécuter le crew multi-agents
Créez des tâches pour chaque agent et exécutez le crew. Le chercheur cherche, le rédacteur synthétise.
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)Exemple 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())Exemple 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);Sortie attendue
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.