Appearance
A2A Java Sample
Clone Code
bash
git clone https://github.com/google-a2a/a2a-samples
cd a2a-samples/samples/javaThis project is a Java implementation example of the Agent2Agent (A2A) protocol, providing complete client and server SDKs, along with an AI-powered translation service demonstration application.
Project Architecture
This project uses a Maven multi-module architecture, containing the following three core modules:
samples/java/
├── model/ # A2A Protocol Data Models
├── server/ # A2A Server SDK & Translation Service
├── client/ # A2A Client SDK & Example Code
└── pom.xml # Parent Maven Configuration FileModule Details
🎯 Model Module (model/)
Core data models for the A2A protocol, providing complete data structures for JSON-RPC 2.0 and A2A protocol:
- Message Models:
Message,Part,TextPart,Artifact - Task Models:
Task,TaskStatus,TaskState - Agent Models:
AgentCard,AgentCapabilities,AgentSkill - JSON-RPC Models:
JSONRPCRequest,JSONRPCResponse,JSONRPCError - Event Models:
TaskStatusUpdateEvent,TaskArtifactUpdateEvent
🚀 Server Module (server/)
Spring Boot-based A2A server SDK, integrated with Spring AI framework:
Core Components:
A2AServer: Main server class managing agent behaviorA2AController: REST controller implementing A2A protocol endpointsTaskHandler: Task processing interfaceA2AServerConfiguration: AI translation bot configuration
Key Features:
- Complete JSON-RPC 2.0 support
- Agent card publishing (
/.well-known/agent-card) - Task management (send, query, cancel)
- Streaming response support (Server-Sent Events)
- Spring AI integration supporting OpenAI and other models
📱 Client Module (client/)
Pure Java A2A client SDK with translation client examples:
Core Components:
A2AClient: Main client class handling all A2A operationsStreamingEventListener: Streaming event listener interfaceA2AClientException: A2A-specific exception handlingA2AClientExample: Complete translation client example
Key Features:
- JSON-RPC 2.0 client implementation
- Agent discovery and capability querying
- Synchronous/asynchronous task operations
- Streaming response handling
- Connection pooling and error recovery
Core Functionality Implementation
🤖 AI Translation Service
The project implements an intelligent translation agent supporting multi-language translation:
Translation Logic:
- Chinese → English
- English → Chinese
- Other languages → English
Technical Features:
- Based on Spring AI ChatClient
- Supports OpenAI, Azure OpenAI, and other models
- Context-aware natural language translation
- Real-time streaming responses
🔄 A2A Protocol Implementation
Complete implementation of A2A protocol specifications:
Core Operations:
tasks/send: Send task messagestasks/get: Query task statustasks/cancel: Cancel task execution
Protocol Features:
- JSON-RPC 2.0 communication
- Agent capability discovery
- Task status tracking
- Streaming event push
- Standardized error codes
📡 Communication Mechanisms
Synchronous Communication:
- HTTP POST
/a2a- Standard JSON-RPC requests - HTTP GET
/.well-known/agent-card- Agent information retrieval
Streaming Communication:
- HTTP POST
/a2a/stream- Server-Sent Events - Real-time task status updates
- Automatic reconnection and error recovery
How to Run
Requirements
- Java: 17 or higher
Step 1: Compile the Project
Execute compilation in the project root directory:
bash
cd samples/java
./mvnw clean install -DskipTestsStep 2: Configure Environment Variables
Set AI model-related environment variables (required for translation functionality):
bash
# OpenAI Configuration
export OPENAI_API_KEY="your-openai-api-key"
export OPENAI_BASE_URL="https://api.openai.com"
export OPENAI_CHAT_MODEL="gpt-4o"
# Or GCP OpenAI Configuration
export OPENAI_API_KEY="your-gcp-api-key"
export OPENAI_BASE_URL="https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi"
export OPENAI_CHAT_MODEL="gemini-2.5-pro-preview-05-06"OpenRouter Configuration
bash
export OPENAI_API_KEY="sk-or-v1-"
export OPENAI_BASE_URL="https://openrouter.ai/api"
export OPENAI_CHAT_MODEL="openai/gpt-4o-2024-11-20"Pay attention to OPENAI_BASE_URL, there is no /v1 in the URL.
Step 3: Start the Translation Server
Start the A2A translation server:
bash
cd server
../mvnw spring-boot:runThe server will start at http://localhost:8080, providing the following endpoints:
http://localhost:8080/.well-known/agent-card- Agent informationhttp://localhost:8080/a2a- A2A protocol endpointhttp://localhost:8080/a2a/stream- Streaming endpoint
Validate the Agent Card:
Step 4: Run the Translation Client
In a new terminal window, run the client example:
bash
cd client
../mvnw exec:java -Dexec.mainClass="com.google.a2a.client.A2AClientExample"Sequence Diagram
The following sequence diagram illustrates the complete interaction flow of the A2A Java sample application, based on the A2AClientExample.java:
Key Interaction Patterns
The sequence diagram demonstrates the following core interaction patterns:
- Client Initialization: Creating an
A2AClientinstance connected to the local server - Agent Discovery: Retrieving agent information via the
/.well-known/agent-cardendpoint - Multi-language Translation Examples:
- French → Chinese translation
- Chinese → English translation
- German → English streaming translation
- Task Management:
- Querying task status
- Canceling task execution
Communication Mechanisms
- Synchronous Translation: Using
POST /a2aendpoint with JSON-RPC requests - Streaming Translation: Using
POST /a2a/streamendpoint with Server-Sent Events (SSE) - Status Queries: Using
tasks/getmethod to check task execution status - Task Cancellation: Using
tasks/cancelmethod to cancel running tasks
API Usage Examples
Get Agent Information
bash
curl -X GET http://localhost:8080/.well-known/agent-card \
-H "Accept: application/json"Send Translation Task
bash
curl -X POST http://localhost:8080/a2a \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": "request-1",
"method": "tasks/send",
"params": {
"id": "translation-task-1",
"message": {
"messageId": "msg-1",
"kind": "message",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Hello, world!"
}
]
}
}
}'Streaming Translation
bash
curl -X POST http://localhost:8080/a2a/stream \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": "stream-request-1",
"method": "tasks/send",
"params": {
"id": "streaming-translation-task",
"message": {
"messageId": "stream-msg-1",
"kind": "message",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Hello world!"
}
]
}
}
}'