CrewAI中如何实现从配置文件动态加载多个agents的代码示例
·
完整、可运行思路 + 示例代码。是目前社区里最常见、也最推荐的做法(YAML + Python Factory 模式)。
一、目录结构示例(推荐)
my_crew/
├── agents/
│ ├── researcher.yaml
│ ├── writer.yaml
│ └── critic.yaml
├── tools/
│ └── search_tool.py
├── config_loader.py # Agent 工厂
└── main.py # 启动 Crew
二、Agent 配置文件(YAML)
agents/researcher.yaml
role: Senior Researcher
goal: Find accurate and up-to-date information
backstory: >
You are an expert researcher with a PhD in AI.
You are meticulous and always cite sources.
tools:
- name: SearchTool
module: tools.search_tool
class: SearchTool
verbose: true
allow_delegation: false
agents/writer.yaml
role: Content Writer
goal: Write engaging blog posts
backstory: >
You are a professional copywriter who specializes in AI topics.
tools: []
verbose: true
✅ 说明
-
tools支持动态导入 Python 类 -
backstory对应你说的 soul.md内容 -
每个 agent 一个文件,易维护
三、Tool 示例(Skill 的实现)
tools/search_tool.py
from crewai.tools import BaseTool
class SearchTool(BaseTool):
name = "SearchTool"
description = "Search the web for information"
def _run(self, query: str) -> str:
return f"Search results for: {query}"
四、Agent 工厂(核心:动态加载)
config_loader.py
import yaml
from crewai import Agent
from importlib import import_module
def load_tool(tool_config):
"""动态加载 Tool"""
module = import_module(tool_config["module"])
tool_class = getattr(module, tool_config["class"])
return tool_class()
def load_agent_from_yaml(yaml_path: str) -> Agent:
with open(yaml_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
tools = []
for tool_cfg in config.get("tools", []):
tools.append(load_tool(tool_cfg))
agent = Agent(
role=config["role"],
goal=config["goal"],
backstory=config["backstory"],
tools=tools,
verbose=config.get("verbose", False),
allow_delegation=config.get("allow_delegation", True),
)
return agent
def load_all_agents(agents_dir: str) -> list[Agent]:
import os
agents = []
for file in os.listdir(agents_dir):
if file.endswith(".yaml"):
path = os.path.join(agents_dir, file)
agents.append(load_agent_from_yaml(path))
return agents
✅ 这里实现了:
-
YAML → Python 对象
-
Tool 的反射式加载
-
多 Agent 批量初始化
五、在 main.py 中启动 Crew
from crewai import Crew, Task
from config_loader import load_all_agents
agents = load_all_agents("agents")
research_task = Task(
description="Research the latest trends in CrewAI",
agent=agents[0] # researcher
)
write_task = Task(
description="Write a blog post based on research",
agent=agents[1] # writer
)
crew = Crew(
agents=agents,
tasks=[research_task, write_task],
verbose=True
)
result = crew.kickoff()
print(result)
六、进阶玩法(可选)
✅ 1. 支持 soul.md / skill.md(社区风格)
你可以把:
backstory_file: souls/researcher.md
skills_file: skills/researcher.md
然后在 loader 中:
with open(config["backstory_file"]) as f:
backstory = f.read()
✅ 2. 支持 JSON / TOML
CrewAI 不关心格式,只要你最终构造出 Agent()即可。
七、总结一句话
CrewAI 本身不“存储” agents,而是通过 Python 对象 + 你自己的配置加载机制来实现动态管理。
更多推荐
所有评论(0)