Claude 4.6 Agent Teams를 활용한 병렬 작업 실행과 효과적인 System Prompt 엔지니어링을 학습합니다.
Agent Team 구축 심화 가이드: 팀 규모 결정, 역할 정의, 조율 전략 등 실전 팀 구축 방법론은 Agent Team Building 가이드를 참고하세요.
Claude 4.6에서 도입된 Multi-Agent 팀 기능은 병렬 작업 실행을 혁신적으로 개선했습니다. 이 문서는 Multi-Agent 시스템 설계와 각 Agent를 효과적으로 구성하는 System Prompt 기법을 다룹니다.
핵심 개념: 각 Agent가 명확한 책임을 가지고 독립적으로 작업하되, 조율을 통해 시너지를 창출합니다.
원칙: 각 팀원이 고유한 파일 또는 디렉토리 세트를 소유
이유:
구현 예시:
class AgentTeam:
def __init__(self):
self.agents = [
Agent(
name="backend-developer",
owned_files=["src/backend/**/*.py", "tests/backend/**"]
),
Agent(
name="frontend-developer",
owned_files=["src/frontend/**/*.tsx", "src/components/**"]
),
Agent(
name="database-specialist",
owned_files=["migrations/**", "schema/**"]
)
]
async def execute_project(self, requirements):
# 각 Agent가 자신의 영역에서 병렬 작업
tasks = [
agent.work_on_requirements(requirements)
for agent in self.agents
]
results = await asyncio.gather(*tasks)
# 통합 및 검증
integrated = await self.integrate_changes(results)
return integrated
자동 컨텍스트 압축:
진행 상황 추적:
# claude-progress.txt 파일 사용
class ProgressTracker:
def __init__(self, progress_file="claude-progress.txt"):
self.progress_file = progress_file
def update(self, agent_name, task, status):
"""진행 상황을 파일에 기록"""
entry = f"""
[{datetime.now().isoformat()}] {agent_name}
Task: {task}
Status: {status}
---
"""
with open(self.progress_file, 'a') as f:
f.write(entry)
def get_current_state(self):
"""새로운 컨텍스트 윈도우에서 현재 상태 파악"""
with open(self.progress_file, 'r') as f:
return f.read()
claude-progress.txt 패턴:
# Project Progress
## Completed Features
- [x] User authentication (backend-developer, 2026-02-13)
- [x] Login UI component (frontend-developer, 2026-02-13)
- [x] User table schema (database-specialist, 2026-02-13)
## In Progress
- [ ] Password reset flow (backend-developer)
- Email service integration needed
- ETA: 1 hour
## Blocked
- [ ] OAuth integration (backend-developer)
- Waiting for: API credentials from ops team
## Testing Status
- ✅ Unit tests passing (98% coverage)
- ⚠️ Integration tests: 2 failures (investigating)
- ❌ E2E tests: Not yet run
사용 시기: Agent 간 의존성이 있는 경우
예시: 설계 → 구현 → 테스트
async def sequential_workflow(requirements):
# Agent 1: 아키텍트가 설계
design = await architect_agent.create_design(requirements)
# Agent 2: 개발자가 구현 (설계 기반)
implementation = await developer_agent.implement(design)
# Agent 3: 테스터가 검증 (구현 기반)
test_results = await tester_agent.verify(implementation)
return test_results
장점:
단점:
사용 시기: 독립적인 작업들을 동시에 수행
예시: 여러 마이크로서비스 동시 개발
async def concurrent_workflow(requirements):
# 모든 Agent가 동시에 작업
results = await asyncio.gather(
auth_service_agent.build(requirements.auth),
payment_service_agent.build(requirements.payment),
notification_service_agent.build(requirements.notifications)
)
# 통합
integrated_system = await integrate_services(results)
return integrated_system
성능 향상:
사용 시기: 조건에 따라 전문가에게 작업 전달
예시: 일반 개발자 → 보안 전문가
class HandoffWorkflow:
async def implement_feature(self, feature_request):
# 일반 개발자가 기본 구현
result = await general_developer.implement(feature_request)
# 보안이 중요한 경우 전문가에게 핸드오프
if self.is_security_critical(result):
result = await security_specialist.review_and_harden(result)
# 성능이 중요한 경우 최적화 전문가에게
if self.requires_optimization(result):
result = await performance_specialist.optimize(result)
return result
def is_security_critical(self, implementation):
"""보안 중요도 판단"""
keywords = ["auth", "password", "token", "payment", "pii"]
return any(kw in implementation.code.lower() for kw in keywords)
사용 시기: Agent 간 협업과 토론이 필요한 경우
예시: 아키텍처 의사결정
class GroupChatWorkflow:
async def design_architecture(self, requirements):
coordinator = CoordinatorAgent()
specialists = {
"backend": BackendArchitect(),
"frontend": FrontendArchitect(),
"database": DatabaseArchitect(),
"devops": DevOpsArchitect()
}
# 초기 제안
proposals = await asyncio.gather(*[
specialist.propose_architecture(requirements)
for specialist in specialists.values()
])
# 토론 및 합의
consensus = await coordinator.facilitate_discussion(
specialists, proposals, rounds=3
)
return consensus
class CoordinatorAgent:
async def facilitate_discussion(self, specialists, proposals, rounds):
current_design = proposals
for round_num in range(rounds):
# 각 전문가가 다른 제안 검토
feedbacks = await asyncio.gather(*[
specialist.review_proposals(current_design)
for specialist in specialists.values()
])
# 피드백 기반 개선
current_design = await self.synthesize_feedback(
current_design, feedbacks
)
# 합의 도달 확인
if await self.has_consensus(feedbacks):
break
return current_design
개념: 여러 단계의 전문화된 Agent들이 파이프라인 형태로 작업
Requirements
↓
[1. Backend Architect]
↓
[2. Database Architect] (병렬)
[3. API Designer] (병렬)
↓
[4. Backend Developer]
↓
[5. Frontend Developer]
↓
[6. Test Automator]
↓
[7. Security Auditor]
↓
[8. Performance Optimizer]
↓
[9. Deployment Engineer]
↓
Production
class SwarmOrchestrator:
def __init__(self):
self.stages = [
("architecture", [BackendArchitect(), DatabaseArchitect()]),
("development", [BackendDev(), FrontendDev()]),
("quality", [TestAutomator(), SecurityAuditor()]),
("optimization", [PerformanceOptimizer()]),
("deployment", [DeploymentEngineer()])
]
async def execute_swarm(self, requirements):
current_state = requirements
for stage_name, agents in self.stages:
print(f"Stage: {stage_name}")
# 단계 내 Agent들은 병렬 실행
tasks = [
agent.execute(current_state)
for agent in agents
]
results = await asyncio.gather(*tasks)
# 결과 통합하여 다음 단계로
current_state = await self.merge_results(results)
# 검증
if not await self.validate_stage(stage_name, current_state):
raise StageValidationError(f"Stage {stage_name} failed")
return current_state
순차 실행 (단일 Agent):
Swarm (병렬 최적화):
원칙: System 파라미터로 역할 설정, 작업별 지침은 user turn에 배치
베스트 프랙티스: Role prompting은 Claude에서 system prompt를 사용하는 가장 강력한 방법입니다.
system_prompt = """You are an expert [ROLE] specializing in [DOMAIN].
Your expertise includes:
- [Expertise 1]
- [Expertise 2]
- [Expertise 3]
Your responsibilities:
- [Responsibility 1]
- [Responsibility 2]
You prioritize:
- [Priority 1]
- [Priority 2]
You follow these guidelines:
- [Guideline 1]
- [Guideline 2]
"""
# 실제 예시
backend_expert_prompt = """You are an expert Python backend developer specializing in
microservices architecture and API design.
Your expertise includes:
- FastAPI and async Python
- PostgreSQL and SQLAlchemy
- REST and GraphQL API design
- Microservices patterns
- Docker and Kubernetes
Your responsibilities:
- Write clean, testable, maintainable code
- Design scalable API endpoints
- Implement proper error handling
- Ensure security best practices
- Optimize database queries
You prioritize:
- Type hints and proper documentation
- Comprehensive error handling
- Performance optimization
- Security (OWASP Top 10)
- Test coverage (minimum 80%)
You follow these guidelines:
- PEP 8 style guide
- SOLID principles
- 12-factor app methodology
- Always validate user input
- Never log sensitive data
"""
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
system=backend_expert_prompt,
messages=[{
"role": "user",
"content": "Implement a user authentication endpoint..."
}]
)
실전 역할 정의: 7가지 핵심 Agent 역할(Architect, Developer, Reviewer, Tester, DevOps, Researcher, Coordinator)의 System Prompt 템플릿은 Agent Team Building 가이드의 Section 2를 참고하세요.
from claude_sdk import Agent
agent = Agent(
system_prompt_preset="claude_code",
additional_instructions="""
Additional project-specific instructions:
- Follow our coding standards in docs/STANDARDS.md
- Use our custom error handling in lib/errors.py
- All API changes require updating OpenAPI spec
- Commit messages must follow Conventional Commits
"""
)
agent = Agent(
system_prompt="""
You are a specialized code refactoring agent.
Your mission:
- Improve code quality without changing behavior
- Extract reusable components
- Reduce code duplication
- Improve naming and structure
Your constraints:
- Never change public APIs
- All tests must still pass
- No new dependencies without approval
- Preserve code comments
Your workflow:
1. Analyze code structure
2. Identify improvement opportunities
3. Propose changes with rationale
4. Implement approved changes
5. Verify tests still pass
"""
)
개념: 프로젝트별 컨텍스트와 지침을 제공하는 지속적 "메모리"
자동 로드: CLAUDE.md는 Agent SDK가 디렉토리에서 실행될 때 자동으로 읽힙니다.
# Project Context
## Overview
FastAPI-based microservices platform for e-commerce.
## Architecture
- **Backend**: FastAPI + PostgreSQL
- **Frontend**: React + TypeScript
- **Caching**: Redis
- **Queue**: RabbitMQ
- **Deployment**: Docker + Kubernetes
## Directory Structure
src/
├── api/ # API endpoints
├── models/ # SQLAlchemy models
├── services/ # Business logic
├── schemas/ # Pydantic schemas
└── utils/ # Utilities
tests/
├── unit/ # Unit tests
├── integration/ # Integration tests
└── e2e/ # End-to-end tests
## Coding Standards
### Python
- Use type hints everywhere
- Prefer async/await over sync
- Max line length: 88 (Black formatter)
- Use Pydantic for data validation
- Never use `any` type
### API Design
- RESTful principles
- Versioning: /api/v1/...
- Always return proper status codes
- Include request ID in responses
- Pagination for list endpoints
### Error Handling
```python
# ✅ Good
from lib.errors import APIError, NotFoundError
@router.get("/users/{user_id}")
async def get_user(user_id: int):
user = await db.get_user(user_id)
if not user:
raise NotFoundError(f"User {user_id} not found")
return user
# ❌ Bad
@router.get("/users/{user_id}")
async def get_user(user_id: int):
return await db.get_user(user_id) # No error handling
feature/descriptionpytestpytest --covblack . && isort .flake8 && mypy .# Always use dependency injection
from dependencies import get_db
@router.get("/items")
async def list_items(db: Session = Depends(get_db)):
return await db.query(Item).all()
# Use Redis for caching
from lib.cache import cache
@cache(ttl=300) # 5 minutes
async def get_user_profile(user_id: int):
return await db.get_user(user_id)
lib/errors.py - Custom exception classeslib/auth.py - Authentication utilitiesdependencies.py - FastAPI dependenciesconfig.py - Configuration managementprint() for logging (use logger)except Exception)
### Subagent System Prompts
**개념:** 각 Subagent는 독립적인 컨텍스트 윈도우와 커스텀 system prompt 보유
```python
# 코드 리뷰 전문가
code_reviewer = Subagent(
name="code-reviewer",
system_prompt="""You are a senior code reviewer focusing on:
**Security:**
- OWASP Top 10 vulnerabilities
- Input validation
- Authentication/authorization
- Data exposure
**Performance:**
- Algorithm complexity
- Database query optimization
- Caching opportunities
- Memory leaks
**Maintainability:**
- Code clarity and readability
- Proper abstraction
- Documentation
- Test coverage
**Best Practices:**
- SOLID principles
- Design patterns
- Error handling
- Logging
Provide constructive, actionable feedback with:
- Severity (CRITICAL/HIGH/MEDIUM/LOW)
- Clear explanation
- Code example of fix
- Impact assessment
""",
tools=["read_file", "search_code", "analyze_dependencies"]
)
# 테스트 작성 전문가
test_writer = Subagent(
name="test-writer",
system_prompt="""You are a test automation specialist.
Write comprehensive tests covering:
**Happy Path:**
- Normal operation scenarios
- Expected inputs and outputs
**Edge Cases:**
- Boundary values
- Empty/null inputs
- Maximum sizes
**Error Conditions:**
- Invalid inputs
- Network failures
- Database errors
**Integration:**
- External service interactions
- Database transactions
- API contracts
Follow TDD principles:
1. Write test first
2. Run test (should fail)
3. Implement minimum code to pass
4. Refactor
5. Repeat
Test quality:
- Clear test names (test_should_reject_invalid_email)
- Arrange-Act-Assert structure
- One assertion per test
- Use fixtures for test data
- Mock external dependencies
""",
tools=["read_file", "write_file", "run_tests"]
)
Multi-Agent 시스템을 이해했다면: