맥락의 길이와 관련성
포괄적인 맥락과 토큰 한도 및 관련성 사이의 균형을 맞춥니다.
맥락의 길이와 관련성은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
context 창 예산
모든 모델에는 하나의 API 호출에서 처리할 수 있는 전체 토큰 수인 최대 context 창이 있습니다. 여기에는 입력(사용자의 프롬프트와 기록)과 출력(모델의 응답)이 모두 포함됩니다.
이 예산을 이해하는 것은 매우 중요합니다. 예산을 초과하면 프롬프트가 잘리거나 출력이 손실됩니다. 관련 없는 context에 예산을 낭비하면 모델이 중요한 내용을 추론할 여지가 줄어듭니다.
context 창 크기
모델마다 context 제한이 다릅니다. 2025년 기준으로는 다음과 같습니다.
- GPT-4o: 128,000토큰
- 클로드 오푸스 4.5: 200,000토큰
- 제미나이 1.5 프로: 1,000,000토큰
- GPT-3.5 터보: 16,385토큰
창이 클수록 더 많은 context를 포함할 수 있지만 호출당 비용도 증가합니다. 대부분의 작업에는 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')포함할 내용: 관련성 점수 매기기
context의 어떤 부분이든 포함하기 전에 다음과 같이 자문하십시오. 이 정보가 답변을 바꾸는가?
간단한 판단 기준으로 각 context 요소에 점수를 매기십시오.
- 높은 관련성(포함): 작업에 직접 영향을 주거나, 어휘를 결정하거나, 선택지를 제한합니다.
- 중간 관련성(상황에 따라 포함): 유용한 맥락을 제공하지만 없어도 출력은 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}')중간 정보 손실 문제
연구에 따르면 LLM은 매우 긴 프롬프트의 중간에 배치된 정보에 덜 주의를 기울입니다. 50,000토큰 프롬프트의 중간에 배치된 중요한 context는 일부 무시될 수 있습니다.
권장 방법은 가장 중요한 context를 프롬프트의 시작이나 끝에 배치하는 것입니다. 모델은 이 위치에 가장 강하게 주의를 기울입니다.
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)긴 문서 나누기
토큰 예산보다 긴 문서를 다뤄야 할 때는 세 가지 방법이 있습니다.
- 먼저 요약하기: 모델에 문서를 압축하도록 요청한 다음 요약본으로 작업합니다.
- 나누어 처리하기: 문서를 여러 부분으로 나누고 각각 처리한 뒤 결과를 결합합니다.
- 추출하여 삽입하기: 프롬프트에 포함하기 전에 관련된 부분만 추출합니다.
context 창을 초과하는 문서를 억지로 넣지 마십시오. 문서가 조용히 잘립니다.
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개의 메시지만 중요한 이메일 대화
- 50개 테이블 중 2개만 관련된 데이터베이스 스키마
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번의 발화만 유지합니다.
- 요약 삽입: 이전 발화를 주기적으로 하나의 메시지로 요약합니다.
- 핵심 사실 추출: 중요한 결정을 글머리 기호 목록으로 추적하고 시스템 context로 삽입합니다.
- 주제가 바뀌면 초기화: 관련 없는 주제로 전환할 때 새 세션을 시작합니다.
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)context 압축 기법
많은 context를 포함해야 하지만 토큰 예산이 빠듯할 때는 압축 기법을 사용하십시오.
- 설명문보다 글머리 기호: 글머리 기호 목록은 문장보다 토큰 효율이 30~50% 높습니다.
- 알려진 용어 줄이기: 처음 사용한 뒤 ‘PostgreSQL 15’를 ‘PG15’로 줄여 쓸 수 있습니다.
- 군더더기 표현 제거: ‘주목할 만한 점은…’이라고 쓰는 대신 사실만 바로 제시하십시오.
- 구조화된 형식 사용: key:value 쌍은 문장보다 더 조밀합니다.
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')동적 context 선택
운영 환경의 AI 애플리케이션에서는 현재 질문과 가장 관련성이 높은 내용을 기준으로 context를 동적으로 선택하는 경우가 많습니다. 이를 검색 증강 생성(RAG)이라고 합니다.
모든 문서를 포함하는 대신 사용자의 질문과 의미적으로 가장 유사한 문서만 검색하여 프롬프트에 삽입합니다. 이렇게 하면 context를 간결하고 매우 관련성 높게 유지할 수 있습니다.
# 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())context 예산 계획하기
운영 환경의 애플리케이션을 만들 때는 구축하기 전에 context 예산을 명시적으로 계획하십시오.
- 출력을 위해 context 창의 25%를 남겨 두십시오.
- 시스템 메시지와 페르소나에 10%를 할당하십시오.
- 가장 최근의 대화 기록에 30%를 할당하십시오.
- 동적 context(검색된 문서와 삽입된 데이터)에 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토큰의 context가 관련성이 낮은 5,000토큰의 context보다 더 나은 결과를 냅니다. 모델이 헤쳐 나가야 할 내용이 적을수록 더 나은 출력을 생성합니다.
context가 지나치게 길고 초점이 흐려졌다는 신호는 다음과 같습니다.
- 모델이 사용자의 제약 조건 중 일부를 무시합니다.
- context가 긴데도 출력이 일반적으로 느껴집니다.
- 모델이 질문의 잘못된 부분을 다룹니다.
- 지연 시간과 비용이 예상보다 높습니다.
이러한 신호가 보이면 context를 줄이고 다시 실행하십시오.
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번의 발화가 지나자 context 창이 가득 차고 있습니다. 중요한 context를 잃지 않고 대화를 계속하려면 어떤 전략이 BEST입니까?
context 길이와 관련성 — 복습
context를 효과적으로 관리하는 것은 핵심적인 프롬프트 작성 기술이며, 운영 환경의 애플리케이션에서는 더욱 중요해집니다. 핵심 원칙은 다음과 같습니다.
- 모든 context 요소에 관련성 점수를 매기십시오. 높음 / 중간 / 낮음 중 높은 관련성만 포함하십시오.
- 중요한 제약 조건은 중간이 아니라 시작이나 끝에 배치하십시오.
- 토큰을 30~50% 절약할 수 있도록 설명문보다 글머리 기호 형식을 사용하십시오.
- 예산을 초과하는 문서는 요약하거나 나누십시오.
- 여러 차례 주고받는 대화에서는 처음부터 다시 시작하기보다 오래된 기록을 압축하십시오.
- context 예산을 코드의 상수로 명시적으로 계획하십시오.
자주 묻는 질문
“맥락의 길이와 관련성” 강의는 무료인가요?
네 — “맥락의 길이와 관련성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
“맥락의 길이와 관련성”에서 뭘 배우나요?
포괄적인 맥락과 토큰 한도 및 관련성 사이의 균형을 맞춥니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“맥락의 길이와 관련성” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 인공지능 프롬프트에서 맥락이란 무엇인가
- 배경 정보 제공하기
- 상황 효과적으로 설정하기
- 맥락의 길이와 관련성