반응형
에이전트를 Opus 4.7로 돌리면 비용이 예측 불가예요.
왜 예측이 안 되냐:
→ 에이전트 루프: 생각 + 툴 호출 + 툴 결과 + 출력이 쌓임
→ xhigh 기본값: 더 많이 생각함
→ 새 토크나이저: 같은 텍스트도 최대 35% 토큰 증가
→ 언제 끝날지 모름 = 비용도 모름
Opus 4.7은 이걸 잡는 두 가지 도구를 줬어요.
1. effort 파라미터: 추론 깊이 조절
2. Task Budget: 에이전트 루프 전체 토큰 예산 설정
하나씩 실제로 써볼게요.
effort 파라미터
5단계 레벨 이해
low → 빠르고 싸다. 복잡한 추론 없음
medium → 균형
high → 기본값 (API 기본값)
xhigh → high와 max 사이 (Claude Code 기본값)
max → 최대 품질, 최고 비용
비용 대비 성능 현실:
xhigh vs max 비교:
- 성능 차이: 약 3%p (agentic coding 기준)
- 비용 차이: max는 xhigh 대비 약 2배
→ max는 "정말 프론티어 문제"에만
low-effort Opus 4.7 ≈ medium-effort Opus 4.6
→ 4.6에서 high 쓰던 작업 → 4.7에서 xhigh 시작
실전 코드
import anthropic
client = anthropic.Anthropic()
# 기본: API 기본값 high
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=64000,
thinking={"type": "adaptive"},
messages=[{"role": "user", "content": "복잡한 분석 작업"}]
)
# xhigh: 에이전트 코딩, 복잡한 멀티스텝
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=64000,
output_config={"effort": "xhigh"},
thinking={"type": "adaptive"},
messages=[{"role": "user", "content": "레포지토리 분석하고 버그 찾아줘"}]
)
# high: 일반 고품질 작업
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=32000,
output_config={"effort": "high"},
messages=[{"role": "user", "content": "이 코드 설명해줘"}]
)
# medium: 분류, 요약, 간단한 추출
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=4000,
output_config={"effort": "medium"},
messages=[{"role": "user", "content": "이 텍스트 감정 분류해줘"}]
)
작업별 권장 레벨
EFFORT_BY_TASK = {
# xhigh 써야 할 때
"agent_coding": "xhigh", # 에이전트 자율 코딩
"multi_step_debug": "xhigh", # 복잡한 디버깅
"architecture_review": "xhigh", # 아키텍처 분석
"long_horizon_task": "xhigh", # 장기 실행 작업
# high로 충분한 것들
"code_review": "high",
"complex_qa": "high",
"financial_analysis": "high",
"document_creation": "high",
# medium으로 충분한 것들
"simple_qa": "medium",
"summarization": "medium",
"translation": "medium",
# low로 충분한 것들
"classification": "low",
"routing": "low",
"extraction": "low",
"format_conversion": "low",
}
def get_effort(task_type: str) -> str:
return EFFORT_BY_TASK.get(task_type, "high")
effort 조정으로 실제 절감 효과
같은 작업, effort만 바꿨을 때:
xhigh → high:
토큰 사용량 약 30~40% 감소
대부분 작업에서 품질 차이 미미
high → medium:
토큰 사용량 약 50% 감소
단순 작업이라면 품질 차이 없음
→ 에이전트 루프 중 단순한 툴 결과 처리는
medium으로 낮추는 것만으로도 큰 절감
Task Budget — 에이전트 루프 비용 상한선
에이전트 루프 전체에 토큰 예산을 주는 기능이에요.
작동 원리:
1. 개발자가 "전체 50,000 토큰 써"라고 설정
2. 모델이 작업하면서 남은 예산 실시간 확인
3. 예산 소진되면 → 우선순위 높은 것만 마무리
4. 예산 내에서 작업 완료
기본 사용법
import anthropic
client = anthropic.Anthropic()
response = client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=128000,
output_config={
"effort": "xhigh",
"task_budget": {
"type": "tokens",
"total": 50000 # 최소 20,000 토큰
}
},
thinking={"type": "adaptive"},
messages=[{
"role": "user",
"content": "이 레포지토리에서 보안 취약점 찾아줘"
}],
betas=["task-budgets-2026-03-13"] # 베타 헤더 필수
)
작업 유형별 Task Budget 권장값
TASK_BUDGETS = {
# 가벼운 작업
"quick_review": 20_000, # 최소값
"simple_fix": 30_000,
# 일반 작업
"code_review": 50_000,
"feature_impl": 80_000,
"bug_investigation": 60_000,
# 무거운 작업
"refactoring": 120_000,
"security_audit": 100_000,
"architecture_design": 150_000,
# 최대 작업 (신중하게)
"full_codebase_analysis": 200_000,
}
def create_agent_task(task_type: str, prompt: str):
budget = TASK_BUDGETS.get(task_type, 50_000)
return client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=128000,
output_config={
"effort": "xhigh" if budget > 80_000 else "high",
"task_budget": {"type": "tokens", "total": budget}
},
thinking={"type": "adaptive"},
messages=[{"role": "user", "content": prompt}],
betas=["task-budgets-2026-03-13"]
)
Task Budget 주의사항
# ❌ 너무 낮은 예산
response = client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=128000,
output_config={
"effort": "xhigh",
"task_budget": {"type": "tokens", "total": 5000} # 최소 20,000 미만
},
# → 에러 또는 작업 거부
)
# ✅ 적절한 예산 + 안전장치
response = client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=128000,
output_config={
"effort": "high",
"task_budget": {"type": "tokens", "total": 50_000}
},
thinking={"type": "adaptive"},
system="""
주어진 작업을 효율적으로 완료하세요.
토큰 예산이 제한되어 있으니 핵심 작업에 집중하세요.
완료 불가능한 부분은 명시적으로 알려주세요.
""",
messages=[{"role": "user", "content": "코드 리뷰해줘"}],
betas=["task-budgets-2026-03-13"]
)
effort + Task Budget 함께 쓰는 실전 패턴
패턴 1 — 동적 effort 라우팅
from anthropic import Anthropic
client = Anthropic()
def smart_agent_call(
prompt: str,
task_complexity: str = "medium"
) -> dict:
"""
복잡도에 따라 effort와 Task Budget 자동 설정
"""
configs = {
"low": {
"effort": "medium",
"budget": 20_000,
"max_tokens": 8000
},
"medium": {
"effort": "high",
"budget": 50_000,
"max_tokens": 32000
},
"high": {
"effort": "xhigh",
"budget": 100_000,
"max_tokens": 64000
},
"critical": {
"effort": "max",
"budget": 200_000,
"max_tokens": 128000
}
}
cfg = configs[task_complexity]
response = client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=cfg["max_tokens"],
output_config={
"effort": cfg["effort"],
"task_budget": {
"type": "tokens",
"total": cfg["budget"]
}
},
thinking={"type": "adaptive"},
messages=[{"role": "user", "content": prompt}],
betas=["task-budgets-2026-03-13"]
)
# 실제 사용 토큰 추적
usage = response.usage
estimated_cost = (
usage.input_tokens / 1_000_000 * 5 +
usage.output_tokens / 1_000_000 * 25
)
return {
"content": response.content[0].text,
"tokens_used": usage.input_tokens + usage.output_tokens,
"budget_set": cfg["budget"],
"cost_usd": estimated_cost,
"budget_utilization": f"{(usage.input_tokens + usage.output_tokens) / cfg['budget'] * 100:.1f}%"
}
# 사용 예
result = smart_agent_call(
prompt="이 PR에서 버그 찾아줘",
task_complexity="medium"
)
print(f"비용: ${result['cost_usd']:.4f}")
print(f"예산 사용률: {result['budget_utilization']}")
패턴 2 — 비용 모니터링 래퍼
import time
from dataclasses import dataclass
from collections import defaultdict
@dataclass
class AgentCallMetrics:
task_id: str
effort: str
budget: int
tokens_used: int
cost_usd: float
duration_sec: float
budget_exceeded: bool
class CostAwareAgent:
def __init__(self, daily_budget_usd: float = 10.0):
self.daily_budget = daily_budget_usd
self.today_spend = 0.0
self.call_history = []
def run(
self,
prompt: str,
effort: str = "high",
task_budget: int = 50_000
) -> str:
# 일일 예산 초과 체크
if self.today_spend >= self.daily_budget:
raise Exception(
f"일일 예산 ${self.daily_budget} 초과. "
f"오늘 지출: ${self.today_spend:.2f}"
)
start = time.time()
response = client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=128000,
output_config={
"effort": effort,
"task_budget": {"type": "tokens", "total": task_budget}
},
thinking={"type": "adaptive"},
messages=[{"role": "user", "content": prompt}],
betas=["task-budgets-2026-03-13"]
)
duration = time.time() - start
usage = response.usage
cost = (
usage.input_tokens / 1_000_000 * 5 +
usage.output_tokens / 1_000_000 * 25
)
self.today_spend += cost
# 예산 대비 실제 사용량 확인
actual_tokens = usage.input_tokens + usage.output_tokens
budget_exceeded = actual_tokens > task_budget
metrics = AgentCallMetrics(
task_id=f"task_{len(self.call_history)}",
effort=effort,
budget=task_budget,
tokens_used=actual_tokens,
cost_usd=cost,
duration_sec=duration,
budget_exceeded=budget_exceeded
)
self.call_history.append(metrics)
if budget_exceeded:
print(f"⚠️ 예산 초과: 설정 {task_budget:,} → 실제 {actual_tokens:,} 토큰")
print(f"✅ 완료: ${cost:.4f} | {actual_tokens:,} 토큰 | {duration:.1f}초")
return response.content[0].text
def report(self):
total_cost = sum(m.cost_usd for m in self.call_history)
total_tokens = sum(m.tokens_used for m in self.call_history)
overruns = sum(1 for m in self.call_history if m.budget_exceeded)
print(f"""
=== 비용 리포트 ===
총 호출: {len(self.call_history)}회
총 비용: ${total_cost:.4f}
총 토큰: {total_tokens:,}
예산 초과: {overruns}회
일일 예산 잔액: ${self.daily_budget - self.today_spend:.4f}
""")
# 사용
agent = CostAwareAgent(daily_budget_usd=5.0)
agent.run(
"이 함수 리팩토링해줘",
effort="high",
task_budget=30_000
)
agent.run(
"전체 레포 보안 감사해줘",
effort="xhigh",
task_budget=100_000
)
agent.report()
Claude Code에서 Task Budget 쓰기
API 말고 Claude Code 터미널에서도 설정 가능해요.
# 세션 전체 Task Budget 설정
> /config task_budget 50000
Task budget set to 50,000 tokens for this session.
Claude will pause and ask for confirmation before exceeding this limit.
# effort 레벨 변경
> /effort high
Effort set to high for this session.
# 현재 설정 확인
> /config show
Model: claude-opus-4-7
Effort: high
Task Budget: 50,000 tokens
Auto Mode: off
정리 — 상황별 세팅 치트시트
코딩 에이전트 (일반):
effort: xhigh | budget: 80,000
코딩 에이전트 (간단한 버그픽스):
effort: high | budget: 30,000
보안 감사:
effort: xhigh | budget: 100,000
PR 코드리뷰:
effort: high | budget: 50,000
단순 분류/추출:
effort: medium | budget: 20,000 (최소값)
RAG 응답 생성:
effort: medium | budget: 20,000
데이터 분석 (복잡):
effort: high | budget: 60,000
반응형
'LLM' 카테고리의 다른 글
| Gemma 4 파인튜닝 Unsloth로 30분에 끝내기 — API 비용 0원, 도메인 특화 모델 (0) | 2026.04.21 |
|---|---|
| LLM 사설 평가셋 50개 만들고 모델 비교하기 — 벤치마크를 믿지 마세요 (1) | 2026.04.20 |
| Claude Opus 4.7 토크나이저 함정 — 같은 가격, 더 많은 비용 (0) | 2026.04.20 |
| Claude Opus 4.7 출시 — SWE-bench Pro 1위, GPT-5.4 완전히 제쳤다 (1) | 2026.04.17 |
| GLM-5.1 vs Claude Opus 4.6 vs GPT-5.4 (0) | 2026.04.16 |