feat(insta-lab): Claude Haiku 카드가치 판단(graceful)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
52
insta-lab/app/selection_judge.py
Normal file
52
insta-lab/app/selection_judge.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
"""Claude Haiku 일괄 카드가치 판단. 실패/미설정 시 빈 dict (graceful)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from anthropic import Anthropic
|
||||||
|
|
||||||
|
from .config import ANTHROPIC_API_KEY, ANTHROPIC_MODEL_HAIKU
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PROMPT = """다음 인스타 카드뉴스 후보 키워드들을 카드로 만들 가치(흥미·시의성·정보성)와
|
||||||
|
리스크(민감·논란)를 종합해 0~1 점수로 평가해라. 코드펜스 없이 JSON 배열로만 출력:
|
||||||
|
[{{"keyword_id": <id>, "score": <0~1>}}, ...]
|
||||||
|
|
||||||
|
후보:
|
||||||
|
{items}"""
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_codefence(s: str) -> str:
|
||||||
|
s = s.strip()
|
||||||
|
if s.startswith("```"):
|
||||||
|
s = re.sub(r"^```(?:json)?\s*|\s*```$", "", s).strip()
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def parse_judge_response(raw: str) -> Dict[int, float]:
|
||||||
|
try:
|
||||||
|
data = json.loads(_strip_codefence(raw))
|
||||||
|
return {int(d["keyword_id"]): float(d["score"]) for d in data}
|
||||||
|
except Exception:
|
||||||
|
logger.warning("judge 응답 파싱 실패")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def judge_candidates(candidates: List[Dict[str, Any]]) -> Dict[int, float]:
|
||||||
|
if not ANTHROPIC_API_KEY or not candidates:
|
||||||
|
return {}
|
||||||
|
items = "\n".join(f'- id={c["id"]}: {c["keyword"]} ({c["category"]})' for c in candidates)
|
||||||
|
try:
|
||||||
|
client = Anthropic(api_key=ANTHROPIC_API_KEY)
|
||||||
|
resp = client.messages.create(
|
||||||
|
model=ANTHROPIC_MODEL_HAIKU, max_tokens=512,
|
||||||
|
messages=[{"role": "user", "content": PROMPT.format(items=items)}],
|
||||||
|
)
|
||||||
|
return parse_judge_response(resp.content[0].text)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("judge_candidates 호출 실패")
|
||||||
|
return {}
|
||||||
20
insta-lab/tests/test_selection_judge.py
Normal file
20
insta-lab/tests/test_selection_judge.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from app import selection_judge
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_judge_response_ok():
|
||||||
|
raw = '[{"keyword_id": 1, "score": 0.8}, {"keyword_id": 2, "score": 0.3}]'
|
||||||
|
assert selection_judge.parse_judge_response(raw) == {1: 0.8, 2: 0.3}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_judge_response_codefence():
|
||||||
|
raw = '```json\n[{"keyword_id": 5, "score": 0.5}]\n```'
|
||||||
|
assert selection_judge.parse_judge_response(raw) == {5: 0.5}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_judge_response_garbage_returns_empty():
|
||||||
|
assert selection_judge.parse_judge_response("not json") == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_judge_candidates_no_key_returns_empty(monkeypatch):
|
||||||
|
monkeypatch.setattr(selection_judge, "ANTHROPIC_API_KEY", "")
|
||||||
|
assert selection_judge.judge_candidates([{"id": 1, "keyword": "x", "category": "economy"}]) == {}
|
||||||
Reference in New Issue
Block a user