CrewAI 能够构建多代理系统,其中专业代理可以协作完成复杂的任务。向 CrewAI 代理添加实时网络搜索,使其能够访问超出其法学硕士培训截止范围的当前信息。本教程构建了一个包装 Scavio API 的自定义 CrewAI 工具,将其注册到研究代理,并运行一个多代理管道,其中一个代理进行搜索,另一个代理综合结果。
前置条件
- Python 3.10 或更高版本
- pip install crewai requests
- Scavio API 密钥
- OpenAI API 密钥或兼容的 LLM
操作指南
步骤 1: 创建 Scavio 搜索工具
将 CrewAI 的 BaseTool 子类化以创建自定义 ScavioSearchTool。定义名称、描述和 _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)步骤 2: 定义研究代理
使用 ScadioSearchTool 创建 CrewAI 代理。该代理将处理所有网络搜索任务。
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
)步骤 3: 定义合成剂
创建第二个代理来接收研究人员的发现并撰写完善的摘要。
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
)步骤 4: 运行多代理团队
为每个代理创建任务并运行工作人员。研究者进行探索,作者进行综合。
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)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())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);预期输出
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.