Content
# A2A C++ SDK
A C++ implementation based on the A2A (Agent-to-Agent) protocol, providing a complete framework for building and connecting intelligent Agents.
## 📖 Project Introduction
The A2A C++ SDK is a production-grade Agent communication framework that implements the complete A2A protocol specification. This project provides a full implementation from the protocol layer to the application layer, supporting the construction of distributed, scalable multi-Agent systems.
**Core Values:**
- 🎯 **Standardized Communication**: Complete implementation of the A2A protocol, ensuring interoperability between Agents.
- 🚀 **Production Ready**: Redis-based distributed TaskStore, supporting persistence and horizontal scaling.
- 🔧 **Easy to Develop**: Clear layered architecture and concise API design.
- 💪 **High Performance**: C++ implementation, supporting high concurrency and low-latency scenarios.
- 🔍 **Service Discovery**: Built-in registry center, supporting dynamic service registration and discovery.
## 🏗️ System Architecture
### 1. SDK Layered Architecture
```
┌─────────────────────────────────────────────────────────┐
│ Application Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Orchestrator │ │ Math Agent │ │ Other Agents │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
├─────────────────────────────────────────────────────────┤
│ Server Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ AgentServer │ │ TaskManager │ │ TaskStore │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
├─────────────────────────────────────────────────────────┤
│ Client Layer │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ AgentClient │ │ HttpClient │ │
│ └──────────────┘ └──────────────┘ │
├─────────────────────────────────────────────────────────┤
│ Core Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ AgentCard │ │ AgentMessage │ │ JSON-RPC │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────┘
```
### 2. Distributed Deployment Architecture (Fixed Address)
```
┌─────────────────┐ ┌─────────────────┐
│ Orchestrator │ │ Math Agent │
│ (Process 1) │ │ (Process 2) │
│ Port: 5000 │ │ Port: 5001 │
└────────┬────────┘ └────────┬────────┘
│ │
│ ┌─────────────────┐ │
└────► Redis Store ◄───┘
│ (TaskStore) │
│ Port: 6379 │
└─────────────────┘
▲
│
Persistence + Inter-Process Sharing
```
### 3. Dynamic Service Discovery Architecture (Recommended)
```
┌──────────────┐ ┌──────────────┐
│ Orchestrator │ │ Math Agent 1 │
│ Port: 5000 │ │ Port: 5001 │
└──────┬───────┘ └──────┬───────┘
│ │
│ ┌──────────────┐ │
│ │ Math Agent 2 │ │
│ │ Port: 5002 │ │
│ └──────┬───────┘ │
│ │ │
└─────────┼──────────────┘
│
┌────────▼────────┐
│ Registry Server │ ← Service Registration and Discovery
│ Port: 8500 │
└────────┬────────┘
│
┌────────▼────────┐
│ Redis Store │ ← Historical Message Persistence
│ Port: 6379 │
└─────────────────┘
```
**Architecture Features:**
- **Independent Processes**: Each Agent is deployed independently, without affecting each other.
- **Service Discovery**: Dynamically locate Agents through the registry center.
- **Load Balancing**: Select available Agent instances using a round-robin method.
- **Redis Persistence**: Historical messages are stored in Redis.
- **Inter-Process Sharing**: Multiple Agents share conversation history.
- **Fault Isolation**: Failure of a single Agent does not affect the overall system.
## 📁 Code Structure
```
a2a-cpp/
├── include/a2a/ # SDK Public Header Files
│ ├── core/ # Core Layer: Protocol Models
│ │ ├── jsonrpc_request.hpp # JSON-RPC Request
│ │ ├── jsonrpc_response.hpp # JSON-RPC Response
│ │ ├── error_code.hpp # Error Code Definitions
│ │ └── types.hpp # Basic Type Definitions
│ ├── models/ # Data Models
│ │ ├── agent_card.hpp # Agent Metadata
│ │ ├── agent_message.hpp # Message Model
│ │ ├── agent_task.hpp # Task Model
│ │ └── message_part.hpp # Message Parts
│ ├── client/ # Client Layer
│ │ └── a2a_client.hpp # A2A Client
│ └── server/ # Server Layer
│ ├── task_manager.hpp # Task Manager
│ ├── task_store.hpp # TaskStore Interface
│ └── memory_task_store.hpp # Memory Implementation
│
├── src/ # SDK Implementation Files
│ ├── core/ # Core Layer Implementation
│ ├── models/ # Model Layer Implementation
│ ├── client/ # Client Layer Implementation
│ └── server/ # Server Layer Implementation
│
├── examples/multi_agent_demo/ # Example: Distributed Multi-Agent System
│ ├── redis_orchestrator.cpp # Fixed Address Orchestrator
│ ├── redis_math_agent.cpp # Fixed Address Math Agent
│ ├── dynamic_orchestrator.cpp # Dynamic Service Discovery Orchestrator
│ ├── dynamic_math_agent.cpp # Dynamic Service Discovery Math Agent
│ ├── registry_server.cpp # Registry Center Server
│ ├── redis_task_store.hpp/cpp # Redis TaskStore Implementation
│ ├── agent_registry.hpp # Core Logic of the Registry Center
│ ├── registry_client.hpp # Registry Center Client
│ ├── interactive_client.cpp # Interactive Test Client
│ ├── start_redis_system.sh # Start Fixed Address System
│ ├── start_dynamic_system.sh # Start Dynamic Service Discovery System
│ ├── test_redis_system.sh # Automation Test Script
│ └── chat.sh # Interactive Chat Script
│
├── build/ # Compilation Output Directory
├── CMakeLists.txt # Main Build Configuration
├── README.md # This Document
├── Architecture_Description.md # Detailed Architecture Document
└── User_Guide.md # Development Guide
```
## ✨ Core Features
### SDK Functions
- ✅ **Complete A2A Protocol Implementation**
- JSON-RPC 2.0 Message Format
- Agent Card Metadata
- Context Management (contextId)
- Historical Length Control (history_length)
- ✅ **Flexible TaskStore**
- Memory Implementation (MemoryTaskStore): Suitable for single-machine development.
- Redis Implementation (RedisTaskStore): Suitable for production environments.
- Extensible Interface (ITaskStore): Supports custom implementations.
- ✅ **Service Registration and Discovery**
- Automatic Service Registration
- Service Lookup by Tags
- Health Check Mechanism
- Load Balancing (Round-Robin)
- ✅ **Production-Grade Features**
- Thread-Safe Design
- HTTP/HTTPS Transport
- Automatic Reconnection Mechanism
- Error Handling and Logging
### Example System Functions
- 🤖 **Intelligent Scheduling**: Orchestrator automatically identifies user intent.
- 🧮 **Mathematical Computation**: Math Agent handles various mathematical problems.
- 💾 **Historical Memory**: Inter-process sharing of conversation history.
- 🔄 **Context Understanding**: Supports multi-turn conversations.
- 🔍 **Dynamic Discovery**: Automatically discovers and selects available Agents.
## 🚀 Quick Start
### 1. Install Dependencies
```bash
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
git \
libcurl4-openssl-dev \
nlohmann-json3-dev \
libhiredis-dev \
redis-server
```
### 2. Compile the Project
```bash
# Replace "own—key" in the project code with your own api_key
```
```bash
# Enter the project directory
cd /home/ubuntu/a2a-cpp
# Create and enter the build directory
mkdir -p build && cd build
# Configure CMake
cmake .. -DCMAKE_BUILD_TYPE=Release
# Compile (use single-threaded to avoid memory issues)
make -j1
```
**Compilation Time:** Approximately 5-8 minutes
**Verify Successful Compilation:**
```bash
$ ls -lh examples/multi_agent_demo/
-rwxrwxr-x redis_orchestrator # Fixed Address Orchestrator
-rwxrwxr-x redis_math_agent # Fixed Address Math Agent
-rwxrwxr-x dynamic_orchestrator # Dynamic Service Discovery Orchestrator
-rwxrwxr-x dynamic_math_agent # Dynamic Service Discovery Math Agent
-rwxrwxr-x registry_server # Registry Center Server
-rwxrwxr-x interactive_client # Interactive Client
```
### 3. Run the System
#### Method A: Fixed Address System (Simple)
Suitable for fixed, known Agent deployment scenarios.
```bash
cd /home/ubuntu/a2a-cpp/examples/multi_agent_demo
# Start the system
./start_redis_system.sh
```
**System Components:**
- Orchestrator (Port 5000)
- Math Agent (Port 5001)
- Redis (Port 6379)
#### Method B: Dynamic Service Discovery System (Recommended)
Suitable for scenarios where the number and addresses of Agents are not fixed.
```bash
cd /home/ubuntu/a2a-cpp/examples/multi_agent_demo
# Start the system
./start_dynamic_system.sh
```
**System Components:**
- Registry Server (Port 8500) - Registry Center
- Orchestrator (Port 5000)
- Math Agent 1 (Port 5001)
- Math Agent 2 (Port 5002) - Demonstrating Load Balancing
- Redis (Port 6379)
### 4. Test the System
#### Automated Testing
```bash
./test_redis_system.sh
```
**Test Content:**
- ✅ Basic Calculation Functionality
- ✅ Context Understanding Capability
- ✅ Inter-Process Historical Sharing
- ✅ Redis Data Persistence
**Expected Output:**
```
✅ Test Passed!
- Orchestrator successfully saved history to Redis
- Math Agent successfully retrieved history from Redis
- Inter-Process historical sharing is functioning normally
- Number of historical messages: 6 (Expected >= 6)
```
#### Interactive Testing (Recommended)
```bash
./chat.sh
```
**Usage Example:**
```
========================================
A2A Interactive Test Client
========================================
Session ID: session-1701234567
Hints:
- Type your question and press enter to send
- Type 'quit' or 'exit' to exit
- Type 'new' to start a new session
- Type 'clear' to clear the screen
----------------------------------------
You> Calculate 15 + 27
Agent> 42
You> Multiply the above answer by 2
Agent> 84
You> Solve the equation 3x + 7 = 22
Agent> x = 5
You> quit
Thank you for using! Goodbye!
```
### 5. Check System Status
```bash
# Check processes
ps aux | grep -E "(redis_orchestrator|redis_math_agent|registry_server)"
# Check logs
tail -f logs/redis_orchestrator.log
tail -f logs/redis_math_agent.log
tail -f logs/registry_server.log
# Check historical data in Redis
redis-cli KEYS "a2a:*"
redis-cli LRANGE "a2a:history:my-session" 0 -1
# Check registered Agents (Dynamic System)
curl http://localhost:8500/v1/agents | jq
```
## Packet Capture Verification
```bash
sudo tcpdump -i any -w a2a_traffic3.pcap 'port 5000 or port 5001 or port 6379 or port 8500'
```
### 6. Stop the System
```bash
# Stop Fixed Address System
pkill -f redis_orchestrator
pkill -f redis_math_agent
# Stop Dynamic Service Discovery System
pkill -f registry_server
pkill -f dynamic_orchestrator
pkill -f dynamic_math_agent
```
## 🧪 Test Scenarios
### Scenario 1: Basic Calculation
```
You> 1+1
Agent> 2
You> Calculate 123 * 456
Agent> 56088
```
### Scenario 2: Context Understanding
```
You> 5 + 3
Agent> 8
You> Multiply the above answer by 10
Agent> 80 # ✅ Remembered the previous answer
You> Divide by 4
Agent> 20 # ✅ Continued to understand context
```
### Scenario 3: Equation Solving
```
You> Solve the equation 2x + 5 = 15
Agent> x = 5
You> Verify
Agent> Substituting x=5: 2*5 + 5 = 15 ✓
```
### Scenario 4: Service Discovery (Dynamic System)
```bash
# Check registered Agents
$ curl http://localhost:8500/v1/agents | jq
{
"success": true,
"agents": [
{
"id": "orch-1",
"name": "Orchestrator",
"address": "http://localhost:5000",
"tags": ["orchestrator", "coordinator"]
},
{
"id": "math-1",
"name": "Math Agent",
"address": "http://localhost:5001",
"tags": ["math", "calculator"]
},
{
"id": "math-2",
"name": "Math Agent",
"address": "http://localhost:5002",
"tags": ["math", "calculator"]
}
],
"count": 3
}
```
## 🔧 Frequently Asked Questions
### Q: What to do if there is insufficient memory during compilation?
**A:** Use single-threaded compilation (`-j1`):
```bash
make -j1
```
### Q: How to verify if the system is running normally?
**A:** Check processes and ports:
```bash
# Check processes
ps aux | grep -E "(redis_|registry_|dynamic_)"
# Check ports
sudo netstat -tlnp | grep -E "(5000|5001|5002|6379|8500)"
# Test Orchestrator
curl http://localhost:5000/.well-known/agent-card.json
```
### Q: What to do if Redis connection fails?
**A:** Ensure Redis service is running:
```bash
# Start Redis
sudo systemctl start redis-server
# Verify
redis-cli ping # Should return PONG
```
### Q: How to clear historical data?
**A:** Clear the Redis database:
```bash
redis-cli FLUSHDB
```
### Q: How to add a new Agent?
**A:**
1. Refer to `dynamic_math_agent.cpp` to write a new Agent.
2. Add the compilation target in `CMakeLists.txt`.
3. Register it with the registry center at startup.
4. The Orchestrator will automatically discover the new Agent.
### Q: How to capture network packets for debugging?
**A:** Use tcpdump:
```bash
# Capture packets on all relevant ports
sudo tcpdump -i any -s 0 -w a2a_traffic.pcap \
'port 5000 or port 5001 or port 5002 or port 6379 or port 8500' -v
# View the captured file
tcpdump -r a2a_traffic.pcap -A
```
## 🛠️ Technology Stack
### Core Dependencies
- **C++17** - Modern C++ Features
- **CMake 3.15+** - Build System
- **libcurl** - HTTP Client
- **nlohmann/json** - JSON Parsing
- **hiredis** - Redis Client
- **redis-server** - Redis Database
### AI Services
- **Alibaba Bailian Platform** - Tongyi Qianwen AI Model
## 📊 System Comparison
| Feature | Fixed Address System | Dynamic Service Discovery System |
|---------|----------------------|---------------------------------|
| **Deployment Complexity** | Simple | Moderate |
| **Service Discovery** | Hardcoded Address | Automatic Discovery |
| **Load Balancing** | Not Supported | Supported (Round-Robin) |
| **Agent Expansion** | Requires Code Modification | Dynamic Addition |
| **Health Check** | None | Automatic Check |
| **Applicable Scenarios** | Fixed Deployment | Dynamic Expansion |
## Project Purpose
This project is a sub-project of the AI Agent project that will be launched next week, which will be even more impressive.
## 📝 License
Apache 2.0
## 🙏 Acknowledgments
Based on the A2A protocol standard implementation.
---
**Start using the A2A C++ SDK to build your intelligent Agent system!** 🚀
## Owner Introduction
Agan from cpp tutoring, founder of the "Running Cpp / C++" knowledge community, specializing in tutoring related to cpp.
vx: LLqueww
The services inside will remain unchanged, with four commitments currently:
1. I will review everyone's check-in content daily and provide reasonable suggestions.
2. If anyone needs resume guidance or feels confused and needs counseling, they can make an appointment for one-on-one tutoring on Saturdays.
3. The Q&A chat every Friday night at 9 PM will remain unchanged.
4. Once you join the community, if there are any other activities or services in the future, they will be free (reasonable fees may be charged for community expenses, but no exploitation will occur, maintaining our original intention).
(Also includes exclusive confidential materials that have stood the test of time)
Students who join the community can ask questions and make appointments for one-on-one resume assistance and career planning guidance, as well as clarifications. High-quality projects and learning materials are also available.
For learning C++ basics, you can utilize the recently developed programming practice platform:
cppagancoding.top