"""채널 URL 발견 — 겹들을 엮어 결과를 만드는 자리. 이 파일이 하는 일은 **엮는 것뿐**이다. 고칠 것이 생기면 해당 겹으로 바로 간다: 무엇을 묻는가 services/prompts/channel_discovery.py 프롬프트·응답 스키마 어떻게 부르는가 services/llm/perplexity.py HTTP·타임아웃·인증 답을 믿을 것인가 services/grounding/channels.py 채널 판정·상세 페이지 필터 무엇을 돌려주는가 여기 호출 → 필터 → 결과 조립 ★ Perplexity 응답을 **사실로 쓰지 않는다.** 산출물은 "여기를 보라"는 URL 포인터일 뿐이고, 사실은 그 URL 을 크롤링해 얻는다. 원문(raw)은 감사·환각 추적용으로 통째로 박제한다. """ from dataclasses import dataclass, field import httpx from common.logger import LOG from services.grounding.channels import ( DiscoveredLink, classify_url, collect_links, filter_links, search_count, ) from services.llm.perplexity import ( DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TIMEOUT, PerplexityError, PerplexityNotConfigured, call, is_configured, ) from services.prompts.channel_discovery import RESPONSE_SCHEMA, SYSTEM_PROMPT, build_prompt # 후기 유입을 막기 위해 공식 채널 도메인만 검색한다. SEARCH_DOMAIN_FILTER = [ "yanolja.com", "goodchoice.kr", "place.naver.com", "map.naver.com", "naver.me", ] # 이 횟수를 넘으면 프롬프트·도메인 필터를 의심한다 — 검색 요금은 토큰 요금과 별도다. SEARCH_COUNT_WARN_THRESHOLD = 8 @dataclass class ChannelDiscovery: """채널 발견 결과. links : 상세 페이지로 판정돼 살아남은 후보 URL. 동일 업소 검증을 통과해야 크롤링 대상이 된다 raw : 응답 원문(본문 + search_results). place_channels.raw 에 통째로 박제한다 search_count : 이번 호출에서 발생한 검색 횟수 — **검색 요금이 토큰 요금과 별도**라 추적한다 filtered_out : 걸러낸 URL 과 사유 [(url, reason), ...]. ★ 조용히 버리지 않는다 — 운영자가 "왜 이 URL 이 빠졌나"를 볼 수 있어야 필터가 과했는지(진짜 채널을 버렸는지) 판단할 수 있다 """ links: list[DiscoveredLink] = field(default_factory=list) raw: dict = field(default_factory=dict) search_count: int = 0 filtered_out: list[tuple[str, str]] = field(default_factory=list) def reason_counts(self) -> dict[str, int]: """탈락 사유별 건수. 로그·운영 화면에서 쓴다.""" counts: dict[str, int] = {} for _url, reason in self.filtered_out: counts[reason] = counts.get(reason, 0) + 1 return counts async def discover_channels( name: str, address: str | None = None, category_hint: str | None = None, *, model: str = DEFAULT_MODEL, include_blogs: bool = False, client: httpx.AsyncClient | None = None, ) -> ChannelDiscovery: """상호명으로 채널 URL 후보를 찾는다. **URL 발견 전용 — 답변을 사실로 쓰지 마라.** 돌려주는 URL 은 아직 '이 가게의 것'이라는 보장이 없다. 동일 업소 검증을 통과해 확정(place_channels.confirmed_at)된 URL 만 크롤링 대상이 된다. 발견된 URL 중 **상세 페이지가 아닌 것(루트·목록·SEO 랜딩)과 블로그는 걸러낸다.** 걸러낸 목록은 `filtered_out` 에 사유와 함께 남는다 — 조용히 버리지 않는다. args: include_blogs : 블로그·카페 URL 도 후보로 남길지. **기본 False** — 블로그는 채널이 아니라 후기라 크롤링해도 공식 정보가 아니다 raises: PerplexityNotConfigured : 키 미설정(이 어댑터만 비활성) PerplexityError : 타임아웃·5xx·응답 파싱 불가 """ if not (name or "").strip(): raise PerplexityError("상호명이 비어 있다") body = { "model": model, "messages": [ { "role": "system", "content": SYSTEM_PROMPT, }, {"role": "user", "content": build_prompt(name, address, category_hint)}, ], "max_tokens": DEFAULT_MAX_TOKENS, "temperature": 0, # URL 수집이라 창의성이 해롭다 "response_format": RESPONSE_SCHEMA, "search_domain_filter": SEARCH_DOMAIN_FILTER, # ★ 야놀자·여기어때·네이버로 한정 } payload = await call(body, client=client) found, dropped_raw = collect_links(payload) links, dropped_quality = filter_links(found, include_blogs) filtered_out = dropped_raw + dropped_quality searches = search_count(payload) result = ChannelDiscovery( links=links, raw=payload, search_count=searches, filtered_out=filtered_out ) # 내부 검색 횟수는 품질·지연 관측값이다. Sonar 과금은 토큰 + 요청 컨텍스트 요금이다. usage = payload.get("usage") or {} reasons = result.reason_counts() reason_text = " ".join(f"{k}{v}" for k, v in sorted(reasons.items())) or "없음" LOG.i( f"[perplexity] '{name}' 검색={searches}회 발견={len(found)} 통과={len(links)} " f"탈락={len(filtered_out)}({reason_text}) tokens={usage.get('total_tokens', '?')}" ) if searches > SEARCH_COUNT_WARN_THRESHOLD: LOG.w( f"[perplexity] 검색 {searches}회 — 기준({SEARCH_COUNT_WARN_THRESHOLD}회) 초과. " f"지연·오탐 후보가 늘 수 있으니 도메인 필터·프롬프트를 확인하라" ) # raw 는 응답 전체를 그대로 둔다 — 나중에 환각 추적에 쓴다(사실 근거로는 쓰지 않는다). return result