PHpullh
학습 라이브러리/AI Prompts/품질 검증 포함 생성 루프

AI PROMPTS · 루프 생성 전략

품질 검증 포함 생성 루프

생성 즉시 품질을 평가하고 기준 미달이면 재생성하는 고품질 루프입니다.

루프 생성 전략

핵심 설명

생성 즉시 품질을 평가하고 기준 미달이면 재생성하는 고품질 루프입니다.

Python 3.11+

#!/usr/bin/env python3
"""
품질 검증이 포함된 항목 생성기
생성 → 자동 품질 평가 → 기준 미달 시 재생성
"""

import anthropic
import json
import os
import time

client = anthropic.Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])

QUALITY_PROMPT = """다음 프로그래밍 학습 항목의 품질을 0-10으로 평가하세요.

항목:
{item}

평가 기준:
1. 코드가 실제 동작하는가? (0-3점)
2. 설명이 명확하고 정확한가? (0-2점)
3. 팁과 실수 항목이 실용적인가? (0-2점)
4. 코드 예제가 적절한 길이인가? (0-2점)
5. HTML 문법 강조가 올바른가? (0-1점)

JSON으로 반환:
{{"score": 점수, "issues": ["문제1", "문제2"], "passed": true/false}}
통과 기준: score >= 7"""

def evaluate_quality(item: dict) -> tuple[bool, float, list[str]]:
    """항목 품질을 LLM으로 평가"""
    try:
        response = client.messages.create(
            model="claude-haiku-4-5",  # 빠른 평가용 소형 모델
            max_tokens=300,
            messages=[{
                "role": "user",
                "content": QUALITY_PROMPT.format(
                    item=json.dumps(item, ensure_ascii=False, indent=2)
                )
            }]
        )
        result = json.loads(response.content[0].text)
        return result['passed'], result['score'], result.get('issues', [])
    except Exception as e:
        print(f"    품질 평가 실패: {e}")
        return True, 8.0, []  # 평가 실패 시 통과 처리

def generate_with_quality(lang: str, num: int, max_attempts: int = 3) -> dict | None:
    """품질 기준을 충족하는 항목이 생성될 때까지 반복"""
    for attempt in range(1, max_attempts + 1):
        print(f"    생성 시도 {attempt}/{max_attempts}...", end=' ')

        # 항목 생성 (기존 generate_item 함수 호출)
        item = generate_item_raw(lang, num)
        if not item:
            print("생성 실패")
            continue

        # 품질 평가
        passed, score, issues = evaluate_quality(item)
        print(f"점수: {score:.1f} {'✅' if passed else '❌'}")

        if passed:
            return item

        if issues:
            print(f"    개선 필요: {', '.join(issues[:2])}")

        time.sleep(0.5)

    print(f"    ⚠️  {max_attempts}회 시도 후 최선 결과 반환")
    return item  # 최선의 결과 반환

def generate_item_raw(lang: str, num: int) -> dict | None:
    """단순 항목 생성 (품질 검증 없음)"""
    # ... 기존 generate_item 함수와 동일한 로직
    pass

# 사용 예시
if __name__ == '__main__':
    for num in range(33, 53):
        print(f"[{num:03d}] kotlin 항목 생성:")
        item = generate_with_quality('kotlin', num)
        if item:
            # 저장
            with open(f"data/generated/kotlin_{num:03d}.json", 'w') as f:
                json.dump(item, f, ensure_ascii=False, indent=2)