AutoGen 多 Agent 程式框架

使用 Microsoft AutoGen 建立多個 AI Agent 對話協作,支援程式執行、人機協作等功能

專案簡介

AutoGen 是 Microsoft 開發的多 Agent 對話框架,讓多個 AI Agent 透過對話協作完成任務。支援程式碼執行、人機協作、自訂 Agent 等功能。

GitHub Stars: 54K+

主要功能

  • 對話式協作 - Agent 透過對話完成任務
  • 程式執行 - 自動執行生成的程式碼
  • 人機協作 - 人類參與 Agent 對話
  • 可擴展 - 自訂 Agent 行為
  • 多模型 - 支援各種 LLM

安裝

1
pip install autogen-agentchat

基本使用

雙 Agent 對話

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from autogen import AssistantAgent, UserProxyAgent

# 設定 LLM
config_list = [
    {
        "model": "gpt-4o",
        "api_key": "your-api-key"
    }
]

# 建立 Assistant
assistant = AssistantAgent(
    name="assistant",
    llm_config={"config_list": config_list}
)

# 建立 User Proxy(可執行程式碼)
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    code_execution_config={"work_dir": "coding"}
)

# 開始對話
user_proxy.initiate_chat(
    assistant,
    message="Write a Python script to scan for open ports on localhost"
)

Agent 類型

AssistantAgent

AI 助手,生成回應:

1
2
3
4
5
6
assistant = AssistantAgent(
    name="security_expert",
    system_message="""You are a cybersecurity expert.
    Help with security analysis and provide recommendations.""",
    llm_config={"config_list": config_list}
)

UserProxyAgent

代表使用者,可執行程式碼:

1
2
3
4
5
6
7
8
9
user_proxy = UserProxyAgent(
    name="user",
    human_input_mode="TERMINATE",  # 結束時請求輸入
    max_consecutive_auto_reply=10,
    code_execution_config={
        "work_dir": "workspace",
        "use_docker": True
    }
)

GroupChat

多 Agent 群組對話:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from autogen import GroupChat, GroupChatManager

researcher = AssistantAgent(name="researcher", ...)
analyst = AssistantAgent(name="analyst", ...)
writer = AssistantAgent(name="writer", ...)

groupchat = GroupChat(
    agents=[user_proxy, researcher, analyst, writer],
    messages=[],
    max_round=20
)

manager = GroupChatManager(
    groupchat=groupchat,
    llm_config={"config_list": config_list}
)

user_proxy.initiate_chat(
    manager,
    message="Research and write a report on SQL injection attacks"
)

程式碼執行

本地執行

1
2
3
4
5
6
7
user_proxy = UserProxyAgent(
    name="executor",
    code_execution_config={
        "work_dir": "coding",
        "use_docker": False
    }
)

Docker 執行

1
2
3
4
5
6
7
user_proxy = UserProxyAgent(
    name="executor",
    code_execution_config={
        "work_dir": "coding",
        "use_docker": "python:3.11"
    }
)

安全研究範例

漏洞分析團隊

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager

config_list = [{"model": "gpt-4o", "api_key": "your-key"}]

# 研究員
researcher = AssistantAgent(
    name="Vulnerability_Researcher",
    system_message="""You are a vulnerability researcher.
    Search and analyze security vulnerabilities.
    Provide CVE details and technical analysis.""",
    llm_config={"config_list": config_list}
)

# 分析師
analyst = AssistantAgent(
    name="Risk_Analyst",
    system_message="""You are a risk analyst.
    Assess the impact and exploitability of vulnerabilities.
    Provide risk scores and prioritization.""",
    llm_config={"config_list": config_list}
)

# 修復建議
remediation = AssistantAgent(
    name="Remediation_Advisor",
    system_message="""You are a remediation advisor.
    Provide patches, workarounds, and mitigation strategies.""",
    llm_config={"config_list": config_list}
)

# 執行者
executor = UserProxyAgent(
    name="Executor",
    human_input_mode="NEVER",
    code_execution_config={"work_dir": "security_analysis"}
)

# 群組對話
groupchat = GroupChat(
    agents=[executor, researcher, analyst, remediation],
    messages=[],
    max_round=15
)

manager = GroupChatManager(
    groupchat=groupchat,
    llm_config={"config_list": config_list}
)

# 開始分析
executor.initiate_chat(
    manager,
    message="""Analyze CVE-2026-12345:
    1. Research the vulnerability details
    2. Assess the risk level
    3. Provide remediation recommendations
    """
)

人機協作

請求人類輸入

1
2
3
4
5
user_proxy = UserProxyAgent(
    name="user",
    human_input_mode="ALWAYS",  # 每次都請求輸入
    max_consecutive_auto_reply=5
)

選項

  • ALWAYS - 每次回覆前請求輸入
  • TERMINATE - 終止對話時請求
  • NEVER - 完全自動

自訂 Agent

函數呼叫

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from autogen import register_function

def scan_ports(target: str, ports: str) -> str:
    """Scan ports on target host"""
    # 實作掃描邏輯
    return f"Scan results for {target}"

register_function(
    scan_ports,
    caller=assistant,
    executor=user_proxy,
    description="Scan network ports on a target"
)

自訂 Agent 類別

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from autogen import ConversableAgent

class SecurityAgent(ConversableAgent):
    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)
        self.register_reply(
            trigger=self._should_scan,
            reply_func=self._scan_reply
        )

    def _should_scan(self, messages):
        return "scan" in messages[-1]["content"].lower()

    def _scan_reply(self, messages, sender, config):
        # 自訂回覆邏輯
        return True, "Scanning..."

模型設定

多模型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
config_list = [
    {"model": "gpt-4o", "api_key": "key1"},
    {"model": "gpt-4o-mini", "api_key": "key2"},
]

# 自動 fallback
llm_config = {
    "config_list": config_list,
    "temperature": 0.7
}

本地模型

1
2
3
4
5
6
7
config_list = [
    {
        "model": "llama3.3",
        "base_url": "http://localhost:11434/v1",
        "api_key": "ollama"
    }
]

對話控制

終止條件

1
2
3
4
5
6
7
def is_termination_msg(msg):
    return "TERMINATE" in msg.get("content", "")

assistant = AssistantAgent(
    name="assistant",
    is_termination_msg=is_termination_msg
)

最大回覆數

1
2
3
4
user_proxy = UserProxyAgent(
    name="user",
    max_consecutive_auto_reply=10
)

相關連結

延伸閱讀

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy