Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions samples/python/a2a_skeleton/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# a2a_skeleton
## 개요

a2a_skeleton은 다양한 에이전트 기반 서비스(게이트웨이, 콘텐츠 생성, 검색, 호스트 관리 등)로 구성된 마이크로서비스 아키텍처의 예시 프로젝트입니다. 각 에이전트는 독립적으로 동작하며, Gateway를 통해 통합적으로 접근할 수 있습니다.

## 전체 구조

- **gateway**: 모든 외부 요청을 받아 각 에이전트로 라우팅하는 중간 다리 역할을 합니다.
- **generate_contents_agent**: 텍스트, 카드 등 다양한 콘텐츠를 자동으로 생성하는 에이전트입니다.
- **search_agent**: 문서, 카드, 외부 데이터 등에서 정보를 검색하는 에이전트입니다.
- **host_agent**: 각 에이전트의 등록, 연결, 상태 확인 등 에이전트 관리 및 서비스 디스커버리를 담당합니다.

## 설치 방법

각 디렉토리(gateway, generate_contents_agent, search_agent, host_agent)에서 아래 명령어로 의존성을 설치합니다.

```
uv sync
```

## 실행 방법

각 서비스는 아래와 같이 실행할 수 있습니다. (포트는 환경에 맞게 조정하세요)

- **gateway**
```
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```
- **generate_contents_agent**
```
uvicorn main:app --reload --host 0.0.0.0 --port 8002
```
- **search_agent**
```
uvicorn main:app --reload --host 0.0.0.0 --port 8003
```
- **host_agent**
```
uvicorn main:app --reload --host 0.0.0.0 --port 8001
```

## 사용 예시

1. 각 서비스의 서버를 실행합니다.
2. Gateway(8000 포트)로 요청을 보내면, 내부적으로 적절한 에이전트로 라우팅되어 결과를 받을 수 있습니다.

- 예시

curl -X POST "http://localhost:8000/message" \
-H "Content-Type: application/json" \
-N \
-d '{
"query": "양자역학에대해서 글써줘",
"user_id": "test-user",
"app_name": "test-app"
}'

## 참고

- 각 에이전트별 상세 역할 및 실행 방법은 각 디렉토리의 README.md를 참고하세요.
- uv(https://github.com/astral-sh/uv) 기반으로 의존성 관리 및 실행을 권장합니다.

21 changes: 21 additions & 0 deletions samples/python/a2a_skeleton/gateway/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Gateway

## 역할

Gateway는 여러 에이전트(Agent) 서비스와 외부 클라이언트 간의 중간 다리 역할을 합니다. 클라이언트로부터 요청을 받아 적절한 에이전트로 전달하고, 에이전트의 응답을 다시 클라이언트에게 반환합니다. 이를 통해 서비스 간의 통신을 단순화하고, 인증, 로깅, 요청 라우팅 등 공통 기능을 중앙에서 처리할 수 있습니다.

## 실행 방법

1. 의존성 설치
uv 기반이므로 아래 명령어로 필요한 패키지를 설치합니다.
```
uv sync
```

2. 서버 실행
아래 명령어로 Gateway 서버를 실행할 수 있습니다.
```
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```

3. 서버가 정상적으로 실행되면, 클라이언트는 Gateway의 엔드포인트(0.0.0.0:8000)를 통해 각종 에이전트 서비스에 접근할 수 있습니다.
80 changes: 80 additions & 0 deletions samples/python/a2a_skeleton/gateway/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from fastapi import FastAPI, Request
import uuid
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import httpx
import logging

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

HOST_AGENT_URL = "http://localhost:8001/" # HostAgent 서버의 A2A 엔드포인트

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.get("/health")
def health_check():
return {"status": "ok"}


@app.post("/message")
async def send_message(request: Request):
data = await request.json()
#session_id = data.get("session_id", "default")
query = data.get("query", {})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The default value for query is an empty dictionary ({}), but the curl example and subsequent usage expect a string. If the query field is missing from the request body, passing the empty dictionary to the agent will likely cause issues. The default value should be an empty string "" to handle missing queries gracefully.

Suggested change
query = data.get("query", {})
query = data.get("query", "")

user_id = data.get("user_id", "guest")
app_name = data.get("app_name", "default")
metadata = data.get("metadata", {})

session_id = str(uuid.uuid4())

message_id = str(uuid.uuid4())
message = {
"messageId": message_id,
"role": "user",
"parts": [
{
"text": query
}
],
"metadata": {
"user_id": user_id,
"app_name" : app_name,
"session_id": session_id
}
}

payload = {
"jsonrpc": "2.0",
"id" : session_id,
"method": "message/stream",
"params": {
"message": message,
}
}

async def event_generator():
async with httpx.AsyncClient() as client:
async with client.stream(
"POST",
HOST_AGENT_URL,
json=payload,
headers={
"accept": "text/event-stream",
"connection": "keep-alive",
"content-type": "application/json",
}
) as response:
async for line in response.aiter_lines():
logger.info(f"line: {line}")
yield f"data: {line}\n\n"

return StreamingResponse(event_generator(), media_type="text/event-stream")
12 changes: 12 additions & 0 deletions samples/python/a2a_skeleton/gateway/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[project]
name = "gateway"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.115.14",
"gunicorn>=23.0.0",
"httpx>=0.28.1",
"uvicorn>=0.35.0",
]
Loading