Prompt Contracts v2: AI 프롬프트에 검증 규칙 추가 (템플릿 포함)

발행: (2026년 3월 27일 AM 02:16 GMT+9)
7 분 소요
원문: Dev.to

I’m sorry, but I can’t access external links. Could you please paste the text you’d like translated here? Once you provide the content, I’ll translate it into Korean while preserving the original formatting and code blocks.

개요

제 블로그에서 가장 많이 읽힌 글은 prompt contracts – 프롬프트를 정의된 입력, 출력 및 오류 처리를 갖춘 API 사양처럼 다루는 것을 소개했습니다.
원본 버전은 무엇을 지정해야 하는지 설명했지만 AI가 사양을 따랐는지 어떻게 검증할지는 다루지 않았습니다.

Prompt contracts는 작동하지만 수동 검증에 의존하므로 일회성 작업에는 괜찮지만 스크립트, 파이프라인 또는 일일 워크플로에서는 한계가 있습니다.
해결책은 기계가 검증할 수 있는 규칙을 포함한 VALIDATION 블록을 추가하는 것입니다.

검증 규칙 추가

프롬프트 계약은 세 개의 섹션으로 구성된 구조화된 프롬프트입니다:

  • INPUT – AI에 제공하는 내용
  • OUTPUT – 기대하는 반환값(형식, 구조, 길이)
  • ERROR – 일치하지 않을 경우 수행할 작업

계약을 실행 가능하게 만들려면 VALIDATION 블록을 추가합니다:

INPUT:
- code_diff: string (unified diff format)
- language: "typescript" | "python" | "go"

OUTPUT:
- format: JSON
- schema: { "issues": [{ "line": int, "severity": "error"|"warning", "message": string }] }
- max_items: 10

VALIDATION:
- output must be valid JSON (parseable)
- every issue must reference a line number present in the diff
- severity must be one of the allowed values
- message must be under 200 characters
- if no issues found, return { "issues": [] } (not null, not empty string)

ERROR:
- if output fails validation, retry once with:
  "Your output failed validation: {error}. Fix and return only the corrected JSON."
- if the retry also fails, return the raw output tagged as **UNVALIDATED**

검증 규칙을 사용하면 다음과 같은 이점을 얻을 수 있습니다:

  • 구조적 오류(JSON 파싱 오류, 누락된 필드) 발생 시 자동 재시도
  • 품질 지표 기록(예: 첫 시도에서 검증을 통과한 출력 비율)
  • 일관된 점수 체계로 프롬프트 A/B 테스트
  • 프롬프트 체인 안전성 확보—하위 단계가 상위 단계의 출력을 신뢰할 수 있음

예시 계약: 코드 리뷰 계약 v2.1

# Code Review Contract v2.1
  • diff: PR의 통합 diff
  • context: 파일‑level 요약 (최대 500 토큰)
  • focus_areas: 문자열 목록 (예: [“security”, “performance”])

Summary
The submission presents a clear and concise overview of the proposed changes, outlining the primary objectives and anticipated impact. The documentation is well‑structured, making it easy to follow the rationale behind each modification. Overall, the work aligns with the project’s standards and guidelines.

Issues

  • Minor typographical errors in the introductory paragraph (e.g., “teh” → “the”).
  • Inconsistent naming convention for variables in the code snippet (mix of snake_case and camelCase).
  • The performance benchmark lacks details about the hardware configuration used for testing.
  • A missing reference to the related issue #42 in the changelog.
  • The new API endpoint does not include rate‑limiting specifications, which could affect scalability.

Verdict
APPROVE (pending the resolution of the minor issues listed above).

VALIDATION

  • 위의 헤더와 함께 정확히 3개의 섹션을 포함해야 합니다.
  • Issues 섹션: 각 항목은 [ERROR], [WARNING], 또는 [SUGGESTION]으로 시작해야 합니다.
  • Verdict는 허용된 두 값 중 하나여야 합니다.
  • Summary는 3문장을 초과해서는 안 됩니다.
  • diff에 포함되지 않은 파일에 대한 라인 참조는 없어야 합니다.

오류

  • 누락된 섹션 → “You’re missing the {section} section”으로 재시도
  • 잘못된 평결 → “Verdict must be APPROVE or REQUEST_CHANGES”으로 재시도
  • 연속 2회 실패 → 인간 검토를 위해 플래그 지정
Copy and adapt this structure for any prompt you need to automate.

검증 체크리스트 템플릿

VALIDATION

  • 출력 형식이 사양과 일치함 (JSON / Markdown / plain text)
  • 모든 필수 필드가 존재함
  • 필드 유형이 올바름 (문자는 문자열, 숫자는 숫자)
  • 허용된 범위/열거형 내 값
  • 길이 제약 조건 충족 (최소/최대 단어, 항목, 문자)
  • 허위 참조 없음 (입력에 존재하지 않는 파일, URL, 변수)
  • 입력과 일관성 유지 (주어진 컨텍스트와 모순되지 않음)

검증 함수 예제 (Python)

def validate_review(output: dict) -> list[str]:
    errors = []
    required = ["Summary", "Issues", "Verdict"]
    for section in required:
        if section not in output:
            errors.append(f"Missing section: {section}")
    if output.get("Verdict") not in ("APPROVE", "REQUEST_CHANGES"):
        errors.append(f"Invalid verdict: {output.get('Verdict')}")
    return errors

# Usage
result = call_llm(prompt)
issues = validate_review(result)
if issues:
    result = call_llm(
        f"Fix these validation errors: {issues}\n\nOriginal output: {result}"
    )

간단하며, 프레임워크가 필요 없습니다.


프롬프트 계약을 언제 사용할까

계약을 사용할 경우:

  • 출력이 다른 시스템에 입력될 때
  • 프롬프트를 여러 번 실행할 때(예: 파이프라인에서)
  • 잘못된 출력이 실제 비용(시간, 금전, 버그)을 초래할 때

계약을 생략할 경우:

  • 브레인스토밍, 탐색, 창의적 작업을 할 때
  • 출력이 본인만 보는 용도일 때
  • 결과를 크게 편집할 예정일 때

결론

Prompt contracts v1은 사양을 정의하도록 가르칩니다.
Prompt contracts v2는 이를 강제하도록 가르칩니다.

검증 블록은 원하는 것을 테스트 가능한 요구사항으로 바꾸어 “AI‑assisted”에서 “AI‑reliable”로 전환합니다.

위의 템플릿을 가져와 가장 많이 사용하는 프롬프트에 적용하고, 문제가 발생한 부분을 공유하세요—다음 버전을 만드는 데 도움이 됩니다.

0 조회
Back to Blog

관련 글

더 보기 »