mcpField
A
autogen-development

autogen-development

github.com/mindrallyAgent 工作流287725 次安装3 周前更新
代码仓库

关于 autogen-development

autogen-development 是使用 Microsoft AutoGen 构建 Python 多 Agent 系统的开发技能,涵盖 Agent 编排、工具使用、代码执行、状态管理与应用模式。

主要功能

  1. 01Agent 与团队编排
  2. 02工具集成和代码执行
  3. 03顺序与层级工作流
  4. 04对话记忆与事件处理
  5. 05错误处理和测试指南

适用场景

  1. 01构建协同的多 Agent 对话
  2. 02创建研究与写作工作流
  3. 03使用 Agent 生成并测试代码
  4. 04开发数据分析流程

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mindrally/skills --skill autogen-development

安装后在 Claude Code 中输入/autogen-development确认已加载。

详细介绍

AutoGen 多 Agent 开发

你是 Microsoft AutoGen 专家。AutoGen 是一个使用 Python 构建多 Agent AI 系统的框架,专注于 Agent 编排、工具集成和可扩展的 AI 应用。

核心原则

  • 使用简洁、技术准确的回复,并提供准确的 Python 示例
  • 使用 async/await 模式进行 Agent 通信
  • 实施恰当的错误处理和日志记录
  • 遵循事件驱动架构模式
  • 为所有函数签名添加类型提示

设置和安装

环境设置
# Install AutoGen
# pip install autogen-agentchat autogen-ext

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient
模型配置
import os

# Configure the model client
model_client = OpenAIChatCompletionClient(
    model="gpt-4o",
    api_key=os.environ.get("OPENAI_API_KEY")
)

核心概念

Agent 类型

AutoGen 提供多种 Agent 类型:

  • AssistantAgent:用于对话和完成任务的 AI 驱动 Agent
  • UserProxyAgent:代表人类用户,可以执行代码
  • GroupChat:编排多 Agent 对话
  • ConversableAgent:自定义 Agent 的基类

创建 Agent

基本助手 Agent
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(model="gpt-4o")

assistant = AssistantAgent(
    name="assistant",
    model_client=model_client,
    system_message="""You are a helpful AI assistant.
    Provide clear, concise responses.
    Ask clarifying questions when needed."""
)
带工具的 Agent
from autogen_agentchat.agents import AssistantAgent
from autogen_core.tools import FunctionTool

def search_database(query: str) -> str:
    """Search the database for information.

    Args:
        query: The search query string

    Returns:
        Search results as a string
    """
    # Implementation
    return f"Results for: {query}"

def calculate(expression: str) -> str:
    """Evaluate a mathematical expression.

    Args:
        expression: Mathematical expression to evaluate

    Returns:
        The result of the calculation
    """
    try:
        result = eval(expression)
        return str(result)
    except Exception as e:
        return f"Error: {str(e)}"

# Create tools
search_tool = FunctionTool(search_database, description="Search the database")
calc_tool = FunctionTool(calculate, description="Perform calculations")

# Create agent with tools
agent = AssistantAgent(
    name="tool_agent",
    model_client=model_client,
    tools=[search_tool, calc_tool],
    system_message="You are an assistant with access to search and calculation tools."
)

多 Agent 对话

双 Agent 聊天
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat

# Create agents
researcher = AssistantAgent(
    name="researcher",
    model_client=model_client,
    system_message="You are a research assistant. Gather and analyze information."
)

writer = AssistantAgent(
    name="writer",
    model_client=model_client,
    system_message="You are a technical writer. Create clear documentation."
)

# Create termination condition
termination = TextMentionTermination("TASK_COMPLETE")

# Create group chat
team = RoundRobinGroupChat(
    [researcher, writer],
    termination_condition=termination
)

# Run the conversation
async def run_team():
    result = await team.run(task="Research and document Python best practices")
    return result
多 Agent 群组聊天
from autogen_agentchat.teams import SelectorGroupChat
from autogen_agentchat.conditions import MaxMessageTermination

# Create specialized agents
planner = AssistantAgent(
    name="planner",
    model_client=model_client,
    system_message="You are a project planner. Break down tasks and create plans."
)

coder = AssistantAgent(
    name="coder",
    model_client=model_client,
    system_message="You are a software developer. Write clean, efficient code."
)

reviewer = AssistantAgent(
    name="reviewer",
    model_client=model_client,
    system_message="You are a code reviewer. Review code for quality and best practices."
)

# Selector-based group chat
team = SelectorGroupChat(
    [planner, coder, reviewer],
    model_client=model_client,
    termination_condition=MaxMessageTermination(20)
)

代码执行

设置代码执行
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor
from autogen_agentchat.agents import AssistantAgent

# Create code executor
code_executor = LocalCommandLineCodeExecutor(
    work_dir="./workspace",
    timeout=60
)

# Agent that can execute code
coding_agent = AssistantAgent(
    name="coder",
    model_client=model_client,
    code_executor=code_executor,
    system_message="""You are a Python developer.
    Write code to solve problems.
    Test your code before providing final answers."""
)
基于 Docker 的执行
from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor

# Secure code execution in Docker
docker_executor = DockerCommandLineCodeExecutor(
    image="python:3.11-slim",
    timeout=120,
    work_dir="./workspace"
)

对话模式

顺序工作流
from autogen_agentchat.teams import Swarm
from autogen_agentchat.agents import AssistantAgent

# Define agents for each step
analyst = AssistantAgent(
    name="analyst",
    model_client=model_client,
    handoffs=["developer"],
    system_message="Analyze requirements and hand off to developer."
)

developer = AssistantAgent(
    name="developer",
    model_client=model_client,
    handoffs=["tester"],
    system_message="Implement the solution and hand off to tester."
)

tester = AssistantAgent(
    name="tester",
    model_client=model_client,
    system_message="Test the implementation and report results."
)

# Create swarm for handoff-based workflow
team = Swarm([analyst, developer, tester])
层级结构
# Manager agent that coordinates others
manager = AssistantAgent(
    name="manager",
    model_client=model_client,
    system_message="""You are a project manager.
    Coordinate between team members.
    Delegate tasks appropriately.
    Synthesize results into final deliverables."""
)

# Worker agents
workers = [
    AssistantAgent(name="researcher", model_client=model_client, ...),
    AssistantAgent(name="analyst", model_client=model_client, ...),
    AssistantAgent(name="writer", model_client=model_client, ...)
]

内存和状态

对话内存
from autogen_agentchat.messages import TextMessage

# Agents maintain conversation history automatically
# Access through the team's message history
async def run_with_memory():
    result = await team.run(task="Initial task")

    # Continue with context
    result = await team.run(task="Follow-up question")

    # Access message history
    for message in result.messages:
        print(f"{message.source}: {message.content}")

事件驱动架构

自定义事件处理
from autogen_core import Event

# Subscribe to events
async def on_message_received(event: Event):
    print(f"Message received: {event.data}")

# Events enable reactive patterns
# - Agent activation
# - Tool execution
# - Error handling
# - State changes

错误处理

稳健的 Agent 设计
from autogen_agentchat.agents import AssistantAgent
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def safe_run_team(team, task: str, max_retries: int = 3):
    """Run team with error handling and retries."""
    for attempt in range(max_retries):
        try:
            result = await team.run(task=task)
            return result
        except Exception as e:
            logger.error(f"Attempt {attempt + 1} failed: {e}")
            if attempt == max_retries - 1:
                raise
    return None

最佳实践

Agent 设计
  • 为 Agent 分配明确、专注的职责
  • 使用描述性系统消息
  • 编写恰当的工具描述
  • 设置适当的终止条件
  • 在复杂工作流中使用交接
性能
  • 使用异步模式执行并发操作
  • 为重复查询实施缓存
  • 设置合理的超时时间
  • 监控令牌用量
  • 为每个 Agent 选择合适规模的模型
安全
  • 切勿直接执行不可信代码
  • 使用 Docker 执行代码
  • 验证工具输入
  • 实施速率限制
  • 记录所有 Agent 操作
测试
  • 对单个 Agent 进行单元测试
  • 对多 Agent 工作流进行集成测试
  • 测试终止条件
  • 验证工具执行
  • 监控对话质量

依赖项

  • autogen-agentchat
  • autogen-core
  • autogen-ext
  • openai(或其他 LLM 提供商)
  • python-dotenv
  • docker(用于安全代码执行)

常见模式

研究和写作
# Pattern: Research -> Analyze -> Write -> Review
agents = [
    AssistantAgent(name="researcher", ...),
    AssistantAgent(name="analyst", ...),
    AssistantAgent(name="writer", ...),
    AssistantAgent(name="reviewer", ...)
]
代码生成
# Pattern: Plan -> Code -> Test -> Review
agents = [
    AssistantAgent(name="architect", ...),
    AssistantAgent(name="developer", code_executor=executor, ...),
    AssistantAgent(name="tester", ...),
    AssistantAgent(name="reviewer", ...)
]
数据分析
# Pattern: Extract -> Transform -> Analyze -> Report
agents = [
    AssistantAgent(name="data_engineer", ...),
    AssistantAgent(name="analyst", tools=[calc_tools], ...),
    AssistantAgent(name="reporter", ...)
]

评论

支持 Markdown