This project demonstrates a multi-agent conversation system using Microsoft AutoGen's RoundRobinGroupChat with LangChain tool integration. The system features a primary agent that searches for flight information and an evaluator agent that provides feedback and approval.
- Multi-Agent RoundRobin Conversation: Alternating turns between primary and evaluator agents
- LangChain Tool Integration: Google Serper API for internet search capabilities
- Iterative Feedback Loop: Evaluator provides constructive feedback until response is approved
- TextMentionTermination: Automatic termination when evaluator responds with "APPROVE"
- GPT-4o-mini Integration: OpenAI model for intelligent agent responses
The system is built around a main FlightResearchSystem class that encapsulates all functionality:
class FlightResearchSystem:
"""A system that manages agents to research flight deals using Serper and OpenAI."""
def __init__(self, model_name: str = "gpt-4o-mini", max_turns: int = 20):
pass
def _validate_environment(self) -> None:
pass
def _setup_team(self) -> RoundRobinGroupChat:
pass
async def run(self, task_prompt: str) -> None:
pass-
Environment Validation:
- Validates required environment variables (
OPENAI_API_KEY,SERPER_API_KEY) - Provides clear error messages for missing configuration
- Validates required environment variables (
-
Logging System:
- Structured logging with timestamps and severity levels
- Error tracking and debugging information
- Console output for real-time monitoring
-
Agent Configuration:
- Primary Agent: Searches for flight information using internet search
- Evaluator Agent: Provides constructive feedback and approval
- RoundRobin Team: Manages turn-based conversation flow
-
Error Handling:
- Try-catch blocks for search operations
- Graceful error recovery and user feedback
- System-level exception handling
Environment Validation → Team Setup → User Request
→ Primary Agent (Search) → Primary Agent (Response)
→ Evaluator Agent (Feedback) → Primary Agent (Refine)
→ Evaluator Agent (Approve) → TERMINATION
- Robust Error Handling: Comprehensive exception management
- Environment Validation: Ensures proper configuration before execution
- Structured Logging: Professional logging with different severity levels
- Modular Design: Clean separation of concerns with dedicated methods
- Concurrent Search: Multiple search queries for comprehensive results
- Python 3.14+
- OpenAI API key
- Google Serper API key
- UV package manager
- Clone the repository:
git clone <repository-url>
cd 39-autogen_agent_chat_roundrobin- Install dependencies:
uv sync- Set up environment variables:
# Create .env file
OPENAI_API_KEY=your_openai_api_key
SERPER_API_KEY=your_serper_api_keyuv run main.py
2026-02-21 01:55:13,928 - autogen_core.events - INFO - {"payload": "{\"message\":{\"id\":\"3c074160-c585-45c1-986d-cdc3a4d2178c\",\"source\":\"evaluator\",\"models_usage\":{\"prompt_tokens\":793,\"completion_tokens\":3},\"metadata\":{},\"created_at\":\"2026-02-21T05:55:13.927573Z\",\"content\":\"APPROVE\",\"type\":\"TextMessage\"}}", "sender": "evaluator_a18d4c8d-128e-4322-93a7-396a00ba019e/a18d4c8d-128e-4322-93a7-396a00ba019e", "receiver": null, "kind": "MessageKind.PUBLISH", "delivery_stage": "DeliveryStage.DELIVER", "type": "Message"}
2026-02-21 01:55:13,930 - autogen_core - INFO - Publishing message of type GroupChatTermination to all subscribers: {'message': StopMessage(id='399c4c73-687c-44b3-b3b5-e50fed1a1c52', source='TextMentionTermination', models_usage=None, metadata={}, created_at=datetime.datetime(2026, 2, 21, 5, 55, 13, 930200, tzinfo=datetime.timezone.utc), content="Text 'APPROVE' mentioned", type='StopMessage'), 'error': None}
2026-02-21 01:55:13,931 - __main__ - INFO - Task completed. Printing results:
==================================================
[USER]:
Find a one-way non-stop flight from JFK to LHR in June 2026.
IMPORTANT: When you provide your answer, you MUST:
1. Focus ONLY on non-stop flights for June 2026
2. Organize the information in a clear, structured format with bullet points
...
[PRIMARY]:
[FunctionCall(id='call_Bkhvmo1nH7tfYtdFFg2bJto7', arguments='{"query":"One-way non-stop flight from JFK to LHR June 2026 prices"}', name='internet_search')]
[PRIMARY]:
[FunctionExecutionResult(content="Cheap Flights from New York (JFK) to London (LHR) start at $205 for one-way and $377 for round trip...")]
[PRIMARY]:
Cheap Flights from New York (JFK) to London (LHR) start at $205 for one-way and $377 for round trip...
[EVALUATOR]:
**Non-Stop Flights from JFK to LHR in June 2026:**
- **British Airways**: Starting at $518 (typical range: $500 - $760)
- **United Airlines**: Starting at $516 (typical range: $500 - $760)
- **Flight Duration**: Approximately 7-8 hours
Please ensure that the flight details, including prices, are up to date at the time of booking.
[PRIMARY]:
**Non-Stop Flights from JFK to LHR in June 2026:**
- **British Airways**: Starting at $518 (typical range: $500 - $760)
- **United Airlines**: Starting at $516 (typical range: $500 - $760)
- **Flight Duration**: Approximately 7-8 hours
Please ensure to check the details and pricing when you're ready to book, as they are subject to change.
[EVALUATOR]:
APPROVE
==================================================
- Model:
gpt-4o-mini - Max Turns: 20
- Termination Condition:
TextMentionTermination("APPROVE")
- Search Tool: Google Serper API via LangChain
- Adapter:
LangChainToolAdapterfor AutoGen compatibility
- Prompt vs System Message: Instructions in user prompt are more effective than system message when using tools
- Iterative Improvement: Multi-turn conversations with feedback produce better results
- Termination Conditions:
TextMentionTerminationworks reliably for approval-based workflows - Tool Integration: LangChain tools can be seamlessly integrated with AutoGen agents
- Class-Based Architecture: Encapsulating functionality in classes improves code organization and reusability
- Environment Validation: Validating configuration early prevents runtime errors and improves user experience
- Structured Logging: Professional logging with different severity levels aids debugging and monitoring
- Error Handling: Comprehensive exception management makes the system more robust and user-friendly
- Missing Environment Variables: The system validates
OPENAI_API_KEYandSERPER_API_KEYon startup - Agent not following instructions: Put detailed instructions in the user prompt rather than system message
- Conversation stopping early: Ensure termination condition is properly configured
- Search tool errors: Check internet connectivity and Serper API quota
- Logging not showing: Ensure logging level is set to INFO in the configuration
The system automatically validates required environment variables:
# Missing variables will cause:
EnvironmentError: Missing required environment variables: OPENAI_API_KEY, SERPER_API_KEYThe system includes comprehensive logging by default:
# Logging configuration
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)Log Levels:
INFO: Normal operation flowERROR: Search failures and system errorsCRITICAL: Application startup failures
The system includes built-in error handling:
try:
return serper.run(query)
except Exception as e:
logger.error(f"Error during internet search: {e}", exc_info=True)
return f"Error executing search: {str(e)}"autogen-agentchat: Multi-agent frameworkautogen-ext.models.openai: OpenAI model integrationautogen-ext.tools.langchain: LangChain tool adapterlangchain-community: Community tools (Google Serper)langchain-core: Core LangChain functionalitypython-dotenv: Environment variable management
- The system demonstrates effective human-AI collaboration patterns with robust error handling
- Class-based architecture provides better code organization and reusability
- Environment validation ensures proper configuration before execution
- Structured logging provides comprehensive debugging and monitoring capabilities
- RoundRobin conversation ensures structured dialogue with built-in error recovery
- Feedback loops improve response quality iteratively with graceful error handling
- Text-based termination provides clear approval workflows with logging confirmation
- Add more sophisticated evaluation criteria with configurable rubrics
- Implement multiple search tools for better information gathering with fallback mechanisms
- Add memory capabilities for context retention across conversations using vector stores
- Implement concurrent tool usage for faster information gathering with async execution
- Add configuration file support for different search scenarios and agent personalities
- Implement metrics collection and performance monitoring for system optimization
- Add support for multiple LLM providers with automatic failover capabilities