AI 에이전트를 위한 API 설계 재고: Data Plumbing에서 지능형 인터페이스로
Source: Dev.to
문제: 인간을 위해 만든 API, 사고하는 기계를 위한 것이 아님
당신의 API는 다른 시대를 위해 설계되었습니다. 다음과 같은 경우를 위해 만들어졌죠:
if문을 작성하는 개발자- 데이터를 가져오는 React 컴포넌트
- 레코드를 표시하는 대시보드
오늘날 자율 AI 에이전트는 단순히 데이터를 가져오는 것이 아니라 이해하고, 추론하고, 결정을 내려야 합니다. 원시 데이터베이스 레코드와 HTTP 상태 코드를 제공하면 에이전트가 API가 이미 수행했어야 할 작업을 스스로 해야 합니다.
가혹한 진실: API가 단순히 데이터를 노출할 뿐이라면, 지능에게 잡음만을 공급하는 겁니다.
전통적인 API 설계에서 에이전트용 API 설계로의 전환은 더 많은 엔드포인트를 추가하는 것이 아니라, API가 제공해야 할 내용을 근본적으로 재고하는 것입니다.
전통적인 API vs. 에이전트‑준비 API
| 전통적인 API | 에이전트‑준비 API |
|---|---|
| 원시 레코드 반환 | 해석된 인사이트 반환 |
| CRUD 작업 노출 | 비즈니스 기능 노출 |
| “데이터 여기 있어요” | “이게 무슨 의미인지 여기 있어요” |
| 세분화된 호출 (작업당 20+ 호출) | 목표 지향적 (작업당 2‑3 호출) |
| 개발자 친화적 | 추론 친화적 |
예시: 유지보수 기록
전통적인 API 응답
{
"equipment_id": "CNC-001",
"last_maintenance": "2024-11-01",
"maintenance_interval_days": 30,
"maintenance_type": "preventive"
}
에이전트는 이제 다음을 수행해야 합니다:
- 연체 여부 계산 (날짜 연산)
- 위험 수준 평가 (비즈니스 로직)
- 우선순위 결정 (도메인 지식)
- 권고안 생성 (추론)
에이전트‑준비 API 응답
{
"equipment_id": "CNC-001",
"last_maintenance": "2024-11-01",
"maintenance_interval_days": 30,
"maintenance_type": "preventive",
// 🔥 Semantic enrichment
"status": "overdue",
"overdue_by_days": 8,
"risk_level": "high",
"priority": 1,
"next_due_date": "2024-12-01",
"recommendation": "Schedule immediately - approaching critical threshold",
"impact_if_delayed": "Estimated 4‑hour production loss, $12,000 cost"
}
이제 에이전트는 계산을 수행하지 않고 바로 행동할 수 있습니다.
나쁜 설계 vs. 좋은 설계
❌ 나쁨: 파편화된 마이크로서비스
GET /users/{id}
GET /accounts/{id}
GET /transactions/{id}
GET /credit_scores/{id}
GET /eligibility_rules
에이전트가 이 모든 것을 조율해야 함.
✅ 좋음: 의도 기반 API
GET /customer_loan_eligibility/{id}
응답
{
"eligible": true,
"confidence": 0.94,
"pre_approved_amount": 50000,
"rationale": "Strong credit history, stable income, low debt ratio",
"next_steps": ["Submit income verification", "Review terms"]
}
한 번의 호출로 다섯 개를 대체하고, 흩어진 로직 대신 명확한 의도를 제공합니다.
상황에 맞는 의미 제공
상황 없이
{
"risk_score": 67,
"incidents_last_90_days": 3
}
에이전트가 답해야 할 질문:
- 67은 높나요 낮나요?
- 3건의 사고가 우려되는가?
- 다음에 무엇을 해야 할까?
상황 포함
{
"risk_score": 67,
"risk_category": "moderate",
"percentile": "82nd", // 동료 82 %보다 나쁨
"incidents_last_90_days": 3,
"trend": "increasing", // 월 1건 → 주 1건
"comparison": "2x industry average",
"interpretation": "Risk level elevated due to incident frequency increase",
"suggested_actions": [
"Implement additional safety protocols",
"Schedule equipment inspection",
"Review operator training records"
]
}
이제 에이전트는 숫자가 의미하는 바와 왜 중요한지를 이해합니다.
일관성 있는 추론을 위한 신뢰성
❌ 일관성 없음 (에이전트 악몽)
- Endpoint A returns
{"created_at": "2024-11-01"} - Endpoint B returns
{"createdDate": "2024-11-01T00:00:00Z"} - Endpoint C returns
{"timestamp": 1698796800}
✅ 일관성 있음 (에이전트 친화)
- 모든 타임스탬프: ISO 8601 형식
- 모든 ID: UUID v4
- 모든 통화: ISO 4217 코드
- 모든 상태 필드: Enum(정의된 값)
에이전트가 계약을 신뢰할 수 있을 때, 대규모로 추론할 수 있습니다.
마이크로서비스 vs. 에이전트‑준비 아키텍처
전통적인 마이크로서비스 흐름 (8 API 호출)
GET /customer/{id}/profileGET /customer/{id}/membership_statusGET /customer/{id}/order_historyGET /orders/{order_id}/itemsGET /inventory/availabilityGET /shipping/zones/{zip}GET /shipping/rates- 에이전트가 복잡한 오케스트레이션 수행
문제점
- 8번의 네트워크 왕복 → 지연
- 8개의 잠재적 장애 지점 → 신뢰성 위험
- 비즈니스 로직이 에이전트 코드에 중복 → 유지보수 어려움
- 에이전트가 전체 서비스 토폴로지를 알아야 함 → 결합도 상승
에이전트‑준비 아키텍처 (1 API 호출)
GET /shipping/eligibility/{order_id}
응답
{
"expedited_eligible": true,
"confidence": 0.97,
"reason": "Premium member + in‑stock inventory + metro area",
"estimated_delivery": "2024-12-11",
"cost": 12.99,
"alternatives": [
{
"type": "standard",
"estimated_delivery": "2024-12-14",
"cost": 5.99
}
]
}
마이크로서비스는 내부 확장성을 위해 여전히 유용하지만, 외부 API 레이어는 목표 지향 엔드포인트 뒤에 복잡성을 숨겨야 합니다.
API를 에이전트‑준비로 전환하기
옵션 1 – 의미 강화 (결정론적 로직)
def enrich_maintenance_record(record):
# Calculate semantic fields
days_overdue = (today - record['last_done']).days - record['interval']
# Apply business rules
if days_overdue > 14:
risk = "critical"
priority = 1
recommendation = "URGENT: Schedule immediately"
elif days_overdue > 7:
risk = "high"
priority = 2
recommendation = "Schedule within 48 hours"
elif days_overdue > 0:
risk = "moderate"
priority = 3
recommendation = "Schedule this week"
else:
risk = "low"
priority = 4
recommendation = f"Due in {abs(days_overdue)} days"
return {
**record,
"status": "overdue" if days_overdue > 0 else "current",
"days_overdue": max(0, days_overdue),
"risk_level": risk,
"priority": priority,
"recommendation": recommendation
}
장점
- ⚡ 빠름 (50‑100 ms)
- 💰 비용 없음 (LLM 비용 없음)
- 🎯 신뢰성 (결정론적 출력)
- 🔍 디버깅 용이 (추적 쉬움)
적합한 경우
- 상태 계산
- 위험 평가
- 우선순위 점수화
- 날짜/시간 연산
- 집계 및 요약
- 규칙 기반 권고
옵션 2 – LLM과 혼합 (선택적 사용)
async def create_maintenance_plan_with_insights(equipment_id):
# ✅ Deterministic: Get and calculate data
equipment = get_equipment_details(equipment_id)
history = get_maintenance_history(equipment_id)
suggested_interval = calculate_optimal_interval(history)
base_instructions = get_template_instructions(equipment['type'])
# 🤖 LLM: Generate contextual insights
if len(history) > 5: # Only if we have data to learn from
context = {
"equipment_type": equipment['type'],
"recent_failures": history[-5:],
"pattern": analyze_failure_pattern(history)
}
insights = await generate_llm_insights(context)
else:
insights = None
return {
"suggested_interval": suggested_interval, # ✅ Calculated
"work_instructions": base_instructions, # ✅ Template
"contextual_recommendations": insights # 🤖 LLM‑generated
}
LLM 활용 사례 (전체의 20 %)
- 이력 패턴 기반 상황별 권고
- 복잡한 시나리오에 대한 자연어 설명
- 유사 사례 학습
- 사용자 행동에 따른 적응형 제안
성능·비용·신뢰성 비교
| 접근 방식 | 지연 시간 (호출당) | 비용 / 1000 호출 | 신뢰성 |
|---|---|---|---|
| 순수 로직 | 50‑100 ms | $0 | 99.9 % |
| 혼합 | 200‑500 ms | $1‑10 | 95 %+ |
| 전체 LLM | 1‑3 s | $50‑200 | 90 % |
추천: 먼저 순수 결정론적 로직으로 시작하고, 결정론적 규칙으로는 포착하기 어려운 뉘앙스가 있을 때만 선택적으로 LLM 호출을 추가하세요.
에이전트 AI를 위한 API 생태계 구조화
┌───────────────────────────────────────┐
│ AI AGENT LAYER │
│ (ChatGPT, Claude, Custom Agents) │
└───────────────────────────────────────┘
│
▼
┌───────────────────────────────────────┐
│ Agent‑Ready API GATEWAY │
│ – Goal‑oriented endpoints │
│ – Semantic enrichment │
│ – Consistent contracts │
└───────────────────────────────────────┘
│
▼
┌───────────────────────────────────────┐
│ Underlying Microservices │
│ – Scalable, independent services │
│ – Internal data stores │
└───────────────────────────────────────┘
에이전트 계층에 얇고 의도‑주도적인 인터페이스를 제공하면서 마이크로서비스 메시는 내부에 유지합니다. 이렇게 하면 에이전트가 효과적으로 추론하고 행동하는 데 필요한 맥락, 일관성, 신뢰성을 확보할 수 있습니다.