LLM 프롬프트 엔지니어링 실전 — 개발자를 위한 패턴 모음
같은 모델에 프롬프트만 바꿔도 품질이 천지차이다. 내가 1년 동안 실험해서 얻은 패턴들을 모았다. 이 패턴들을 마스터하면, LLM을 훨씬 효율적으로 사용할 수 있다.
System Prompt 디자인
System prompt는 모든 대화의 기초다. 여기서 모델의 성격과 행동을 정의한다.
기본 패턴
You are an expert software engineer with 20 years of experience.
Your specialty is backend systems and performance optimization.
You should:
1. Provide detailed, practical solutions
2. Include code examples whenever relevant
3. Explain trade-offs and alternatives
4. Consider security and performance
You should NOT:
1. Make assumptions about the user's environment
2. Provide copy-paste solutions without explanation
3. Recommend tools without justification
역할 기반 프롬프트
You are a code reviewer. Your job is to:
1. Identify bugs and edge cases
2. Suggest performance improvements
3. Recommend best practices
4. Point out security issues
Format your response as:
- Critical Issues: [list of critical problems]
- Improvements: [list of non-critical improvements]
- Best Practices: [relevant best practices]
Few-Shot 학습
모델이 원하는 형식을 예제로 보여주면, 정확성이 크게 높아진다.
You are a code analyzer. Extract variables, functions, and their purposes.
Format:
VARIABLE: name, type, purpose
FUNCTION: name, parameters, return type, purpose
Examples:
Code: "let user = { name: 'John', age: 30 }; function getName(u) { return u.name; }"
VARIABLE: user, object, stores user data
VARIABLE: name, string, user's name
VARIABLE: age, number, user's age
FUNCTION: getName, parameters: u, return type: string, purpose: retrieves user's name
---
Now analyze this code:
[USER CODE]
정확성이 95% 이상으로 올라간다.
Chain-of-Thought 프롬프팅
복잡한 문제는 단계별로 생각하도록 지시한다.
You are solving a technical problem. Think step by step.
Format:
1. Understanding: [understand the problem]
2. Analysis: [analyze the problem]
3. Solution: [provide solution]
4. Verification: [verify the solution works]
Problem: How would you optimize a database query that's taking 10 seconds?
Please think through each step.
이렇게 하면 모델이 성급한 결론을 내리지 않고, 더 깊이 있는 답변을 제공한다.
구조화된 출력 (JSON Mode)
프로그래밍 처리를 위해 JSON 형식으로 출력하도록 지시한다.
Respond in valid JSON format only.
You are analyzing a GitHub issue. Extract:
- title: the issue title
- description: brief description
- priority: "critical", "high", "medium", or "low"
- category: "bug", "feature", or "improvement"
- estimated_effort: number of hours (1-40)
Issue: [ISSUE TEXT]
Respond with:
{
"title": "...",
"description": "...",
"priority": "...",
"category": "...",
"estimated_effort": ...
}
Claude와 GPT-4는 json_schema를 지원하므로, 더 정확한 구조를 강제할 수 있다.
from anthropic import Anthropic
client = Anthropic()
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Extract issue information from: [ISSUE TEXT]"
}
],
system="You are analyzing GitHub issues. Return JSON with keys: title, description, priority, category, estimated_effort"
)
Temperature와 Top-P 튜닝
모델의 창의성 수준을 조절할 수 있다.
| 온도 | 용도 | 예제 |
|---|---|---|
| 0.0 | 정확성 중시 | 코드 생성, 사실 답변 |
| 0.5 | 균형잡힘 | 대부분의 작업 |
| 1.0 | 창의성 | 아이디어 생성, 스토리텔링 |
| 1.5+ | 고창의성 | 창작, 실험적 작업 |
# 정확한 코드 생성
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
temperature=0, # 가장 높은 확률의 응답만
messages=[{"role": "user", "content": "Write a Node.js Express server"}]
)
# 창의적인 아이디어
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
temperature=1.0, # 다양한 선택지 고려
messages=[{"role": "user", "content": "What are innovative features for a blogging platform?"}]
)
RAG 패턴 (Retrieval-Augmented Generation)
외부 데이터를 모델에 제공하면, hallucination을 줄일 수 있다.
from anthropic import Anthropic
client = Anthropic()
# 문서 검색 (실제로는 벡터 DB 사용)
def search_documents(query: str) -> str:
# 예제: 관련 문서 찾기
documents = {
"node-best-practices": "Node.js 베스트 프랙티스...",
"security-guide": "보안 가이드라인..."
}
return documents.get(query, "")
user_question = "Node.js에서 보안을 어떻게 강화할 수 있을까?"
# 관련 문서 검색
context = search_documents("Node.js security")
# 모델에 컨텍스트와 함께 질문
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=2048,
messages=[
{
"role": "user",
"content": f