usage.py

파일 다운로드

"""호출별 원장. 토큰 사용량 미확인은 0으로 치환하지 않는다."""
from contextlib import contextmanager
from contextvars import ContextVar
from datetime import datetime, timezone
from decimal import Decimal
from pathlib import Path
from threading import Lock
from urllib.request import urlopen
import json
import os
import time
import uuid

ROOT = Path(__file__).resolve().parent
RUNTIME = Path(os.getenv('MOA_RUNTIME_DIR', str(ROOT / 'runtime')))
RATES = json.loads((ROOT / 'data/rates.json').read_text(encoding='utf-8'))
CURRENT = ContextVar('usage_scope', default=None)
LOCK = Lock()


def cost_fields(model, usage, endpoint):
    unknown = {'prompt_tokens': None, 'completion_tokens': None, 'cached_tokens': None,
               'cache_write_tokens': None, 'cost_usd': None, 'cost_status': 'USAGE_UNKNOWN'}
    if not isinstance(usage, dict):
        return unknown
    prompt = usage.get('prompt_tokens')
    output = 0 if endpoint == 'embedding' else usage.get('completion_tokens')
    details = usage.get('prompt_tokens_details')
    cached = (0 if endpoint == 'embedding' else
              details.get('cached_tokens') if isinstance(details, dict) else None)
    write = (0 if endpoint == 'embedding' else
             details.get('cache_write_tokens', 0) if isinstance(details, dict) else None)
    valid = lambda x: type(x) is int and x >= 0
    if not valid(prompt) or not valid(output):
        return unknown
    fields = dict(prompt_tokens=prompt, completion_tokens=output, cached_tokens=cached,
                  cache_write_tokens=write, cost_usd=None, cost_status='RATE_OR_CACHE_USAGE_UNKNOWN')
    rate = RATES['models'].get(model)
    if (not rate or not valid(cached) or not valid(write) or cached + write > prompt
            or (write > 0 and 'cache_write' not in rate)):
        return fields
    amount = ((Decimal(prompt-cached-write) * Decimal(rate['input'])
               + Decimal(cached) * Decimal(rate['cached_input'])
               + (Decimal(write) * Decimal(rate['cache_write']) if write else Decimal(0))
               + Decimal(output) * Decimal(rate['output'])) / Decimal(1000000))
    return {**fields, 'cost_usd': str(amount), 'cost_status': 'ESTIMATED_STANDARD_TEXT_RATE'}


def append_row(row):
    RUNTIME.mkdir(parents=True, exist_ok=True)
    with LOCK:
        with (RUNTIME / 'usage.jsonl').open('a', encoding='utf-8') as stream:
            stream.write(json.dumps(row, ensure_ascii=False) + '\n')
    current = CURRENT.get()
    if current is not None:
        current['events'].append(row)


@contextmanager
def usage_scope(task, request_id=None):
    state = {'task': task, 'request_id': request_id or uuid.uuid4().hex, 'events': []}
    token = CURRENT.set(state)
    try:
        yield state
    finally:
        CURRENT.reset(token)


def request_json(request, timeout=30, task=None):
    payload = json.loads(request.data)
    endpoint = 'embedding' if request.full_url.endswith('/embeddings') else 'generation'
    state = CURRENT.get() or {'task': 'unscoped', 'request_id': uuid.uuid4().hex}
    row = dict(call_id=uuid.uuid4().hex, request_id=state['request_id'], task=task or state['task'],
               timestamp=datetime.now(timezone.utc).isoformat(), endpoint=endpoint,
               requested_model=payload.get('model'), rate_date=RATES['rate_date'],
               pricing_basis=RATES['basis'], new_api_calls=1)
    start = time.perf_counter()
    raw = None
    try:
        with urlopen(request, timeout=timeout) as response:
            row['http_status'] = getattr(response, 'status', 200)
            raw = json.load(response)
        row['status'] = 'HTTP_JSON_OK'
        return raw
    except Exception as error:
        row.update(status='ERROR', error_type=type(error).__name__, http_status=getattr(error, 'code', None))
        raise
    finally:
        row['elapsed_seconds'] = round(time.perf_counter()-start, 6)
        row['model'] = raw.get('model', payload.get('model')) if isinstance(raw, dict) else payload.get('model')
        row['usage'] = raw.get('usage') if isinstance(raw, dict) else None
        row.update(cost_fields(row['model'], row['usage'], endpoint))
        append_row(row)


def summarize_events(events):
    costs = [e['cost_usd'] for e in events]
    return {'new_api_calls': len(events), 'known_cost_usd': str(sum((Decimal(c) for c in costs if c is not None), Decimal(0))),
            'total_cost_usd': None if any(c is None for c in costs) else str(sum((Decimal(c) for c in costs), Decimal(0))),
            'unknown_cost_calls': sum(c is None for c in costs), 'rate_date': RATES['rate_date']}