Skip to content

jesamkim/hyperagent

Repository files navigation

HyperAgent Banner

HyperAgent

Meta의 HyperAgents(arXiv:2603.19461) 메커니즘을 Amazon Bedrock에서 재현하는 자기참조적 자기개선 에이전트 시스템

AI 에이전트가 단순히 작업을 수행하는 것을 넘어, 자신의 개선 메커니즘(harness) 자체를 수정합니다. 에이전트를 Config(JSON)으로 직렬화하여, Meta Agent가 진화시키고, 진화된 Config으로 새 에이전트를 인스턴스화하는 루프를 구현합니다.


핵심 개념

에이전트를 자기개선하도록 놓아두면, 개발자가 수작업으로 만드는 것과 동일한 구성요소를 독립적으로 발명합니다:

구성요소 HyperAgent 구현
영속 메모리 AgentCore Memory
성능 추적 LLM-as-Judge (Opus 4.6)
다단계 평가 Staged Assessment Pipeline
도메인 지식 Tool Registry + Meta Rules
자기 교정 Safety Guard + Rollback

3단계 진화 루프

Evolution Loop
Phase 수정 대상 전환 조건
Phase 1: Prompt system prompt만 기본
Phase 2: Tool + tool 추가/수정/삭제 avg score > 0.7 (5세대 연속)
Phase 3: Self-Ref + meta_rules (자기 개선 전략) avg score > 0.8 (5세대 연속)

아키텍처

Architecture

핵심 흐름

Orchestrator ──dispatch──> Task Agent (Sonnet 4.6)
      ^                          |
      |                     execute in AgentCore Runtime
  new config                     |
      |                       result
Meta Agent (Opus) <──trigger── Judge Agent (Opus 4.6)
      |                          |
      v                       score
AgentCore Memory <──store──  Evolution Engine

프레임워크 역할 분담

역할 프레임워크 모델
Orchestrator Strands Agent SDK -
Meta Agent Strands Agent SDK Opus 4.6
Task Agent Claude Agent SDK Sonnet 4.6
Judge Agent LLM-as-Judge Opus 4.6
Runtime Bedrock AgentCore Runtime -
Memory Bedrock AgentCore Memory -

빠른 시작

설치

git clone https://github.com/jesamkim/hyperagent.git
cd hyperagent

python3.12 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"

CLI 실행

# 시스템 정보 확인
python -m hyperagent info

# 단일 태스크 실행
python -m hyperagent run "Explain quantum computing in simple terms"

# 진화 사이클 실행 (5회)
python -m hyperagent evolve --cycles 5

대시보드 실행

# FastAPI 백엔드 (데모 데이터 포함)
pip install fastapi uvicorn
uvicorn hyperagent.api.server:app --port 8000 --app-dir src &

# React 대시보드
cd dashboard && npm install && npm run dev
Dashboard

Docker

docker compose up
# app: http://localhost:8000 (API + React)
# agentcore: http://localhost:8080

프로젝트 구조

hyperagent/
+-- src/hyperagent/
|   +-- config/
|   |   +-- agent_config.py      # AgentConfig (frozen dataclass, JSON serialization)
|   |   +-- settings.py          # Settings (YAML loader)
|   +-- core/
|   |   +-- orchestrator.py      # E2E: submit -> execute -> assess -> store
|   |   +-- evolution_engine.py  # 진화 루프, phase transition
|   |   +-- runtime_manager.py   # AgentCore Runtime 세션 관리
|   |   +-- llm_backend.py       # LLM Backend Protocol
|   |   +-- tool_registry.py     # Tool Registry + Validator
|   |   +-- safety.py            # SafetyGuard (mutation rate, rollback)
|   +-- agents/
|   |   +-- task_agent.py        # Task Agent (Claude Agent SDK)
|   |   +-- judge_agent.py       # Judge Agent (LLM-as-Judge)
|   |   +-- meta_agent.py        # Meta Agent (3-phase evolution)
|   +-- memory/
|   |   +-- memory_store.py      # AgentCore Memory wrapper
|   +-- assessment/
|   |   +-- scorer.py            # Rubric + Scoring logic
|   +-- api/
|       +-- server.py            # FastAPI REST API
+-- dashboard/                   # React + Vite + TypeScript + Tailwind
+-- configs/
|   +-- settings.yaml            # 시스템 설정
|   +-- default_agent.json       # 초기 AgentConfig (generation 0)
+-- tests/                       # 273 tests, 96%+ coverage
+-- docs/                        # 다이어그램, 설계 문서
+-- Dockerfile                   # Multi-stage build
+-- docker-compose.yml

설정

configs/settings.yaml:

region: us-west-2

models:
  meta_agent: global.anthropic.claude-opus-4-6-v1    # Meta Agent (분석/생성)
  task_agent: global.anthropic.claude-sonnet-4-6      # Task Agent (태스크 실행)
  judge_agent: global.anthropic.claude-opus-4-6-v1   # Judge Agent (평가)

evolution:
  variants_per_generation: 3     # 세대당 variant 수
  phase_1_to_2_threshold: 0.7   # Phase 1->2 전환 임계값
  phase_2_to_3_threshold: 0.8   # Phase 2->3 전환 임계값
  consecutive_generations_required: 5
  max_generations: 100
  max_mutation_rate: 0.3         # 안전 제한: 최대 변이율

assessment:
  default_rubric:
    accuracy: 0.3
    completeness: 0.3
    efficiency: 0.2
    creativity: 0.2

테스트

# 전체 테스트
pytest tests/ -v

# 커버리지
pytest tests/ --cov=hyperagent --cov-report=term-missing

# 린트
ruff check src/ tests/
항목 결과
Tests 273 passed
Coverage 96.55%
Lint All checks passed

Amazon Bedrock AgentCore 설정 (새 환경)

새로운 환경에서 실행하려면 아래 설정이 필요합니다.

1. AWS 자격 증명

# AWS CLI 설정
aws configure
# Region: us-west-2

# 또는 환경변수
export AWS_DEFAULT_REGION=us-west-2
export AWS_ACCESS_KEY_ID=your-key
export AWS_SECRET_ACCESS_KEY=your-secret

2. Bedrock 모델 액세스 활성화

AWS Console > Amazon Bedrock > Model access에서 다음 모델 활성화:

  • anthropic.claude-sonnet-4-6 (Task Agent)
  • anthropic.claude-opus-4-6 (Meta Agent, Judge Agent)

Cross-region inference 사용 시 global. prefix 모델 ID 사용:

# configs/settings.yaml
models:
  task_agent: global.anthropic.claude-sonnet-4-6
  judge_agent: global.anthropic.claude-opus-4-6-v1
  meta_agent: global.anthropic.claude-opus-4-6-v1

3. AgentCore Runtime 설정

# AgentCore starter toolkit 설치
pip install bedrock-agentcore-starter-toolkit

# IAM Role 생성 (AgentCore 실행용)
aws iam create-role \
  --role-name HyperAgentCoreRole \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": {"Service": "bedrock-agentcore.amazonaws.com"},
      "Action": "sts:AssumeRole"
    }]
  }'

# Bedrock InvokeModel 권한 추가
aws iam put-role-policy \
  --role-name HyperAgentCoreRole \
  --policy-name BedrockAccess \
  --policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
      "Resource": "arn:aws:bedrock:*::foundation-model/*"
    }]
  }'

4. AgentCore 배포

# 로컬 테스트
python agentcore_main.py &
curl http://localhost:8080/invocations -d '{"prompt": "Hello"}'

# 프로덕션 배포
agentcore configure -e agentcore_main.py -n hyperagent
agentcore deploy

사용 시나리오

Scenario 1: 단일 태스크 실행 -- "개선 전 baseline 성능 측정"

초기 AgentConfig(generation 0)로 태스크를 실행하여 baseline 점수를 측정합니다. 이 점수가 진화의 출발점이 되며, 이후 세대별로 얼마나 개선되는지 비교합니다.

$ python -m hyperagent run "Write a Python function to calculate fibonacci numbers"
Config: gen-0-default (Phase: PROMPT, Gen: 0)
Executing task...

Score: 0.720
  accuracy:     0.80   # 기능적으로 정확
  completeness: 0.75   # 기본 구현은 완성
  efficiency:   0.60   # naive recursion - 개선 여지
  creativity:   0.55   # 단순 접근
Feedback: The function is correct but uses naive recursion.
          Consider memoization for better efficiency.

결과 해석: 초기 prompt("You are a helpful assistant")로는 0.72점. Meta Agent가 이 피드백을 분석하여 "efficiency가 낮다" → "step-by-step 분석 후 최적화된 코드를 작성하라"는 개선된 prompt를 생성할 수 있습니다.

Scenario 2: 진화 사이클 -- "5세대 만에 15% 성능 향상"

Meta Agent가 성능 이력을 분석하고, 매 세대마다 3개의 variant prompt를 생성합니다. Judge(Opus)가 각 variant를 채점하고, 가장 높은 점수의 variant가 다음 세대의 부모가 됩니다.

$ python -m hyperagent evolve --cycles 5
=== Evolution Cycle 1/5 ===
Current: gen-0-default (score: 0.720, phase: PROMPT)
Meta Agent analyzing: "efficiency(0.60) is the weakest criterion"
Generating 3 variants...
  Variant 1: 0.745  "Think step-by-step before coding"
  Variant 2: 0.680  "Be concise" (too terse, completeness dropped)
  Variant 3: 0.760  "Analyze complexity, then implement optimal solution"
Best: Variant 3 wins (0.760 > 0.720)

=== Evolution Cycle 3/5 ===
Current: var-e4f5g6 (score: 0.792, phase: PROMPT)
Meta Agent analyzing: "accuracy(0.88) strong, creativity(0.65) still low"
  Variant 1: 0.805  "Consider multiple approaches before choosing"
  Variant 2: 0.798  Added edge case handling focus
  Variant 3: 0.810  "Explore creative alternatives, then pick optimal"
Best: Variant 3 wins (0.810 > 0.792)

=== Evolution Cycle 5/5 ===
Current: var-x9y8z7 (score: 0.830, phase: PROMPT)
Phase transition: 0.830 > 0.7 threshold (5/5 consecutive) -> TOOL

Summary:
  Generations: 0 -> 5
  Score: 0.720 -> 0.830 (+15.3%)
  Phase: PROMPT -> TOOL (now Meta Agent can modify tools!)

결과 해석: 인간 개입 없이 system prompt만 진화시켜 15% 성능 향상 달성. 핵심 발견은 "efficiency가 약하다"는 Judge 피드백을 Meta Agent가 자동으로 분석하여 "복잡도 분석 후 최적 구현" 전략을 스스로 발명한 점입니다. Phase 2로 전환되면 tool 추가/제거를 통한 추가 개선이 시작됩니다.

Scenario 3: 대시보드 -- "진화 과정을 실시간으로 관찰"

React 대시보드에서 에이전트 진화의 전체 과정을 시각적으로 모니터링합니다.

uvicorn hyperagent.api.server:app --port 8000 --app-dir src &
cd dashboard && npm run dev
Tab 확인할 수 있는 것 활용
Timeline 세대별 점수 추이 + Phase 전환 시점 진화가 수렴하는지 / 발산하는지 판단
Lineage Config 간 부모-자식 계보 어떤 variant가 선택되었고 왜 다른 건 탈락했는지 추적
Inspector prompt, tools, meta_rules 상세 세대별로 prompt가 어떻게 변화했는지 diff 비교
Assessments 기준별 점수 분해 accuracy는 높은데 efficiency가 낮은 패턴 발견

Scenario 4: Safety Guard -- "자기수정의 폭주 방지"

Phase 3(Self-Referential)에서 Meta Agent가 자기 자신의 개선 전략까지 수정할 때, SafetyGuard가 과도한 변이를 차단합니다. 이를 통해 안정적인 점진 개선을 보장합니다.

=== Evolution Cycle 12/20 (Phase: SELF_REF) ===
Meta Agent self-modifying: "Add rule: increase temperature when stuck"

  Variant 1: mutation rate 0.45 > 0.30 limit
    -> REJECTED by SafetyGuard (prompt 40% + tools 30% + meta 100% change)
  Variant 2: mutation rate 0.22 -> OK, score 0.840
  Variant 3: mutation rate 0.28 -> OK, score 0.862
Best: Variant 3 (0.862)

Rollback check: [0.845, 0.850, 0.862] -> improving, no rollback needed

결과 해석: Variant 1은 prompt, tools, meta_rules를 동시에 대폭 변경하려 했으나 SafetyGuard가 차단(mutation rate 0.45 > 0.30 제한). 이는 원본 HyperAgents 논문에서도 지적한 "catastrophic forgetting" 방지 메커니즘입니다. Variant 3처럼 적당한 변이율(0.28)로 점진적 개선이 안정적입니다.


실험 결과 (실제 Bedrock 호출)

Experiment Setup

항목
Task Agent Claude Sonnet 4.6 (global.anthropic.claude-sonnet-4-6)
Meta/Judge Agent Claude Opus 4.6 (global.anthropic.claude-opus-4-6-v1)
Region us-west-2
Rubric accuracy(0.3), completeness(0.3), efficiency(0.2), creativity(0.2)
Domain Python coding (palindrome, LRU cache, list flatten)

Baseline Score (Generation 0)

초기 prompt "You are a helpful assistant that writes Python code."로 실행:

Score: 0.965
  accuracy:     0.95
  completeness: 1.00
  efficiency:   1.00
  creativity:   0.90

Sonnet 4.6은 coding 태스크에서 이미 매우 높은 baseline을 보여줌 (ceiling effect).

Phase 1: Prompt Evolution (Opus Meta Agent)

Opus가 "efficiency가 약하다"는 Judge 피드백을 분석하고, 개선된 prompt variant를 자발적으로 생성:

Original: "You are a helpful assistant that writes Python code."
Variant 1: "You are an expert Python developer who writes high-quality,
            production-ready code. When solving problems:
            1. Accuracy first - handle all edge cases
            2. Efficiency - analyze complexity, optimize
            3. Completeness - include docstrings, type hints, examples..."
Score: 0.910 -> 0.940 (+3.3%)

Phase 2: Tool Evolution (Opus Meta Agent)

Opus가 기존 tool [code_analyzer]를 분석하고, 추가 tool을 자발적으로 제안:

Original tools: [code_analyzer]
Variant 1 tools: [code_analyzer, code_executor, calculator]
Variant 2 tools: [code_analyzer, code_executor, calculator, web_search]

Meta Agent가 "code_executor는 코드 정확성 검증에 필요하다"고 스스로 판단.

Phase 3: Self-Referential (핵심 발견)

이것이 HyperAgents 논문의 하이라이트입니다. Opus가 자기 자신의 개선 전략(meta_rules)을 자발적으로 작성했습니다:

Input meta_rules:
  "Focus on code correctness first. Evaluate edge cases carefully."

Opus가 생성한 Variant 1 meta_rules:
  "Focus prompt changes on the weakest scoring criterion (currently creativity
   at 0.72). Increase temperature slightly when creativity scores are below 0.80.
   Prioritize accuracy as a hard constraint (never let it drop below 0.85).
   When scores plateau across all dimensions, introduce new tools or restructure
   the system prompt significantly."

Opus가 생성한 Variant 2 meta_rules:
  "Target the weakest criterion aggressively: creativity is at 0.72 and needs
   to reach 0.85+. Use code_executor tool to ensure correctness doesn't regress
   when pushing for creative outputs. If all scores exceed 0.85, shift focus to
   achieving 0.90+ on accuracy and completeness. Consider raising temperature
   further (up to 0.9) only if creativity remains stubbornly below 0.80 after
   two improvement cycles."

Meta Agent가 인간 개발자가 작성할 법한 세밀한 개선 전략을 독립적으로 발명했습니다:

  • 약점 기준(creativity) 자동 식별 + 집중 공략
  • 안전 제약 자발적 설정 (accuracy > 0.85 hard constraint)
  • 조건부 전략 (plateau 시 tool 추가, temperature 조정)
  • 다단계 목표 (0.85 달성 후 0.90 목표 전환)

Math Domain: 12세대 진화 + Phase Transition 관찰

수학 증명/추론 태스크 (귀납법, 마방진, 피타고라스, 무리수 증명 등)로 12세대 실행:

Rubric: correctness(0.35), rigor(0.25), clarity(0.20), insight(0.20)
Initial prompt: "You are an assistant. Answer the math question."

Gen  0 [PROMPT] 0.960   Gen  4 [PROMPT] 0.973  PHASE TRANSITION!
Gen  1 [PROMPT] 0.838   Gen  5 [TOOL  ] 0.963
Gen  2 [PROMPT] 0.947   Gen  6 [TOOL  ] 0.982
Gen  3 [PROMPT] 1.000   Gen  7 [TOOL  ] 0.967
                         ...
                         Gen 10 [TOOL  ] 1.000
                         Gen 11 [TOOL  ] 0.967

Phase Transition: Gen 4에서 PROMPT -> TOOL 전환 발동 (5세대 연속 > 0.70 threshold)

관찰: Gen 1에서 0.838로 하락 후 진화를 통해 Gen 3에서 1.000으로 복구. Phase 2 진입 후 안정적으로 0.96+ 유지.

Honest Assessment: Ceiling Effect

도메인 Baseline 진화 후 Delta 원인
Coding 0.965 0.970 +0.5% Sonnet 4.6이 이미 우수
Math 0.960 0.967 +0.7% 동일

Sonnet 4.6은 coding과 math 모두에서 baseline이 이미 0.96 수준입니다. 이는 모델 자체의 능력이 높아서 prompt 진화의 정량적 delta가 작다는 것을 의미합니다.

하지만 정성적 발견은 유의미합니다:

  1. Phase 전환 메커니즘이 실제로 동작 - 연속 고점수 감지 후 자동 전환
  2. Opus가 meta_rules를 자발적으로 설계 - 약점 분석, 안전 제약, 조건부 전략
  3. 하락 후 복구 패턴 - Gen 1 하락(0.838) -> Gen 3 완전 복구(1.000)

더 드라마틱한 delta를 얻으려면: 약한 모델(Haiku 4.5) 사용, 또는 multi-modal/reasoning chain 같은 복합 태스크 도메인이 필요합니다.

핵심 발견 요약

발견 증거
Meta Agent가 개선 전략을 자발적으로 발명 Opus가 "creativity < 0.80이면 temperature 올리기" 등 세밀한 meta_rules 생성
Phase 전환이 자동으로 발동 Gen 4에서 PROMPT -> TOOL (5세대 연속 threshold 충족)
Tool 추가를 자발적으로 제안 [code_analyzer] -> [code_analyzer, code_executor, calculator, web_search]
하락 후 복구 능력 Gen 1(0.838) -> Gen 3(1.000) = 진화 엔진의 선택 압력이 작동

기술 스택

Layer Technology
Agent Framework Strands Agent SDK 1.35.0, Claude Agent SDK 0.1.58
LLM Claude Opus 4.6, Claude Sonnet 4.6 on Bedrock
Runtime Amazon Bedrock AgentCore Runtime
Memory Amazon Bedrock AgentCore Memory
Backend FastAPI, Python 3.12
Frontend React 19, TypeScript, Vite, Tailwind CSS, Recharts
Deploy Docker, ECS, AgentCore Runtime
Test pytest, ruff, 96%+ coverage

참고 자료


라이선스

MIT License - Copyright (c) 2026 Jesam Kim

자세한 내용은 LICENSE 파일을 참조하세요.

About

Self-referential self-improving agent system on Amazon Bedrock (Meta HyperAgents mechanism)

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors