A2A Protocol

BeeAI 프레임워크 기반 A2A 서비스 구현 문서

MILO
Share
BeeAI Framework A2A Service Implementation Guide

개요

이 문서는 BeeAI 프레임워크를 사용하여 Agent2Agent (A2A) 통신을 구현하는 방법을 보여줍니다. 서버 측(Agent)과 클라이언트 측(Host)의 완전한 구현이 포함되어 있습니다. 이 예제는 웹 검색과 날씨 조회 기능을 갖춘 지능형 채팅 에이전트를 시연합니다.

아키텍처 개요

sequenceDiagram
    participant User as 사용자
    participant Client as BeeAI Chat Client
    participant Server as BeeAI Chat Agent
    participant LLM as Ollama (granite3.3:8b)
    participant Tools as 도구 모음
    
    User->>Client: 채팅 메시지 입력
    Client->>Server: HTTP 요청 (A2A Protocol)
    Server->>LLM: 사용자 요청 처리
    LLM->>Tools: 도구 호출 (검색/날씨 등)
    Tools-->>LLM: 도구 결과 반환
    LLM-->>Server: 응답 생성
    Server-->>Client: A2A 응답 반환
    Client-->>User: 채팅 결과 표시

프로젝트 구조

samples/python/
├── agents/beeai-chat/          # A2A 서버 (Agent)
│   ├── __main__.py            # 서버 메인 프로그램
│   ├── pyproject.toml         # 의존성 설정
│   ├── Dockerfile             # 컨테이너화 설정
│   └── README.md              # 서버 문서
└── hosts/beeai-chat/           # A2A 클라이언트 (Host)
    ├── __main__.py            # 클라이언트 메인 프로그램
    ├── console_reader.py      # 콘솔 상호작용 인터페이스
    ├── pyproject.toml         # 의존성 설정
    ├── Dockerfile             # 컨테이너화 설정
    └── README.md              # 클라이언트 문서

환경 준비

시스템 요구사항

  • Python 3.11 이상
  • uv 패키지 매니저
  • Ollama 로컬 LLM 서비스

uv 설치

# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# 또는 pip 사용
pip install uv

Ollama 및 모델 설치

# Ollama 설치
curl -fsSL https://ollama.com/install.sh | sh

# 필요한 모델 다운로드
ollama pull granite3.3:8b

A2A 서버 구현 (Agent)

핵심 구현 분석

서버는 BeeAI 프레임워크의 RequirementAgentA2AServer를 사용하여 지능형 에이전트 서비스를 제공합니다:

def main() -> None:
    # LLM 모델 설정
    llm = ChatModel.from_name(os.environ.get("BEEAI_MODEL", "ollama:granite3.3:8b"))
    
    # 에이전트 생성, 도구 세트 설정
    agent = RequirementAgent(
        llm=llm,
        tools=[ThinkTool(), DuckDuckGoSearchTool(), OpenMeteoTool(), WikipediaTool()],
        memory=UnconstrainedMemory(),
    )

    # A2A 서버 시작
    A2AServer(
        config=A2AServerConfig(port=int(os.environ.get("A2A_PORT", 9999))), 
        memory_manager=LRUMemoryManager(maxsize=100)
    ).register(agent).serve()

주요 기능

  • 도구 통합: 사고, 웹 검색, 날씨 조회, Wikipedia 조회 지원
  • 메모리 관리: LRU 캐시를 사용하여 세션 상태 관리
  • 환경 설정: 환경 변수를 통한 모델 및 포트 설정 지원

uv로 서버 실행

git clone https://github.com/a2aproject/a2a-samples.git
# 서버 디렉토리로 이동
cd samples/python/agents/beeai-chat

# uv로 가상 환경 생성 및 의존성 설치
uv venv
source .venv/bin/activate  # Linux/macOS
uv pip install -e .

# 중요 참고사항
uv add "a2a-sdk[http-server]"

# 서버 시작
uv run python __main__.py

환경 변수 설정

export BEEAI_MODEL="ollama:granite3.3:8b"  # LLM 모델
export A2A_PORT="9999"                     # 서버 포트
export OLLAMA_API_BASE="http://localhost:11434"  # Ollama API 주소

A2A 클라이언트 구현 (Host)

핵심 구현 분석

클라이언트는 A2AAgent를 사용하여 서버와 통신하고 대화형 콘솔 인터페이스를 제공합니다:

async def main() -> None:
    reader = ConsoleReader()
    
    # A2A 클라이언트 생성
    agent = A2AAgent(
        url=os.environ.get("BEEAI_AGENT_URL", "http://127.0.0.1:9999"), 
        memory=UnconstrainedMemory()
    )
    
    # 사용자 입력 처리 루프
    for prompt in reader:
        response = await agent.run(prompt).on(
            "update",
            lambda data, _: (reader.write("Agent 🤖 (debug) : ", data)),
        )
        reader.write("Agent 🤖 : ", response.result.text)

대화형 인터페이스 기능

  • 실시간 디버깅: 에이전트 처리 과정의 디버그 정보 표시
  • 우아한 종료: 'q' 입력으로 프로그램 종료
  • 오류 처리: 빈 입력 및 네트워크 예외 처리

uv로 클라이언트 실행

# 클라이언트 디렉토리로 이동
cd samples/python/hosts/beeai-chat

# uv로 가상 환경 생성 및 의존성 설치
uv venv
source .venv/bin/activate  # Linux/macOS
uv pip install -e .

# 클라이언트 시작
uv run python __main__.py

환경 변수 설정

export BEEAI_AGENT_URL="http://127.0.0.1:9999"  # 서버 주소

완전한 실행 흐름

1. 서버 시작

# 터미널 1: A2A 서버 시작
cd samples/python/agents/beeai-chat
uv venv && source .venv/bin/activate
uv pip install -e .
uv add "a2a-sdk[http-server]"
uv run python __main__.py
# 출력
INFO:     Started server process [73108]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:9999 (Press CTRL+C to quit)

2. 클라이언트 시작

# 터미널 2: A2A 클라이언트 시작
cd samples/python/hosts/beeai-chat
uv venv && source .venv/bin/activate
uv pip install -e .
uv run python __main__.py
# 출력
Interactive session has started. To escape, input 'q' and submit.
User 👤 : what is the weather of new york today
Agent 🤖 (debug) :  value={'id': 'cb4059ebd3a44a2f8b428d83bbff8cac', 'jsonrpc': '2.0', 'result': {'contextId': 'b8a8d863-4c7d-48b7-9bdd-2848abccaae3', 'final': False, 'kind': 'status-update', 'status': {'state': 'submitted', 'timestamp': '2025-09-02T07:52:09.588387+00:00'}, 'taskId': '6e0fce64-51f0-4ad3-b0d5-c503b41bf63a'}}
Agent 🤖 (debug) :  value={'id': 'cb4059ebd3a44a2f8b428d83bbff8cac', 'jsonrpc': '2.0', 'result': {'contextId': 'b8a8d863-4c7d-48b7-9bdd-2848abccaae3', 'final': False, 'kind': 'status-update', 'status': {'state': 'working', 'timestamp': '2025-09-02T07:52:09.588564+00:00'}, 'taskId': '6e0fce64-51f0-4ad3-b0d5-c503b41bf63a'}}
Agent 🤖 (debug) :  value={'id': 'cb4059ebd3a44a2f8b428d83bbff8cac', 'jsonrpc': '2.0', 'result': {'contextId': 'b8a8d863-4c7d-48b7-9bdd-2848abccaae3', 'final': True, 'kind': 'status-update', 'status': {'message': {'contextId': 'b8a8d863-4c7d-48b7-9bdd-2848abccaae3', 'kind': 'message', 'messageId': '8dca470e-1665-41af-b0cf-6b47a1488f89', 'parts': [{'kind': 'text', 'text': 'The current weather in New York today is partly cloudy with a temperature of 16.2°C, 82% humidity, and a wind speed of 7 km/h.'}], 'role': 'agent', 'taskId': '6e0fce64-51f0-4ad3-b0d5-c503b41bf63a'}, 'state': 'completed', 'timestamp': '2025-09-02T07:52:39.928963+00:00'}, 'taskId': '6e0fce64-51f0-4ad3-b0d5-c503b41bf63a'}}
Agent 🤖 :  The current weather in New York today is partly cloudy with a temperature of 16.2°C, 82% humidity, and a wind speed of 7 km/h.
User 👤 : 

3. 상호작용 예제

Interactive session has started. To escape, input 'q' and submit.
User 👤 : 오늘 서울 날씨는 어떤가요?
Agent 🤖 (debug) : 서울 날씨 정보를 조회 중...
Agent 🤖 : 최신 날씨 데이터에 따르면, 서울은 오늘 흐림이며 기온 15-22°C, 습도 65%, 풍속 3m/s입니다.

User 👤 : 인공지능의 최신 발전에 대해 검색해주세요
Agent 🤖 (debug) : AI 관련 정보를 검색 중...
Agent 🤖 : 검색 결과에 따르면, 인공지능 분야의 최근 주요 발전 사항은...

User 👤 : q

기술 요점

의존성 관리

두 프로젝트 모두 pyproject.toml을 사용하여 의존성을 관리합니다:

서버 의존성:

dependencies = [
    "beeai-framework[a2a,search] (>=0.1.36,<0.2.0)"
]

클라이언트 의존성:

dependencies = [
    "beeai-framework[a2a] (>=0.1.36,<0.2.0)",
    "pydantic (>=2.10,<3.0.0)",
]

메모리 관리

  • 서버는 LRUMemoryManager를 사용하여 세션 수를 제한
  • 클라이언트와 서버 모두 UnconstrainedMemory를 사용하여 대화 기록 유지

도구 통합

서버는 여러 도구를 통합합니다:

  • ThinkTool: 내부 사고 및 추론
  • DuckDuckGoSearchTool: 웹 검색
  • OpenMeteoTool: 날씨 조회
  • WikipediaTool: Wikipedia 조회

확장 및 사용자 정의

새 도구 추가

from beeai_framework.tools.custom import CustomTool

agent = RequirementAgent(
    llm=llm,
    tools=[
        ThinkTool(), 
        DuckDuckGoSearchTool(), 
        OpenMeteoTool(), 
        WikipediaTool(),
        CustomTool()  # 사용자 정의 도구 추가
    ],
    memory=UnconstrainedMemory(),
)

사용자 정의 클라이언트 인터페이스

ConsoleReader를 대체하여 GUI 또는 웹 인터페이스를 구현할 수 있습니다:

class WebInterface:
    async def get_user_input(self):
        # 웹 인터페이스 입력 구현
        pass
    
    async def display_response(self, response):
        # 웹 인터페이스 출력 구현
        pass

요약

이 구현 문서는 BeeAI 프레임워크와 uv 패키지 매니저를 사용하여 완전한 A2A 통신 시스템을 구축하는 방법을 보여주었습니다. 서버의 지능형 에이전트와 클라이언트의 대화형 인터페이스를 통해 기능이 풍부한 챗봇 시스템을 구현했습니다. 이 아키텍처는 우수한 확장성을 가지며 새로운 도구와 기능을 쉽게 추가할 수 있습니다.

더 많은 A2A Protocol 예제