o2o-site-AEO/solution/backend/services/external/site_ontology.py
hbyang 94c4116689 [feat] solution/backend: 발행 때 온톨로지 키워드 생성을 켠다 — 호텔 판정 · 업종별 유형어 게이트
generate:false 로 불러 새 숙소가 사전 밖 단어를 받지 못했다. 생성을 켜면 호텔이 펜션 사전의
`군산 독채펜션` 을 받는데, 메타 게이트가 '펜션' 을 업종어로 보고 자료 없이 통과시켰다.

- site_ontology: generate+sync — 처음 보는 숙소만 저쪽이 기다리게 하고 publish 상한 60초
- seo_keywords: 외부 분류(없으면 상호)에 '호텔' 이면 stay.hotel, 자기 유형어만 자료 없이 통과
- snapshot: place.external_category 를 실음 — 호텔 판정 근거
- .env.example · ARCHITECTURE · DEVLOG: ONTOLOGY_LLM_PROVIDER, 발행 흐름, 실측

test_seo_keywords 20 passed(호텔 4건 추가). 전체 1041 passed / 47 failed —
47건은 이 변경 전 main 과 같은 목록

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 13:49:37 +09:00

65 lines
2.7 KiB
Python

"""SiteOntology(o2o-site-ontology) 클라이언트 — 이 가게에 맞는 검색 키워드를 받아 온다."""
import httpx
from common.logger import LOG
from config.server_configs import external_api_config
# 로컬 임베딩 모델이라 호출당 1~2초다.
TIMEOUT_SEC = 15.0
# 처음 보는 업체는 publish 가 OpenAI 키워드 생성을 기다린다(키워드 15개 + 질문 5개).
PUBLISH_TIMEOUT_SEC = 60.0
DEFAULT_LIMIT = 40
PUBLISH_PATH = "/v1/merchants/publish"
MATCH_PATH = "/v1/match"
class SiteOntologyError(RuntimeError):
"""SiteOntology 호출 실패(네트워크·타임아웃·4xx/5xx·업체 미해석)."""
def base_url() -> str:
return (external_api_config.site_ontology_url or "").strip().rstrip("/")
def is_configured() -> bool:
return bool(base_url())
async def _post(client: httpx.AsyncClient, path: str, body: dict, timeout: float = TIMEOUT_SEC) -> dict:
res = await client.post(f"{base_url()}{path}", json=body, timeout=timeout)
if res.status_code >= 400:
raise SiteOntologyError(f"{path} HTTP {res.status_code}: {res.text[:200]}")
try:
data = res.json()
except ValueError as ex:
raise SiteOntologyError(f"{path} 응답이 JSON 이 아니다: {res.text[:200]}") from ex
if not isinstance(data, dict):
raise SiteOntologyError(f"{path} 응답 모양이 다르다: {type(data).__name__}")
return data
async def match_for_merchant(merchant: dict, limit: int = DEFAULT_LIMIT) -> dict:
"""업체를 저장하고, 그 업체로 해석된 추천 결과(/v1/match 응답)를 돌려준다."""
# sync 는 처음 보는 업체에만 먹는다 — 첫 발행부터 새 키워드가 실리고, 갱신은 저쪽 큐가 한다.
body = {**merchant, "generate": True, "sync": True}
try:
async with httpx.AsyncClient(timeout=TIMEOUT_SEC) as client:
try:
await _post(client, PUBLISH_PATH, body, PUBLISH_TIMEOUT_SEC)
except SiteOntologyError as ex:
if not body.get("regionId"):
raise
LOG.w(f"[site-ontology] regionId={body['regionId']} 로 저장하지 못했다 — 지역 없이 다시 보낸다: {ex}")
body = {**body, "regionId": None}
await _post(client, PUBLISH_PATH, body, PUBLISH_TIMEOUT_SEC)
result = await _post(client, MATCH_PATH, {"query": merchant["externalId"], "limit": limit})
except httpx.HTTPError as ex:
raise SiteOntologyError(f"{type(ex).__name__}: {ex}") from ex
resolved = result.get("resolved") or {}
if resolved.get("externalId") != merchant["externalId"]:
raise SiteOntologyError(f"업체가 해석되지 않았다 — externalId={merchant['externalId']}")
return result