
프로젝트 개요
이것은 Agent2Agent (A2A) protocol 기반 숫자 맞추기 게임 예제로, 3개의 가벼운 A2A 에이전트가 어떻게 협력하여 고전적인 숫자 맞추기 게임을 완성하는지 시연합니다. 이 프로젝트는 A2A protocol과 Python SDK의 실용적인 입문 예제로 기능하며, 다음과 같은 특징이 있습니다:
- LLM 의존성 없음: API 키나 대형 언어 모델 불필요
- 로컬 실행: 3개 에이전트 모두 원격 서버 없이 로컬 실행
- 쉬운 설치: 최소한의 외부 의존성
- 핵심 개념 시연: A2A protocol의 핵심 기능 소개
에이전트 역할 설명
| 에이전트 | 역할 | 기능 |
|---|---|---|
| AgentAlice | 평가자 | 1-100의 비밀 숫자 선택, 추측 평가 및 힌트 제공 |
| AgentBob | CLI 프론트엔드 | 플레이어 추측 중계, Alice의 힌트 표시, Carol과 협상 |
| AgentCarol | 시각화 | 추측 기록의 텍스트 시각화 생성, 요청 시 기록을 무작위 셔플 |
상세 코드 파일 분석
1. 설정 파일 (config.py)
AGENT_ALICE_PORT = 8001
AGENT_BOB_PORT = 8002
AGENT_CAROL_PORT = 8003
기능: 포트 설정을 중앙 관리하여 포트 충돌 방지. 모든 에이전트가 이 모듈에서 설정을 가져와 포트 할당의 일관성 보장.
2. AgentAlice (agent_Alice.py)
핵심 기능:
- 시작 시 1-100의 비밀 숫자를 무작위 선택
NumberGuessExecutor클래스를 구현하여 추측 평가 처리- A2A SDK의
AgentExecutor인터페이스를 통해 메시지 처리
주요 메서드:
execute(): 새로 수신된 메시지 처리,process_guess()를 호출하여 추측 평가cancel(): 지정된 작업 거부
응답 유형:
"Go higher"- 추측이 비밀 숫자보다 작음"Go lower"- 추측이 비밀 숫자보다 큼"correct! attempts: <n>"- 추측이 정확함, 시도 횟수 표시
3. AgentBob (agent_Bob.py)
핵심 기능:
- CLI 프론트엔드로 기능, 플레이어를 다른 에이전트와 연결
- 게임 상태와 기록 관리
- Carol과 협상하여 기록을 정렬
주요 메서드:
_handle_guess(): 추측을 Alice에게 전달하고 피드백 반환_negotiate_sorted_history(): 기록이 정렬될 때까지 Carol과 협상_visualise_history(): 포맷된 기록 시각화 요청 및 출력play_game(): 대화형 CLI 루프 실행
협상 로직:
- Carol에게 초기 셔플 요청 전송
- 반환된 목록이 정렬되었는지 확인
- 정렬되지 않은 경우 "Try again"을 전송하여 협상 계속
- 정렬된 경우 "Well done!"을 전송하여 협상 완료
4. AgentCarol (agent_Carol.py)
핵심 기능:
- 추측 기록을 시각화
- 기록 목록을 무작위 셔플
- 멀티턴 대화 및 작업 참조 지원
주요 메서드:
_handle_initial(): 새 대화에서 초기 메시지 처리_handle_followup(): 기존 작업을 참조하는 후속 메시지 처리execute(): 메시지 유형에 따라 적절한 핸들러로 디스패치
스킬 정의:
history_visualiser: 포맷된 추측 기록 요약 생성history_shuffler: 기록 항목 순서를 무작위 셔플
5. 유틸리티 모듈 (utils/)
game_logic.py
핵심 기능:
process_guess(): 개별 추측을 평가하고 피드백 반환build_visualisation(): 사람이 읽을 수 있는 기록 렌더링 생성is_sorted_history(): 기록이 추측 값으로 정렬되었는지 확인process_history_payload(): 기록 관련 요청 처리
protocol_wrappers.py
핵심 기능:
send_text(): 대상 에이전트에 텍스트 메시지 동기 전송send_followup(): 후속 메시지 전송, 대화 컨텍스트 유지cancel_task(): 원격 에이전트에서 작업 취소extract_text(): Task 또는 Message 객체에서 일반 텍스트 추출
server.py
핵심 기능:
run_agent_blocking(): 블로킹 에이전트 서버 시작- Starlette + Uvicorn을 HTTP 서버로 사용
시스템 아키텍처 플로우차트
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
메시지 플로우 다이어그램
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
uv로 프로젝트 실행
1. 환경 설정
uv가 설치되어 있는지 확인:
# uv 설치 (아직 설치되지 않은 경우)
curl -LsSf https://astral.sh/uv/install.sh | sh
2. 프로젝트 설정
# 프로젝트 클론
git clone https://github.com/a2aproject/a2a-samples.git
cd a2a-samples/samples/python/agents/number_guessing_game
# uv를 사용하여 가상 환경 생성 및 의존성 설치
uv venv
source .venv/bin/activate # Linux/macOS
# 또는 .venv\Scripts\activate # Windows
# 의존성 설치
uv pip install -r requirements.txt
3. 게임 실행
3개의 터미널 창을 열고 각각에서 가상 환경 활성화:
# 터미널 1 - Alice (평가자) 시작
uv run python agent_Alice.py
# 터미널 2 - Carol (시각화) 시작
uv run python agent_Carol.py
# 터미널 3 - Bob (CLI 프론트엔드) 시작
uv run python agent_Bob.py
4. 게임플레이
Bob의 터미널에서 게임이 1-100 사이의 숫자를 입력하라고 안내합니다. 올바르게 추측할 때까지 Alice의 피드백을 바탕으로 계속 추측하세요.
게임 플로우 예제:
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…
프로젝트 요약
기술적 특징
-
A2A Protocol 실습:
- 에이전트 간 통신의 핵심 개념 시연
- 메시지 전송, 작업 관리, 상태 추적 구현
- 멀티턴 대화 및 작업 참조 메커니즘 표시
-
모듈러 설계:
- 명확한 책임 분리: Alice는 평가, Bob은 상호작용, Carol은 시각화 처리
- 확장 및 유지보수가 쉬운 재사용 가능한 유틸리티 모듈
-
오류 처리:
- 입력 검증 및 오류 프롬프트
- 네트워크 통신 예외 처리
- 작업 취소 및 타임아웃 메커니즘
학습 가치
- A2A 입문: A2A protocol을 이해하기 위한 간단하고 이해하기 쉬운 예제 제공
- 에이전트 협력: 여러 에이전트가 복잡한 작업을 완료하기 위해 협력하는 방법 표시
- 비동기 프로그래밍: 비동기 메시지 처리 및 상태 관리 시연
- Protocol 설계: 명확한 에이전트 인터페이스 및 스킬 정의 설계 방법 표시
확장 가능성
- 더 많은 에이전트 추가: 통계 분석가, 전략 고문 등의 새로운 에이전트 역할 도입
- 게임 로직 강화: 시간 제한, 점수 시스템 등의 더 복잡한 게임 규칙 추가
- 네트워크 배포: 에이전트를 다른 머신에 배포하여 분산 에이전트 시스템 시연
- LLM 통합: 지능적인 힌트와 전략 제안을 제공하는 AI 에이전트 추가
보안 고려사항
프로젝트 문서에서 언급했듯이 프로덕션 환경에서는:
- 외부 에이전트는 신뢰할 수 없는 엔티티로 취급해야 함
- 수신된 모든 데이터는 검증 및 무해화 필요
- 입력 검증 및 자격 증명 보호와 같은 적절한 보안 조치 구현
이 예제는 개발자에게 A2A protocol을 학습하고 실험할 수 있는 안전하고 제어된 환경을 제공하며, 분산 에이전트 시스템 구축의 기본 패턴을 시연합니다.
관련 케이스 스터디
🚀 시작 예제
-
A2A Samples: Hello World Agent
- A2A Python SDK를 사용하여 Hello World 에이전트를 구축하는 완전한 가이드
- 상세한 환경 설정 및 테스트 지침 포함
-
A2A SDK Currency Agent Tutorial
- 통화 변환 에이전트 구축의 단계별 가이드
- OpenRouter AI 서비스 통합
🐍 Python 구현 케이스
-
A2A Python Example: GitHub Agent
- a2a-python을 사용하여 GitHub 에이전트 생성 및 연결
- 코드 저장소 정보 쿼리 기능 구현
-
A2A Example: Travel Planning Assistant
- OpenRouter를 통합한 여행 계획 에이전트 구현
- Python a2a-sdk를 사용하여 구축
-
- 심층적인 A2A SDK Python 개발 튜토리얼
- 워크플로우 다이어그램 및 실용적인 코드 예제 포함
🟨 JavaScript/TypeScript 케이스
-
- TMDB API 및 OpenRouter AI와의 통합
- Express.js 서버 구현
-
- TypeScript 타입 안전 구현
- Express.js 서버 SDK 및 스트리밍 처리
☕ Java 구현 케이스
- A2A Java Example
- Maven 멀티 모듈 아키텍처
- Spring Boot 서버 SDK 구현
- AI 번역 서비스 예제
🔧 프레임워크 통합 케이스
-
- Google ADK 프레임워크를 사용하여 A2A 지능형 에이전트 시스템 구현
- 완전한 개발 워크플로우 커버
-
- Google ADK 및 A2A protocol 기반 지능형 경비 정산 에이전트
- 양식 보완 정보 자동 생성
-
- CrewAI 프레임워크를 사용하여 데이터 분석 에이전트 구축
- 차트 생성 및 데이터 시각화 기능 통합
🛠️ 개발 도구
-
A2A Inspector: Agent2Agent 통신 디버깅 설명
- 강력한 웹 기반 디버깅 도구
- 에이전트 카드 및 JSON-RPC 통신의 실시간 검사
-
- Google A2A Protocol v0.2.1을 구현하는 .NET 라이브러리
- ASP.NET Core 애플리케이션에 적합
📚 Protocol 이해 및 모범 사례
-
- A2A protocol을 이해하기 위한 포괄적 가이드
- 핵심 개념 및 AI 에이전트 상호 운용성 장점
-
- Python 구현 사양의 포괄적 가이드
- 에이전트 카드, 메시징, 작업 관리를 포함한 핵심 기능 커버
-
- A2A protocol의 포괄적 소개 및 실용 가이드
- 기본 개념부터 고급 애플리케이션까지 완전 커버
🌟 생태계 리소스
-
- Google A2A protocol의 완전한 생태계 탐색
- 공식 문서, 커뮤니티 구현, 샘플 프로젝트, 통합 가이드 포함
-
- A2A protocol의 다양한 오픈 소스 구현 탐색
- Java, TypeScript, Go, Rust, Python 등 포함
이러한 케이스 스터디를 통해 간단한 Hello World 예제부터 복잡한 멀티 에이전트 시스템까지 다양한 시나리오에서의 A2A protocol 애플리케이션에 대한 깊은 통찰을 얻을 수 있으며, A2A 개발 여정에 풍부한 참고 자료를 제공합니다.
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.