Welcome back!
By now, you've created a multi-agent system where a Researcher passes info to a Writer. But what if you want to reuse that structure, or build more complex workflows with built-in logic?
That’s where AG-2 Patterns come in.
In this lesson, we’ll explore:
- What AG-2 Patterns are
- How to use a built-in pattern (TaskWithQA)
- How to create your own custom pattern
Let’s go!
What Are Patterns?
Patterns are reusable orchestration templates. Instead of manually defining from → to
rules between agents every time, you can:
- Use pre-built flows (like “Agent + Reviewer”)
- Create modular, readable code
- Focus on agent roles instead of plumbing
Think of Patterns as conversation blueprints.
Step 1: Use a Built-in Pattern – TaskWithQA
This pattern follows a simple structure:
- Agent A completes a task
- Agent B (reviewer) checks the result
- Optionally loops back if something needs to be redone
Let’s implement it.
from ag2 import Agent, Pattern, Conversation
import os
os.environ["OPENAI_API_KEY"] = "your-api-key-here"
# Task agent
writer = Agent(
name="writer",
llm="openai/gpt-4",
system_message="Write a response based on the given prompt.",
)
# QA agent (Reviewer)
reviewer = Agent(
name="reviewer",
llm="openai/gpt-4",
system_message="Review the response and provide feedback if needed. If it's good, approve it.",
)
# Use the built-in TaskWithQA pattern
pattern = Pattern.TaskWithQA(task_agent=writer, qa_agent=reviewer)
# Create a conversation using the pattern
conv = Conversation(pattern=pattern)
conv.send("Write a brief description of how photosynthesis works.")
Step 2: Run It
python task_with_qa.py
Expected flow:
- Writer generates a description
- Reviewer reads and critiques (or approves)
- Conversation ends or loops with edits if necessary
Simple, powerful, and structured!
Step 3: Custom Patterns (Optional Preview)
You can also define your own custom pattern using Python classes, giving you full control over how agents interact — conditionally, sequentially, even with retries or external triggers.
We’ll cover that in detail in the next lesson.
What’s Next?
In the next post, we’ll:
- Build a custom Pattern class
- Explore conditional logic, like “if reviewer rejects, retry”
- Use Tools + Patterns for real automation pipelines
Keep coding :)
Top comments (0)