
Project Overview
This is a number guessing game example based on the Agent2Agent (A2A) protocol, demonstrating how three lightweight A2A agents collaborate to complete a classic number guessing game. This project serves as a practical introductory example for the A2A protocol and Python SDK, featuring:
- No LLM dependency: No API keys or large language models required
- Local execution: All three agents run locally without remote servers
- Easy installation: Minimal external dependencies
- Core concept demonstration: Showcases core A2A protocol functionality
Agent Role Description
Agent | Role | Function |
---|---|---|
AgentAlice | Evaluator | Selects a secret number from 1-100, evaluates guesses and provides hints |
AgentBob | CLI Frontend | Relays player guesses, displays Alice's hints, negotiates with Carol |
AgentCarol | Visualizer | Generates text visualization of guess history, randomly shuffles history on request |
Detailed Code File Analysis
1. Configuration File (config.py
)
AGENT_ALICE_PORT = 8001
AGENT_BOB_PORT = 8002
AGENT_CAROL_PORT = 8003
Function: Centrally manages port configuration to avoid port conflicts. All agents import configuration from this module, ensuring consistency in port allocation.
2. AgentAlice (agent_Alice.py
)
Core Functions:
- Randomly selects a secret number from 1-100 at startup
- Implements
NumberGuessExecutor
class to handle guess evaluation - Processes messages through A2A SDK's
AgentExecutor
interface
Key Methods:
execute()
: Processes newly received messages, callsprocess_guess()
to evaluate guessescancel()
: Rejects specified tasks
Response Types:
"Go higher"
- Guess is lower than the secret number"Go lower"
- Guess is higher than the secret number"correct! attempts: <n>"
- Guess is correct, shows attempt count
3. AgentBob (agent_Bob.py
)
Core Functions:
- Acts as CLI frontend, connecting players with other agents
- Manages game state and history records
- Negotiates with Carol to sort history records
Key Methods:
_handle_guess()
: Forwards guesses to Alice and returns feedback_negotiate_sorted_history()
: Negotiates with Carol until history is sorted_visualise_history()
: Requests and prints formatted history visualizationplay_game()
: Runs interactive CLI loop
Negotiation Logic:
- Sends initial shuffle request to Carol
- Checks if returned list is sorted
- If not sorted, sends "Try again" to continue negotiation
- If sorted, sends "Well done!" to complete negotiation
4. AgentCarol (agent_Carol.py
)
Core Functions:
- Visualizes guess history records
- Randomly shuffles history record lists
- Supports multi-turn dialogue and task references
Key Methods:
_handle_initial()
: Handles initial messages in new conversations_handle_followup()
: Handles follow-up messages referencing existing tasksexecute()
: Dispatches to appropriate handlers based on message type
Skill Definitions:
history_visualiser
: Generates formatted guess history summarieshistory_shuffler
: Randomly shuffles history record entry order
5. Utility Modules (utils/
)
game_logic.py
Core Functions:
process_guess()
: Evaluates individual guesses and returns feedbackbuild_visualisation()
: Creates human-readable history record renderingis_sorted_history()
: Checks if history is sorted by guess valuesprocess_history_payload()
: Processes history-related requests
protocol_wrappers.py
Core Functions:
send_text()
: Synchronously sends text messages to target agentssend_followup()
: Sends follow-up messages, maintaining conversation contextcancel_task()
: Cancels tasks on remote agentsextract_text()
: Extracts plain text from Task or Message objects
server.py
Core Functions:
run_agent_blocking()
: Starts blocking agent server- Uses Starlette + Uvicorn as HTTP server
System Architecture Flowchart
graph TD
A[Player] --> B[AgentBob CLI]
B --> C[AgentAlice Evaluator]
B --> D[AgentCarol Visualizer]
C --> E[Secret Number 1-100]
C --> F[Evaluate Guess]
F --> G{Guess Result}
G -->|Too Low| H[Return Go higher]
G -->|Too High| I[Return Go lower]
G -->|Correct| J[Return correct! attempts: N]
B --> K[Game History]
K --> L[Send to Carol for Visualization]
L --> M[Generate Formatted Table]
M --> N[Display to Player]
B --> O[Negotiate Sorting]
O --> P[Send Shuffle Request]
P --> Q[Carol Random Shuffle]
Q --> R{Check if Sorted}
R -->|Not Sorted| S[Send Try again]
R -->|Sorted| T[Send Well done!]
S --> Q
T --> U[Update History]
style A fill:#e1f5fe
style B fill:#f3e5f5
style C fill:#e8f5e8
style D fill:#fff3e0
style E fill:#ffebee
style F fill:#e8f5e8
style K fill:#f3e5f5
style O fill:#f3e5f5
Message Flow Diagram
sequenceDiagram
participant Player as Player
participant Bob as AgentBob
participant Alice as AgentAlice
participant Carol as AgentCarol
Note over Player,Carol: Game Start
Player->>Bob: Input guess number
Bob->>Alice: Send guess
Alice->>Bob: Return evaluation result
Bob->>Player: Display hint
Note over Player,Carol: Record History
Bob->>Bob: Add to game history
Note over Player,Carol: Visualize History
Bob->>Carol: Send history records
Carol->>Bob: Return formatted table
Bob->>Player: Display history visualization
Note over Player,Carol: Negotiate Sorting
Bob->>Carol: Send shuffle request
Carol->>Bob: Return shuffled list
Bob->>Bob: Check if sorted
alt Not Sorted
Bob->>Carol: Send "Try again"
Carol->>Bob: Shuffle list again
Bob->>Bob: Recheck sorting
else Sorted
Bob->>Carol: Send "Well done!"
Carol->>Bob: Complete task
Bob->>Bob: Update history
end
Note over Player,Carol: Continue Game or End
alt Guess Correct
Bob->>Player: Display victory message
else Guess Incorrect
Player->>Bob: Continue inputting guesses
end
Running the Project with uv
1. Environment Setup
Ensure uv is installed:
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
2. Project Setup
# Clone the project
git clone https://github.com/a2aproject/a2a-samples.git
cd a2a-samples/samples/python/agents/number_guessing_game
# Create virtual environment and install dependencies using uv
uv venv
source .venv/bin/activate # Linux/macOS
# or .venv\Scripts\activate # Windows
# Install dependencies
uv pip install -r requirements.txt
3. Running the Game
Open three terminal windows and activate the virtual environment in each:
# Terminal 1 - Start Alice (Evaluator)
uv run python agent_Alice.py
# Terminal 2 - Start Carol (Visualizer)
uv run python agent_Carol.py
# Terminal 3 - Start Bob (CLI Frontend)
uv run python agent_Bob.py
4. Gameplay
In Bob's terminal, the game will prompt you to enter numbers between 1-100. Continue guessing based on Alice's feedback until you guess correctly.
Example Game Flow:
Guess the number AgentAlice chose (1-100)!
Your guess: 50
Alice says: Go higher
=== Carol's visualisation (sorted) ===
Guesses so far:
1. 50 -> Go higher
============================
Your guess: 75
Alice says: Go lower
=== Carol's visualisation (sorted) ===
Guesses so far:
1. 50 -> Go higher
2. 75 -> Go lower
============================
Your guess: 62
Alice says: correct! attempts: 3
You won! Exiting…
Project Summary
Technical Features
-
A2A Protocol Practice:
- Demonstrates core concepts of inter-agent communication
- Implements message sending, task management, and state tracking
- Shows multi-turn dialogue and task reference mechanisms
-
Modular Design:
- Clear separation of responsibilities: Alice handles evaluation, Bob handles interaction, Carol handles visualization
- Reusable utility modules for easy extension and maintenance
-
Error Handling:
- Input validation and error prompts
- Network communication exception handling
- Task cancellation and timeout mechanisms
Learning Value
- A2A Introduction: Provides simple, understandable examples for understanding the A2A protocol
- Agent Collaboration: Shows how multiple agents collaborate to complete complex tasks
- Asynchronous Programming: Demonstrates asynchronous message processing and state management
- Protocol Design: Shows how to design clear agent interfaces and skill definitions
Extension Possibilities
- Add More Agents: Introduce new agent roles like statistical analysts, strategy advisors, etc.
- Enhanced Game Logic: Add more complex game rules like time limits, scoring systems, etc.
- Network Deployment: Deploy agents to different machines, demonstrating distributed agent systems
- LLM Integration: Add AI agents providing intelligent hints and strategy suggestions
Security Considerations
As mentioned in the project documentation, in production environments:
- External agents should be treated as untrusted entities
- All received data needs validation and sanitization
- Implement appropriate security measures like input validation and credential protection
This example provides developers with a safe, controlled environment to learn and experiment with the A2A protocol while demonstrating basic patterns for building distributed agent systems.
Related Case Studies
🚀 Getting Started Examples
-
A2A Samples: Hello World Agent
- Complete guide to building Hello World agents using A2A Python SDK
- Includes detailed environment setup and testing instructions
-
A2A SDK Currency Agent Tutorial
- Step-by-step guide to building currency conversion agents
- Integrates OpenRouter AI services
🐍 Python Implementation Cases
-
A2A Python Example: GitHub Agent
- Creating and connecting GitHub agents using a2a-python
- Implements code repository information query functionality
-
A2A Example: Travel Planning Assistant
- Travel planning agent implementation integrating OpenRouter
- Built using Python a2a-sdk
-
A2A SDK Python Practical Guide
- In-depth A2A SDK Python development tutorial
- Includes workflow diagrams and practical code examples
🟨 JavaScript/TypeScript Cases
-
- Integration with TMDB API and OpenRouter AI
- Express.js server implementation
-
A2A JavaScript SDK Complete Tutorial
- TypeScript type-safe implementation
- Express.js server SDK and streaming processing
☕ Java Implementation Cases
- A2A Java Example
- Maven multi-module architecture
- Spring Boot server SDK implementation
- AI translation service example
🔧 Framework Integration Cases
-
Implementing A2A Agents with ADK: Complete Development Guide
- Implementing A2A intelligent agent systems using Google ADK framework
- Covers complete development workflow
-
A2A ADK Expense Reimbursement Agent
- Intelligent expense reimbursement agent based on Google ADK and A2A protocol
- Automatically generates form supplementary information
-
A2A CrewAI Analysis Chart Agent
- Building data analysis agents using CrewAI framework
- Integrates chart generation and data visualization functionality
🛠️ Development Tools
-
A2A Inspector: Agent2Agent Communication Debugging Explained
- Powerful web-based debugging tool
- Real-time inspection of agent cards and JSON-RPC communication
-
A2A .NET SDK Comprehensive Documentation
- .NET library implementing Google A2A Protocol v0.2.1
- Suitable for ASP.NET Core applications
📚 Protocol Understanding and Best Practices
-
Understanding A2A Protocol: Comprehensive Guide
- Comprehensive guide to understanding the A2A protocol
- Core concepts and AI agent interoperability advantages
-
A2A Protocol Specification (Python)
- Comprehensive guide to Python implementation specifications
- Covers core functionality including agent cards, messaging, task management
-
2025 Complete Guide to A2A Protocol
- Comprehensive introduction and practical guide to the A2A protocol
- Complete coverage from basic concepts to advanced applications
🌟 Ecosystem Resources
-
- Explore the complete ecosystem of Google A2A protocol
- Includes official documentation, community implementations, sample projects, and integration guides
-
- Explore various open-source implementations of the A2A protocol
- Includes Java, TypeScript, Go, Rust, Python, and more
Through these case studies, you can gain deep insights into A2A protocol applications in different scenarios, from simple Hello World examples to complex multi-agent systems, providing rich reference resources for your A2A development journey.