0Pricing
AI Prompt Engineering · レッスン

アサーションベースのプロンプトテスト

contains()、正規表現、JSONスキーマ、LLM-as-judgeを使って出力を検証します。

「アサーションベースのプロンプトテスト」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Prompt Engineering学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Prompt Engineeringコースには全4レッスンが含まれています。

LLM出力に対するアサーション

アサーションベースのテストでは、ユニットテストで使われる原則をLLMにも適用します。つまり、出力に含まれるべきもの、または含まれてはいけないものを明示的に宣言し、その宣言に違反した時点ですぐに失敗させます。

決定論的な関数を対象とするユニットテストとは異なり、LLMのアサーションでは確率的なテキスト出力を扱います。そのため、より柔軟なアサーションの種類が必要です。contains、matches_schema、satisfies_regex、llm_judge_score_aboveなどがあります。

基本的なアサーション: contains と not_contains

最も単純なアサーションでは、キーワードが含まれているか、含まれていないかを確認します。分類タスク、構造化出力、安全性チェックに適しています。

import openai
client = openai.OpenAI(api_key='sk-...')

def call_prompt(system, user, temperature=0):
    resp = client.chat.completions.create(
        model='gpt-4o',
        messages=[
            {'role': 'system', 'content': system},
            {'role': 'user', 'content': user}
        ],
        temperature=temperature
    )
    return resp.choices[0].message.content

# Keyword presence assertion
def assert_contains(output, keyword, case_sensitive=False):
    text = output if case_sensitive else output.lower()
    kw = keyword if case_sensitive else keyword.lower()
    assert kw in text, f'Expected "{keyword}" in output, got: {output[:100]}'

# Keyword absence assertion
def assert_not_contains(output, forbidden, case_sensitive=False):
    text = output if case_sensitive else output.lower()
    kw = forbidden if case_sensitive else forbidden.lower()
    assert kw not in text, f'Forbidden "{forbidden}" found in output: {output[:100]}'

JSON Schemaの検証

プロンプトが構造化されたJSONを返す想定の場合は、スキーマに対して出力を検証します。スキーマ検証に失敗した場合、プロンプトに形式上の問題があります。モデルが説明文を追加したか、JSONの構造が正しくありません。

import json
from jsonschema import validate, ValidationError

PRODUCT_SCHEMA = {
    'type': 'object',
    'properties': {
        'name': {'type': 'string'},
        'price': {'type': 'number', 'minimum': 0},
        'available': {'type': 'boolean'}
    },
    'required': ['name', 'price', 'available'],
    'additionalProperties': False
}

def assert_valid_json_schema(output, schema):
    try:
        data = json.loads(output.strip())
    except json.JSONDecodeError as e:
        raise AssertionError(f'Output is not valid JSON: {e}\nOutput: {output[:200]}')
    try:
        validate(instance=data, schema=schema)
    except ValidationError as e:
        raise AssertionError(f'JSON does not match schema: {e.message}\nOutput: {output[:200]}')
    return data

# Test
output = call_prompt(
    'Extract product info as JSON: {"name": ..., "price": ..., "available": ...}',
    'Widget Pro costs $49.99 and is in stock.'
)
product = assert_valid_json_schema(output, PRODUCT_SCHEMA)
print('Parsed product:', product)

正規表現マッチング

正規表現アサーションでは、出力形式を正確に検証します。日付、電話番号、構造化コードなど、特定のパターンに従う必要がある出力に役立ちます。

import re

def assert_matches_regex(output, pattern, flags=0):
    if not re.search(pattern, output, flags):
        raise AssertionError(
            f'Output does not match pattern /{pattern}/\nOutput: {output[:200]}'
        )

def assert_output_is_label(output, valid_labels):
    cleaned = output.strip().upper()
    assert cleaned in valid_labels, (
        f'Expected one of {valid_labels}, got: {repr(cleaned)}'
    )

# Examples
output = call_prompt('Classify sentiment as POSITIVE, NEGATIVE, or NEUTRAL:', 'Great product!')
assert_output_is_label(output, {'POSITIVE', 'NEGATIVE', 'NEUTRAL'})

date_output = call_prompt('Extract the date in YYYY-MM-DD format:', 'Meeting on November 15, 2024')
assert_matches_regex(date_output, r'^\d{4}-\d{2}-\d{2}$')

LLM-as-Judgeによるスコアリング

自由記述形式の出力には、2回目のLLM呼び出しを使って品質を評価します。これをLLM-as-judgeと呼びます。判定モデルには元のプロンプト、出力、評価基準を渡し、スコアを返します。

def llm_judge_score(original_prompt, output, criteria, max_score=10):
    judge_prompt = (
        f'Evaluate the following AI response on a scale of 1-{max_score}.\n'
        f'Evaluation criteria: {criteria}\n\n'
        f'Original prompt: {original_prompt}\n\n'
        f'AI response: {output}\n\n'
        f'Return only a number from 1 to {max_score}.'
    )
    resp = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': judge_prompt}],
        temperature=0
    )
    score_text = resp.choices[0].message.content.strip()
    return int(score_text)

def assert_llm_score_above(original_prompt, output, criteria, min_score=7):
    score = llm_judge_score(original_prompt, output, criteria)
    assert score >= min_score, f'LLM judge score {score} < minimum {min_score}'

プロンプトテストでpytestを使う

pytestは標準的なPythonテストフレームワークであり、プロンプトテストにも適しています。各テスト関数が1つのテストケースに対応します。pytestはテストを自動的に収集、実行、報告します。

# test_sentiment_prompt.py
import pytest
import openai

client = openai.OpenAI(api_key='sk-...')
SYSTEM_PROMPT = 'Classify the sentiment as POSITIVE, NEGATIVE, or NEUTRAL. Return only the label.'

def classify(text):
    resp = client.chat.completions.create(
        model='gpt-4o',
        messages=[
            {'role': 'system', 'content': SYSTEM_PROMPT},
            {'role': 'user', 'content': text}
        ],
        temperature=0
    )
    return resp.choices[0].message.content.strip().upper()

# pytest automatically discovers functions starting with test_
def test_positive_sentiment():
    assert classify('I love this product!') == 'POSITIVE'

def test_negative_sentiment():
    assert classify('Terrible experience.') == 'NEGATIVE'

def test_neutral_sentiment():
    assert classify('It arrived on time.') == 'NEUTRAL'

# Run: pytest test_sentiment_prompt.py -v

pytestでのパラメータ化テスト

@pytest.mark.parametrizeを使うと、コードを繰り返し記述せずに、同じテスト関数を多数の入力に対して実行できます。包括的なテストスイートを構築する最もすっきりした方法です。

# test_sentiment_parametrized.py
import pytest

TEST_CASES = [
    ('I love this!', 'POSITIVE'),
    ('Worst purchase ever.', 'NEGATIVE'),
    ('It works.', 'NEUTRAL'),
    ('Amazing!', 'POSITIVE'),
    ('Terrible!', 'NEGATIVE'),
    ('OK I guess.', 'NEUTRAL'),
]

@pytest.mark.parametrize('text,expected', TEST_CASES)
def test_sentiment_classification(text, expected):
    result = classify(text)
    assert result == expected, f'For "{text}": expected {expected}, got {result}'

# pytest test_sentiment_parametrized.py -v
# Output shows each test case individually:
# PASSED test_sentiment_parametrized.py::test_sentiment_classification[I love this!-POSITIVE]
# PASSED test_sentiment_parametrized.py::test_sentiment_classification[Worst purchase ever.-NEGATIVE]

プロンプトの共有状態に対するフィクスチャ

pytestのフィクスチャを使うと、プロンプトテンプレートの読み込みやAPIクライアントの作成など、コストの高いセットアップをテスト間で共有できます。テストセッションごとに1回だけ実行することも可能です。

# conftest.py — fixtures available to all test files in the directory
import pytest
import openai

@pytest.fixture(scope='session')
def llm_client():
    return openai.OpenAI(api_key='sk-...')

@pytest.fixture(scope='session')
def sentiment_prompt():
    with open('prompts/sentiment_v3.txt') as f:
        return f.read()

# test_sentiment.py
def test_positive_with_fixture(llm_client, sentiment_prompt):
    resp = llm_client.chat.completions.create(
        model='gpt-4o',
        messages=[
            {'role': 'system', 'content': sentiment_prompt},
            {'role': 'user', 'content': 'I love this!'}
        ],
        temperature=0
    )
    assert 'POSITIVE' in resp.choices[0].message.content.upper()

不安定なテストへの対処

LLMの出力は確率的です。temperature=0であっても、異なるモデルのデプロイやバージョンによって出力が変わる場合があります。リトライ処理と許容しきい値を使って、不安定さに対処します。

import pytest

def run_with_retry(fn, n=3):
    '''Run fn up to n times, pass if any run succeeds.'''
    failures = []
    for _ in range(n):
        try:
            fn()
            return  # passed
        except AssertionError as e:
            failures.append(str(e))
    raise AssertionError(f'Failed all {n} attempts. Last: {failures[-1]}')

def test_positive_with_retry():
    def check():
        result = classify('I love this!')
        assert result == 'POSITIVE'
    run_with_retry(check, n=3)

# Or use pytest-retry plugin:
# @pytest.mark.flaky(reruns=3)
# def test_positive_sentiment():
#     assert classify('I love this!') == 'POSITIVE'

テストのパフォーマンスとコスト

各テストケースはAPI呼び出しです。100個のテストケースを1回あたり$0.005で実行すると、テスト全体の1回の実行に$0.50かかります。コストを管理する方法は次のとおりです。

  • 静的なテスト入力に対するレスポンスをキャッシュし、CIではキャッシュから実行する
  • フルスイートは毎晩実行し、各PRではスモークテストのサブセット(10ケース)のみを実行する
  • ほとんどのテストには安価なモデル(gpt-4o-mini)を使い、リグレッションスイートだけgpt-4oで実行する
import hashlib, json

RESPONSE_CACHE = {}

def cached_classify(text, use_cache=True):
    key = hashlib.md5(text.encode()).hexdigest()
    if use_cache and key in RESPONSE_CACHE:
        return RESPONSE_CACHE[key]
    result = classify(text)
    RESPONSE_CACHE[key] = result
    return result

# Persist cache to disk for CI
def load_cache(path='test_cache.json'):
    global RESPONSE_CACHE
    try:
        with open(path) as f:
            RESPONSE_CACHE = json.load(f)
    except FileNotFoundError:
        RESPONSE_CACHE = {}

def save_cache(path='test_cache.json'):
    with open(path, 'w') as f:
        json.dump(RESPONSE_CACHE, f, indent=2)

テスト結果レポート

pytestは、どのテストケースがなぜ失敗したのかを詳しく示すレポートを生成します。簡潔な失敗メッセージを表示するには、pytest --tb=short -vを使います。CIでは、--junitxmlを使って、GitHub Actions、GitLab CI、Jenkinsと互換性のあるJUnit XMLレポートを生成します。

# Run test suite and generate reports
# In terminal:
# pytest tests/prompt/ -v --tb=short --junitxml=test_results.xml

# In Python (for programmatic use):
import subprocess

def run_prompt_tests(test_dir='tests/prompt'):
    result = subprocess.run(
        ['pytest', test_dir, '-v', '--tb=short', '--junitxml=test_results.xml'],
        capture_output=True, text=True
    )
    print(result.stdout)
    if result.returncode != 0:
        print('TESTS FAILED')
        print(result.stderr)
    return result.returncode == 0

passed = run_prompt_tests()

理解度チェック

プロンプトテストで、完全一致アサーションの代わりにLLM-as-judgeによるスコアリングを使うのはどのような場合ですか。

まとめ: アサーションベースのプロンプトテスト

LLMの出力に対する主なアサーションの種類は次のとおりです。

  • contains / not_contains: キーワードの有無を確認します。ラベルや安全性チェックに適しています
  • JSON Schemaの検証: 構造化された出力形式を検証します
  • 正規表現マッチング: 特定のパターン(日付、コード)を検証します
  • LLM-as-judge: 自由記述の品質を評価します

@pytest.mark.parametrizeを使ったpytestで、整理されたスケーラブルなテストスイートを構築します。コストを管理するにはレスポンスをキャッシュします。各PRではスモークテストのサブセットを実行し、フルスイートは毎晩実行します。次のレッスンでは、モデル更新に対するリグレッションテストを扱います。

よくある質問

「アサーションベースのプロンプトテスト」レッスンは無料ですか?

はい。「アサーションベースのプロンプトテスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。

「アサーションベースのプロンプトテスト」で何を学びますか?

contains()、正規表現、JSONスキーマ、LLM-as-judgeを使って出力を検証します。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Prompt Engineeringを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「アサーションベースのプロンプトテスト」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Prompt Engineeringレッスンでコードを書いて実行できますか?

はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. プロンプトのテストケース作成
  2. アサーションベースのプロンプトテスト
  3. モデル更新をまたぐ回帰テスト
  4. プロンプトテストスイートの構築
← AI Prompt Engineeringに戻る