0Pricing
AI Prompt Engineering · บทเรียน

ความยาวและความเกี่ยวข้องของบริบท

สร้างสมดุลระหว่างบริบทที่ครอบคลุม ขีดจำกัดของโทเคน และความเกี่ยวข้อง

ความยาวและความเกี่ยวข้องของบริบท เป็นบทเรียน AI Prompt Engineering ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Prompt Engineering และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน

งบประมาณหน้าต่างบริบท

โมเดลทุกตัวมีหน้าต่างบริบทสูงสุด ซึ่งหมายถึงจำนวนโทเคนทั้งหมดที่สามารถประมวลผลได้ในการเรียกใช้ส่วนต่อประสานโปรแกรมหนึ่งครั้ง ซึ่งรวมทั้งข้อมูลเข้า (พรอมต์ของคุณและประวัติการสนทนา) และข้อมูลออก (คำตอบของโมเดล)

การเข้าใจงบประมาณนี้เป็นเรื่องสำคัญอย่างยิ่ง เพราะหากใช้เกินขีดจำกัด พรอมต์ของคุณอาจถูกตัดทอนหรือผลลัพธ์อาจสูญหาย การใช้พื้นที่กับบริบทที่ไม่เกี่ยวข้องอย่างสิ้นเปลืองยังทำให้โมเดลเหลือพื้นที่น้อยลงสำหรับใช้เหตุผลกับสิ่งที่สำคัญ

ขนาดหน้าต่างบริบท

โมเดลแต่ละตัวมีขีดจำกัดบริบทแตกต่างกัน ณ ปี 2025:

  • GPT-4o: 128,000 โทเคน
  • โคลด โอปุส 4.5: 200,000 โทเคน
  • เจมินี 1.5 โปร: 1,000,000 โทเคน
  • GPT-3.5 เทอร์โบ: 16,385 โทเคน

หน้าต่างที่ใหญ่ขึ้นทำให้ใส่บริบทได้มากขึ้น แต่มีค่าใช้จ่ายต่อการเรียกใช้สูงขึ้น สำหรับงานส่วนใหญ่ 8,000-16,000 โทเคนก็เพียงพอ หน้าต่างที่ใหญ่กว่าไม่ได้ดีกว่าเสมอไป หากต้องใส่เนื้อหาที่ไม่เกี่ยวข้องเข้าไปด้วย

import tiktoken

def estimate_tokens(text, model='gpt-4o'):
    encoding = tiktoken.encoding_for_model(model)
    return len(encoding.encode(text))

# Quick token budget calculator
models = {
    'GPT-3.5 Turbo':  16385,
    'GPT-4o':        128000,
    'Claude Opus 4.5': 200000,
}

prompt = 'Explain the concept of technical debt in 500 words for a non-technical CEO.'
prompt_tokens = estimate_tokens(prompt)

for model_name, limit in models.items():
    reserved_for_output = 1024
    available = limit - prompt_tokens - reserved_for_output
    print(f'{model_name}: limit={limit:,} | prompt={prompt_tokens} | '
          f'context budget={available:,} tokens')

สิ่งที่ควรใส่: การให้คะแนนความเกี่ยวข้อง

ก่อนใส่บริบทส่วนใดก็ตาม ให้ถามว่า ข้อมูลส่วนนี้เปลี่ยนคำตอบหรือไม่

กรอบคิดง่าย ๆ คือให้คะแนนองค์ประกอบของบริบทแต่ละส่วน:

  • เกี่ยวข้องสูง (ใส่): ส่งผลโดยตรงต่องาน กำหนดคำศัพท์ หรือจำกัดตัวเลือก
  • เกี่ยวข้องปานกลาง (อาจใส่): ให้รายละเอียดประกอบที่เป็นประโยชน์ แต่ผลลัพธ์ก็ยังใช้ได้ OK หากไม่มีข้อมูลนี้
  • เกี่ยวข้องต่ำ (ไม่ต้องใส่): เป็นความจริง แต่ไม่ส่งผลต่อคำตอบแต่อย่างใด
def score_context_element(element, task):
    '''
    Heuristic: does this context element directly constrain or shape the answer?
    Returns: HIGH / MEDIUM / LOW
    '''
    high_signals = ['stack', 'constraint', 'deadline', 'must', 'cannot', 'budget',
                    'audience', 'goal', 'version', 'scale', 'limit']
    low_signals  = ['founded', 'headquartered', 'fun fact', 'history', 'awards',
                    'team building', 'company culture', 'office location']

    el_lower = element.lower()
    if any(s in el_lower for s in high_signals):
        return 'HIGH'
    if any(s in el_lower for s in low_signals):
        return 'LOW'
    return 'MEDIUM'

context_elements = [
    'Our stack is Python FastAPI and PostgreSQL',
    'We cannot use any paid third-party APIs',
    'Our company was founded in Berlin in 2020',
    'We need the solution to handle 1000 requests/second',
    'We won a startup award last year',
]

for el in context_elements:
    score = score_context_element(el, task='optimize our API')
    print(f'[{score:6}] {el}')

ปัญหาข้อมูลช่วงกลางถูกละเลย

งานวิจัยแสดงให้เห็นว่าโมเดลภาษาขนาดใหญ่ให้ความสนใจกับข้อมูลที่อยู่ในช่วงกลางของพรอมต์ที่ยาวมากน้อยลง บริบทสำคัญที่อยู่กลางพรอมต์ขนาด 50,000 โทเคนอาจถูกละเลยไปบางส่วน

แนวทางที่ดีที่สุดคือวางบริบทที่สำคัญที่สุดไว้ที่ต้นหรือท้ายพรอมต์ เพราะโมเดลจะให้ความสนใจกับตำแหน่งเหล่านี้มากที่สุด

import anthropic

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

# Structure: critical constraint at the TOP, then the body, then the task
well_structured_prompt = (
    # Critical constraint FIRST
    'CRITICAL CONSTRAINT: Output must be under 50 words and contain no code.\n\n'
    # Background in the middle
    'Background: we are explaining our API rate limiting policy to non-technical support agents. '
    'They handle billing inquiries and need to explain errors to customers. '
    'Our rate limit is 100 requests per minute per API key.\n\n'
    # Task at the end
    'Task: Write the explanation.'
)

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

การแบ่งเอกสารยาวเป็นส่วน

เมื่อคุณต้องทำงานกับเอกสารที่ยาวเกินงบประมาณโทเคนของคุณ มีสามทางเลือก:

  • สรุปก่อน: ขอให้โมเดลย่อเอกสาร แล้วทำงานกับบทสรุป
  • แบ่งเป็นส่วนแล้วประมวลผล: แบ่งเอกสารเป็นส่วน ๆ ประมวลผลแต่ละส่วน แล้วรวมผลลัพธ์
  • ดึงข้อมูลแล้วใส่เข้าไป: ดึงเฉพาะส่วนที่เกี่ยวข้องก่อนใส่ลงในพรอมต์

อย่าพยายามฝืนใส่เอกสารที่เกินหน้าต่างบริบท เพราะเอกสารจะถูกตัดทอนโดยไม่มีการแจ้งเตือน

import anthropic

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

def chunk_and_summarize(long_text, chunk_size=2000):
    '''Split text into chunks, summarize each, combine summaries.'''
    words = long_text.split()
    chunks = []
    for i in range(0, len(words), chunk_size):
        chunk = ' '.join(words[i:i + chunk_size])
        chunks.append(chunk)

    summaries = []
    for idx, chunk in enumerate(chunks):
        response = client.messages.create(
            model='claude-opus-4-5',
            max_tokens=256,
            messages=[{
                'role': 'user',
                'content': f'Summarize this section in 3 bullet points:\n\n{chunk}'
            }]
        )
        summaries.append(f'Section {idx+1}:\n{response.content[0].text}')

    return '\n\n'.join(summaries)

# Example usage
long_doc = 'word ' * 5000  # placeholder for a real document
print('Chunks needed:', len(long_doc.split()) // 2000 + 1)

การกรองความเกี่ยวข้องในการใช้งานจริง

การกรองความเกี่ยวข้องหมายถึงการดึงเฉพาะส่วนที่เกี่ยวข้องจากเอกสารขนาดใหญ่ก่อนใส่ลงในพรอมต์ ซึ่งสำคัญเป็นพิเศษสำหรับ:

  • รายงานยาวที่มีเพียงส่วนเดียวเกี่ยวข้อง
  • ไฟล์โค้ดที่มีเพียงฟังก์ชันเดียวต้องได้รับการตรวจสอบ
  • ชุดข้อความอีเมลที่มีเพียง 3 ข้อความล่าสุดเท่านั้นที่สำคัญ
  • โครงสร้างฐานข้อมูลที่มีเพียง 2 จาก 50 ตารางที่เกี่ยวข้อง
import openai

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

# Step 1: Filter first, then ask
full_schema = (
    'Table: users (id, name, email, created_at, role)\n'
    'Table: products (id, name, price, stock, category_id)\n'
    'Table: orders (id, user_id, total, status, created_at)\n'
    'Table: order_items (id, order_id, product_id, quantity, unit_price)\n'
    'Table: categories (id, name, parent_id)\n'
    'Table: reviews (id, product_id, user_id, rating, body)\n'
    'Table: sessions (id, user_id, token, expires_at)'
)

# Only include relevant tables for the specific question
relevant_context = (
    'Relevant tables for this query:\n'
    'Table: orders (id, user_id, total, status, created_at)\n'
    'Table: order_items (id, order_id, product_id, quantity, unit_price)\n'
)

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{
        'role': 'user',
        'content': f'{relevant_context}\nWrite SQL to find the top 5 orders by total value this month.'
    }]
)
print(response.choices[0].message.content)

การจัดการประวัติการสนทนา

ในการสนทนาหลายรอบ ประวัติจะเพิ่มขึ้นในทุกรอบ การจัดการอย่างชาญฉลาดช่วยให้งบประมาณโทเคนยังอยู่ในระดับเหมาะสม:

  • หน้าต่างเลื่อน: เก็บไว้เฉพาะการสนทนา N รอบล่าสุด
  • การใส่บทสรุป: สรุปรอบเก่า ๆ เป็นระยะให้เหลือข้อความเดียว
  • การดึงข้อเท็จจริงสำคัญ: ติดตามการตัดสินใจสำคัญเป็นรายการหัวข้อย่อย แล้วใส่เป็นบริบทระบบ
  • เริ่มใหม่เมื่อเปลี่ยนหัวข้อ: เริ่มช่วงการสนทนาใหม่เมื่อเปลี่ยนไปยังหัวข้อที่ไม่เกี่ยวข้อง
import openai

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

def summarize_history(old_history):
    '''Compress old conversation turns into a brief summary.'''
    history_text = '\n'.join(
        f'{m["role"].upper()}: {m["content"]}' for m in old_history
    )
    response = client.chat.completions.create(
        model='gpt-4o',
        max_tokens=200,
        messages=[{
            'role': 'user',
            'content': (
                'Summarize this conversation history in 3 bullet points. '
                'Focus on decisions made and key information established.\n\n'
                + history_text
            )
        }]
    )
    return response.choices[0].message.content

# Example: compressing old history before continuing
old_turns = [
    {'role': 'user',      'content': 'We are building a Kanban app.'},
    {'role': 'assistant', 'content': 'Great, what is your stack?'},
    {'role': 'user',      'content': 'React + FastAPI + PostgreSQL.'},
    {'role': 'assistant', 'content': 'Good choice for a Kanban app.'}
]
summary = summarize_history(old_turns)
print('Summary of old history:', summary)

เทคนิคการบีบอัดบริบท

เมื่อจำเป็นต้องใส่บริบทจำนวนมากแต่มีงบประมาณโทเคนจำกัด ให้ใช้เทคนิคการบีบอัด:

  • ใช้หัวข้อย่อยแทนร้อยแก้ว: รายการหัวข้อย่อยใช้โทเคนอย่างมีประสิทธิภาพมากกว่าประโยค 30-50%
  • ย่อคำศัพท์ที่รู้จัก: ใช้ “PostgreSQL 15” → “พีจี15” หลังจากกล่าวถึงครั้งแรก
  • ตัดวลีเติมแต่ง: เปลี่ยน “ควรสังเกตว่า...” เป็นการกล่าวข้อเท็จจริงโดยตรง
  • ใช้รูปแบบที่มีโครงสร้าง: คู่ชื่อ:ค่าแน่นกว่าประโยค
import tiktoken

def count_tokens(text):
    enc = tiktoken.encoding_for_model('gpt-4o')
    return len(enc.encode(text))

# Same information, different token counts
prose_context = (
    'Our company is a startup that was founded recently and we are building '
    'a data analytics platform. It is worth noting that we use Python for our backend. '
    'Additionally, we have chosen PostgreSQL as our primary database. '
    'Furthermore, we deploy on AWS using ECS containers.'
)

bullet_context = (
    'Company: data analytics startup\n'
    'Stack: Python backend, PostgreSQL, AWS ECS'
)

print('Prose context tokens: ', count_tokens(prose_context))
print('Bullet context tokens:', count_tokens(bullet_context))
print('Tokens saved:', count_tokens(prose_context) - count_tokens(bullet_context))
print('Same information? Yes — same facts, 60% fewer tokens')

การเลือกบริบทแบบปรับตามสถานการณ์

ในแอปพลิเคชันปัญญาประดิษฐ์สำหรับใช้งานจริง มักเลือกบริบทแบบปรับตามสถานการณ์โดยพิจารณาจากสิ่งที่เกี่ยวข้องกับคำถามปัจจุบันมากที่สุด กระบวนการนี้เรียกว่า การสร้างเนื้อหาเสริมด้วยการค้นคืน (RAG)

แทนที่จะใส่เอกสารทั้งหมด คุณจะค้นคืนเฉพาะเอกสารที่มีความหมายใกล้เคียงกับคำถามของผู้ใช้มากที่สุด แล้วใส่เอกสารเหล่านั้นลงในพรอมต์ วิธีนี้ช่วยให้บริบทกระชับและเกี่ยวข้องอย่างยิ่ง

# Simplified RAG pattern: retrieve relevant chunks, inject into prompt
import openai

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

# Simulated knowledge base (in production: vector database)
knowledge_base = [
    {'id': 1, 'topic': 'billing',   'text': 'Refunds are processed within 5-7 business days.'},
    {'id': 2, 'topic': 'shipping',  'text': 'Standard shipping takes 3-5 days.'},
    {'id': 3, 'topic': 'returns',   'text': 'Returns accepted within 30 days with receipt.'},
    {'id': 4, 'topic': 'warranty',  'text': 'All products come with a 1-year warranty.'},
]

def get_relevant_docs(user_query, kb, top_k=2):
    '''Simplified relevance: keyword match. Production uses embeddings.'''
    scored = [(doc, sum(w in user_query.lower() for w in doc['topic'].split())) for doc in kb]
    scored.sort(key=lambda x: x[1], reverse=True)
    return [doc['text'] for doc, _ in scored[:top_k]]

query = 'Can I return this and get my money back?'
relevant = get_relevant_docs(query, knowledge_base)
context = '\n'.join(relevant)
print('Injected context:', context)
response = client.chat.completions.create(
    model='gpt-4o', max_tokens=80,
    messages=[{'role': 'user', 'content': f'Context:\n{context}\n\nQuestion: {query}'}]
)
print('Answer:', response.choices[0].message.content.strip())

การวางแผนงบประมาณบริบท

สำหรับแอปพลิเคชันที่ใช้งานจริง ให้กำหนดงบประมาณบริบทอย่างชัดเจนก่อนเริ่มสร้าง:

  • สำรอง 25% ของหน้าต่างบริบทไว้สำหรับผลลัพธ์
  • จัดสรร 10% สำหรับข้อความระบบและบุคลิก
  • จัดสรร 30% สำหรับประวัติการสนทนาล่าสุด
  • เหลือ 35% สำหรับบริบทแบบปรับตามสถานการณ์ (เอกสารที่ค้นคืนและข้อมูลที่ใส่เพิ่ม)

บันทึกการจัดสรรเหล่านี้เป็นค่าคงที่ในโค้ด เพื่อให้ปรับได้ง่ายเมื่อกรณีใช้งานของคุณเปลี่ยนแปลง

# Context budget planner
MODEL_LIMIT = 128000  # GPT-4o

BUDGET = {
    'output_reserve':  int(MODEL_LIMIT * 0.25),  # 32,000 tokens
    'system_message':  int(MODEL_LIMIT * 0.05),  # 6,400 tokens
    'recent_history':  int(MODEL_LIMIT * 0.30),  # 38,400 tokens
    'dynamic_context': int(MODEL_LIMIT * 0.35),  # 44,800 tokens
    'task_prompt':     int(MODEL_LIMIT * 0.05),  # 6,400 tokens
}

total_input = sum(v for k, v in BUDGET.items() if k != 'output_reserve')
print('Context budget plan:')
for key, tokens in BUDGET.items():
    pct = round(tokens / MODEL_LIMIT * 100)
    print(f'  {key:<20}: {tokens:>7,} tokens ({pct}%)')
print(f'  {"total input":<20}: {total_input:>7,} tokens')
print(f'  {"+ output reserve":<20}: {BUDGET["output_reserve"]:>7,} tokens')
print(f'  {"= model limit":<20}: {MODEL_LIMIT:>7,} tokens')

เมื่อความเกี่ยวข้องสำคัญกว่าความยาว

บริบทที่เกี่ยวข้องอย่างยิ่งขนาด 500 โทเคนให้ผลดีกว่าบริบทขนาด 5,000 โทเคนที่เกี่ยวข้องอย่างหลวม ๆ โมเดลจะสร้างผลลัพธ์ได้ดีกว่าเมื่อมีเนื้อหาให้ต้องค้นหาผ่านน้อยลง

สัญญาณที่บ่งบอกว่าบริบทของคุณยาวเกินไปและไม่มีจุดเน้น:

  • โมเดลละเลยข้อจำกัดบางอย่างของคุณ
  • ผลลัพธ์ดูเป็นคำตอบทั่วไปแม้จะมีบริบทยาว
  • โมเดลตอบผิดส่วนของคำถาม
  • เวลาแฝงและค่าใช้จ่ายสูงกว่าที่คาดไว้

เมื่อพบสัญญาณเหล่านี้ ให้ตัดบริบทแล้วเรียกใช้งานอีกครั้ง

import anthropic

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

# Demonstrating: lean context produces sharper output
lean_context = (
    'Task: write a 50-word product tagline.\n'
    'Product: CLI tool that auto-generates Git commit messages from your diff.\n'
    'Audience: senior developers who hate writing commit messages.\n'
    'Tone: dry, witty, technical.'
)

response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=100,
    messages=[{'role': 'user', 'content': lean_context}]
)
print('Lean context output:')
print(response.content[0].text.strip())

ตรวจสอบความรู้

นักพัฒนากำลังสร้างแชตบอตที่มีประวัติการสนทนา 20 รอบ หลังจากสนทนาไป 20 รอบ หน้าต่างบริบทใกล้เต็มแล้ว กลยุทธ์ใดคือ BEST สำหรับสนทนาต่อโดยไม่สูญเสียบริบทสำคัญ

ความยาวและความเกี่ยวข้องของบริบท — ทบทวน

การจัดการบริบทอย่างมีประสิทธิภาพเป็นทักษะหลักในการเขียนพรอมต์ และจะยิ่งสำคัญอย่างยิ่งในแอปพลิเคชันที่ใช้งานจริง หลักการสำคัญมีดังนี้:

  • ให้คะแนนองค์ประกอบบริบททุกส่วนตามระดับสูง / ปานกลาง / ต่ำของความเกี่ยวข้อง — ใส่เฉพาะส่วนที่เกี่ยวข้องสูง
  • วางข้อจำกัดสำคัญไว้ที่ต้นหรือท้าย ไม่ใช่ตรงกลาง
  • ใช้รูปแบบหัวข้อย่อยแทนร้อยแก้วเพื่อประหยัดโทเคน 30-50%
  • สรุปหรือแบ่งเป็นส่วนเอกสารที่เกินงบประมาณ
  • ในการสนทนาหลายรอบ ให้บีบอัดประวัติเก่าแทนการเริ่มต้นใหม่
  • วางแผนงบประมาณบริบทอย่างชัดเจนในรูปค่าคงที่ของโค้ด

คำถามที่พบบ่อย

บทเรียน “ความยาวและความเกี่ยวข้องของบริบท” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ความยาวและความเกี่ยวข้องของบริบท” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Prompt Engineering ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ความยาวและความเกี่ยวข้องของบริบท”

สร้างสมดุลระหว่างบริบทที่ครอบคลุม ขีดจำกัดของโทเคน และความเกี่ยวข้อง คุณปฏิบัติ AI Prompt Engineering ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Prompt Engineering หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Prompt Engineering บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “ความยาวและความเกี่ยวข้องของบริบท” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Prompt Engineering นี้ได้ไหม

ได้ บทเรียน AI Prompt Engineering ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. บริบทในการเขียนพรอมต์ให้ปัญญาประดิษฐ์หมายถึงอะไร
  2. การให้ข้อมูลพื้นฐาน
  3. การกำหนดฉากอย่างมีประสิทธิภาพ
  4. ความยาวและความเกี่ยวข้องของบริบท
← กลับไปที่ AI Prompt Engineering