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:
1 parent
61b9e6ae82
commit
69f6641c27
10 files changed
+168
-17
No files matched your search
+37
-15
@@ -14,9 +14,11 @@
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from common.enums import JobType
|
||||
from common.logger import LOG
|
||||
from services.metrics import SearchMetrics
|
||||
from services.search.contract import SearchAdapter, NormalizedProduct
|
||||
from services.search.card_parser import canonical_mall, MALL_BY_SOURCE
|
||||
from services.search.util import parse_price
|
||||
@@ -52,6 +54,7 @@ def build_search_handler(
|
||||
neg_cache=None,
|
||||
history=None,
|
||||
fallback_adapters: dict[str, SearchAdapter] | None = None,
|
||||
ai_model: str = "",
|
||||
):
|
||||
"""검색 핸들러 생성.
|
||||
judge: SimilarityJudge(같은 상품 판정) / keyword_gen: KeywordGenerator(정밀·광역 재검색어) /
|
||||
@@ -70,9 +73,21 @@ def build_search_handler(
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(f"[history] 스냅샷 기록 실패(무시): {ex}")
|
||||
|
||||
async def _search_round(query: str):
|
||||
"""한 라운드: 모든 소스 동시 검색 → (products, per_source, tech_failed)."""
|
||||
results = await asyncio.gather(*[adapters[s].search(query, limit=limit) for s in use], return_exceptions=True)
|
||||
async def _timed_search(adapter, query: str, source: str, metrics: SearchMetrics, crawl: bool):
|
||||
"""어댑터 검색 1건을 타이밍+바이트 계측하며 실행. 예외는 그대로 전파(호출부가 처리)."""
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
res = await adapter.search(query, limit=limit)
|
||||
metrics.add_fetch(source, getattr(adapter, "last_bytes", 0), int((time.monotonic() - t0) * 1000), crawl=crawl)
|
||||
return res
|
||||
except Exception:
|
||||
metrics.add_fetch(source, 0, int((time.monotonic() - t0) * 1000), crawl=crawl)
|
||||
raise
|
||||
|
||||
async def _search_round(query: str, metrics: SearchMetrics):
|
||||
"""한 라운드: 모든 소스 동시 검색 → (products, per_source, tech_failed). 소스별 시간/바이트 계측."""
|
||||
results = await asyncio.gather(*[_timed_search(adapters[s], query, s, metrics, False) for s in use],
|
||||
return_exceptions=True)
|
||||
products, per_source, tech_failed = [], {}, False
|
||||
for src, res in zip(use, results):
|
||||
if isinstance(res, Exception):
|
||||
@@ -84,15 +99,16 @@ def build_search_handler(
|
||||
per_source[src] = {"count": len(res)}
|
||||
return products, per_source, tech_failed
|
||||
|
||||
async def _match(target: dict, products: list, base_price):
|
||||
"""필터 → (있으면) AI 같은상품 판정 → 매칭 후보. 폴백 크롤 결과 판정에도 재사용."""
|
||||
async def _match(target: dict, products: list, base_price, metrics: SearchMetrics):
|
||||
"""필터 → (있으면) AI 같은상품 판정 → 매칭 후보. AI 토큰은 metrics 에 누적."""
|
||||
candidates, _ = apply_filters(products, base_price=base_price)
|
||||
if judge is not None and candidates:
|
||||
verdicts = await judge.judge(target, candidates)
|
||||
metrics.add_ai(judge.last_usage)
|
||||
candidates = [c for c, v in zip(candidates, verdicts) if v.is_match]
|
||||
return candidates
|
||||
|
||||
async def _enrich_with_fallback(target: dict, query: str, matched: list, base_price):
|
||||
async def _enrich_with_fallback(target: dict, query: str, matched: list, base_price, metrics: SearchMetrics):
|
||||
"""네이버가 커버 못 한 오픈마켓만 직접 크롤(폴백) → 같은상품 판정 후 병합.
|
||||
사용자 규칙: '네이버로 그 몰 값 확보 성공 → 그 값, 실패(몰 없음) → 실사이트 크롤'."""
|
||||
if not fallbacks:
|
||||
@@ -103,21 +119,22 @@ def build_search_handler(
|
||||
if mall in covered: # 네이버가 이미 그 몰 최저가 확보 → 크롤 생략
|
||||
continue
|
||||
try:
|
||||
crawled = await adapter.search(query, limit=limit)
|
||||
crawled = await _timed_search(adapter, query, src, metrics, crawl=True)
|
||||
except Exception as ex:
|
||||
LOG.w(f"[fallback:{src}] 크롤 실패(무시): {type(ex).__name__}: {ex}")
|
||||
continue
|
||||
hits = await _match(target, crawled, base_price)
|
||||
hits = await _match(target, crawled, base_price, metrics)
|
||||
if hits:
|
||||
LOG.d(f"[fallback:{src}] 크롤 {len(crawled)}건 중 같은상품 {len(hits)}건 병합")
|
||||
matched = matched + hits
|
||||
return matched
|
||||
|
||||
async def _round_queries(base_query: str, target: dict):
|
||||
async def _round_queries(base_query: str, target: dict, metrics: SearchMetrics):
|
||||
"""라운드 쿼리 지연 생성: 원본 → (0매칭 시에만 LLM 호출로) 정밀 → 광역."""
|
||||
yield ("original", base_query)
|
||||
if keyword_gen is not None:
|
||||
kw = await keyword_gen.generate(target) # 원본이 실패해 여기까지 온 경우에만 호출됨
|
||||
metrics.add_ai(keyword_gen.last_usage)
|
||||
seen = {base_query}
|
||||
for label, q in (("precise", kw.precise), ("broad", kw.broad)):
|
||||
q = (q or "").strip()
|
||||
@@ -136,23 +153,26 @@ def build_search_handler(
|
||||
target = {k: payload.get(k, "") for k in ("product_name", "model", "specification", "company")}
|
||||
base_price = parse_price(payload.get("price"))
|
||||
cache_key = payload.get("product_code") or base_query
|
||||
metrics = SearchMetrics(ai_model) # 검색 1건의 리소스/비용/시간 계측
|
||||
|
||||
# 0) 네거티브 캐시 — 최근 not_found면 재검색 생략
|
||||
if neg_cache is not None and await neg_cache.is_negative(cache_key):
|
||||
return {"outcome": "not_found", "cached": True, "query": base_query,
|
||||
"rounds_tried": 0, "lowest": None, "top": [], "stages": [], "sources": {}}
|
||||
"rounds_tried": 0, "lowest": None, "top": [], "stages": [], "sources": {},
|
||||
"metrics": metrics.snapshot()}
|
||||
|
||||
rounds_done = 0
|
||||
last_stages, last_sources = [], {}
|
||||
async for label, query in _round_queries(base_query, target):
|
||||
async for label, query in _round_queries(base_query, target, metrics):
|
||||
if rounds_done >= max_rounds:
|
||||
break
|
||||
rounds_done += 1
|
||||
|
||||
products, per_source, tech_failed = await _search_round(query)
|
||||
products, per_source, tech_failed = await _search_round(query, metrics)
|
||||
candidates, stages = apply_filters(products, base_price=base_price)
|
||||
if judge is not None and candidates:
|
||||
verdicts = await judge.judge(target, candidates)
|
||||
metrics.add_ai(judge.last_usage)
|
||||
matched = [c for c, v in zip(candidates, verdicts) if v.is_match]
|
||||
stages.append({"stage": "ai_match", "in": len(candidates), "out": len(matched)})
|
||||
candidates = matched
|
||||
@@ -160,11 +180,12 @@ def build_search_handler(
|
||||
|
||||
if candidates: # 찾음 → 오픈마켓 폴백 보강 후 종료
|
||||
before = len(candidates)
|
||||
candidates = await _enrich_with_fallback(target, query, candidates, base_price)
|
||||
candidates = await _enrich_with_fallback(target, query, candidates, base_price, metrics)
|
||||
if len(candidates) > before:
|
||||
stages.append({"stage": "fallback_crawl", "in": before, "out": len(candidates)})
|
||||
result = rank_result(candidates, len(products), stages, top_n)
|
||||
result.update(outcome="found", query=query, round=label, rounds_tried=rounds_done, sources=per_source)
|
||||
result.update(outcome="found", query=query, round=label, rounds_tried=rounds_done,
|
||||
sources=per_source, metrics=metrics.snapshot())
|
||||
await _record_history(cache_key, job.get("job_id"), "found", candidates)
|
||||
return result
|
||||
|
||||
@@ -175,7 +196,8 @@ def build_search_handler(
|
||||
if neg_cache is not None:
|
||||
await neg_cache.put(cache_key, reason=f"not_found after {rounds_done} rounds")
|
||||
result = rank_result([], 0, last_stages, top_n)
|
||||
result.update(outcome="not_found", query=base_query, rounds_tried=rounds_done, sources=last_sources)
|
||||
result.update(outcome="not_found", query=base_query, rounds_tried=rounds_done,
|
||||
sources=last_sources, metrics=metrics.snapshot())
|
||||
await _record_history(cache_key, job.get("job_id"), "not_found", [])
|
||||
return result
|
||||
|
||||
|
||||
Reference in new issue
Block a user