[feat] solution/backend: LLM 공급자를 OpenAI 기본값으로 전환, Perplexity 실비용 계측 추가
## 1. Gemini -> OpenAI 공급자 추상화
Gemini 쿼터/인증 실패로 COPY 잡(소개문·FAQ 생성)이 반복 DEAD 되는 걸 보고, 공급자를
OpenAI로 바꾸되 설정 하나로 되돌릴 수 있게 했다.
- services/llm/errors.py·types.py(신규): 공급자 무관 예외·Usage·ImagePart·LlmResult
- services/llm/gemini.py: 기존 call() 은 그대로 두고 generate() 인터페이스 추가
- services/llm/openai.py(신규): OpenAI Chat Completions 구현. 실측(2026-09-16):
gpt-5.6-luna 는 temperature 커스텀 값을 거부한다("Only the default (1) value is
supported") — 아예 안 보낸다.
- services/llm/provider.py(신규): LLM_PROVIDER 설정(기본 openai, 모르는 값은 gemini)으로
둘 중 하나를 고른다.
- gemini_text.py·gemini.py(vision)·gemini_extract.py: 공개 함수 이름은 그대로 두고
내부만 provider.active() 로 배선 — vision_service.py 등 6개 호출부는 무변경.
단 model 선택 로직(vision_service.py·copy_steps.py)은 공급자에 맞는 모델명을 고르도록 한 줄씩 고쳤다.
- config_models.py: llm_provider·openai_api_key·openai_text_model·openai_vision_model 추가.
## 2. Perplexity 실비용 계측 추가
OpenAI 전환 김에 실제 발행 파이프라인(스테이,머뭄 기준)을 끝까지 돌려 LLM 비용을 재보니,
services/llm/perplexity.py 에는 애초에 토큰·비용 계측이 없었다. 추가하는 과정에서
실측(2026-09-16, 실제 API 응답): `usage.cost` 는 문서 예시(평평한 숫자)와 달리
`{input_tokens_cost, output_tokens_cost, request_cost, total_cost}` 객체였다 — 그대로
가정하고 배포했다가 지역 이야기 생성(LOCAL_SYNC) 잡이 재시도 3회 후 DEAD 로 떨어지는 걸
라이브에서 확인하고 고쳤다. 어떤 모양이 와도 예외를 던지지 않게 방어했다.
- services/llm/perplexity.py: Usage·read_usage() 추가(usage.cost.total_cost 를 그대로 읽는다
— 토큰 단가표로 역산하지 않는다. 검색 컨텍스트 요금까지 포함된 진짜 값이라서다)
- external/perplexity.py·place_research.py·story_service.py·itinerary_llm_service.py·
external/restaurant_discovery.py: 각 호출부에 tokens/비용 로그 추가
실측(스테이,머뭄 1건 발행, 지역 콘텐츠는 캐시): Perplexity $0.050(일정 생성이 절반 이상),
OpenAI $0.019(비전 $0.015 + 소개문·FAQ $0.003 + 가사 $0.0006).
검증: 신규/영향받은 테스트 전부 통과(services/llm 신규 3파일, gemini_extract 최초 HTTP
계층 테스트, perplexity 비용 계측 등). 실 OpenAI/Perplexity API로 사업장 수집→비전→
소개문·FAQ→발행까지 라이브로 왕복 확인.
## 3. site/EssentialInfoSection.tsx
미확인 항목 개수 안내 문구 제거(별도 작업, 스테이징된 상태 그대로 포함).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
33d27980c4
commit
dbae2d4f35
19 files changed
+410
-192
No files matched your search
@@ -0,0 +1,16 @@
|
||||
"""공급자 무관 LLM 예외. Gemini·OpenAI 구현이 둘 다 이 클래스를 던진다.
|
||||
|
||||
★ 이름을 'Llm*'으로 새로 지었지만 services/llm/gemini.py 가 GeminiError = LlmError 식으로
|
||||
같은 클래스를 재노출한다 — 기존 6개 파일의 `except GeminiNotConfigured` 는 한 글자도 안 바뀐다."""
|
||||
|
||||
|
||||
class LlmError(RuntimeError):
|
||||
"""LLM 호출 실패."""
|
||||
|
||||
|
||||
class LlmNotConfigured(LlmError):
|
||||
"""API 키 미설정 또는 인증 실패(401/403)."""
|
||||
|
||||
|
||||
class LlmInvalidOutput(LlmError):
|
||||
"""응답이 기대한 모양이 아니다."""
|
||||
@@ -8,11 +8,17 @@
|
||||
여기가 책임지지 않는 것: 무엇을 물을지(services/prompts/), 답을 믿을지(services/grounding/).
|
||||
"""
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
import base64
|
||||
import json
|
||||
|
||||
import httpx
|
||||
|
||||
from config.server_configs import external_api_config
|
||||
from services.llm.errors import LlmError as GeminiError
|
||||
from services.llm.errors import LlmInvalidOutput
|
||||
from services.llm.errors import LlmInvalidOutput as GeminiInvalidOutput # noqa: F401 (하위 호환 재노출)
|
||||
from services.llm.errors import LlmNotConfigured as GeminiNotConfigured
|
||||
from services.llm.types import ImagePart, LlmResult, Usage
|
||||
|
||||
_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/models"
|
||||
|
||||
@@ -26,28 +32,6 @@ _PRICE_PER_1M_OUTPUT = {"gemini-3.7-flash": 3.75, "gemini-3.6-flash": 3.75, "gem
|
||||
_RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
|
||||
|
||||
|
||||
class GeminiError(RuntimeError):
|
||||
"""Gemini 호출 실패 — 호출측은 ErrorType.GENERATOR_CALL_FAILED 로 매핑한다."""
|
||||
|
||||
|
||||
class GeminiNotConfigured(GeminiError):
|
||||
"""GEMINI_API_KEY 미설정 또는 인증 실패.
|
||||
|
||||
★ 서버 부팅은 막지 않는다 — 이 어댑터만 비활성이고 나머지 파이프라인은 돈다."""
|
||||
|
||||
|
||||
class GeminiInvalidOutput(GeminiError):
|
||||
"""응답이 기대한 모양이 아니다 — ErrorType.GENERATOR_INVALID_OUTPUT."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Usage:
|
||||
"""호출 1회(또는 여러 회 합산)의 토큰 사용량. 비용 로그의 근거다."""
|
||||
|
||||
input_tokens: int = 0
|
||||
output_tokens: int = 0
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
"""키가 있는지 — 어댑터 등록/스킵 판단용. 예외를 던지지 않는다."""
|
||||
return bool(external_api_config.gemini_api_key)
|
||||
@@ -121,3 +105,37 @@ def price(model: str, usage: Usage) -> float:
|
||||
inp = _PRICE_PER_1M_INPUT.get(model, 0.0) * usage.input_tokens / 1_000_000
|
||||
out = _PRICE_PER_1M_OUTPUT.get(model, 0.0) * usage.output_tokens / 1_000_000
|
||||
return round(inp + out, 4)
|
||||
|
||||
|
||||
async def generate(
|
||||
client: httpx.AsyncClient,
|
||||
model: str,
|
||||
*,
|
||||
prompt: str,
|
||||
images: list[ImagePart] | None = None,
|
||||
response_schema: dict | None = None,
|
||||
temperature: float = 0.2,
|
||||
max_retries: int = 2,
|
||||
) -> LlmResult:
|
||||
"""공급자 무관 인터페이스. services/llm/openai.py 가 같은 시그니처로 구현한다."""
|
||||
parts: list[dict] = [{"text": prompt}]
|
||||
for image in images or []:
|
||||
if image.label:
|
||||
parts.append({"text": image.label})
|
||||
parts.append({"inline_data": {"mime_type": image.mime_type, "data": base64.b64encode(image.data).decode()}})
|
||||
|
||||
generation_config: dict = {"temperature": temperature}
|
||||
if response_schema is not None:
|
||||
generation_config["responseMimeType"] = "application/json"
|
||||
generation_config["responseSchema"] = response_schema
|
||||
|
||||
body = {"contents": [{"role": "user", "parts": parts}], "generationConfig": generation_config}
|
||||
payload = await call(client, model, body, max_retries)
|
||||
text = extract_text(payload)
|
||||
parsed = None
|
||||
if response_schema is not None:
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
except json.JSONDecodeError as ex:
|
||||
raise LlmInvalidOutput(f"구조화 출력 파싱 실패: {ex}") from ex
|
||||
return LlmResult(json=parsed, text=text, usage=read_usage(payload))
|
||||
@@ -0,0 +1,127 @@
|
||||
"""OpenAI Chat Completions 호출 — services/llm/gemini.py 와 같은 자리, 다른 공급자.
|
||||
|
||||
여기가 책임지는 것: 주소·인증 헤더·재시도·구조화 출력 스키마 변환·응답 파싱·토큰 집계·비용 계산.
|
||||
여기가 책임지지 않는 것: 무엇을 물을지(services/prompts/), 답을 믿을지(services/grounding/)."""
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
|
||||
import httpx
|
||||
|
||||
from config.server_configs import external_api_config
|
||||
from services.llm.errors import LlmError, LlmInvalidOutput, LlmNotConfigured
|
||||
from services.llm.types import ImagePart, LlmResult, Usage
|
||||
|
||||
_BASE_URL = "https://api.openai.com/v1/chat/completions"
|
||||
|
||||
DEFAULT_MODEL = "gpt-5.6-luna"
|
||||
|
||||
_PRICE_PER_1M_INPUT = {"gpt-5.6-luna": 0.20, "gpt-5.6-terra": 2.00, "gpt-5.6-sol": 5.00}
|
||||
_PRICE_PER_1M_OUTPUT = {"gpt-5.6-luna": 1.20, "gpt-5.6-terra": 12.00, "gpt-5.6-sol": 30.00}
|
||||
|
||||
_RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return bool(external_api_config.openai_api_key)
|
||||
|
||||
|
||||
def _to_strict_schema(schema: dict) -> dict:
|
||||
"""OpenAI strict 모드 요구사항(모든 object 에 additionalProperties:false,
|
||||
모든 property 가 required)을 만족하도록 재귀 변환한다.
|
||||
|
||||
★ Gemini용 RESPONSE_SCHEMA(OpenAPI 서브셋, services/prompts/*.py)를 그대로 받아
|
||||
변환한다 — 두 벌 관리하지 않는다."""
|
||||
schema = dict(schema)
|
||||
if schema.get("type") == "object" and "properties" in schema:
|
||||
schema["properties"] = {k: _to_strict_schema(v) for k, v in schema["properties"].items()}
|
||||
schema["required"] = list(schema["properties"].keys())
|
||||
schema["additionalProperties"] = False
|
||||
elif schema.get("type") == "array" and "items" in schema:
|
||||
schema["items"] = _to_strict_schema(schema["items"])
|
||||
return schema
|
||||
|
||||
|
||||
def _build_messages(prompt: str, images: list[ImagePart] | None) -> list[dict]:
|
||||
content: list[dict] = [{"type": "text", "text": prompt}]
|
||||
for image in images or []:
|
||||
if image.label:
|
||||
content.append({"type": "text", "text": image.label})
|
||||
b64 = base64.b64encode(image.data).decode()
|
||||
content.append({"type": "image_url", "image_url": {"url": f"data:{image.mime_type};base64,{b64}"}})
|
||||
return [{"role": "user", "content": content}]
|
||||
|
||||
|
||||
async def generate(
|
||||
client: httpx.AsyncClient,
|
||||
model: str,
|
||||
*,
|
||||
prompt: str,
|
||||
images: list[ImagePart] | None = None,
|
||||
response_schema: dict | None = None,
|
||||
temperature: float = 0.2,
|
||||
max_retries: int = 2,
|
||||
) -> LlmResult:
|
||||
# ★ 실측(2026-09-16): gpt-5.6-luna 는 temperature 커스텀 값을 거부한다
|
||||
# ("Only the default (1) value is supported" — 400). Gemini 와 달리 이 파라미터를
|
||||
# 그냥 안 보낸다 — 공급자가 강제하는 값이라 우리가 흉내 낼 방법이 없다.
|
||||
body: dict = {
|
||||
"model": model,
|
||||
"messages": _build_messages(prompt, images),
|
||||
}
|
||||
if response_schema is not None:
|
||||
body["response_format"] = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {"name": "result", "strict": True, "schema": _to_strict_schema(response_schema)},
|
||||
}
|
||||
|
||||
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {external_api_config.openai_api_key}"}
|
||||
last = None
|
||||
payload = None
|
||||
for attempt in range(max_retries + 1):
|
||||
try:
|
||||
resp = await client.post(_BASE_URL, json=body, headers=headers)
|
||||
except (httpx.TimeoutException, httpx.TransportError) as ex:
|
||||
last = f"{type(ex).__name__}: {ex}"
|
||||
else:
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
break
|
||||
if resp.status_code in (401, 403):
|
||||
raise LlmNotConfigured(f"인증 실패 status={resp.status_code} — API 키를 확인하세요")
|
||||
if resp.status_code not in _RETRYABLE_STATUS:
|
||||
raise LlmError(f"status={resp.status_code} body={resp.text[:200]}")
|
||||
last = f"status={resp.status_code}"
|
||||
|
||||
if attempt < max_retries:
|
||||
await asyncio.sleep(min(8.0, 1.0 * (2 ** attempt)))
|
||||
|
||||
if payload is None:
|
||||
raise LlmError(f"{max_retries + 1}회 시도 실패: {last}")
|
||||
|
||||
choices = payload.get("choices") or []
|
||||
if not choices:
|
||||
raise LlmInvalidOutput("choices 가 비었다(안전 필터 차단 가능)")
|
||||
text = (choices[0].get("message") or {}).get("content") or ""
|
||||
if not text.strip():
|
||||
raise LlmInvalidOutput(f"텍스트가 없다 finish_reason={choices[0].get('finish_reason')}")
|
||||
|
||||
parsed = None
|
||||
if response_schema is not None:
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
except json.JSONDecodeError as ex:
|
||||
raise LlmInvalidOutput(f"구조화 출력 파싱 실패: {ex}") from ex
|
||||
|
||||
usage_raw = payload.get("usage") or {}
|
||||
usage = Usage(
|
||||
input_tokens=int(usage_raw.get("prompt_tokens") or 0),
|
||||
output_tokens=int(usage_raw.get("completion_tokens") or 0),
|
||||
)
|
||||
return LlmResult(json=parsed, text=text, usage=usage)
|
||||
|
||||
|
||||
def price(model: str, usage: Usage) -> float:
|
||||
inp = _PRICE_PER_1M_INPUT.get(model, 0.0) * usage.input_tokens / 1_000_000
|
||||
out = _PRICE_PER_1M_OUTPUT.get(model, 0.0) * usage.output_tokens / 1_000_000
|
||||
return round(inp + out, 4)
|
||||
@@ -9,6 +9,7 @@
|
||||
나중에 환각을 추적할 수 있게 한다.
|
||||
"""
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -36,6 +37,39 @@ def is_configured() -> bool:
|
||||
return bool((external_api_config.perplexity_api_key or "").strip())
|
||||
|
||||
|
||||
@dataclass
|
||||
class Usage:
|
||||
"""호출 1회의 실제 사용량·비용.
|
||||
|
||||
★ cost 는 우리가 계산한 값이 아니라 Perplexity 가 응답에 직접 실어주는 실제 청구액(USD)이다
|
||||
(`usage.cost.total_cost`) — 검색 컨텍스트 요금(request_cost)까지 포함된 진짜 값이라,
|
||||
Gemini·OpenAI 처럼 토큰 단가표로 역산하는 것보다 정확하다.
|
||||
★ 실측(2026-09-16): `usage.cost` 는 평평한 숫자가 아니라
|
||||
`{"input_tokens_cost", "output_tokens_cost", "request_cost", "total_cost"}` 객체다 —
|
||||
문서 예시(평평한 숫자)와 다르다. num_search_queries 는 비용은 아니지만 검색 남용 감시용으로 같이 둔다."""
|
||||
|
||||
input_tokens: int = 0
|
||||
output_tokens: int = 0
|
||||
num_search_queries: int = 0
|
||||
cost: float = 0.0
|
||||
|
||||
|
||||
def read_usage(payload: dict) -> Usage:
|
||||
"""응답의 usage 를 읽는다. 필드가 없거나 모양이 다르면 0 — 계측 실패가 본 기능을 막으면 안 된다."""
|
||||
u = payload.get("usage") or {}
|
||||
cost_field = u.get("cost")
|
||||
if isinstance(cost_field, dict):
|
||||
cost = cost_field.get("total_cost")
|
||||
else:
|
||||
cost = cost_field
|
||||
return Usage(
|
||||
input_tokens=int(u.get("prompt_tokens") or 0),
|
||||
output_tokens=int(u.get("completion_tokens") or 0),
|
||||
num_search_queries=int(u.get("num_search_queries") or 0),
|
||||
cost=float(cost) if isinstance(cost, (int, float)) else 0.0,
|
||||
)
|
||||
|
||||
|
||||
async def call(body: dict, *, client: httpx.AsyncClient | None = None) -> dict:
|
||||
"""★ LLM 이 실제로 불리는 지점. chat/completions 1회.
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
"""LLM_PROVIDER 설정으로 gemini/openai 구현 중 하나를 고른다.
|
||||
|
||||
★ 모르는 값은 gemini 로 떨어진다 — 오타 하나로 사진분류·소개문·FAQ 가 전부
|
||||
조용히 꺼지는 것보다, 기존에 검증된 공급자로 계속 도는 쪽이 안전하다."""
|
||||
from config.server_configs import external_api_config
|
||||
from services.llm import gemini, openai
|
||||
|
||||
|
||||
def active():
|
||||
return openai if external_api_config.llm_provider == "openai" else gemini
|
||||
@@ -0,0 +1,28 @@
|
||||
"""공급자 무관 값 타입. gemini.py·openai.py 가 동일하게 이 타입을 쓰고 돌려준다."""
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class Usage:
|
||||
input_tokens: int = 0
|
||||
output_tokens: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImagePart:
|
||||
mime_type: str
|
||||
data: bytes
|
||||
label: str = "" # 있으면 이 이미지 직전에 라벨 텍스트를 넣는다(사진 여러 장을 ref로 매칭할 때 쓴다)
|
||||
|
||||
|
||||
@dataclass
|
||||
class LlmResult:
|
||||
"""generate() 의 반환값.
|
||||
|
||||
json: response_schema 를 줬을 때 파싱된 결과(스키마 없이 부르면 None).
|
||||
text: 원문 텍스트(요약처럼 스키마 없는 호출에서 이걸 쓴다)."""
|
||||
|
||||
json: Optional[dict]
|
||||
text: str
|
||||
usage: Usage
|
||||
Reference in new issue
Block a user