본문으로 건너뛰기

ApiUsageAnalytics

API 사용량 분석 — LiteLLM SpendLog 동기화 + composite 실제 비용 병합 + 운영 대시보드 집계

상태

항목
Layercomposite
TierBusiness
Statusreleased
Version1.0.0
가격Free (subscription)
**카�
�고리**AI / LLM

개요

개요

ApiUsageAnalytics 는 multi-saas-kit 의 Layer 2 Composite Plugin (Business tier) � 니다. AiRelay 또는 프로젝트 고유 API 호출 로그 위에 실제 비용 동기화 레이어를 얹어, estimated 비용을 LiteLLM SpendLog 의 actual 비용으로 갱신합니다.

고객사 과금, rate card, 내부 안전마진, 역마진 보정은 ApiBilling plugin � 임� 니다. 이 Plugin 은 저장된 usage/cost 로그의 집계와 actual cost 동기화를 담당합니다.

핵심 컴포넌트

CostBreakdownMerger (Pure)

apis.how LiteLLMActualCostSynchronizer::applySpendLog 의 비용 병합 로직 추출.

Composite 비용 공식:

actual_cost = estimated_stt_cost + estimated_tts_cost + actual_llm_cost
| (사전 계산값) (사전 계산값) (LiteLLM SpendLog 의 spend)

Breakdown 7개 필드 추가:

  • actual_llm_cost — SpendLog 의 spend 값
  • actual_llm_request_id — SpendLog 의 request_id (없으면 기존 litellm_call_id 폴백)
  • actual_llm_providercustom_llm_provider
  • actual_llm_modelmodel
  • actual_prompt_tokens / actual_completion_tokens — 실제 토큰 수
  • actual_cost_coverage'llm_actual_tts_stt_estimated' 라벨

기존 field 보존extra_field 등은 그대로 유지.

LiteLLMSpendLogClient

/spend/logs/v2?request_id=... 호출. apis.how LiteLLMActualCostSynchronizer::fetchSpendLog 추출.

  • Authorization: Bearer {admin_key} + x-litellm-api-key 동시 헤더
  • 4xx/5xx → null, 빈 data → null, 네트워크 예외 → null (caller 가 카운트 집계)
  • isConfigured() 헬퍼 — admin key 미설정 시 sync 자체 skip
  • 트레일링 슬래시 base_url 자동 정규화

UsageSummaryAggregator (Pure)

운영 대시보드, quota 알림, 리포트가 공통으로 사용할 수 있는 read-model 집계기. 프로젝트별 ApiUsageLog Eloquent 모델에 의존하지 않고 array/object iterable 을 � 력받습니다.

  • estimated_cost, actual_cost, effective_cost 합계
  • actualized_requests, estimated_only_requests, missing_request_id_requests 집계
  • provider/model/service/status 별 그룹 집계
  • actual 비용이 있으면 effective 비용으로 actual 을 우선 사용, 없으면 estimated 사용

설정 (config/api-usage-analytics.php)

return [
'enabled' => env('PLG_API_USAGE_ANALYTICS_ENABLED', true),
'litellm_admin' => [
'base_url' => env('LITELLM_ADMIN_API_BASE', 'https://llm.apis.how'),
'api_key' => env('LITELLM_ADMIN_API_KEY'), // ⚠️ admin/master key
'spend_log_path' => '/spend/logs/v2',
'timeout_seconds' => 30,
],
'cost_merging' => [
'currency' => 'USD',
'composite_source' => 'speech_composite_mixed_litellm_spend_log',
'coverage_label' => 'llm_actual_tts_stt_estimated',
],
'sync' => [
'default_limit' => 100,
'services' => ['speech'],
],
];

사용 예시

use App\Plugins\ApiUsageAnalytics\Services\{CostBreakdownMerger, LiteLLMSpendLogClient};

$merger = CostBreakdownMerger::fromConfig(config('api-usage-analytics'));
$client = LiteLLMSpendLogClient::fromConfig(config('api-usage-analytics'));

if (! $client->isConfigured()) {
return ['skipped' => true, 'reason' => 'litellm_admin_not_configured'];
}

// pending logs 동기화
foreach ($pendingLogs as $log) {
$requestId = $merger->extractRequestId($log->cost_breakdown);
if (! $requestId) continue;

$payload = $client->fetch($requestId);
if (! $payload) continue;

$merged = $merger->merge($log->cost_breakdown, $payload);
$log->forceFill([
'actual_cost' => $merged['actual_cost'],
'actual_cost_source' => $merged['actual_cost_source'],
'cost_currency' => $merged['cost_currency'],
'cost_breakdown' => $merged['cost_breakdown'],
'provider' => $merged['provider'] ?? $log->provider,
'model' => $merged['model'] ?? $log->model,
'input_tokens' => $merged['input_tokens'] ?? $log->input_tokens,
'output_tokens' => $merged['output_tokens'] ?? $log->output_tokens,
])->save();
}

출처

apis.how App\Services\ApiUsage\LiteLLMActualCostSynchronizer (119줄) 추출. ApiUsageLog Eloquent 의존 + 페이지네이� � 흐름은 프로젝트 � 임으로 분리, Pure 비용 병합 + HTTP fetch 만 plugin.

의존성

  • AiRelay — LLM 호출 시 relay_meta 의 정보가 SpendLog 와 결합
  • ApiBilling plugin — 고객사 과금, rate card, 안전마진, 정산 보정 소유

다음 단계 (Phase 3+)

  • 표준 Sync Artisan Command (cron 등록 가능)
  • OpenAI-compatible/LiteLLM-compatible SpendLog 어댑터 추가
  • Chorus 비용은 AgentCliBridge/ChorusBridge 가 usage event 를 제공하면 AiTracking/ApiUsageAnalytics 에서 소비
  • Filament Dashboard Page (UsageSummaryAggregator 결과 렌더링)
  • Tenant/User 별 사용량 quota 알림
  • AiTracking 통합 (호출 → SpendLog → audit 트레이스)

라이선스

MIT

의존성

데모


🛒 Plugin Store에서 보기: store.codebase.how/plugins/api-usage-analytics