Communitygithub.com

AG2 (AutoGen) — 多代理對話框架

你是AG2(原AutoGen)的專家,這是一個開源的多代理對話框架。你幫助開發者建立系統,讓多個AI代理透過結構化對話協作,支援工具使用、人機協作、程式碼執行、群組聊天協調和巢狀對話,適用於軟體開發、研究和資料分析等複雜任務。

AG2 (AutoGen) — 多代理對話框架 是什麼?

這個技能將你定位為 AG2(原名 AutoGen)的專家,這是一個開源的多代理對話框架,旨在幫助開發者建立由多個 AI 代理透過結構化對話協作的系統。它支援工具使用、人機協作、程式碼執行、群組聊天協調和巢狀對話,非常適合軟體開發、研究和資料分析等複雜任務。技能文檔提供了多個核心功能的 Python 程式碼範例,包括雙代理對話、群組聊天與工具使用,並說明了安裝方式與最佳實踐。使用此技能時,開發者可以快速建立具有清楚系統提示、自動發言者選擇、終止條件控制、Docker 安全程式碼執行、人機協作模式及精細工具註冊的代理系統。該框架支援多種 LLM 供應商,如 OpenAI 的 GPT-4o,並允許透過 `max_round` 和 `max_consecutive_auto_reply` 控制成本。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/TerminalSkills/skills/tree/HEAD/skills/ag2

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

AG2 (AutoGen) — 多代理對話框架 是做什麼的?

你是 AG2(原 AutoGen)的專家,這是一個開源的多代理對話框架。你幫助開發者建立系統,讓多個 AI 代理透過結構化對話協作——支援工具使用、人機協作、程式碼執行、群組聊天協調和巢狀對話——適用於軟體開發、研究和資料分析等複雜任務。

核心功能

雙代理對話

from autogen import ConversableAgent, UserProxyAgent

# AI 助理代理
assistant = ConversableAgent(
    name="Engineer",
    system_message="""你是一位資深軟體工程師。
撰寫乾淨、經過測試的 Python 程式碼。解釋你的設計決策。""",
    llm_config={"model": "gpt-4o", "temperature": 0.2},
)

# 人類代理(可自動批准或要求人類輸入)
user_proxy = UserProxyAgent(
    name="User",
    human_input_mode="NEVER",             # NEVER / ALWAYS / TERMINATE
    max_consecutive_auto_reply=10,
    is_termination_msg=lambda msg: "TERMINATE" in msg.get("content", ""),
    code_execution_config={
        "work_dir": "workspace",
        "use_docker": True,               # 在 Docker 中安全執行程式碼
    },
)

# 開始對話——代理會持續交談直到任務完成
result = user_proxy.initiate_chat(
    assistant,
    message="建立一個使用 JWT 進行使用者驗證的 FastAPI 應用程式。包含測試。",
)
# 工程師撰寫程式碼 → 使用者代理執行 → 工程師審視輸出 → 迭代

群組聊天(多個代理)

from autogen import GroupChat, GroupChatManager

# 專業代理
architect = ConversableAgent(
    name="Architect",
    system_message="你設計系統架構。專注於可擴展性、可靠性與清晰的介面。",
    llm_config={"model": "gpt-4o"},
)

developer = ConversableAgent(
    name="Developer",
    system_message="你根據架構師的設計實作功能。撰寫生產級別的程式碼。",
    llm_config={"model": "gpt-4o"},
)

reviewer = ConversableAgent(
    name="Reviewer",
    system_message="你檢查程式碼中的錯誤、安全性問題與最佳實踐。要徹底但具有建設性。",
    llm_config={"model": "gpt-4o"},
)

tester = ConversableAgent(
    name="Tester",
    system_message="你撰寫全面的測試。涵蓋邊界情況與整合場景。",
    llm_config={"model": "gpt-4o"},
)

# 群組聊天,可選擇輪流或由 AI 選擇發言者
group_chat = GroupChat(
    agents=[user_proxy, architect, developer, reviewer, tester],
    messages=[],
    max_round=20,
    speaker_selection_method="auto",      # LLM 根據上下文選擇下一個發言者
)

manager = GroupChatManager(groupchat=group_chat, llm_config={"model": "gpt-4o"})

user_proxy.initiate_chat(
    manager,
    message="建立一個即時通知服務,支援 WebSocket、Redis pub/sub 與速率限制。",
)
# 架構師設計 → 開發者實作 → 審查者發現問題 → 開發者修正 → 測試者加入測試

工具使用

from autogen import register_function

def search_codebase(query: str, file_pattern: str = "*.py") -> str:
    """在程式碼庫中搜尋特定模式。

    Args:
        query: 搜尋查詢(支援正規表示式)
        file_pattern: 要搜尋的檔案 glob 模式
    """
    import subprocess
    result = subprocess.run(["grep", "-rn", query, "--include", file_pattern, "."],
                           capture_output=True, text=True)
    return result.stdout[:2000]

def run_tests(test_path: str = "tests/") -> str:
    """在指定的測試目錄中執行 pytest。

    Args:
        test_path: 測試檔案或目錄的路徑
    """
    import subprocess
    result = subprocess.run(["python", "-m", "pytest", test_path, "-v", "--tb=short"],
                           capture_output=True, text=True)
    return f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"

# 為特定代理註冊工具
register_function(search_codebase, caller=developer, executor=user_proxy,
    description="在程式碼庫中搜尋程式碼模式")
register_function(run_tests, caller=tester, executor=user_proxy,
    description="執行測試以驗證程式碼正確性")

安裝

pip install ag2                           # 或:pip install pyautogen

最佳實踐

  1. 清晰的系統提示 —— 精確定義每個代理的角色;模糊的指令會導致對話失焦
  2. 發言者選擇 —— 在群組聊天中使用 auto 讓 LLM 選擇發言者;使用 round_robin 實現可預測的流程
  3. 終止條件 —— 設置 is_termination_msg 和 max_consecutive_auto_reply;防止無限迴圈
  4. Docker 用於程式碼執行 —— 啟用 use_docker: True 以安全執行程式碼;代理可以執行不受信任的程式碼
  5. 人機協作 —— 使用 TERMINATE 模式在關鍵操作時請求批准;使用 NEVER 實現完全自主
  6. 工具註冊 —— 使用特定的呼叫者/執行者配對註冊工具;並非每個代理都需要所有工具
  7. 巢狀對話 —— 為子任務使用巢狀對話;代理可以發起側邊對話並返回結果
  8. 成本控制 —— 設置 max_round 和 max_consecutive_auto_reply;在群組聊天中監控 token 使用量

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

TerminalSkills/skills

>- Run GitHub Actions locally with act. Use when a user asks to test GitHub Actions workflows locally, debug CI pipelines without pushing, or run workflows offline.

TerminalSkills/skills

>- Generate short-form videos with AI — script writing, text-to-speech narration, stock footage selection, subtitle generation, and video assembly. Use when: creating TikTok/YouTube Shorts/Reels content, automating video production, building content pipelines.

TerminalSkills/skills

>- Animate 3D objects and characters in Blender with Python. Use when the user wants to keyframe properties, create armatures and rigs, set up IK/FK chains, animate shape keys for facial animation, edit F-Curves, use the NLA editor to blend actions, add drivers for expression-based animation, or script any animation workflow in Blender.

TerminalSkills/skills

>- Automate motion capture and tracking workflows in Blender with Python. Use when the user wants to import BVH or FBX mocap data, retarget motion to armatures, track camera or object motion from video, solve camera motion, clean up motion capture data, or script any tracking pipeline in Blender.

TerminalSkills/skills

>- You are an expert in Bolt.new by StackBlitz, the AI-powered full-stack development environment that runs entirely in the browser. You help developers go from idea to deployed app in minutes using natural language prompts — Bolt generates complete applications with frontend, backend, database, and deployment, all running in a WebContainer without local setup.

TerminalSkills/skills

>- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime.

TerminalSkills/skills

>- Self-host customer support with Chatwoot. Use when a user asks to set up open-source customer support, add live chat without SaaS costs, build a multi-channel inbox, or deploy a free Intercom alternative.

TerminalSkills/skills

>- You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.

TerminalSkills/skills

When the user wants to edit, review, or improve existing marketing copy. Also use when the user mentions 'edit this copy,' 'review my copy,' 'copy feedback,' 'proofread,' 'polish this,' 'make this better,' or 'copy sweep.' This skill provides a systematic approach to editing marketing copy through multiple focused passes.

TerminalSkills/skills

>- Add live chat and customer support with Crisp. Use when a user asks to add a chat widget, implement live customer support, set up a help desk, create a knowledge base, or add a chatbot to a website.

TerminalSkills/skills

>- Assists with building custom interactive data visualizations using D3.js. Use when creating charts, graphs, maps, force layouts, or hierarchical diagrams that require fine-grained control beyond what charting libraries provide. Trigger words: d3, data visualization, chart, svg, scales, force graph, treemap, choropleth.

TerminalSkills/skills

dbt (data build tool) transforms data in your warehouse using SQL SELECT statements. Learn project setup, models, tests, documentation, incremental materializations, and integration with data warehouses like PostgreSQL, BigQuery, and Snowflake.

TerminalSkills/skills

>- You are an expert in dlt, the open-source Python library for building data pipelines. You help developers load data from any API, file, or database into warehouses and lakes using simple Python decorators — with automatic schema inference, incremental loading, and built-in data contracts. dlt is the "requests library for data pipelines.

TerminalSkills/skills

Data Version Control for ML projects. Track large datasets and models alongside Git, build reproducible ML pipelines, and run experiments with metric comparison. Works with any storage backend including S3, GCS, Azure, and local filesystems.

TerminalSkills/skills

>- You are an expert in E2B, the cloud platform for running AI-generated code in secure sandboxes. You help developers give AI agents the ability to execute code, install packages, read/write files, and run long processes in isolated cloud environments — each sandbox is a lightweight VM that boots in ~150ms with full Linux, filesystem, and networking.

TerminalSkills/skills

>- Transcode, convert, edit, and process audio and video with FFmpeg. Use when a user asks to convert video formats (webm to mp4, mkv to mp4), extract audio from video, compress video files, trim or cut clips, concatenate videos, add subtitles, create thumbnails, apply filters, change resolution or bitrate, re-encode media, create GIFs from video, add watermarks, normalize audio, stream media, or build automated media processing pipelines.

TerminalSkills/skills

>- Create advanced animations with GSAP. Use when building complex timelines, scroll-driven animations, SVG morphing, text animations, or high-performance web animations beyond CSS capabilities.

TerminalSkills/skills

>- Generate deterministic MP4 videos from HTML, CSS, media, and seekable animations using HeyGen's HyperFrames framework. Use when someone asks to "render HTML to video", "make a video with HyperFrames", "create a programmatic video", "turn an animation into MP4", "build a launch/product video from HTML", "render GSAP/Lottie/Three.js to video", or set up an agent-driven video pipeline. Covers init/preview/render/add/lint/inspect commands, data-* timing attributes, animation adapters, and the component catalog.

TerminalSkills/skills

When the user wants to perform load testing, stress testing, or performance testing of APIs and websites using k6. Also use when the user mentions "k6," "load test," "performance test," "stress test," "spike test," "soak test," "thresholds," "virtual users," or "VUs." For browser-based testing, see selenium.

TerminalSkills/skills

>- Lovable (formerly GPT Engineer) is a browser-based AI app builder that turns a natural-language description into a working full-stack web app with a built-in backend, authentication, database and one-click publishing. Use when the user wants to prototype or ship a web app with Lovable, write effective Lovable prompts, connect Supabase or GitHub, review generated security rules, or move a Lovable project into their own editor.

相關技能