0Pricing
AI Prompt Engineering · レッスン

AI プロンプトにおけるコンテキストとは

背景情報がモデルの応答の方向性をどのように形作るかを学びます。

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

コンテキスト:モデルへの背景説明

コンテキストとは、モデルが関連性と正確性を備え、状況に適した回答を返すための背景情報です。

コンテキストがなければ、モデルはあなたが何者で、何を必要としていて、どの分野で活動し、どの程度の詳しさが適切なのかを推測します。その推測は、あなたの実際の状況ではなく、統計的に最も平均的な解釈に基づきます。

コンテキストがないとどうなるか

同じトピックについて、次の2つの依頼を比較してみましょう:

コンテキストなし:「データベースの問題について、どうすればよいですか?」
モデルには、どのデータベースなのか、問題は何なのか、あなたの状況で「どうすればよい」が何を意味するのかがまったく分かりません。

コンテキストあり:「AWS RDSでPostgreSQL 15を実行しています。昨日スキーマを移行した後、クエリの応答時間が20msから800msに急増しました。移行では3つの新しいインデックスを追加しています。まず何を調査すべきですか?」

2つ目の質問には、分野、技術、時系列、症状、最近行った変更が含まれており、有用な回答に必要な情報がすべてそろっています。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

no_context = 'What should I do about the database issue?'

with_context = (
    'We are running PostgreSQL 15 on AWS RDS. '
    'Query response time spiked from 20ms to 800ms after a schema migration yesterday. '
    'The migration added 3 new indexes on the orders table (500M rows). '
    'No other infrastructure changes were made. '
    'What should I investigate first to diagnose the slowdown?'
)

for label, prompt in [('NO CONTEXT', no_context), ('WITH CONTEXT', with_context)]:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=200,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'--- {label} ---')
    print(response.content[0].text[:300])
    print()

4種類のコンテキスト

すべてのプロンプトは、最大4種類のコンテキストから恩恵を受けられます:

  1. ドメインコンテキスト — 取り組んでいる分野や業界
  2. 対象読者のコンテキスト — 出力を使う人、または読む人
  3. 目的のコンテキスト — 最終的に達成しようとしていること
  4. 制約のコンテキスト — 存在する制限(時間、予算、技術スタック、ルール)

すべてのプロンプトに4種類すべてが必要なわけではありません。しかし、カテゴリーを理解しておくと、不足している情報を特定しやすくなります。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

# Prompt with all 4 context types explicitly labelled
response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Domain context: B2B SaaS, fintech, invoice reconciliation.\n'
            'Audience context: mid-market CFOs with basic Excel skills, no coding.\n'
            'Goal context: write a one-pager that convinces them to book a demo.\n'
            'Constraint context: max 300 words, no technical jargon, no pricing mentioned.\n\n'
            'Task: Write the one-pager.'
        )
    }]
)
print(response.choices[0].message.content)

ドメインコンテキスト

ドメインコンテキストは、扱っている分野、業界、または専門領域をモデルに伝えるものです。語彙、前提とする知識のレベル、関連する考慮事項を設定します。

同じ質問でも、分野が変われば意味はまったく異なります。ソフトウェアエンジニアリングにおける「エラーを適切に処理するにはどうすればよいですか?」は例外処理についての質問ですが、カスタマーサービスでは事態を悪化させないための対応技術、医療ではヒヤリ・ハット報告についての質問になります。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

# Same question, different domain context
domains = [
    ('Software Engineering', 'We build Python microservices.'),
    ('Customer Service', 'We run a 50-agent call center for an e-commerce brand.'),
    ('Surgical Team', 'We are a hospital OR team implementing WHO checklists.'),
]

for domain, context in domains:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=80,
        messages=[{
            'role': 'user',
            'content': f'Context: {context}\n\nQuestion: How do I handle errors gracefully? (1 sentence answer)'
        }]
    )
    print(f'[{domain}]: {response.content[0].text.strip()}')
    print()

対象読者のコンテキスト

対象読者のコンテキストは、出力を読む人、聞く人、または使う人をモデルに伝えるものです。これにより、次の点が決まります。

  • 語彙のレベルと前提とする知識
  • 必要な説明の深さ
  • 語調(フォーマルか会話調か)
  • 使用するたとえ
  • 省く内容(基礎的すぎるもの、または高度すぎるもの)

対象読者によって、すべてが変わります。同じ概念でも、幼稚園児に説明する場合と博士課程の学生に説明する場合では、内容はまったく異なるものになります。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

audiences = [
    'a 10-year-old who loves video games',
    'a first-year computer science university student',
    'a senior software architect with 15 years of experience'
]

for audience in audiences:
    response = client.chat.completions.create(
        model='gpt-4o',
        max_tokens=80,
        messages=[{
            'role': 'user',
            'content': f'Explain recursion in 2 sentences for {audience}.'
        }]
    )
    print(f'Audience: {audience}')
    print(response.choices[0].message.content.strip())
    print()

目標コンテキスト

目標コンテキストは、出力が最終的に何のために使われるのかを説明するものです。これはタスクそのものとは異なり、その先にある目的を指します。

  • タスク:「製品説明を書いてください」
  • 目標:「これはPPCランディングページで、私たちのことをまったく知らない潜在顧客をコンバージョンさせるために使います」

モデルが目標を把握していれば、何を含めるか、どの程度説得力を持たせるか、読者がどのような疑問を持つかについて、より適切な判断ができます。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

goals = [
    'Internal documentation for our own engineering team',
    'A sales one-pager to send cold prospects who know nothing about our product',
    'A support article for existing customers who are confused about the feature'
]

for goal in goals:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=100,
        messages=[{
            'role': 'user',
            'content': (
                f'Goal: {goal}\n\n'
                f'Task: Write 2 sentences about our new AI-powered search feature '
                f'that finds relevant documents from a knowledge base.'
            )
        }]
    )
    print(f'Goal: {goal}')
    print(response.content[0].text.strip())
    print()

制約コンテキスト

制約コンテキストは、出力が従わなければならない制限を説明するものです。

  • 技術:「インターネット接続なしで動作する必要がある」「Python 3.9のみ、サードパーティライブラリは禁止」
  • 予算:「無料プランのみ」「解決策の費用は月額50ドル未満である必要がある」
  • 規制:「HIPAAに準拠」「GDPRが適用されるため、プロンプトにユーザーデータを含めない」
  • 組織:「リリース前に法務部門の承認を得る必要がある」「データベーススキーマは変更できない」

制約コンテキストにより、実際の状況では実現不可能な解決策をモデルが提案するのを防げます。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Suggest 3 ways to cache API responses in a Python backend.\n\n'
            'Constraint context:\n'
            '- Python 3.11, stdlib only (no Redis, no Memcached, no third-party libraries)\n'
            '- The backend is a single process (no distributed cache needed)\n'
            '- Cache must expire after 5 minutes automatically\n'
            '- Solution must work on a server without internet access'
        )
    }]
)
print(response.choices[0].message.content)

コンテキストが不足するとモデルは推測する

ここで重要なメンタルモデルを紹介します。不足しているコンテキストの一つひとつは、モデルがあなたに代わって下す判断です。しかも、モデルはそのことを伝えません。

ドメインが不足 → モデルはその話題で最も一般的なドメインを選ぶ
対象読者が不足 → モデルは最も一般的な読者向けに書く
目標が不足 → モデルは最も明白な目標を選ぶ
制約が不足 → モデルはすべての制限を無視する

このような無言の選択があるため、技術的には正しいものの、自分の状況には合っていないと感じる回答がよく返ってきます。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

# Demonstrate: same question, very different useful answers with context
without_context = 'How should I structure my data?'

with_full_context = (
    'Domain: mobile gaming backend, 10M daily active users.\n'
    'Technology: Python FastAPI + PostgreSQL + Redis.\n'
    'Goal: store player inventory items (weapon skins, power-ups) with fast reads.\n'
    'Constraint: reads happen 50x more than writes; schema changes are expensive.\n\n'
    'How should I structure my data? Give 2 options with tradeoffs.'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=300,
    messages=[{'role': 'user', 'content': with_full_context}]
)
print(response.content[0].text)

各コンテキストタイプが特に重要になる場面

すべてのプロンプトに4種類すべてのコンテキストが必要なわけではありません。ただし、特定のタスクカテゴリでは、特定のコンテキストが特に役立ちます。

  • 技術的なタスク:ドメインコンテキストと制約コンテキストが最も重要です
  • 文章作成タスク:対象読者のコンテキストと目標コンテキストによって改善効果が最も大きくなります
  • 説明:対象読者のコンテキストだけでも、出力品質を大きく変えられます
  • 意思決定支援:制約コンテキストによって役に立たない提案を防げます
  • クリエイティブなタスク:目標コンテキストとドメインコンテキストによって、適切な創作の枠組みが決まります
import openai

client = openai.OpenAI(api_key='sk-your-key-here')

# Context selection for a creative task
response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': (
            'Domain: luxury skincare brand (eco-conscious, premium, women 35-55).\n'
            'Goal: Valentine\'s Day campaign headline — will run on Instagram and in email.\n'
            'Constraint: must not mention price, discount, or sale. Max 8 words.\n\n'
            'Generate 5 headline options.'
        )
    }]
)
print(response.choices[0].message.content)

コンテキストとプロンプト汚染

コンテキストは多ければよいとは限りません。無関係なコンテキストはプロンプトを汚染し、モデルを混乱させて、話題から外れた回答につながる可能性があります。

整理されたコンテキストにするためのルール:

  • 出力に直接影響する情報だけを含める
  • 2文の要約で済む場合に、文書全体を貼り付けない
  • 互いに矛盾するコンテキストを削除する
  • 関連性があるか迷う場合は、いったん省き、出力の質が下がった場合にだけ追加する
import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

# Polluted context (too much irrelevant info)
polluted = (
    'I started my company in 2019. We have 12 employees. We use Slack. '
    'Our office is in Berlin. We had a good Q3. Our CEO is named Thomas. '
    'We have a dog-friendly office. We use Python for our backend. '
    'Last year we moved to a new CRM. We sponsor a local football team.\n\n'
    'Write a 2-sentence company bio for our website.'
)

# Clean context (only relevant info)
clean = (
    'Company: B2B SaaS, Berlin, founded 2019, 12 employees. '
    'Product: Python-based CRM for mid-market sales teams.\n\n'
    'Write a 2-sentence company bio for our website.'
)

for label, prompt in [('POLLUTED', polluted), ('CLEAN', clean)]:
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=100,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'--- {label} ---')
    print(response.content[0].text.strip())
    print()

標準的な実践としてのコンテキスト

最も効果的なプロンプト作成者は、すべてのタスク指示の前に置く標準テンプレートのセクションとしてコンテキストを扱います。

シンプルなテンプレート:

Context: [domain, technology, role, situation]
Audience: [who reads/uses the output]
Goal: [what this will accomplish]
Constraints: [what must/must not be included]
Task: [the actual instruction]

すべてのプロンプトを作成する前にこのテンプレートを埋めるのにかかる時間は30秒です。それだけで、何時間も書き直す事態を防げます。

# Standard context template implementation
def build_prompt(context, audience, goal, constraints, task):
    sections = []
    if context:     sections.append(f'Context: {context}')
    if audience:    sections.append(f'Audience: {audience}')
    if goal:        sections.append(f'Goal: {goal}')
    if constraints: sections.append(f'Constraints: {constraints}')
    sections.append(f'Task: {task}')
    return '\n'.join(sections)

prompt = build_prompt(
    context='Python open-source project, MIT license, 2,000 GitHub stars',
    audience='New contributors who know Python but are unfamiliar with our codebase',
    goal='Help them submit their first pull request within 30 minutes of reading',
    constraints='Max 400 words. No command-line flags beyond git basics. No Docker.',
    task='Write a Getting Started contributing guide.'
)
print(prompt)

理解度チェック

ある開発者がAIに「クエリの最適化を手伝ってください」と尋ねました。AIは、その開発者の環境には当てはまらない、一般的なSQL最適化のヒントを返しました。最も重要なものとして不足しているコンテキストの種類は何でしょうか。

AIプロンプトにおけるコンテキスト — まとめ

コンテキストとは、一般的な回答ではなく、役に立つ的を絞った回答を返すためにモデルが必要とする背景情報です。4種類は次のとおりです。

  • ドメインコンテキスト:分野、業界、技術スタック
  • 対象読者のコンテキスト:誰が出力を読むのか、その背景と専門知識
  • 目標コンテキスト:出力が最終的に何のために使われるのか
  • 制約コンテキスト:どのような制限を守る必要があるのか

不足しているコンテキスト要素の一つひとつは、モデルがあなたに代わって無言で下す判断です。重要なプロンプトを作成する前に、コンテキストテンプレートを使って必要な情報を体系的に含めるようにしましょう。

よくある質問

「AI プロンプトにおけるコンテキストとは」レッスンは無料ですか?

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

「AI プロンプトにおけるコンテキストとは」で何を学びますか?

背景情報がモデルの応答の方向性をどのように形作るかを学びます。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

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

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

「AI プロンプトにおけるコンテキストとは」レッスンにはどのくらい時間がかかりますか?

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

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

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

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

  1. AI プロンプトにおけるコンテキストとは
  2. 背景情報を提供する
  3. 効果的に状況を設定する
  4. コンテキストの長さと関連性
← AI Prompt Engineeringに戻る