A2A Protocol

A2A Multi-Agent Example: Number Guessing Game

MILO
Share
A2A Multi-Agent Example: Number Guessing Game

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, calls process_guess() to evaluate guesses
  • cancel(): 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 visualization
  • play_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 tasks
  • execute(): Dispatches to appropriate handlers based on message type

Skill Definitions:

  • history_visualiser: Generates formatted guess history summaries
  • history_shuffler: Randomly shuffles history record entry order

5. Utility Modules (utils/)

game_logic.py

Core Functions:

  • process_guess(): Evaluates individual guesses and returns feedback
  • build_visualisation(): Creates human-readable history record rendering
  • is_sorted_history(): Checks if history is sorted by guess values
  • process_history_payload(): Processes history-related requests

protocol_wrappers.py

Core Functions:

  • send_text(): Synchronously sends text messages to target agents
  • send_followup(): Sends follow-up messages, maintaining conversation context
  • cancel_task(): Cancels tasks on remote agents
  • extract_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

  1. 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
  2. Modular Design:

    • Clear separation of responsibilities: Alice handles evaluation, Bob handles interaction, Carol handles visualization
    • Reusable utility modules for easy extension and maintenance
  3. Error Handling:

    • Input validation and error prompts
    • Network communication exception handling
    • Task cancellation and timeout mechanisms

Learning Value

  1. A2A Introduction: Provides simple, understandable examples for understanding the A2A protocol
  2. Agent Collaboration: Shows how multiple agents collaborate to complete complex tasks
  3. Asynchronous Programming: Demonstrates asynchronous message processing and state management
  4. Protocol Design: Shows how to design clear agent interfaces and skill definitions

Extension Possibilities

  1. Add More Agents: Introduce new agent roles like statistical analysts, strategy advisors, etc.
  2. Enhanced Game Logic: Add more complex game rules like time limits, scoring systems, etc.
  3. Network Deployment: Deploy agents to different machines, demonstrating distributed agent systems
  4. 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

🐍 Python Implementation Cases

🟨 JavaScript/TypeScript Cases

Java Implementation Cases

  • A2A Java Example
    • Maven multi-module architecture
    • Spring Boot server SDK implementation
    • AI translation service example

🔧 Framework Integration Cases

🛠️ Development Tools

📚 Protocol Understanding and Best Practices

🌟 Ecosystem Resources

  • Awesome A2A Directory

    • Explore the complete ecosystem of Google A2A protocol
    • Includes official documentation, community implementations, sample projects, and integration guides
  • A2A Implementation Collection

    • 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.