
Code klonen
git clone https://github.com/google-a2a/a2a-samples
cd a2a-samples/samples/java
Dieses Projekt ist ein Java-Implementierungsbeispiel des Agent2Agent (A2A) Protokolls, das vollständige Client- und Server-SDKs sowie eine KI-gestützte Übersetzungsservice-Demonstrationsanwendung bereitstellt.
Projektarchitektur
Dieses Projekt verwendet eine Maven-Multi-Modul-Architektur und enthält die folgenden drei Kernmodule:
samples/java/
├── model/ # A2A-Protokoll-Datenmodelle
├── server/ # A2A Server SDK & Übersetzungsservice
├── client/ # A2A Client SDK & Beispielcode
└── pom.xml # Übergeordnete Maven-Konfigurationsdatei
Moduldetails
🎯 Model-Modul (model/)
Kern-Datenmodelle für das A2A-Protokoll, die vollständige Datenstrukturen für JSON-RPC 2.0 und A2A-Protokoll bereitstellen:
- Nachrichtenmodelle:
Message,Part,TextPart,Artifact - Aufgabenmodelle:
Task,TaskStatus,TaskState - Agent-Modelle:
AgentCard,AgentCapabilities,AgentSkill - JSON-RPC-Modelle:
JSONRPCRequest,JSONRPCResponse,JSONRPCError - Event-Modelle:
TaskStatusUpdateEvent,TaskArtifactUpdateEvent
🚀 Server-Modul (server/)
Spring Boot-basiertes A2A Server SDK, integriert mit Spring AI Framework:
-
Kernkomponenten:
A2AServer: Hauptserverklasse zur Verwaltung des Agent-VerhaltensA2AController: REST-Controller zur Implementierung von A2A-Protokoll-EndpunktenTaskHandler: AufgabenverarbeitungsschnittstelleA2AServerConfiguration: AI-Übersetzungsbot-Konfiguration
-
Hauptfunktionen:
- Vollständige JSON-RPC 2.0-Unterstützung
- Agent-Karten-Veröffentlichung (
/.well-known/agent-card) - Aufgabenverwaltung (senden, abfragen, abbrechen)
- Streaming-Antwort-Unterstützung (Server-Sent Events)
- Spring AI-Integration mit Unterstützung für OpenAI und andere Modelle
📱 Client-Modul (client/)
Reines Java A2A Client SDK mit Übersetzungsclient-Beispielen:
-
Kernkomponenten:
A2AClient: Hauptclientklasse zur Behandlung aller A2A-OperationenStreamingEventListener: Streaming-Event-Listener-SchnittstelleA2AClientException: A2A-spezifische AusnahmebehandlungA2AClientExample: Vollständiges Übersetzungsclient-Beispiel
-
Hauptfunktionen:
- JSON-RPC 2.0-Client-Implementierung
- Agent-Erkennung und Fähigkeitsabfrage
- Synchrone/asynchrone Aufgabenoperationen
- Streaming-Antwortbehandlung
- Verbindungspooling und Fehlerwiederherstellung
Kernfunktionalitätsimplementierung
🤖 AI-Übersetzungsservice
Das Projekt implementiert einen intelligenten Übersetzungsagenten, der mehrsprachige Übersetzung unterstützt:
Übersetzungslogik:
- Chinesisch → Englisch
- Englisch → Chinesisch
- Andere Sprachen → Englisch
Technische Funktionen:
- Basiert auf Spring AI ChatClient
- Unterstützt OpenAI, Azure OpenAI und andere Modelle
- Kontextbewusste natürliche Sprachübersetzung
- Echtzeit-Streaming-Antworten
🔄 A2A-Protokoll-Implementierung
Vollständige Implementierung der A2A-Protokollspezifikationen:
Kernoperationen:
tasks/send: Aufgabennachrichten sendentasks/get: Aufgabenstatus abfragentasks/cancel: Aufgabenausführung abbrechen
Protokollfunktionen:
- JSON-RPC 2.0-Kommunikation
- Agent-Fähigkeitserkennung
- Aufgabenstatusverfolgung
- Streaming-Event-Push
- Standardisierte Fehlercodes
📡 Kommunikationsmechanismen
Synchrone Kommunikation:
- HTTP POST
/a2a- Standard-JSON-RPC-Anfragen - HTTP GET
/.well-known/agent-card- Agent-Informationsabruf
Streaming-Kommunikation:
- HTTP POST
/a2a/stream- Server-Sent Events - Echtzeit-Aufgabenstatusupdates
- Automatische Wiederverbindung und Fehlerwiederherstellung
Ausführung
Anforderungen
- Java: 17 oder höher
Schritt 1: Projekt kompilieren
Kompilierung im Projekthauptverzeichnis ausführen:
cd samples/java
./mvnw clean install -DskipTests
Schritt 2: Umgebungsvariablen konfigurieren
AI-modellbezogene Umgebungsvariablen setzen (erforderlich für Übersetzungsfunktionalität):
# OpenAI-Konfiguration
export OPENAI_API_KEY="your-openai-api-key"
export OPENAI_BASE_URL="https://api.openai.com"
export OPENAI_CHAT_MODEL="gpt-4o"
# Oder GCP OpenAI-Konfiguration
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-Konfiguration
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"
Achten Sie auf OPENAI_BASE_URL, es gibt kein /v1 in der URL.
Schritt 3: Übersetzungsserver starten
A2A-Übersetzungsserver starten:
cd server
../mvnw spring-boot:run
Der Server startet unter http://localhost:8080 und stellt die folgenden Endpunkte bereit:
http://localhost:8080/.well-known/agent-card- Agent-Informationenhttp://localhost:8080/a2a- A2A-Protokoll-Endpunkthttp://localhost:8080/a2a/stream- Streaming-Endpunkt
Agent-Karte validieren:
Schritt 4: Übersetzungsclient ausführen
In einem neuen Terminalfenster das Client-Beispiel ausführen:
cd client
../mvnw exec:java -Dexec.mainClass="com.google.a2a.client.A2AClientExample"
Sequenzdiagramm
Das folgende Sequenzdiagramm veranschaulicht den vollständigen Interaktionsablauf der A2A Java-Beispielanwendung, basierend auf A2AClientExample.java:
sequenceDiagram
participant Example as A2AClientExample
participant Client as A2AClient
participant Server as A2A Server<br/>(localhost:8080)
Note over Example,Server: A2A Java Beispiel Sequenzdiagramm
%% 1. Client initialisieren
Example->>Client: new A2AClient("http://localhost:8080")
activate Client
%% 2. Agent-Karte abrufen
Example->>Client: getAgentCard()
Client->>Server: GET /.well-known/agent-card
Server-->>Client: AgentCard (name, description, version, skills)
Client-->>Example: AgentCard
Note over Example: Agent-Informationen ausgeben
%% 3. Französisch zu Chinesisch Übersetzung
Example->>Client: sendTask(frenchToChineseParams)
Note right of Example: TextPart: "Bonjour le monde!<br/>Comment allez-vous?"
Client->>Server: POST /a2a<br/>JSON-RPC: tasks/send
Server-->>Client: Task (id, status, history)
Client-->>Example: JSONRPCResponse<Task>
Note over Example: Übersetzungsergebnis ausgeben
%% 4. Chinesisch zu Englisch Übersetzung
Example->>Client: sendTask(chineseParams)
Note right of Example: TextPart: "你好,世界!<br/>欢迎使用AI翻译机器人。"
Client->>Server: POST /a2a<br/>JSON-RPC: tasks/send
Server-->>Client: Task (id, status, history)
Client-->>Example: JSONRPCResponse<Task>
Note over Example: Übersetzungsergebnis ausgeben
%% 5. Streaming-Übersetzung
Example->>Client: sendTaskStreaming(frenchParams, StreamingEventListener)
Note right of Example: TextPart: "Bonjour le monde!<br/>Comment allez-vous?"
Client->>Server: POST /a2a/stream<br/>Server-Sent Events
activate Server
loop Streaming-Antwort
Server-->>Client: SSE Event (Übersetzungsfortschritt)
Client-->>Example: onEvent(event)
Note over Example: Echtzeit-Übersetzungsereignisse ausgeben
end
Server-->>Client: SSE Complete
deactivate Server
Client-->>Example: onComplete()
Note over Example: Streaming-Übersetzung abgeschlossen
%% 6. Aufgabenstatus abfragen
Example->>Client: getTask(queryParams)
Note right of Example: Französische Übersetzungsaufgabenstatus abfragen
Client->>Server: POST /a2a<br/>JSON-RPC: tasks/get
Server-->>Client: Task (aktualisierter Status)
Client-->>Example: JSONRPCResponse<Task>
Note over Example: Aufgabenstatus ausgeben
%% 7. Aufgabe zum Abbrechen senden
Example->>Client: sendTask(cancelParams)
Note right of Example: TextPart: "Diese Übersetzung<br/>wird abgebrochen." (Deutsch)
Client->>Server: POST /a2a<br/>JSON-RPC: tasks/send
Server-->>Client: Task (id, status)
Client-->>Example: JSONRPCResponse<Task>
%% 8. Aufgabe abbrechen
Example->>Client: cancelTask(cancelTaskParams)
Client->>Server: POST /a2a<br/>JSON-RPC: tasks/cancel
Server-->>Client: Task (abgebrochener Status)
Client-->>Example: JSONRPCResponse<Task>
Note over Example: Abbruchergebnis ausgeben
deactivate Client
Note over Example,Server: Beispielprogrammausführung abgeschlossen
Wichtige Interaktionsmuster
Das Sequenzdiagramm demonstriert die folgenden Kern-Interaktionsmuster:
- Client-Initialisierung: Erstellen einer
A2AClient-Instanz, die mit dem lokalen Server verbunden ist - Agent-Erkennung: Abrufen von Agent-Informationen über den
/.well-known/agent-card-Endpunkt - Mehrsprachige Übersetzungsbeispiele:
- Französisch → Chinesisch Übersetzung
- Chinesisch → Englisch Übersetzung
- Deutsch → Englisch Streaming-Übersetzung
- Aufgabenverwaltung:
- Aufgabenstatus abfragen
- Aufgabenausführung abbrechen
Kommunikationsmechanismen
- Synchrone Übersetzung: Verwendung des
POST /a2a-Endpunkts mit JSON-RPC-Anfragen - Streaming-Übersetzung: Verwendung des
POST /a2a/stream-Endpunkts mit Server-Sent Events (SSE) - Statusabfragen: Verwendung der
tasks/get-Methode zur Überprüfung des Aufgabenausführungsstatus - Aufgabenabbruch: Verwendung der
tasks/cancel-Methode zum Abbrechen laufender Aufgaben
API-Verwendungsbeispiele
Agent-Informationen abrufen
curl -X GET http://localhost:8080/.well-known/agent-card \
-H "Accept: application/json"
Übersetzungsaufgabe senden
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-Übersetzung
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!"
}
]
}
}
}'
Related Articles
Explore more content related to this topic
A2UI Introduction - Declarative UI Protocol for Agent-Driven Interfaces
Discover A2UI, the declarative UI protocol that enables AI agents to generate rich, interactive user interfaces. Learn how A2UI works, who it's for, how to use it, and see real-world examples from Google Opal, Gemini Enterprise, and Flutter GenUI SDK.
Agent Gateway Protocol (AGP): Practical Tutorial and Specification
Learn the Agent Gateway Protocol (AGP): what it is, problems it solves, core spec (capability announcements, intent payloads, routing and error codes), routing algorithm, and how to run a working simulation.
Integrating A2A Protocol - Intelligent Agent Communication Solution for BeeAI Framework
Using A2A protocol instead of ACP is a better choice for BeeAI, reducing protocol fragmentation and improving ecosystem integration.
A2A vs ACP Protocol Comparison Analysis Report
A2A (Agent2Agent Protocol) and ACP (Agent Communication Protocol) represent two mainstream technical approaches in AI multi-agent system communication: 'cross-platform interoperability' and 'local/edge autonomy' respectively. A2A, with its powerful cross-vendor interconnection capabilities and rich task collaboration mechanisms, has become the preferred choice for cloud-based and distributed multi-agent scenarios; while ACP, with its low-latency, local-first, cloud-independent characteristics, is suitable for privacy-sensitive, bandwidth-constrained, or edge computing environments. Both protocols have their own focus in protocol design, ecosystem construction, and standardization governance, and are expected to further converge in openness in the future. Developers are advised to choose the most suitable protocol stack based on actual business needs.
Building an A2A Currency Agent with LangGraph
This guide provides a detailed explanation of how to build an A2A-compliant agent using LangGraph and the Google Gemini model. We'll walk through the Currency Agent example from the A2A Python SDK, explaining each component, the flow of data, and how the A2A protocol facilitates agent interactions.