AI Prompt Engineering · レッスン

穴埋めパターンを作成する

Python で {{variable}} プレースホルダーと文字列置換を使います。

レッスン 2/413 ステップ

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

プレースホルダーの規約

穴埋め式のプロンプトパターンでは、モデルに送信する前に実際の値へ置き換えるプロンプトの一部を、プレースホルダーで示します。

最も一般的なプレースホルダーの規約は、二重の波括弧です:{{variable_name}}。この規約は読みやすく、通常のテキストに偶然現れる可能性が低く、多くのテンプレートライブラリで広くサポートされています。

ほかにも、単一の波括弧{variable}、山括弧<variable>、大文字のみの変数があります。どれか1つを選び、一貫して使用してください。

基本的なプレースホルダー置換

最も単純な穴埋めパターンは、文字列を直接置換する方法です:

テンプレート: 「{{word_count}}語の{{product}}について、{{audience}}向けに説明を書いてください。」

置換後: 「小規模事業者向けにTaskFlow Proについて150語で説明を書いてください。」

置換は文字列がモデルに送信される前に行われます。モデルに渡されるのは、プレースホルダーの記号がない、完全で明確なプロンプトです。プレースホルダーは前処理の一環であり、モデル自身が処理するものではありません。

一般的なプレースホルダーのカテゴリ

ほとんどのユースケースをカバーできる、標準的なプレースホルダーのカテゴリを使ってテンプレートを作成してください:

  • {{customer_name}} — 受信者または対象者の名前
  • {{product}} — 文章の対象となる製品、サービス、またはトピック
  • {{tone}} — 例: プロフェッショナル、カジュアル、緊急、熱意のある表現
  • {{audience}} — コンテンツの対象者
  • {{word_count}} — 目標とする長さ
  • {{format}} — 箇条書き、段落、番号付きリスト
  • {{context}} — このケースに固有の背景情報

テンプレート間で一貫した命名を行うと、ライブラリ内を移動しやすくなり、エラーも減らせます。

Pythonの文字列formatによる置換

Python組み込みの文字列.format()メソッドは、{variable}構文を使ってプレースホルダーを埋める簡単な方法です:

import openai

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

EMAIL_TEMPLATE = '''Write a follow-up email from {sender_name} to {recipient_name}.
Context: {context}
Tone: {tone}
Length: {word_count} words.
Include a clear call to action: {cta}.
Do not mention competitors. Active voice. No bullet points.'''

def generate_email(sender, recipient, context, tone, word_count, cta):
    prompt = EMAIL_TEMPLATE.format(
        sender_name=sender,
        recipient_name=recipient,
        context=context,
        tone=tone,
        word_count=word_count,
        cta=cta
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

result = generate_email(
    sender='Sarah Chen',
    recipient='Mr. Patel',
    context='We met at the DevConf conference last week and discussed API integration.',
    tone='warm and professional',
    word_count=120,
    cta='Schedule a 20-minute demo call'
)
print(result)

Pythonのf-stringアプローチ

Pythonのf-stringは、可読性の高さから好む開発者もいる、インライン置換構文を提供します:

import openai

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

def generate_product_description(product, audience, tone, word_count, key_benefit):
    prompt = (
        f'Write a product description for {product}, designed for {audience}. '
        f'Tone: {tone}. '
        f'Length: {word_count} words. '
        f'Lead with this key benefit: {key_benefit}. '
        'Active voice. No bullet points. No pricing mentions.'
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

print(generate_product_description(
    product='FocusFlow, a time-blocking productivity app',
    audience='freelancers and independent consultants',
    tone='energetic and practical',
    word_count=150,
    key_benefit='Reclaim two hours every day by blocking distractions automatically'
))

プレースホルダー内の特殊文字の扱い

よくあるバグとして、ユーザーが入力した値に波括弧、引用符、改行が含まれていると、文字列の置換が壊れることがあります。

防御的なアプローチ:

  • 置換前に入力値をサニタイズする — 必要に応じて特殊文字を削除またはエスケープします
  • 複数行のテンプレートには三重引用符文字列を使い、改行を安全に処理します
  • 変数の値自体に波括弧が含まれる場合(例: コード)は、変数の値をリテラルとして扱う方法を使います(Jinja2はこの処理に適しています)

テンプレートは必ず、空の文字列、引用符を含む文字列、改行を含む文字列、非常に長い文字列など、エッジケースの入力でテストしてください。

テンプレートのデフォルト値

すべての変数を必須にする必要はありません。オプションのパラメーターにデフォルト値を設定すると、テンプレートの柔軟性が高まります:

def build_prompt(product, audience, tone='professional and friendly', word_count=200, format_style='prose'):
    format_instruction = {
        'prose': 'Write in continuous paragraphs. No bullet points.',
        'bullets': 'Use bullet points. Each point is one sentence.',
        'numbered': 'Use a numbered list. Each item is one sentence.'
    }.get(format_style, 'Write in continuous paragraphs.')

    return (
        f'Write a description of {product} for {audience}. '
        f'Tone: {tone}. '
        f'Length: {word_count} words. '
        f'{format_instruction} '
        'Active voice. No competitor mentions.'
    )

# Minimal call — uses all defaults
print(build_prompt('Notion', 'students'))

# Full call — overrides defaults
print(build_prompt('Notion', 'students', tone='casual', word_count=100, format_style='bullets'))

複数ブロックのテンプレート

複雑なプロンプトには、複数の変数ブロックが含まれる場合があります。たとえば、システムプロンプト用ブロックとユーザーメッセージ用ブロックに、それぞれ独自のプレースホルダーを持たせます:

SYSTEM_TEMPLATE = 'You are a {role} writing for {company}. Your audience is {audience}. Style: {style}.'

USER_TEMPLATE = 'Write a {content_type} about {topic}. Length: {word_count} words. Deadline tone: {urgency}.'

import openai

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

def generate(role, company, audience, style, content_type, topic, word_count, urgency):
    system_msg = SYSTEM_TEMPLATE.format(
        role=role, company=company, audience=audience, style=style
    )
    user_msg = USER_TEMPLATE.format(
        content_type=content_type, topic=topic,
        word_count=word_count, urgency=urgency
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[
            {'role': 'system', 'content': system_msg},
            {'role': 'user', 'content': user_msg}
        ]
    )
    return response.choices[0].message.content

レンダリング前のプレースホルダーの検証

プロンプトを送信する前に、必須のプレースホルダーがすべて埋められていることを必ず検証してください。プレースホルダーが欠けていると、モデルには{{product}}のようなリテラルテキストが渡され、予想外の出力が生成されることがあります:

import re

def validate_template(template_str, provided_vars):
    required = set(re.findall(r'\{\{(\w+)\}\}', template_str))
    missing = required - set(provided_vars.keys())

    if missing:
        raise ValueError(f'Missing required template variables: {missing}')

    return True

template = 'Write a {{word_count}}-word {{tone}} description of {{product}} for {{audience}}.'
vars_provided = {'word_count': 150, 'tone': 'friendly', 'product': 'TaskFlow'}

try:
    validate_template(template, vars_provided)
except ValueError as e:
    print(f'Template error: {e}')
    # Output: Template error: Missing required template variables: {{'audience'}}

条件付きテンプレートブロック

変数が指定されている場合にだけ表示したいテンプレートのセクションもあります。Pythonでは、条件付きで文字列を組み立てることで実装できます:

def build_report_prompt(topic, audience, word_count, include_recommendations=False, cta=None):
    prompt = f'Write a report on {topic} for {audience}. Length: {word_count} words. Active voice.'

    if include_recommendations:
        prompt += ' End with a numbered list of 3 specific recommendations.'

    if cta:
        prompt += f' Close with this call to action: {cta}'

    return prompt

# Without optional sections
print(build_report_prompt('cloud cost optimization', 'engineering managers', 400))

# With optional sections
print(build_report_prompt(
    topic='cloud cost optimization',
    audience='engineering managers',
    word_count=600,
    include_recommendations=True,
    cta='Book a cost audit with our team at cloudcost.io'
))

列挙型の選択肢変数

テンプレート変数の中には、有効な選択肢を固定された集合に制限すべきものがあります。enum形式の検証でこの制約を適用してください:

VALID_TONES = ['professional', 'casual', 'urgent', 'empathetic', 'enthusiastic']
VALID_FORMATS = ['prose', 'bullets', 'numbered', 'table']

def generate_content(topic, tone, format_style, word_count):
    if tone not in VALID_TONES:
        raise ValueError(f'Invalid tone: {tone}. Choose from: {VALID_TONES}')
    if format_style not in VALID_FORMATS:
        raise ValueError(f'Invalid format: {format_style}. Choose from: {VALID_FORMATS}')

    format_map = {
        'prose': 'continuous paragraphs, no lists',
        'bullets': 'bullet points',
        'numbered': 'numbered list',
        'table': 'a markdown table'
    }

    prompt = (f'Write about {topic} in {tone} tone. '
              f'Format: {format_map[format_style]}. '
              f'Length: {word_count} words. Active voice.')

    return prompt

知識チェック: 穴埋めパターン

次のテンプレートがあるとします: 'Write a {tone} email to {recipient} about {topic}. Length: {word_count} words.'

これを次のように呼び出します: tone='formal', recipient='the team', word_count=100 — ただし、topicパラメーターを忘れています。

何が起こるでしょうか。

まとめ: 穴埋めパターンの作成

穴埋めプロンプトパターンでは、プレースホルダー({{variable}}、{variable}など)を使って、再利用可能なテンプレート内の可変部分を示します。Pythonの.format()とf-stringが、最も一般的な置換メカニズムです。

ベストプラクティスは、レンダリング前に必須のプレースホルダーをすべて検証すること、オプションの変数にはデフォルト値を使うこと、列挙型の変数を制約すること、そしてエッジケースの入力(空の文字列、特殊文字)を防御的に処理することです。

次のレッスンでは、より高度な変数置換のニーズに対応するJinja2とPythonのstring.Templateについて学びます。

無料で開始

AI チューターと学ぶ AI Prompt Engineering — 無料

ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。

コース
53
レッスン
199

よくある質問

「穴埋めパターンを作成する」レッスンは無料ですか?

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

「穴埋めパターンを作成する」で何を学びますか?

Python で {{variable}} プレースホルダーと文字列置換を使います。 ブラウザで直接実行するハンズオンコードで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に戻る