Hey again!
So far, you’ve seen AG-2’s built-in patterns and multi-agent setups. Now, it’s time to level up by creating your own custom pattern with conditional logic — plus, we’ll integrate a tool so agents can perform actions beyond chatting.
Why Custom Patterns?
Sometimes, you want workflows that:
- Retry if quality checks fail
- Branch based on agent feedback
- Use tools dynamically during conversations
Custom patterns give you that full control.
Step 1: Define a Custom Pattern with Conditional Logic
Here’s an example pattern where:
- Agent A writes a draft
- Agent B reviews it
- If review fails, Agent A rewrites and resubmits
from ag2 import Agent, Pattern, Conversation
import os
os.environ["OPENAI_API_KEY"] = "your-api-key-here"
class ReviewRewritePattern(Pattern):
def __init__(self, writer, reviewer, max_retries=2):
super().__init__()
self.writer = writer
self.reviewer = reviewer
self.max_retries = max_retries
def run(self, prompt):
retries = 0
while retries <= self.max_retries:
# Step 1: Writer drafts
draft = self.writer.chat(prompt)
# Step 2: Reviewer reviews
review = self.reviewer.chat(draft)
# Step 3: Check if approved
if "approve" in review.lower():
return draft
retries += 1
prompt = f"Rewrite based on review: {review}"
return f"Max retries reached. Last draft:\n{draft}"
# Agents
writer = Agent(
name="writer",
llm="openai/gpt-4",
system_message="Write clear and detailed responses.",
)
reviewer = Agent(
name="reviewer",
llm="openai/gpt-4",
system_message="Review the text carefully and say 'approve' if good, otherwise give feedback.",
)
pattern = ReviewRewritePattern(writer, reviewer)
conv = Conversation(pattern=pattern)
result = conv.send("Explain quantum computing in simple terms.")
print(result)
Step 2: Adding a Tool to Your Agent
Let’s add a simple math tool that your writer agent can call to do calculations.
from ag2 import Tool
def calculator(a: int, b: int) -> int:
return a + b
calc_tool = Tool(
name="calculator",
description="Performs addition of two integers",
func=calculator,
)
writer.tools = [calc_tool]
Now your writer can call calculator
in its reasoning.
Step 3: Run the Full Workflow
python custom_pattern_tool.py
Watch the interaction as the writer drafts, the reviewer approves or requests edits, and the writer uses the calculator if needed.
What’s Next?
In upcoming lessons, we’ll explore:
- More complex tool integrations (APIs, databases)
- Human-in-the-loop workflows for final approval
- Debugging and monitoring agent conversations
Keep coding
Top comments (0)