Skip to content

Add AG2 multi-agent tutorial - #49

Open
faridun-ag2 wants to merge 2 commits into
NirDiamant:mainfrom
faridun-ag2:add-ag2-multi-agent-tutorial
Open

Add AG2 multi-agent tutorial#49
faridun-ag2 wants to merge 2 commits into
NirDiamant:mainfrom
faridun-ag2:add-ag2-multi-agent-tutorial

Conversation

@faridun-ag2

@faridun-ag2 faridun-ag2 commented Mar 28, 2026

Copy link
Copy Markdown

Summary

  • Add comprehensive tutorial for AG2 — open-source multi-agent framework with 500K+ monthly PyPI downloads
  • 4-part notebook: two-agent basics → tool registration → GroupChat orchestration → production patterns
  • Standalone app.py with CLI (default, --query, --interactive modes)
  • Tested and working with AG2 0.11.4

What's included

  • tutorials/ag2-multi-agent/ — complete tutorial folder
  • ag2_tutorial.ipynb — step-by-step notebook
  • app.py — runnable multi-agent system with CLI
  • README.md, requirements.txt, .env.example, GroupChat architecture diagram

Tutorial Contents

  1. Two-agent conversation — AssistantAgent + UserProxyAgent fundamentals
  2. Tool registration — AG2's dual register_for_llm + register_for_execution pattern
  3. GroupChat orchestration — multi-agent system with automatic speaker selection
  4. Production patterns — termination strategies, human-in-the-loop, safety tips

Test plan

  • pip install -r requirements.txt succeeds (Python 3.10+)
  • python app.py runs default demo query
  • python app.py --query "test" runs custom query
  • python app.py --interactive starts conversation loop
  • ag2_tutorial.ipynb is valid JSON and opens in Jupyter
  • All external links have UTM parameters
  • Existing tutorials untouched
  • Root README updated with AG2 entry in Agent Frameworks section

Summary by CodeRabbit

  • New Features

    • Added a new multi-agent tutorial showcasing AG2-driven agent orchestration, automatic speaker selection, interactive demo mode, and production-safe termination patterns.
  • Documentation

    • Added tutorial README entry (with "NEW" badge), architecture image, Google Colab link, and a comprehensive Jupyter walkthrough demonstrating setup, tool patterns, and orchestration.
  • Chores

    • Added example env placeholder and a requirements list for easy setup.

@coderabbitai

coderabbitai Bot commented Mar 28, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

A new AG2 (formerly AutoGen) multi-agent tutorial has been added to the repository, including a main README entry, tutorial documentation, a Jupyter notebook with step-by-step examples, an executable Python application demonstrating multi-agent orchestration with tool registration, and supporting configuration files.

Changes

AG2 multi-agent tutorial

Layer / File(s) Summary
Repository index and setup
README.md, tutorials/ag2-multi-agent/.env.example, tutorials/ag2-multi-agent/requirements.txt
Adds a README table row linking the new tutorial, an OPENAI_API_KEY placeholder .env.example, and requirements.txt with ag2[openai]>=0.11.0 and python-dotenv>=1.0.0.
Tutorial README and assets
tutorials/ag2-multi-agent/README.md
New tutorial README with overview, learning objectives, notebook and Colab links, architecture image, prerequisites, and resource links.
Notebook: examples & patterns
tutorials/ag2-multi-agent/ag2_tutorial.ipynb
Adds a comprehensive notebook demonstrating basic agent chat, dual tool registration, GroupChat orchestration with speaker_selection_method="auto", production termination patterns, human-in-the-loop modes, and additional considerations.
Example app: agents, tools, orchestration, CLI/REPL
tutorials/ag2-multi-agent/app.py
Adds executable example defining search_knowledge_base and generate_report tools, create_agents() with Planner/Researcher/Writer/Reviewer/UserProxy agents, GroupChatManager orchestration, run_query, interactive REPL, and main() CLI entry.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant Manager as GroupChatManager
  participant Planner as Planner Agent
  participant Researcher as Researcher Agent
  participant Writer as Writer Agent
  participant Reviewer as Reviewer Agent
  participant Tool as Tool Registry

  User->>Manager: Initiate chat with query
  Manager->>Manager: Select next speaker (auto mode)
  activate Manager
  
  Manager->>Planner: Execute turn
  Planner->>Manager: Message/plan
  
  Manager->>Manager: Select next speaker
  Manager->>Researcher: Execute turn
  Researcher->>Tool: search_knowledge_base()
  Tool->>Researcher: Results
  Researcher->>Manager: Report findings
  
  Manager->>Manager: Select next speaker
  Manager->>Writer: Execute turn
  Writer->>Tool: generate_report()
  Tool->>Writer: Formatted report
  Writer->>Manager: Submit draft
  
  Manager->>Manager: Select next speaker
  Manager->>Reviewer: Execute turn
  Reviewer->>Manager: Feedback/approval
  
  Manager->>Manager: Max rounds reached?
  deactivate Manager
  Manager->>User: Return final message
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hoppy, hoppy, agents dance,
AG2 gives them room to prance,
GroupChat hums as roles conspire,
Tools and reports light the fire,
Multi-minds together, inspired.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add AG2 multi-agent tutorial' directly and accurately summarizes the main change: introducing a new AG2 tutorial with comprehensive documentation and examples.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@faridun-ag2

Copy link
Copy Markdown
Author

Hi @NirDiamant 👋

Thanks for building such an amazing resource — Agents Towards Production is a fantastic playbook for the community!

We're from the AG2 team (formerly AutoGen), and we'd love to contribute a tutorial covering AG2's approach to multi-agent systems. AG2 has 500K+ monthly PyPI downloads and takes a conversation-centric approach that's quite different from graph-based frameworks — we think it would be a great addition alongside the existing LangGraph tutorial.

What this PR adds:

  • A complete 4-part tutorial going from a simple two-agent chat to a fully orchestrated GroupChat with tool use
  • A standalone app.py with CLI modes for easy experimentation
  • All tested and working with AG2 0.11.4

We followed the CONTRIBUTING.md guidelines (UTM links, required file structure, explanatory markdown before every code cell, etc.). Happy to iterate on any feedback!

Best,
The AG2 Team

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
tutorials/ag2-multi-agent/app.py (1)

27-27: Consider validating OPENAI_API_KEY environment variable.

The script loads environment variables but doesn't validate that OPENAI_API_KEY is set. Users will get a confusing error from the AG2/OpenAI client if the key is missing.

💡 Proposed enhancement
 load_dotenv()
+
+if not os.getenv("OPENAI_API_KEY"):
+    raise EnvironmentError(
+        "OPENAI_API_KEY not found. Copy .env.example to .env and add your key."
+    )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tutorials/ag2-multi-agent/app.py` at line 27, After calling load_dotenv(),
add a validation check for the OPENAI_API_KEY environment variable (via
os.getenv or similar) and fail fast with a clear error message if it's missing;
update the startup flow (around load_dotenv()) so that when OPENAI_API_KEY is
None or empty you log/raise a descriptive error and exit (e.g., raise
RuntimeError or sys.exit(1)) to avoid confusing downstream AG2/OpenAI client
errors.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@README.md`:
- Around line 548-554: The badge <img> tags are missing alt text; update the two
image elements (the NEW badge img with src
"https://img.shields.io/badge/NEW-brightgreen" and the GitHub badge img with src
"https://img.shields.io/badge/GitHub-View-blue") to include descriptive alt
attributes (e.g., alt="New tutorial" and alt="View on GitHub") so screen readers
can announce the badges.

In `@tutorials/ag2-multi-agent/README.md`:
- Line 1: The analytics tracking image uses markdown with no alt text
(`![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme)`);
update that markdown to include an explicit empty alt attribute (e.g., change to
`![](... " ")` is not ideal — instead use `![‌](...)` or replace with HTML `<img
src="https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme"
alt="" />`) so the tracking pixel is marked decorative and accessible.

---

Nitpick comments:
In `@tutorials/ag2-multi-agent/app.py`:
- Line 27: After calling load_dotenv(), add a validation check for the
OPENAI_API_KEY environment variable (via os.getenv or similar) and fail fast
with a clear error message if it's missing; update the startup flow (around
load_dotenv()) so that when OPENAI_API_KEY is None or empty you log/raise a
descriptive error and exit (e.g., raise RuntimeError or sys.exit(1)) to avoid
confusing downstream AG2/OpenAI client errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 15028284-d610-4451-a2fe-31654500b7e1

📥 Commits

Reviewing files that changed from the base of the PR and between 29be6d8 and c6297f2.

⛔ Files ignored due to path filters (1)
  • tutorials/ag2-multi-agent/assets/group-chat.png is excluded by !**/*.png
📒 Files selected for processing (6)
  • README.md
  • tutorials/ag2-multi-agent/.env.example
  • tutorials/ag2-multi-agent/README.md
  • tutorials/ag2-multi-agent/ag2_tutorial.ipynb
  • tutorials/ag2-multi-agent/app.py
  • tutorials/ag2-multi-agent/requirements.txt

Comment thread README.md
@@ -0,0 +1,45 @@
![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add alt text to the analytics tracking image.

The tracking pixel lacks alt text. Even for tracking images, an empty alt (alt="") is recommended for accessibility compliance to indicate it's decorative.

🔧 Proposed fix
-![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme)
+![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme "")

Or use HTML for explicit empty alt:

<img src="https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme" alt="" />
🧰 Tools
🪛 markdownlint-cli2 (0.22.0)

[warning] 1-1: Images should have alternate text (alt text)

(MD045, no-alt-text)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tutorials/ag2-multi-agent/README.md` at line 1, The analytics tracking image
uses markdown with no alt text
(`![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme)`);
update that markdown to include an explicit empty alt attribute (e.g., change to
`![](... " ")` is not ideal — instead use `![‌](...)` or replace with HTML `<img
src="https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--readme"
alt="" />`) so the tracking pixel is marked decorative and accessible.

@NirDiamant NirDiamant left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AG2 is a solid framework - a tutorial showing multi-agent coordination patterns would be a good addition.

Will review the notebook format and content quality.

@NirDiamant

Copy link
Copy Markdown
Owner

hey @faridun-ag2 !
can you please send me a DM on linkedin: https://www.linkedin.com/in/nir-diamant-ai/
so we can further discuss it.
thanks!

Add a comprehensive tutorial for AG2 (formerly AutoGen), covering
conversation-centric multi-agent design, dual tool registration,
GroupChat orchestration with automatic speaker selection, and
production safety patterns. Tested and working with AG2 0.11.4.
- Add alt text to AG2 tutorial badges in README for accessibility
- Validate OPENAI_API_KEY at startup in app.py with a clear error
- Remove stray logs.txt run artifact
@faridun-ag2
faridun-ag2 force-pushed the add-ag2-multi-agent-tutorial branch from c6297f2 to ddb6e18 Compare June 13, 2026 06:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tutorials/ag2-multi-agent/ag2_tutorial.ipynb`:
- Around line 70-77: The prose currently tells readers to pass llm_config to
each agent but the example omits it for UserProxyAgent; update the explanation
to state that llm_config is required only for LLM-backed agents (e.g.,
AssistantAgent) and is optional/omitted for proxy or non-LLM agents (e.g.,
UserProxyAgent), and add a short clarifying sentence next to the example
referencing AssistantAgent and UserProxyAgent by name so readers understand why
llm_config appears for one and not the other.
- Line 7: Replace the decorative markdown image token
"![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--ag2-tutorial)"
with an explicit empty-alt HTML image tag (e.g. <img
src="https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--ag2-tutorial"
alt=""/>) so the tracking pixel is still present but accessibility/lint checks
see an explicit alt="".
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9acc6bc5-1c72-46b5-87b2-acd956c81489

📥 Commits

Reviewing files that changed from the base of the PR and between c6297f2 and ddb6e18.

⛔ Files ignored due to path filters (1)
  • tutorials/ag2-multi-agent/assets/group-chat.png is excluded by !**/*.png
📒 Files selected for processing (6)
  • README.md
  • tutorials/ag2-multi-agent/.env.example
  • tutorials/ag2-multi-agent/README.md
  • tutorials/ag2-multi-agent/ag2_tutorial.ipynb
  • tutorials/ag2-multi-agent/app.py
  • tutorials/ag2-multi-agent/requirements.txt
✅ Files skipped from review due to trivial changes (1)
  • tutorials/ag2-multi-agent/.env.example
🚧 Files skipped from review as they are similar to previous changes (2)
  • tutorials/ag2-multi-agent/requirements.txt
  • tutorials/ag2-multi-agent/app.py

"cell_type": "markdown",
"metadata": {},
"source": [
"![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--ag2-tutorial)\n",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add explicit empty alt text for the tracking pixel.

This image is decorative, but ![](...) still trips accessibility/lint checks. Use an explicit empty alt or HTML with alt="".

🔧 Proposed fix
-![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--ag2-tutorial)
+<img src="https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--ag2-tutorial" alt="" />
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tutorials/ag2-multi-agent/ag2_tutorial.ipynb` at line 7, Replace the
decorative markdown image token
"![](https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--ag2-tutorial)"
with an explicit empty-alt HTML image tag (e.g. <img
src="https://europe-west1-atp-views-tracker.cloudfunctions.net/working-analytics?notebook=tutorials--ag2-multi-agent--ag2-tutorial"
alt=""/>) so the tracking pixel is still present but accessibility/lint checks
see an explicit alt="".

Comment on lines +70 to +77
"source": "---\n\n## Part 1: Two-Agent Conversation\n\nAG2's fundamental pattern is a conversation between two agents:\n\n- **AssistantAgent** — LLM-powered agent that reasons and generates responses\n- **UserProxyAgent** — represents the human, can execute tools and provide input\n\nThis is the building block for all AG2 applications. Pass `llm_config` to each agent to configure which LLM it uses."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "assistant = AssistantAgent(\n name=\"Assistant\",\n system_message=(\n \"You are a helpful research assistant. Provide clear, well-structured \"\n \"answers with key facts and actionable insights.\"\n ),\n llm_config=llm_config,\n)\n\nuser_proxy = UserProxyAgent(\n name=\"User\",\n human_input_mode=\"NEVER\", # Automated mode (no manual input)\n max_consecutive_auto_reply=1,\n code_execution_config=False,\n)"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Tighten the llm_config guidance.

The prose says to pass llm_config to each agent, but the example intentionally omits it for UserProxyAgent. Clarify that only LLM-backed agents need it.

✏️ Proposed wording change
-Pass `llm_config` to each agent to configure which LLM it uses.
+Pass `llm_config` to each LLM-backed agent to configure which LLM it uses.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"source": "---\n\n## Part 1: Two-Agent Conversation\n\nAG2's fundamental pattern is a conversation between two agents:\n\n- **AssistantAgent** — LLM-powered agent that reasons and generates responses\n- **UserProxyAgent** — represents the human, can execute tools and provide input\n\nThis is the building block for all AG2 applications. Pass `llm_config` to each agent to configure which LLM it uses."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "assistant = AssistantAgent(\n name=\"Assistant\",\n system_message=(\n \"You are a helpful research assistant. Provide clear, well-structured \"\n \"answers with key facts and actionable insights.\"\n ),\n llm_config=llm_config,\n)\n\nuser_proxy = UserProxyAgent(\n name=\"User\",\n human_input_mode=\"NEVER\", # Automated mode (no manual input)\n max_consecutive_auto_reply=1,\n code_execution_config=False,\n)"
"source": "---\n\n## Part 1: Two-Agent Conversation\n\nAG2's fundamental pattern is a conversation between two agents:\n\n- **AssistantAgent** — LLM-powered agent that reasons and generates responses\n- **UserProxyAgent** — represents the human, can execute tools and provide input\n\nThis is the building block for all AG2 applications. Pass `llm_config` to each LLM-backed agent to configure which LLM it uses."
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": "assistant = AssistantAgent(\n name=\"Assistant\",\n system_message=(\n \"You are a helpful research assistant. Provide clear, well-structured \"\n \"answers with key facts and actionable insights.\"\n ),\n llm_config=llm_config,\n)\n\nuser_proxy = UserProxyAgent(\n name=\"User\",\n human_input_mode=\"NEVER\", # Automated mode (no manual input)\n max_consecutive_auto_reply=1,\n code_execution_config=False,\n)"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tutorials/ag2-multi-agent/ag2_tutorial.ipynb` around lines 70 - 77, The prose
currently tells readers to pass llm_config to each agent but the example omits
it for UserProxyAgent; update the explanation to state that llm_config is
required only for LLM-backed agents (e.g., AssistantAgent) and is
optional/omitted for proxy or non-LLM agents (e.g., UserProxyAgent), and add a
short clarifying sentence next to the example referencing AssistantAgent and
UserProxyAgent by name so readers understand why llm_config appears for one and
not the other.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants