o2o-site-AEO/backend/services/llm/perplexity.py
Mina Choi 6784e59ca5 최초 커밋 — 기존 코드 전체 + 문서 체계 신설
git 저장소가 없어 히스토리·협업 기반이 아예 없던 상태를 연다.
함께 문서를 재편했다. 그동안 문서가 있어도 "이 제품이 뭘 푸는가"와
"어떻게 도는가"를 담은 문서가 없어서, 목표 문장이 backend/frontend
README 두 곳에 복붙돼 있었다 — 상위 문서가 없어 아래로 샌 것이다.

신설
  README.md               레포 진입점 + 문서 지도 + 문서 규칙 4가지
  AGENTS.md               에이전트·신규 합류자용 함정 목록과 규약
                          (CLAUDE.md 는 여기로 걸린 심볼릭 링크)
  docs/PRODUCT.md         제품 정의 — 문제·사용자·원칙·**non-goals**·성공 기준
  docs/ARCHITECTURE.md    payload 경계·발행 파이프라인·서빙 결정·앱 분리 설계

이동
  backend/docs/DECISIONS.md → docs/DECISIONS.md
    백엔드만의 결정이 아니다. 게다가 코드 주석 ~25곳이 이미
    `docs/DECISIONS.md` 로 적고 있어 레포 루트 기준으로는 그게 맞다.

갱신
  docs/DEPLOY.md          서빙 결정 반영 — nginx 정적 서빙이 지금 경로(3절),
                          Azure 는 나중에 켤 때(4절)로 분리
  docs/ARCHITECTURE.md    사이트 = 한 장(2026-08-31) 구조 반영
  docs/COLLECTION_SEO_AEO_FLOW.md
                          robots.txt·sitemap.xml 은 오리진 루트에만 굽는다는 점 명시
  frontend/site/scripts/prerender.ts
                          헤더 주석의 렌더 보고서 경로가 실제(422줄)와 달라 수정

.gitignore
  ★ CLAUDE.md 를 더 이상 무시하지 않는다. 에이전트 지침은 팀과 모든
    에이전트가 공유하는 규약이라 커밋해야 한다 — 무시하면 클론한 사람이
    "배포 후 republish_all.py 필수" 같은 함정을 전달받지 못한다.
    개인용 오버라이드는 ~/.claude/CLAUDE.md 에 둔다.
2026-08-31 13:57:59 +09:00

75 lines
3.2 KiB
Python

"""Perplexity 호출 — 이 프로젝트에서 Perplexity 로 나가는 **유일한 통로**.
여기가 책임지는 것: 주소·인증 헤더·타임아웃·응답 파싱.
여기가 책임지지 않는 것: 무엇을 물을지(services/prompts/channel_discovery.py),
답으로 받은 URL 을 믿을지(services/grounding/channels.py).
★ Perplexity 답변을 **사실로 쓰지 않는다.** 이 어댑터의 산출물은 "여기를 보라"는 URL 포인터일
뿐이고, 실제 사실은 그 URL 을 크롤링해서 얻는다. 그래서 응답 원문(raw)을 통째로 박제해
나중에 환각을 추적할 수 있게 한다.
"""
import json
import httpx
from config.server_configs import external_api_config
API_URL = "https://api.perplexity.ai/chat/completions"
DEFAULT_MODEL = "sonar"
# 첫 구조화 출력 요청은 스키마 준비에 10~30초가 걸린다 — 그 시간을 포함한 값이다.
DEFAULT_TIMEOUT = httpx.Timeout(90.0, connect=10.0)
DEFAULT_MAX_TOKENS = 2048
class PerplexityError(RuntimeError):
"""Perplexity 호출 실패. 호출측(collector)은 ErrorType.COLLECT_FETCH_FAILED 로 매핑한다."""
class PerplexityNotConfigured(PerplexityError):
"""PERPLEXITY_API_KEY 미설정 — 이 어댑터만 비활성. **서버 부팅을 막지 않는다.**"""
def is_configured() -> bool:
"""키가 설정돼 있는지. 어댑터 등록 여부를 판단할 때 쓴다."""
return bool((external_api_config.perplexity_api_key or "").strip())
async def call(body: dict, *, client: httpx.AsyncClient | None = None) -> dict:
"""★ LLM 이 실제로 불리는 지점. chat/completions 1회.
Gemini 쪽(services/llm/gemini.py)과 달리 재시도하지 않는다 — 이 호출은 검색을 동반해
한 번이 비싸고 느리다. 실패하면 수집 파이프라인이 등록된 링크로 그냥 진행한다
(services/collect_service.py 의 discover_links 참조).
응답 본문(dict)을 그대로 돌려준다. 해석은 부르는 쪽 몫이다.
"""
api_key = (external_api_config.perplexity_api_key or "").strip()
if not api_key:
raise PerplexityNotConfigured("PERPLEXITY_API_KEY 미설정 — 채널 발견을 건너뛴다")
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
owns_client = client is None
http = client or httpx.AsyncClient(timeout=DEFAULT_TIMEOUT)
try:
resp = await http.post(API_URL, json=body, headers=headers)
except httpx.TimeoutException as ex:
raise PerplexityError(f"Perplexity 타임아웃: {ex}") from ex
except httpx.HTTPError as ex:
raise PerplexityError(f"Perplexity 호출 실패: {type(ex).__name__}: {ex}") from ex
finally:
if owns_client:
await http.aclose()
if resp.status_code != 200:
raise PerplexityError(f"Perplexity 응답 오류: status={resp.status_code} body={resp.text[:200]}")
try:
payload = resp.json()
except (json.JSONDecodeError, ValueError) as ex:
raise PerplexityError(f"Perplexity 응답 JSON 파싱 실패: {ex}") from ex
if not isinstance(payload, dict):
raise PerplexityError("Perplexity 응답이 객체가 아니다")
return payload