Files
sam-manage/app/Helpers/AiTokenHelper.php
김보곤 d121a319b3 feat:GCS 업로드/STT 사용량 토큰 기록 추가
- AiTokenHelper: saveGcsStorageUsage(), saveSttUsage() 메서드 추가
- GoogleCloudService: uploadToStorage 반환값 배열로 변경 (uri + size)
- AiVoiceRecordingService: GCS/STT 각각 토큰 사용량 기록
- MeetingLogService: uploadToStorage 반환값 변경 대응

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 13:45:50 +09:00

128 lines
4.4 KiB
PHP

<?php
namespace App\Helpers;
use App\Models\System\AiTokenUsage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class AiTokenHelper
{
/**
* Gemini API 응답에서 토큰 사용량 저장
*/
public static function saveGeminiUsage(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 기준 단가
$inputPrice = 0.10 / 1_000_000;
$outputPrice = 0.40 / 1_000_000;
self::save($model, $menuName, $promptTokens, $completionTokens, $totalTokens, $inputPrice, $outputPrice);
} catch (\Exception $e) {
Log::warning('AI token usage save failed (Gemini)', ['error' => $e->getMessage()]);
}
}
/**
* Claude API 응답에서 토큰 사용량 저장
*/
public static function saveClaudeUsage(array $apiResult, string $model, string $menuName): void
{
try {
$usage = $apiResult['usage'] ?? null;
if (! $usage) {
return;
}
$promptTokens = $usage['input_tokens'] ?? 0;
$completionTokens = $usage['output_tokens'] ?? 0;
$totalTokens = $promptTokens + $completionTokens;
// Claude 3 Haiku 기준 단가
$inputPrice = 0.25 / 1_000_000;
$outputPrice = 1.25 / 1_000_000;
self::save($model, $menuName, $promptTokens, $completionTokens, $totalTokens, $inputPrice, $outputPrice);
} catch (\Exception $e) {
Log::warning('AI token usage save failed (Claude)', ['error' => $e->getMessage()]);
}
}
/**
* Google Cloud Storage 업로드 사용량 저장
* GCS Class A 오퍼레이션: $0.005 / 1,000건, Storage: $0.02 / GB / month
*/
public static function saveGcsStorageUsage(string $menuName, int $fileSizeBytes): void
{
try {
$fileSizeMB = $fileSizeBytes / (1024 * 1024);
// 업로드 API 호출 비용 ($0.005/1000 operations) + 월 스토리지 비용 ($0.02/GB, 7일 기준)
$operationCost = 0.005 / 1000;
$storageCost = ($fileSizeMB / 1024) * 0.02 * (7 / 30); // 7일 보관 기준
$costUsd = $operationCost + $storageCost;
self::save('google-cloud-storage', $menuName, $fileSizeBytes, 0, $fileSizeBytes, $costUsd / max($fileSizeBytes, 1), 0);
} catch (\Exception $e) {
Log::warning('AI token usage save failed (GCS)', ['error' => $e->getMessage()]);
}
}
/**
* Google Speech-to-Text 사용량 저장
* STT latest_long 모델: $0.009 / 15초
*/
public static function saveSttUsage(string $menuName, int $durationSeconds): void
{
try {
// latest_long 모델: $0.009 per 15 seconds = $0.0006 per second
$costUsd = ceil($durationSeconds / 15) * 0.009;
self::save('google-speech-to-text', $menuName, $durationSeconds, 0, $durationSeconds, $costUsd / max($durationSeconds, 1), 0);
} catch (\Exception $e) {
Log::warning('AI token usage save failed (STT)', ['error' => $e->getMessage()]);
}
}
/**
* 공통 저장 로직
*/
private static function save(
string $model,
string $menuName,
int $promptTokens,
int $completionTokens,
int $totalTokens,
float $inputPricePerToken,
float $outputPricePerToken,
): void {
$costUsd = ($promptTokens * $inputPricePerToken) + ($completionTokens * $outputPricePerToken);
$exchangeRate = (float) config('services.gemini.exchange_rate', 1400);
$costKrw = $costUsd * $exchangeRate;
$tenantId = session('selected_tenant_id', 1);
AiTokenUsage::create([
'tenant_id' => $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' => auth()->id(),
]);
}
}