feat:AI 토큰 사용량 추적 기능 추가
- ai_token_usages 테이블 마이그레이션 생성 - AiTokenUsage 모델 생성 - AiReportService에 usageMetadata 추출 및 저장 로직 추가 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
37
app/Models/Tenants/AiTokenUsage.php
Normal file
37
app/Models/Tenants/AiTokenUsage.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Tenants;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class AiTokenUsage extends Model
|
||||
{
|
||||
protected $table = 'ai_token_usages';
|
||||
|
||||
protected $fillable = [
|
||||
'tenant_id',
|
||||
'model',
|
||||
'menu_name',
|
||||
'prompt_tokens',
|
||||
'completion_tokens',
|
||||
'total_tokens',
|
||||
'cost_usd',
|
||||
'cost_krw',
|
||||
'request_id',
|
||||
'created_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'prompt_tokens' => 'integer',
|
||||
'completion_tokens' => 'integer',
|
||||
'total_tokens' => 'integer',
|
||||
'cost_usd' => 'decimal:6',
|
||||
'cost_krw' => 'decimal:2',
|
||||
];
|
||||
|
||||
public function creator(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(\App\Models\Members\User::class, 'created_by');
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Tenants\AiReport;
|
||||
use App\Models\Tenants\AiTokenUsage;
|
||||
use App\Models\Tenants\Card;
|
||||
use App\Models\Tenants\Deposit;
|
||||
use App\Models\Tenants\Purchase;
|
||||
@@ -13,6 +14,7 @@
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class AiReportService extends Service
|
||||
{
|
||||
@@ -361,6 +363,9 @@ private function callGeminiApi(array $inputData): array
|
||||
$result = $response->json();
|
||||
$text = $result['candidates'][0]['content']['parts'][0]['text'] ?? '';
|
||||
|
||||
// 토큰 사용량 저장
|
||||
$this->saveTokenUsage($result, $model, 'AI리포트');
|
||||
|
||||
// JSON 파싱
|
||||
$parsed = json_decode($text, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
@@ -378,6 +383,46 @@ private function callGeminiApi(array $inputData): array
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰 사용량 저장
|
||||
*/
|
||||
private function saveTokenUsage(array $apiResult, string $model, string $menuName): void
|
||||
{
|
||||
try {
|
||||
$usage = $apiResult['usageMetadata'] ?? null;
|
||||
if (! $usage) {
|
||||
return;
|
||||
}
|
||||
|
||||
$promptTokens = $usage['promptTokenCount'] ?? 0;
|
||||
$completionTokens = $usage['candidatesTokenCount'] ?? 0;
|
||||
$totalTokens = $usage['totalTokenCount'] ?? 0;
|
||||
|
||||
// Gemini 2.0 Flash 기준 단가 (USD per token)
|
||||
$inputPricePerToken = 0.10 / 1_000_000; // $0.10 / 1M tokens
|
||||
$outputPricePerToken = 0.40 / 1_000_000; // $0.40 / 1M tokens
|
||||
|
||||
$costUsd = ($promptTokens * $inputPricePerToken) + ($completionTokens * $outputPricePerToken);
|
||||
$exchangeRate = (float) config('services.gemini.exchange_rate', 1400);
|
||||
$costKrw = $costUsd * $exchangeRate;
|
||||
|
||||
AiTokenUsage::create([
|
||||
'tenant_id' => $this->tenantId(),
|
||||
'model' => $model,
|
||||
'menu_name' => $menuName,
|
||||
'prompt_tokens' => $promptTokens,
|
||||
'completion_tokens' => $completionTokens,
|
||||
'total_tokens' => $totalTokens,
|
||||
'cost_usd' => $costUsd,
|
||||
'cost_krw' => $costKrw,
|
||||
'request_id' => Str::uuid()->toString(),
|
||||
'created_by' => $this->apiUserId(),
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('AI token usage save failed', ['error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 프롬프트 생성
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user