feat(lps): 검색 1건 원가 계측 — AI 토큰·비용 + 시간 + 크롤 트래픽

검색이 소모하는 리소스/비용/시간을 잡 단위로 집계해 result.metrics 로 적재(API/FE 노출).
지금까진 타임스탬프만 있고 실제 비용 동인(AI 토큰·대역폭)은 버려지고 있었다.

- services/metrics.SearchMetrics: duration_ms + ai(calls/tokens/est_cost_usd, gpt-4o-mini 단가)
  + crawl(fetches/html_bytes/malls_crawled) + source_ms
- AI 클라이언트: resp.usage 를 last_usage 로 노출(그동안 폐기하던 토큰)
- 어댑터: last_bytes(처리 HTML 바이트) 노출 — naver/coupang/browser_base 공통
- handler: 각 fetch 타이밍+바이트, AI 호출 토큰을 metrics 로 누적 → 결과에 스냅샷
- FE: 작업 카드에 원가 4타일(소요/AI비용/토큰/크롤 트래픽)
- 테스트 2종. ⚠️ html_bytes 는 대역폭 근사(오픈마켓 리소스 미차단분 제외=하한), CDP 정확화는 백로그

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
민헌andClaude Fable 5 committed 2026-07-09 15:14:35 +09:00
1 parent 61b9e6ae82
commit 69f6641c27
10 files changed
+168 -17

No files matched your search

+2
View File
@@ -30,6 +30,7 @@ class KeywordGenerator:
def __init__(self, model: str | None = None, api_key: str | None = None):
self._model = model or openai_config.model
self._client = AsyncOpenAI(api_key=api_key or openai_config.api_key)
self.last_usage = None # 직전 호출 토큰 usage(계측용)
async def generate(self, target: dict) -> Keywords:
user = (
@@ -44,6 +45,7 @@ class KeywordGenerator:
response_format=Keywords,
temperature=0,
)
self.last_usage = getattr(resp, "usage", None)
kw = resp.choices[0].message.parsed or Keywords(precise="", broad="")
LOG.d(f"[ai] 검색어 생성 precise={kw.precise!r} broad={kw.broad!r}")
return kw
+3
View File
@@ -37,9 +37,11 @@ class SimilarityJudge:
def __init__(self, model: str | None = None, api_key: str | None = None):
self._model = model or openai_config.model
self._client = AsyncOpenAI(api_key=api_key or openai_config.api_key)
self.last_usage = None # 직전 호출 토큰 usage(계측용) — 호출부가 await 직후 읽는다
async def judge(self, target: dict, candidates: list[NormalizedProduct]) -> list[Judgment]:
"""후보별 동일상품 여부 판정. candidates 와 같은 순서/길이로 Judgment 리스트 반환."""
self.last_usage = None
if not candidates:
return []
@@ -60,6 +62,7 @@ class SimilarityJudge:
response_format=JudgmentList,
temperature=0,
)
self.last_usage = getattr(resp, "usage", None)
parsed = resp.choices[0].message.parsed
by_idx = {j.index: j for j in (parsed.judgments if parsed else [])}
# 누락된 후보는 보수적으로 불일치 처리
+75
View File
@@ -0,0 +1,75 @@
"""검색 1건의 리소스/비용/시간 계측(관측용).
한 상품 검색이 소모하는 것을 잡 단위로 집계한다:
- 시간: 전체 소요 + 소스별 소요(ms)
- AI: 호출 수 + 토큰(prompt/completion) + 추정 비용($)
- 크롤: 외부 fetch 수 + 처리 HTML 바이트 + 크롤한 몰
핸들러가 각 호출을 타이밍하고, AI 클라이언트/어댑터가 노출하는 last_usage/last_bytes 를 읽어 누적한다.
결과는 job.result.metrics 로 적재돼 API/FE 에서 검색 원가를 확인할 수 있다.
⚠️ HTML 바이트는 '처리한 응답 본문' 기준(대역폭 근사). 쿠팡은 리소스 차단이라 실제와 근접하지만,
오픈마켓(리소스 미차단)은 CSS/JS/이미지가 빠져 실제 대역폭보다 작다(하한). 정확 대역폭은 백로그(CDP).
"""
import time
# 모델별 1M 토큰당 단가(USD). input=prompt, output=completion. 모르면 0(비용 미추정).
_PRICING = {
"gpt-4o-mini": (0.150, 0.600),
"gpt-4o": (2.50, 10.00),
"gpt-4.1-mini": (0.40, 1.60),
}
def estimate_cost(model: str, prompt_tokens: int, completion_tokens: int) -> float:
inp, out = _PRICING.get(model, (0.0, 0.0))
return round(prompt_tokens / 1_000_000 * inp + completion_tokens / 1_000_000 * out, 6)
class SearchMetrics:
"""검색 1건의 누적 계측기. 스레드/코루틴 공유 X — 잡마다 새로 만든다."""
def __init__(self, model: str = ""):
self._start = time.monotonic()
self._model = model
self.ai_calls = 0
self.ai_prompt = 0
self.ai_completion = 0
self.fetches = 0
self.html_bytes = 0
self.source_ms: dict[str, int] = {}
self.crawled_malls: list[str] = []
def add_ai(self, usage):
"""OpenAI resp.usage(prompt_tokens/completion_tokens) 누적. None 이면 무시."""
if not usage:
return
self.ai_calls += 1
self.ai_prompt += getattr(usage, "prompt_tokens", 0) or 0
self.ai_completion += getattr(usage, "completion_tokens", 0) or 0
def add_fetch(self, source: str, html_bytes: int, ms: int, crawl: bool = False):
"""외부 fetch 1건(소스·바이트·소요) 누적. crawl=True 면 오픈마켓 폴백 크롤."""
self.fetches += 1
self.html_bytes += html_bytes or 0
self.source_ms[source] = self.source_ms.get(source, 0) + ms
if crawl and source not in self.crawled_malls:
self.crawled_malls.append(source)
def snapshot(self) -> dict:
return {
"duration_ms": int((time.monotonic() - self._start) * 1000),
"ai": {
"calls": self.ai_calls,
"prompt_tokens": self.ai_prompt,
"completion_tokens": self.ai_completion,
"est_cost_usd": estimate_cost(self._model, self.ai_prompt, self.ai_completion),
},
"crawl": {
"fetches": self.fetches,
"html_bytes": self.html_bytes,
"malls_crawled": self.crawled_malls,
},
"source_ms": self.source_ms,
}
+2
View File
@@ -67,6 +67,7 @@ class BrowserSearchAdapter(SearchAdapter):
self._lock = asyncio.Lock()
self._ok = 0
self._blocked = 0
self.last_bytes = 0 # 직전 search 의 처리 HTML 바이트(계측용) — 호출부가 await 직후 읽는다
# ---- 사이트별 훅 --------------------------------------------------
@abstractmethod
@@ -149,6 +150,7 @@ class BrowserSearchAdapter(SearchAdapter):
except Exception as ex:
raise AdapterError(f"{self.source} 검색 실패: {ex}", source=self.source) from ex
self.last_bytes = len(html.encode("utf-8"))
products = self._parse(html)
if products:
self._ok += 1
+2
View File
@@ -69,6 +69,7 @@ class CoupangAdapter(SearchAdapter):
self._lock = asyncio.Lock()
self._ok = 0
self._blocked = 0
self.last_bytes = 0 # 직전 search 의 처리 HTML 바이트(계측용)
async def _route(self, route):
if route.request.resource_type in _BLOCKED_RESOURCES:
@@ -130,6 +131,7 @@ class CoupangAdapter(SearchAdapter):
except Exception as ex:
raise AdapterError(f"쿠팡 검색 실패: {ex}", source=self.source) from ex
self.last_bytes = len(html.encode("utf-8"))
products = parse_search_html(html, source=self.source)
if products:
self._ok += 1
+3
View File
@@ -33,6 +33,7 @@ class NaverAdapter(SearchAdapter):
self._timeout = timeout
self._ok = 0
self._blocked = 0
self.last_bytes = 0 # 직전 search 의 응답 바이트(계측용)
def _headers(self) -> dict:
cid, csec = self._keys[self._idx]
@@ -45,6 +46,7 @@ class NaverAdapter(SearchAdapter):
if not self._keys:
raise AdapterError("네이버 API 키 없음(config.local.toml [NaverConfig].keys)", source=self.source)
self.last_bytes = 0
collected: list[dict] = []
async with httpx.AsyncClient(timeout=self._timeout) as client:
start = 1
@@ -74,6 +76,7 @@ class NaverAdapter(SearchAdapter):
await self._rl.wait()
r = await client.get(_API, params=params, headers=self._headers())
if r.status_code == 200:
self.last_bytes += len(r.content)
return r.json()
if r.status_code in (429, 403):
self._blocked += 1