Split View: AI 프롬프트 엔지니어링 완전 가이드: 개발자가 알아야 할 프롬프트 기법 30선
AI 프롬프트 엔지니어링 완전 가이드: 개발자가 알아야 할 프롬프트 기법 30선
- 1. 프롬프트 엔지니어링이 왜 중요한가 (2025)
- 2. 기초 기법 (1-10)
- 기법 1: Zero-shot Prompting
- 기법 2: Few-shot Prompting
- 기법 3: Role Prompting (역할 부여)
- 기법 4: System Prompt 설계
- 기법 5: Instruction Formatting (지시 형식화)
- 기법 6: Output Format Specification (출력 형식 지정)
- 기법 7: Delimiter Usage (구분자 활용)
- 기법 8: Constraint Setting (제약 조건 설정)
- 기법 9: Temperature와 Top-p 튜닝
- 기법 10: Token Budgeting (토큰 예산 관리)
- 3. 추론 강화 기법 (11-20)
- 4. 코딩 특화 기법 (21-30)
- 기법 21: Context-aware Code Generation (컨텍스트 인식 코드 생성)
- 기법 22: Rubber Duck Debugging Prompt
- 기법 23: Code Review Prompt Template
- 기법 24: Test Generation from Implementation
- 기법 26: Architecture Design Prompts
- 기법 27: Documentation Generation
- 기법 28: Error Explanation and Fix
- 기법 29: Performance Optimization Prompts
- 기법 30: Security Audit Prompts
- 5. 모델별 최적화
- 6. 프롬프트 안티패턴
- 7. 프롬프트 체이닝과 에이전트
- 8. 실전 템플릿 10개
- 퀴즈
- 참고 자료
1. 프롬프트 엔지니어링이 왜 중요한가 (2025)
AI 시대의 핵심 역량
2025년, AI는 개발자의 일상이 되었습니다. GitHub Copilot, Claude, GPT-4, Gemini를 사용하지 않는 개발자를 찾기 힘든 시대입니다. Stack Overflow의 2025 개발자 설문에 따르면 84%의 개발자가 AI 코딩 도구를 사용하고 있습니다.
하지만 같은 도구를 사용해도 결과는 천차만별입니다. 어떤 개발자는 AI를 통해 생산성을 3배 높이고, 어떤 개발자는 "AI가 쓸모없다"고 불평합니다. 차이는 무엇일까요? 프롬프트의 품질입니다.
프롬프트 엔지니어의 가치
실리콘밸리에서 Senior Prompt Engineer의 연봉은 30만 달러 이상에 달합니다. Anthropic, OpenAI, Google 같은 기업에서는 프롬프트 엔지니어링을 전문 직군으로 채용하고 있습니다.
프롬프트 품질에 따른 출력 차이는 실제로 10배 이상 벌어집니다. 아래 예시를 비교해 보세요.
나쁜 프롬프트:
API 만들어줘
좋은 프롬프트:
Node.js Express로 사용자 인증 REST API를 만들어주세요.
요구사항:
1. POST /auth/register - 이메일, 비밀번호로 회원가입
2. POST /auth/login - JWT 토큰 발급
3. GET /auth/me - 현재 사용자 정보 (인증 필요)
기술 스택:
- Express 4.x, TypeScript
- bcrypt로 비밀번호 해싱
- jsonwebtoken으로 JWT 관리
- Zod로 입력값 검증
출력 형식: 각 파일별로 코드 블록으로 분리해서 보여주세요.
두 번째 프롬프트가 훨씬 구체적이고, AI가 정확하게 원하는 결과를 만들어냅니다.
이 가이드의 대상
이 글은 다음과 같은 개발자를 위해 작성되었습니다:
- AI 코딩 도구를 처음 사용하는 개발자
- 이미 사용하고 있지만 더 효과적으로 쓰고 싶은 개발자
- 프롬프트 엔지니어링을 체계적으로 배우고 싶은 개발자
- Claude, GPT-4, Gemini 각각의 최적 활용법을 알고 싶은 개발자
2. 기초 기법 (1-10)
기법 1: Zero-shot Prompting
Zero-shot은 예시 없이 직접 지시만으로 AI에게 작업을 수행시키는 가장 기본적인 기법입니다. 대부분의 일상적인 AI 사용이 이 방식입니다.
핵심 원칙: 지시는 구체적이고 명확해야 합니다.
다음 Python 함수의 시간 복잡도를 분석해주세요:
def find_duplicates(arr):
seen = set()
duplicates = []
for item in arr:
if item in seen:
duplicates.append(item)
else:
seen.add(item)
return duplicates
Zero-shot이 적합한 경우:
- 단순한 코드 설명, 번역, 요약
- 잘 알려진 패턴의 코드 생성
- 문법 오류 수정
부적합한 경우:
- 복잡한 비즈니스 로직 구현
- 특정 코딩 스타일을 따라야 하는 경우
- 도메인 특화 작업
기법 2: Few-shot Prompting
Few-shot은 몇 가지 예시를 프롬프트에 포함하여 AI가 원하는 패턴을 학습하게 하는 기법입니다. Zero-shot보다 정확도가 크게 향상됩니다.
아래 예시처럼 커밋 메시지를 작성해주세요:
예시 1:
변경: 로그인 페이지에 소셜 로그인 버튼 추가
커밋: feat(auth): add social login buttons to login page
예시 2:
변경: 사용자 목록 API 응답 속도 개선
커밋: perf(api): optimize user list query with pagination
예시 3:
변경: 결제 금액 계산 오류 수정
커밋: fix(payment): correct total amount calculation logic
이제 다음 변경에 대한 커밋 메시지를 작성해주세요:
변경: 다크 모드에서 차트 색상이 안 보이는 문제 해결
Few-shot 팁:
- 예시는 3-5개가 최적 (너무 많으면 토큰 낭비)
- 다양한 케이스를 커버하는 예시 선택
- 일관된 형식 유지
기법 3: Role Prompting (역할 부여)
AI에게 특정 역할을 부여하면 해당 전문성에 맞는 응답을 생성합니다.
당신은 10년 경력의 시니어 백엔드 엔지니어입니다.
대규모 트래픽 처리, 마이크로서비스 아키텍처, 데이터베이스 최적화에 깊은 전문성을 가지고 있습니다.
다음 코드를 리뷰해주세요. 프로덕션 환경에서 문제가 될 수 있는 부분을 찾아주세요.
보안, 성능, 에러 처리 관점에서 분석해주세요.
효과적인 역할 설정 공식:
당신은 [경력]년 경력의 [직책]입니다.
[전문 분야 1], [전문 분야 2], [전문 분야 3]에 깊은 전문성을 가지고 있습니다.
[회사 유형] 환경에서의 경험이 풍부합니다.
기법 4: System Prompt 설계
System prompt는 AI의 기본 행동을 정의합니다. API를 통해 AI를 활용할 때 특히 중요합니다.
[System]
당신은 TypeScript 코드 리뷰 전문가입니다.
규칙:
1. 코드의 타입 안전성을 최우선으로 평가합니다
2. any 타입 사용을 발견하면 반드시 지적합니다
3. 응답은 한국어로 합니다
4. 각 지적사항에 수정 코드를 포함합니다
5. 심각도를 Critical, Warning, Info로 분류합니다
출력 형식:
## 리뷰 결과
### Critical
- [파일명:줄번호] 설명
### Warning
- [파일명:줄번호] 설명
### Info
- [파일명:줄번호] 설명
기법 5: Instruction Formatting (지시 형식화)
프롬프트의 구조와 형식이 응답 품질을 크게 좌우합니다.
비구조화된 프롬프트 (나쁜 예):
리액트 컴포넌트 만들어줘 사용자 프로필 보여주는 거 이름 이메일 프로필 사진 있어야 하고 반응형이어야 하고 다크모드 지원해야 해
구조화된 프롬프트 (좋은 예):
## 요청
React 사용자 프로필 컴포넌트를 작성해주세요.
## 필수 요소
1. 사용자 이름
2. 이메일 주소
3. 프로필 사진 (원형 썸네일)
## 기술 요구사항
- React 18 + TypeScript
- Tailwind CSS 사용
- 반응형 디자인 (모바일/데스크톱)
- 다크 모드 지원 (CSS 변수 또는 Tailwind dark:)
## 추가 사항
- Props 인터페이스를 별도로 정의해주세요
- 로딩 상태를 위한 스켈레톤 UI도 포함해주세요
기법 6: Output Format Specification (출력 형식 지정)
AI의 출력 형식을 명시하면 후처리가 쉽고 일관된 결과를 얻습니다.
JSON 출력 요청:
다음 로그 메시지를 분석하고 JSON 형식으로 결과를 반환해주세요.
로그:
ERROR 2025-03-15 14:32:01 [PaymentService] Failed to process payment for order #12345.
Reason: Insufficient funds. User: user@example.com
출력 JSON 스키마:
{
"timestamp": "ISO 8601 형식",
"level": "로그 레벨",
"service": "서비스 이름",
"message": "핵심 메시지",
"context": {
"orderId": "주문 ID",
"reason": "실패 사유",
"user": "사용자 식별자"
}
}
다양한 출력 형식:
- JSON: API 응답 파싱, 데이터 변환
- Markdown 테이블: 비교 분석, 기능 정리
- XML: 구조화된 문서, 설정 파일
- YAML: 설정, 쿠버네티스 매니페스트
- Mermaid 다이어그램: 아키텍처, 시퀀스 다이어그램
기법 7: Delimiter Usage (구분자 활용)
구분자를 사용하면 프롬프트의 각 부분을 명확히 분리할 수 있습니다.
XML 태그 구분 (Claude에서 특히 효과적):
<context>
이 프로젝트는 Next.js 14 App Router 기반의 이커머스 플랫폼입니다.
데이터베이스는 PostgreSQL, ORM은 Prisma를 사용합니다.
</context>
<task>
상품 검색 API를 구현해주세요.
전문 검색(full-text search)을 지원해야 합니다.
</task>
<constraints>
- 검색 응답 시간 200ms 이내
- SQL Injection 방지
- 페이지네이션 필수 (cursor 기반)
</constraints>
<output_format>
1. Prisma 스키마 변경사항
2. API Route 코드
3. 검색 쿼리 최적화 설명
</output_format>
기법 8: Constraint Setting (제약 조건 설정)
명확한 제약은 AI가 범위를 벗어나는 것을 방지합니다.
다음 규칙을 반드시 따라주세요:
반드시 해야 할 것:
- TypeScript strict 모드 사용
- 모든 함수에 JSDoc 주석 작성
- 에러 처리를 위한 커스텀 Error 클래스 사용
- 환경 변수는 process.env 직접 접근 대신 config 모듈 통해 접근
절대 하지 말아야 할 것:
- any 타입 사용 금지
- console.log 사용 금지 (logger 라이브러리 사용)
- 동기 파일 I/O 금지
- 하드코딩된 상수 금지
기법 9: Temperature와 Top-p 튜닝
Temperature와 top_p는 출력의 무작위성을 제어하는 핵심 파라미터입니다.
Temperature 가이드:
| Temperature | 용도 | 예시 |
|---|---|---|
| 0.0 | 결정적, 일관된 출력 | 코드 생성, 수학 문제, 데이터 파싱 |
| 0.3 | 약간의 변형 허용 | 코드 리뷰, 기술 문서 |
| 0.7 | 균형 잡힌 창의성 | 블로그 작성, 브레인스토밍 |
| 1.0 | 최대 창의성 | 스토리 작성, 아이디어 발산 |
개발자를 위한 권장 설정:
- 코드 생성: temperature 0.0~0.2
- 코드 리뷰: temperature 0.1~0.3
- 문서 작성: temperature 0.3~0.5
- 아이디어 도출: temperature 0.7~0.9
기법 10: Token Budgeting (토큰 예산 관리)
토큰은 비용이자 컨텍스트 윈도우의 한계입니다. 효율적인 토큰 관리가 필요합니다.
토큰 절약 팁:
# 나쁜 예 (불필요하게 긴 프롬프트)
안녕하세요. 저는 지금 Python 프로젝트를 하고 있는데요,
혹시 시간이 되시면 아래 코드를 봐주실 수 있을까요?
정말 감사하겠습니다. 코드는 다음과 같습니다...
# 좋은 예 (간결한 프롬프트)
다음 Python 코드를 최적화해주세요. 시간 복잡도 O(n)으로 개선이 목표입니다.
모델별 컨텍스트 윈도우 (2025년 기준):
- Claude 3.5 Sonnet: 200K 토큰
- GPT-4 Turbo: 128K 토큰
- Gemini 1.5 Pro: 2M 토큰
3. 추론 강화 기법 (11-20)
기법 11: Chain-of-Thought (CoT)
Chain-of-Thought는 AI에게 단계별로 추론하도록 유도하는 기법입니다. 복잡한 문제에서 정확도를 크게 향상시킵니다.
기본 CoT 프롬프트:
다음 마이크로서비스 아키텍처의 병목 지점을 분석해주세요.
단계별로 생각해봅시다.
아키텍처:
- API Gateway -> User Service -> PostgreSQL
- API Gateway -> Order Service -> MongoDB
- Order Service -> Payment Service (HTTP)
- Payment Service -> External Payment API
- Order Service -> Notification Service (Kafka)
각 단계에서:
1. 해당 서비스의 잠재적 병목 요인을 나열하세요
2. 부하가 초당 10,000 요청일 때 어떤 일이 발생하는지 분석하세요
3. 개선 방안을 제시하세요
CoT가 효과적인 상황:
- 알고리즘 문제 풀이
- 시스템 디자인 분석
- 디버깅 (에러 원인 추적)
- 성능 최적화 분석
기법 12: Zero-shot CoT
"Let's think step by step"이라는 간단한 문구만 추가해도 추론 품질이 향상됩니다.
이 SQL 쿼리가 느린 이유를 분석하고 최적화해주세요.
단계별로 생각해봅시다.
SELECT u.name, COUNT(o.id) as order_count, SUM(o.total) as total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= '2025-01-01'
GROUP BY u.name
HAVING total_spent > 1000
ORDER BY total_spent DESC;
기법 13: Tree-of-Thought (ToT)
ToT는 여러 추론 경로를 탐색하고 최적의 해결책을 선택하는 고급 기법입니다.
다음 시스템의 캐싱 전략을 설계해주세요.
시스템: 하루 1000만 조회의 뉴스 피드 서비스
3가지 다른 접근법을 각각 탐색해주세요:
접근법 A: Redis 기반 중앙 집중식 캐시
- 장점과 단점을 분석하세요
- 예상 성능 수치를 제시하세요
접근법 B: CDN + 엣지 캐싱
- 장점과 단점을 분석하세요
- 예상 성능 수치를 제시하세요
접근법 C: 하이브리드 (로컬 캐시 + 분산 캐시 + CDN)
- 장점과 단점을 분석하세요
- 예상 성능 수치를 제시하세요
최종적으로 각 접근법을 비교하고, 이 시스템에 가장 적합한 전략을 선택해주세요.
선택 이유를 비용, 성능, 복잡도 관점에서 설명해주세요.
기법 14: Self-Consistency
동일한 질문에 대해 여러 번 추론한 후 가장 일관된 답변을 선택하는 기법입니다.
다음 코드의 버그를 3가지 다른 관점에서 분석해주세요.
코드:
async function processOrders(orders) {
const results = [];
for (const order of orders) {
const result = await processPayment(order);
results.push(result);
}
return results;
}
관점 1 (성능 엔지니어): 성능 문제를 찾아주세요
관점 2 (보안 엔지니어): 보안 취약점을 찾아주세요
관점 3 (SRE 엔지니어): 안정성 문제를 찾아주세요
각 관점의 분석 결과를 종합하여 최종 개선안을 제시해주세요.
기법 15: ReAct (Reasoning + Acting)
ReAct는 추론과 행동을 번갈아 수행하는 에이전트 프롬프트 패턴입니다.
다음 프로세스를 따라 버그를 해결해주세요.
문제: 프로덕션에서 간헐적으로 500 에러 발생
각 단계를 "생각 -> 행동 -> 관찰" 형식으로 진행하세요:
생각 1: 어떤 정보를 먼저 확인해야 할까?
행동 1: 에러 로그를 분석한다
관찰 1: (분석 결과를 기록)
생각 2: 로그에서 어떤 패턴이 보이는가?
행동 2: (다음 행동 결정)
관찰 2: (관찰 결과 기록)
이 과정을 근본 원인을 찾을 때까지 반복하세요.
마지막에 수정 코드와 재발 방지 대책을 제시하세요.
기법 16: Reflection (자기 반성)
AI에게 자신의 답변을 비판적으로 검토하게 합니다.
다음 작업을 수행해주세요:
1단계: 아래 요구사항에 맞는 인증 미들웨어를 구현하세요
2단계: 구현한 코드를 스스로 리뷰하세요 - 보안 취약점, 엣지 케이스, 성능 문제를 찾으세요
3단계: 리뷰에서 발견한 문제를 수정한 최종 버전을 제시하세요
요구사항:
- JWT 기반 인증
- 토큰 만료 처리
- Role 기반 접근 제어
- Rate limiting 통합
기법 17: Decomposition (분해)
복잡한 문제를 작은 하위 문제로 분해하여 해결합니다.
다음 기능을 하위 작업으로 분해하고, 각각을 구현해주세요.
기능: 실시간 채팅 시스템 (WebSocket 기반)
분해:
1. 먼저 전체 기능을 독립적인 모듈로 나누세요
2. 각 모듈의 인터페이스(입출력)를 정의하세요
3. 의존성이 없는 모듈부터 순서대로 구현하세요
4. 모듈 간 통합 방법을 설명하세요
5. 전체 동작 흐름을 시퀀스 다이어그램으로 보여주세요
기법 18: Analogical Reasoning (유추 추론)
익숙한 개념에 비유하여 복잡한 시스템을 설명하게 합니다.
쿠버네티스의 핵심 개념을 식당 운영에 비유해서 설명해주세요.
각 개념별로:
1. 쿠버네티스 용어
2. 식당 비유
3. 실제 동작 설명
4. 코드 예시 (YAML)
다룰 개념: Pod, Deployment, Service, Ingress, ConfigMap, Secret, PVC
기법 19: Meta-prompting (메타 프롬프팅)
프롬프트를 생성하는 프롬프트입니다. 프롬프트 자체를 최적화할 때 사용합니다.
나는 AI 코드 리뷰 자동화 시스템을 만들고 있습니다.
다음 요구사항을 충족하는 최적의 시스템 프롬프트를 만들어주세요:
1. 목적: PR 코드 리뷰 자동화
2. 입력: Git diff 형식의 코드 변경사항
3. 출력: 구조화된 리뷰 코멘트
4. 검토 항목: 보안, 성능, 가독성, 테스트 커버리지
5. 톤: 건설적이고 교육적
6. 언어: 한국어
프롬프트에는 다음이 포함되어야 합니다:
- 역할 정의
- 상세한 검토 기준
- 출력 형식 템플릿
- 예외 처리 규칙
- Few-shot 예시 1개
기법 20: Constitutional AI Prompting
AI에게 **헌법(규칙)**을 제시하고 그 규칙에 따라 행동하게 합니다.
다음 원칙을 반드시 준수하며 코드를 생성해주세요:
원칙 1 - 보안: OWASP Top 10 취약점을 절대 포함하지 않는다
원칙 2 - 접근성: WCAG 2.1 AA 기준을 충족한다
원칙 3 - 성능: Core Web Vitals 기준을 충족한다
원칙 4 - 유지보수성: SOLID 원칙을 따른다
원칙 5 - 테스트: 각 함수에 대해 최소 2개의 테스트 케이스를 작성한다
각 코드 블록 후에 어떤 원칙들을 충족하는지 체크리스트로 보여주세요.
4. 코딩 특화 기법 (21-30)
기법 21: Context-aware Code Generation (컨텍스트 인식 코드 생성)
기존 코드베이스의 스타일과 패턴을 AI에게 알려주면 일관된 코드를 생성합니다.
다음은 프로젝트의 기존 서비스 코드 패턴입니다:
<existing_pattern>
// services/user.service.ts
export class UserService {
constructor(
private readonly userRepo: UserRepository,
private readonly logger: Logger,
) {}
async findById(id: string): Promise<Result<User, ServiceError>> {
try {
const user = await this.userRepo.findById(id);
if (!user) {
return err(new NotFoundError('User', id));
}
return ok(user);
} catch (error) {
this.logger.error('Failed to find user', { id, error });
return err(new InternalError('Failed to find user'));
}
}
}
</existing_pattern>
이 패턴과 동일한 스타일로 ProductService를 작성해주세요.
필요한 메서드: findById, findAll (페이지네이션), create, update, delete
기법 22: Rubber Duck Debugging Prompt
AI를 고무 오리 디버깅 파트너로 활용합니다.
나의 디버깅 파트너로서 다음 문제를 함께 해결해주세요.
증상: 사용자 로그인 후 3분 뒤에 자동으로 로그아웃됨
내가 알고 있는 것:
- JWT 토큰 만료 시간은 1시간으로 설정
- 로컬 환경에서는 재현되지 않음
- 프로덕션에서만 발생
- 3월 14일 배포 이후부터 시작
내가 시도한 것:
- 토큰 만료 시간 확인 -> 정상
- 브라우저 쿠키 확인 -> 토큰이 사라짐
질문 형식으로 나를 가이드해주세요:
1. 아직 확인하지 않은 가능한 원인은?
2. 각 원인을 검증하기 위한 구체적 단계는?
3. 가장 가능성이 높은 원인은 무엇이라고 추론하는지?
기법 23: Code Review Prompt Template
체계적인 코드 리뷰를 위한 템플릿입니다.
다음 코드를 아래 체크리스트에 따라 리뷰해주세요.
리뷰 체크리스트:
1. 정확성: 의도한 대로 동작하는가?
2. 보안: SQL Injection, XSS, CSRF 등의 취약점은 없는가?
3. 성능: 불필요한 연산, N+1 쿼리, 메모리 누수는 없는가?
4. 에러 처리: 모든 실패 경로가 적절히 처리되는가?
5. 가독성: 변수명, 함수명이 의미를 잘 전달하는가?
6. 테스트: 테스트하기 쉬운 구조인가?
7. 확장성: 요구사항 변경에 유연한가?
출력 형식:
각 항목별로 Pass/Fail/Warning을 표시하고,
Fail이나 Warning인 경우 구체적인 개선 코드를 제시해주세요.
심각도: Critical > Major > Minor > Suggestion
기법 24: Test Generation from Implementation
구현 코드를 기반으로 테스트를 자동 생성합니다.
다음 함수에 대한 포괄적인 테스트를 작성해주세요.
함수:
```typescript
export function calculateDiscount(
originalPrice: number,
membershipTier: 'basic' | 'silver' | 'gold' | 'platinum',
couponCode?: string,
): { finalPrice: number; discountRate: number; appliedDiscounts: string[] } {
// ... 구현 코드
}
테스트 요구사항:
- 테스트 프레임워크: Vitest
- 각 멤버십 등급별 할인 테스트
- 쿠폰 코드 적용 테스트
- 경계값 테스트 (가격 0, 음수, 매우 큰 값)
- 에러 케이스 (잘못된 쿠폰, 잘못된 등급)
- 복합 할인 (멤버십 + 쿠폰) 테스트
- describe/it 패턴으로 구조화
- 각 테스트에 한국어 설명 주석
### 기법 25: Refactoring with Specific Goals
리팩토링 목표를 구체적으로 제시합니다.
```text
다음 코드를 리팩토링해주세요.
리팩토링 목표:
1. 함수 분리: 하나의 함수는 하나의 책임만
2. 매직 넘버 제거: 의미 있는 상수로 교체
3. Early return 패턴 적용: 중첩 if문 제거
4. 타입 안전성 강화: 유니온 타입과 타입 가드 활용
리팩토링 과정:
- 변경 전후를 나란히 보여주세요
- 각 변경의 이유를 설명해주세요
- 동작이 변경되지 않았음을 설명해주세요
기법 26: Architecture Design Prompts
시스템 아키텍처 설계를 AI와 함께합니다.
다음 요구사항에 맞는 시스템 아키텍처를 설계해주세요.
서비스: 실시간 경매 플랫폼
- 동시 사용자: 최대 10만 명
- 실시간 입찰 업데이트 (지연 100ms 이내)
- 결제 처리 (PG사 연동)
- 이미지 업로드 (상품당 최대 10장)
제출물:
1. 고수준 아키텍처 다이어그램 (Mermaid)
2. 각 컴포넌트의 기술 스택 선정 및 이유
3. 데이터 흐름 다이어그램
4. 확장성 전략 (수평 스케일링 포인트)
5. 장애 대응 전략 (SPOF 식별 및 대안)
6. 예상 월 비용 (AWS 기준)
기법 27: Documentation Generation
코드에서 문서를 자동 생성합니다.
다음 API 엔드포인트 코드를 기반으로 API 문서를 작성해주세요.
형식: OpenAPI 3.0 YAML
포함할 내용:
1. 엔드포인트 설명
2. 요청 파라미터 (path, query, body)
3. 응답 스키마 (성공/실패 모두)
4. 인증 방식
5. Rate limit 정보
6. 사용 예시 (curl)
7. 에러 코드 표
기법 28: Error Explanation and Fix
에러 메시지를 분석하고 수정 방법을 제시합니다.
다음 에러를 분석하고 수정해주세요.
에러 메시지:
TypeError: Cannot read properties of undefined (reading 'map')
at UserList (UserList.tsx:15:23)
at renderWithHooks (react-dom.development.js:16305:18)
컨텍스트:
- React 18 + TypeScript 프로젝트
- API에서 사용자 목록을 가져와서 렌더링하는 컴포넌트
- 가끔만 발생 (네트워크 느릴 때)
다음을 포함해주세요:
1. 에러 원인 분석 (왜 undefined인지)
2. 수정 코드
3. 같은 패턴의 에러를 방지하기 위한 일반적 가이드라인
4. 타입으로 이 에러를 컴파일 타임에 잡는 방법
기법 29: Performance Optimization Prompts
성능 최적화를 체계적으로 수행합니다.
다음 API 엔드포인트의 성능을 최적화해주세요.
현재 상태:
- 평균 응답 시간: 2.5초
- P99 응답 시간: 8초
- 초당 요청: 500 RPS
- 목표: 평균 200ms 이내, P99 500ms 이내
분석 순서:
1. 현재 코드에서 성능 병목 지점을 식별하세요
2. 각 병목에 대한 최적화 방안을 제시하세요
3. 예상 개선 효과를 수치로 표시하세요
4. 최적화된 코드를 제시하세요
5. 최적화 전후를 비교하는 벤치마크 코드를 작성하세요
기법 30: Security Audit Prompts
보안 감사를 AI를 활용하여 수행합니다.
다음 코드에 대해 보안 감사를 수행해주세요.
검사 항목:
1. OWASP Top 10 (2021) 기준 취약점
2. 인증/인가 취약점
3. 데이터 노출 위험
4. 의존성 취약점 가능성
5. 설정 오류
출력 형식:
각 발견사항에 대해:
- 취약점 유형: (예: A01 Broken Access Control)
- 심각도: Critical / High / Medium / Low
- 위치: 파일명과 줄 번호
- 설명: 취약점이 어떻게 악용될 수 있는지
- 수정 코드: 안전한 코드 예시
- 참고: CWE 번호 또는 관련 문서 링크
5. 모델별 최적화
Claude, GPT-4, Gemini 비교
| 기법 | Claude | GPT-4 | Gemini |
|---|---|---|---|
| XML 태그 구분 | 매우 효과적 | 보통 | 보통 |
| JSON 모드 | 지원 | 네이티브 지원 | 지원 |
| 시스템 프롬프트 | 매우 중요 | 중요 | 중요 |
| 긴 컨텍스트 | 200K | 128K | 2M |
| 멀티모달 | 이미지 분석 | 이미지+DALL-E | 이미지+동영상+오디오 |
| 코드 실행 | 없음 | Code Interpreter | 코드 실행 지원 |
| 함수 호출 | Tool Use | Function Calling | Function Calling |
Claude 최적화 팁
Claude에서 최고의 결과를 얻기 위한 팁입니다:
1. XML 태그를 적극 활용하세요
<context>프로젝트 배경과 기술 스택</context>
<task>구체적인 작업 내용</task>
<constraints>제약 조건</constraints>
<examples>참고 예시</examples>
<output_format>원하는 출력 형식</output_format>
2. "Think step by step"을 명시적으로 요청하세요
이 문제를 단계별로 분석해주세요.
각 단계의 추론 과정을 보여주세요.
3. 시스템 프롬프트를 충분히 활용하세요
Claude는 시스템 프롬프트에 특히 강하게 반응합니다. 역할, 규칙, 형식을 시스템 프롬프트에 넣으면 일관된 결과를 얻습니다.
GPT-4 최적화 팁
1. JSON 모드를 활용하세요
응답을 JSON 형식으로 해주세요.
다른 텍스트 없이 순수 JSON만 반환하세요.
2. Function Calling을 활용하세요
GPT-4의 네이티브 Function Calling은 구조화된 출력에 매우 효과적입니다. API 통합 시 특히 유용합니다.
3. Code Interpreter를 활용하세요
데이터 분석, 시각화, 복잡한 계산이 필요한 경우 Code Interpreter를 활용하면 정확한 결과를 얻습니다.
Gemini 최적화 팁
1. 긴 컨텍스트를 활용하세요
Gemini의 2M 토큰 컨텍스트 윈도우는 전체 코드베이스를 한 번에 분석할 때 유리합니다.
다음은 프로젝트의 전체 소스 코드입니다.
(전체 코드 첨부)
이 코드베이스 전체를 분석하여 아키텍처 개선점을 제안해주세요.
2. 멀티모달 입력을 활용하세요
스크린샷, 화이트보드 사진, 다이어그램 이미지를 입력으로 활용할 수 있습니다.
3. Grounding을 활용하세요
Google 검색 기반 grounding으로 최신 정보를 활용한 응답을 받을 수 있습니다.
6. 프롬프트 안티패턴
안티패턴 1: 모호한 지시
# 나쁜 예
코드 좀 고쳐줘
# 좋은 예
다음 Python 함수에서 N+1 쿼리 문제를 해결해주세요.
SQLAlchemy의 joinedload를 사용하여 최적화하세요.
안티패턴 2: 정보 과부하
# 나쁜 예
(10,000줄의 코드를 전부 붙여넣기)
이 코드 전부 리뷰해줘
# 좋은 예
다음은 결제 처리 모듈의 핵심 로직입니다 (관련 부분만 발췌).
결제 금액 계산 부분에서 부동소수점 오류가 의심됩니다.
해당 부분을 집중적으로 검토해주세요.
안티패턴 3: 상충하는 제약 조건
# 나쁜 예
빠르게 동작하면서도 메모리를 최소한으로 쓰고
코드도 최대한 읽기 쉽게 작성해줘
모든 엣지 케이스를 처리하되 코드는 20줄 이내로
# 좋은 예
우선순위:
1. (필수) 메모리 사용 100MB 이내
2. (중요) 응답 시간 200ms 이내
3. (권장) 코드 가독성 (가능한 범위 내에서)
안티패턴 4: 환각 유발 프롬프트
# 나쁜 예
React 25의 새로운 Server Actions API 사용법을 알려줘
(존재하지 않는 버전/기능에 대해 질문)
# 좋은 예
React의 최신 Server Actions API에 대해 알고 있는 범위에서 설명해줘.
확실하지 않은 정보는 그렇다고 알려줘.
안티패턴 5: 단순 작업에 과도한 프롬프트
# 나쁜 예 (단순 변수 이름 변경에 장문의 프롬프트)
당신은 20년 경력의 소프트웨어 아키텍트입니다.
클린 코드 원칙에 따라 다음 변수의 이름을 개선해주세요.
변수명: x
컨텍스트: 사용자의 나이를 저장하는 변수입니다.
# 좋은 예
변수명 x를 의미 있는 이름으로 바꿔주세요. (사용자 나이 저장용)
7. 프롬프트 체이닝과 에이전트
프롬프트 체이닝 개요
프롬프트 체이닝은 여러 프롬프트를 순차적으로 연결하여 복잡한 작업을 수행하는 기법입니다. 하나의 프롬프트 출력이 다음 프롬프트의 입력이 됩니다.
예시: 코드 리팩토링 체인
Chain 1: 분석
"다음 코드의 코드 스멜을 나열해주세요. JSON 배열로 출력하세요."
Chain 2: 우선순위
"다음 코드 스멜 목록을 심각도 순으로 정렬해주세요. (입력: Chain 1 출력)"
Chain 3: 수정
"가장 심각한 3개의 코드 스멜을 수정한 코드를 제시해주세요. (입력: Chain 2 출력)"
Chain 4: 검증
"수정된 코드가 원본과 동일하게 동작하는지 검증해주세요. (입력: Chain 3 출력)"
에이전트 루프 (Observe - Think - Act)
AI 에이전트는 관찰-사고-행동 루프를 반복하여 복잡한 작업을 수행합니다.
다음 에이전트 루프를 사용하여 프로덕션 인시던트를 해결해주세요:
루프:
1. OBSERVE: 현재 상태 확인 (로그, 메트릭, 알림)
2. THINK: 원인 분석 및 행동 계획 수립
3. ACT: 구체적 조치 실행
4. VERIFY: 조치 결과 확인
인시던트: 데이터베이스 커넥션 풀 고갈
각 루프 반복을 명시적으로 보여주세요.
VERIFY에서 문제가 해결될 때까지 루프를 반복하세요.
MCP (Model Context Protocol) 통합
MCP를 통해 AI를 외부 도구와 연결할 수 있습니다.
다음 도구들을 사용하여 코드 품질 검사를 수행해주세요:
사용 가능한 도구:
1. file_read: 파일 읽기
2. file_write: 파일 쓰기
3. terminal: 터미널 명령 실행
4. git: Git 명령 실행
작업 순서:
1. git diff로 변경된 파일 목록 확인
2. 각 파일 읽기
3. ESLint 실행
4. TypeScript 컴파일 체크
5. 테스트 실행
6. 결과 종합 보고서 생성
메모리와 컨텍스트 관리
긴 대화에서 컨텍스트를 효율적으로 관리하는 방법입니다.
이전 대화 요약 (컨텍스트 압축):
프로젝트: Next.js 이커머스
완료: 상품 목록 API, 장바구니 API
현재 작업: 결제 처리 API
기술 결정: Stripe 사용, Webhook으로 결제 상태 관리
위 컨텍스트를 기반으로 결제 처리 API의 다음 단계를 진행해주세요.
8. 실전 템플릿 10개
템플릿 1: 새 기능 구현
## 기능 요청
[기능 이름과 간단한 설명]
## 배경
- 왜 이 기능이 필요한가?
- 어떤 문제를 해결하는가?
## 기술 스택
- 프레임워크:
- 언어:
- 데이터베이스:
- 기존 패턴 참고:
## 요구사항
1. [필수 요구사항]
2. [필수 요구사항]
3. [선택 요구사항]
## 제약 조건
- [성능 요구사항]
- [보안 요구사항]
## 출력
1. 구현 코드
2. 단위 테스트
3. API 문서 (해당 시)
템플릿 2: 버그 수정 요청
## 버그 설명
[어떤 증상이 발생하는지]
## 재현 단계
1. [단계 1]
2. [단계 2]
3. [단계 3]
## 예상 동작
[어떻게 동작해야 하는지]
## 실제 동작
[현재 어떻게 동작하는지]
## 관련 코드
[코드 붙여넣기]
## 환경
- OS:
- Node.js:
- 브라우저:
## 요청
1. 원인 분석
2. 수정 코드
3. 재발 방지를 위한 테스트
템플릿 3: 코드 리뷰 요청
## PR 요약
[이 PR이 무엇을 변경하는지]
## 변경 코드
[diff 또는 코드]
## 리뷰 관점
- [ ] 로직 정확성
- [ ] 보안
- [ ] 성능
- [ ] 에러 처리
- [ ] 테스트 커버리지
- [ ] 코딩 컨벤션
## 특별히 확인해주세요
[특정 부분에 대한 우려사항]
템플릿 4: 아키텍처 설계
## 시스템 개요
[시스템의 목적과 핵심 기능]
## 비기능 요구사항
- 동시 사용자:
- 응답 시간:
- 가용성:
- 데이터 보존:
## 기존 인프라
[현재 사용 중인 기술과 인프라]
## 요청
1. 아키텍처 다이어그램
2. 기술 스택 선정 및 근거
3. 데이터 모델
4. API 설계
5. 확장 전략
6. 비용 추정
템플릿 5: 데이터베이스 스키마 설계
## 도메인
[비즈니스 도메인 설명]
## 엔티티
[주요 엔티티와 관계]
## 요구사항
- 읽기/쓰기 비율:
- 데이터 크기 예상:
- 쿼리 패턴:
## 요청
1. ERD (Mermaid)
2. SQL DDL
3. 인덱스 전략
4. 마이그레이션 스크립트
템플릿 6: API 설계
## API 목적
[API가 제공하는 기능]
## RESTful 설계
- 리소스 정의
- HTTP 메서드 매핑
- URL 구조
## 요청
1. OpenAPI 3.0 스펙
2. 요청/응답 예시
3. 에러 코드 정의
4. 인증/인가 방식
5. Rate limiting 정책
6. 버전 관리 전략
템플릿 7: CI/CD 파이프라인
## 프로젝트 정보
- 언어/프레임워크:
- 배포 대상:
- 브랜치 전략:
## 요구사항
- 빌드 단계
- 테스트 단계 (단위, 통합, E2E)
- 보안 스캔
- 배포 전략 (Blue-Green / Canary / Rolling)
## 요청
1. 파이프라인 YAML (GitHub Actions / GitLab CI)
2. 각 단계의 설명
3. 시크릿 관리 방법
4. 롤백 전략
템플릿 8: 성능 최적화
## 현재 상태
- 측정 지표: [응답 시간, 처리량, 에러율]
- 병목 의심 지점: [설명]
## 목표
- 응답 시간: [현재] -> [목표]
- 처리량: [현재] -> [목표]
## 코드
[최적화 대상 코드]
## 요청
1. 병목 분석
2. 최적화 방안 (우선순위순)
3. 최적화된 코드
4. 벤치마크 코드
템플릿 9: 마이그레이션 가이드
## 마이그레이션 대상
- FROM: [현재 기술/버전]
- TO: [목표 기술/버전]
## 현재 코드
[마이그레이션 대상 코드]
## 요구사항
- 하위 호환성 유지 여부
- 점진적 마이그레이션 가능 여부
- 다운타임 허용 범위
## 요청
1. 마이그레이션 계획 (단계별)
2. 변경 코드
3. 호환성 확인 테스트
4. 롤백 계획
템플릿 10: 장애 대응
## 인시던트 정보
- 발생 시간:
- 영향 범위:
- 심각도:
## 현재 증상
[에러 로그, 메트릭 스크린샷, 알림 내용]
## 시스템 구성
[관련 서비스 아키텍처]
## 요청
1. 즉각 대응 (완화 조치)
2. 근본 원인 분석
3. 수정 방안
4. 재발 방지 대책
5. 포스트모템 초안
퀴즈
지금까지 배운 내용을 테스트해봅시다.
퀴즈 1: 다음 중 Few-shot prompting의 올바른 설명은?
정답: 소수의 예시를 프롬프트에 포함하여 AI가 원하는 패턴을 학습하게 하는 기법
Zero-shot은 예시 없이 지시만 하는 것이고, Few-shot은 3-5개의 예시를 포함합니다. 예시가 많을수록 좋은 것은 아닙니다 - 토큰 비용과 컨텍스트 윈도우를 고려해야 합니다.
퀴즈 2: Temperature 0.0으로 설정하면 어떤 특성의 출력을 얻는가?
정답: 결정적(deterministic) 출력 - 동일한 입력에 대해 항상 같은 결과
Temperature 0.0은 코드 생성, 데이터 파싱 등 정확성이 중요한 작업에 적합합니다. 창의적인 작업에는 0.7 이상이 권장됩니다.
퀴즈 3: Chain-of-Thought와 Tree-of-Thought의 차이점은?
정답:
- CoT: 하나의 추론 경로를 단계별로 진행 (선형적)
- ToT: 여러 추론 경로를 동시에 탐색하고 최적을 선택 (분기적)
CoT는 "A를 분석하면 B이고, B에서 C를 알 수 있다"처럼 순차적입니다. ToT는 "A, B, C 세 가지 접근법 중 최적을 비교 선택"하는 방식입니다.
퀴즈 4: Claude에서 가장 효과적인 프롬프트 구분 방법은?
정답: XML 태그 사용
Claude는 XML 태그에 특히 잘 반응합니다. context, task, constraints, output_format 등의 태그로 프롬프트를 구조화하면 더 정확한 응답을 얻을 수 있습니다.
퀴즈 5: ReAct 패턴의 3단계는 무엇인가?
정답: 생각(Reasoning) - 행동(Acting) - 관찰(Observation)
ReAct는 추론과 행동을 번갈아 수행하는 에이전트 패턴입니다. AI가 문제에 대해 생각하고, 행동을 취하고, 결과를 관찰한 후 다시 생각하는 루프를 반복합니다. 이 패턴은 복잡한 디버깅이나 시스템 문제 해결에 매우 효과적입니다.
참고 자료
논문 및 학술 자료
- Chain-of-Thought Prompting Elicits Reasoning in Large Language Models - Wei et al., 2022
- Tree of Thoughts: Deliberate Problem Solving with Large Language Models - Yao et al., 2023
- ReAct: Synergizing Reasoning and Acting in Language Models - Yao et al., 2022
- Self-Consistency Improves Chain of Thought Reasoning - Wang et al., 2022
- Constitutional AI: Harmlessness from AI Feedback - Bai et al., 2022
공식 문서
- Anthropic Prompt Engineering Guide - docs.anthropic.com
- OpenAI Prompt Engineering Guide - platform.openai.com
- Google AI Prompt Engineering - ai.google.dev
- GitHub Copilot Best Practices - docs.github.com
실전 가이드
- Prompt Engineering Guide - promptingguide.ai
- LangChain Documentation - docs.langchain.com
- LlamaIndex Documentation - docs.llamaindex.ai
- Brex Prompt Engineering - GitHub (brexhq/prompt-engineering)
도구 및 프레임워크
- LangSmith - 프롬프트 테스트 및 평가 도구
- PromptLayer - 프롬프트 관리 플랫폼
- Weights and Biases Prompts - 프롬프트 버전 관리
- Helicone - LLM 모니터링 및 프롬프트 분석
커뮤니티
- r/PromptEngineering - Reddit 커뮤니티
- Awesome Prompt Engineering - GitHub 큐레이션
- AI Developer Discord Communities - 실시간 지식 교류
AI Prompt Engineering Complete Guide: 30 Techniques Every Developer Should Know
- 1. Why Prompt Engineering Matters (2025)
- 2. Foundational Techniques (1-10)
- Technique 1: Zero-shot Prompting
- Technique 2: Few-shot Prompting
- Technique 3: Role Prompting
- Technique 4: System Prompt Design
- Technique 5: Instruction Formatting
- Technique 6: Output Format Specification
- Technique 7: Delimiter Usage
- Technique 8: Constraint Setting
- Technique 9: Temperature and Top-p Tuning
- Technique 10: Token Budgeting
- 3. Reasoning Enhancement Techniques (11-20)
- Technique 11: Chain-of-Thought (CoT)
- Technique 12: Zero-shot CoT
- Technique 13: Tree-of-Thought (ToT)
- Technique 14: Self-Consistency
- Technique 15: ReAct (Reasoning + Acting)
- Technique 16: Reflection (Self-Critique)
- Technique 17: Decomposition
- Technique 18: Analogical Reasoning
- Technique 19: Meta-prompting
- Technique 20: Constitutional AI Prompting
- 4. Coding-Specific Techniques (21-30)
- Technique 21: Context-aware Code Generation
- Technique 22: Rubber Duck Debugging Prompt
- Technique 23: Code Review Prompt Template
- Technique 24: Test Generation from Implementation
- Technique 26: Architecture Design Prompts
- Technique 27: Documentation Generation
- Technique 28: Error Explanation and Fix
- Technique 29: Performance Optimization Prompts
- Technique 30: Security Audit Prompts
- 5. Model-Specific Optimization
- 6. Prompt Anti-patterns
- 7. Prompt Chaining and Agents
- 8. Practical Templates (10)
- Template 1: New Feature Implementation
- Template 2: Bug Fix Request
- Template 3: Code Review Request
- Template 4: Architecture Design
- Template 5: Database Schema Design
- Template 6: API Design
- Template 7: CI/CD Pipeline
- Template 8: Performance Optimization
- Template 9: Migration Guide
- Template 10: Incident Response
- Quiz
- References
1. Why Prompt Engineering Matters (2025)
The Core Skill of the AI Era
In 2025, AI has become a daily part of every developer's workflow. It is hard to find a developer who does not use GitHub Copilot, Claude, GPT-4, or Gemini. According to Stack Overflow's 2025 Developer Survey, 84% of developers use AI coding tools.
Yet the same tools yield wildly different results. Some developers triple their productivity with AI while others complain that "AI is useless." What makes the difference? Prompt quality.
The Value of Prompt Engineers
In Silicon Valley, Senior Prompt Engineer salaries exceed $300K. Companies like Anthropic, OpenAI, and Google are hiring prompt engineering as a dedicated role.
The output difference based on prompt quality is actually 10x or more. Compare these examples:
Bad prompt:
Make me an API
Good prompt:
Build a user authentication REST API using Node.js Express.
Requirements:
1. POST /auth/register - Sign up with email and password
2. POST /auth/login - Issue JWT token
3. GET /auth/me - Current user info (auth required)
Tech stack:
- Express 4.x, TypeScript
- bcrypt for password hashing
- jsonwebtoken for JWT management
- Zod for input validation
Output format: Show code in separate code blocks for each file.
The second prompt is far more specific and enables the AI to produce exactly what you need.
Who This Guide Is For
This guide is written for:
- Developers new to AI coding tools
- Developers already using AI but wanting to be more effective
- Developers who want to systematically learn prompt engineering
- Developers who want to learn the best practices for Claude, GPT-4, and Gemini
2. Foundational Techniques (1-10)
Technique 1: Zero-shot Prompting
Zero-shot is the most basic technique where you give direct instructions without any examples. Most everyday AI usage falls into this category.
Core principle: Instructions must be specific and clear.
Analyze the time complexity of the following Python function:
def find_duplicates(arr):
seen = set()
duplicates = []
for item in arr:
if item in seen:
duplicates.append(item)
else:
seen.add(item)
return duplicates
When Zero-shot works well:
- Simple code explanations, translations, summaries
- Generating code for well-known patterns
- Fixing syntax errors
When it falls short:
- Complex business logic implementation
- When specific coding styles must be followed
- Domain-specific tasks
Technique 2: Few-shot Prompting
Few-shot includes several examples in the prompt so the AI learns the desired pattern. Accuracy improves significantly over Zero-shot.
Write commit messages following these examples:
Example 1:
Change: Added social login buttons to login page
Commit: feat(auth): add social login buttons to login page
Example 2:
Change: Improved user list API response speed
Commit: perf(api): optimize user list query with pagination
Example 3:
Change: Fixed payment amount calculation error
Commit: fix(payment): correct total amount calculation logic
Now write a commit message for:
Change: Fixed chart colors not visible in dark mode
Few-shot tips:
- 3-5 examples is optimal (too many wastes tokens)
- Choose examples that cover diverse cases
- Maintain consistent formatting
Technique 3: Role Prompting
Assigning a specific role to the AI makes it generate responses aligned with that expertise.
You are a senior backend engineer with 10 years of experience.
You have deep expertise in high-traffic systems, microservice architecture,
and database optimization.
Review the following code. Find issues that could be problematic in production.
Analyze from security, performance, and error handling perspectives.
Effective role setting formula:
You are a [title] with [years] years of experience.
You have deep expertise in [specialty 1], [specialty 2], [specialty 3].
You have extensive experience in [company type] environments.
Technique 4: System Prompt Design
System prompts define the AI's baseline behavior. They are especially important when using AI through APIs.
[System]
You are a TypeScript code review specialist.
Rules:
1. Evaluate type safety as the top priority
2. Always flag any usage of the 'any' type
3. Respond in English
4. Include corrected code for each issue found
5. Classify severity as Critical, Warning, or Info
Output format:
## Review Results
### Critical
- [filename:line] Description
### Warning
- [filename:line] Description
### Info
- [filename:line] Description
Technique 5: Instruction Formatting
The structure and format of your prompt significantly affects response quality.
Unstructured prompt (bad):
make me a react component that shows user profile with name email and profile pic needs to be responsive and support dark mode
Structured prompt (good):
## Request
Create a React user profile component.
## Required Elements
1. User name
2. Email address
3. Profile picture (circular thumbnail)
## Technical Requirements
- React 18 + TypeScript
- Tailwind CSS
- Responsive design (mobile/desktop)
- Dark mode support (CSS variables or Tailwind dark:)
## Additional
- Define a separate Props interface
- Include a skeleton UI for loading state
Technique 6: Output Format Specification
Specifying the output format makes post-processing easier and produces consistent results.
JSON output request:
Analyze the following log message and return results in JSON format.
Log:
ERROR 2025-03-15 14:32:01 [PaymentService] Failed to process payment for order #12345.
Reason: Insufficient funds. User: user@example.com
Output JSON schema:
{
"timestamp": "ISO 8601 format",
"level": "log level",
"service": "service name",
"message": "core message",
"context": {
"orderId": "order ID",
"reason": "failure reason",
"user": "user identifier"
}
}
Various output formats:
- JSON: API response parsing, data transformation
- Markdown tables: Comparative analysis, feature summaries
- XML: Structured documents, configuration files
- YAML: Configuration, Kubernetes manifests
- Mermaid diagrams: Architecture, sequence diagrams
Technique 7: Delimiter Usage
Delimiters clearly separate different parts of your prompt.
XML tag delimiters (especially effective with Claude):
<context>
This project is a Next.js 14 App Router-based e-commerce platform.
Database is PostgreSQL, ORM is Prisma.
</context>
<task>
Implement a product search API.
It must support full-text search.
</task>
<constraints>
- Search response time under 200ms
- SQL injection prevention
- Pagination required (cursor-based)
</constraints>
<output_format>
1. Prisma schema changes
2. API Route code
3. Search query optimization explanation
</output_format>
Technique 8: Constraint Setting
Clear constraints prevent the AI from going out of scope.
You must follow these rules:
ALWAYS do:
- Use TypeScript strict mode
- Write JSDoc comments for all functions
- Use custom Error classes for error handling
- Access environment variables through a config module, not process.env directly
NEVER do:
- Use the 'any' type
- Use console.log (use a logger library)
- Use synchronous file I/O
- Use hardcoded constants
Technique 9: Temperature and Top-p Tuning
Temperature and top_p are key parameters that control output randomness.
Temperature guide:
| Temperature | Use Case | Examples |
|---|---|---|
| 0.0 | Deterministic, consistent output | Code generation, math problems, data parsing |
| 0.3 | Slight variation allowed | Code review, technical documentation |
| 0.7 | Balanced creativity | Blog writing, brainstorming |
| 1.0 | Maximum creativity | Story writing, idea generation |
Recommended settings for developers:
- Code generation: temperature 0.0-0.2
- Code review: temperature 0.1-0.3
- Documentation: temperature 0.3-0.5
- Ideation: temperature 0.7-0.9
Technique 10: Token Budgeting
Tokens are both cost and context window limits. Efficient token management is essential.
Token saving tips:
# Bad (unnecessarily long prompt)
Hello! I'm working on a Python project right now,
and I was wondering if you might have time to look at the code below?
I would really appreciate it. The code is as follows...
# Good (concise prompt)
Optimize the following Python code. Target time complexity is O(n).
Context windows by model (2025):
- Claude 3.5 Sonnet: 200K tokens
- GPT-4 Turbo: 128K tokens
- Gemini 1.5 Pro: 2M tokens
3. Reasoning Enhancement Techniques (11-20)
Technique 11: Chain-of-Thought (CoT)
Chain-of-Thought guides the AI to reason step by step. It significantly improves accuracy on complex problems.
Basic CoT prompt:
Analyze the bottlenecks in the following microservice architecture.
Let's think step by step.
Architecture:
- API Gateway -> User Service -> PostgreSQL
- API Gateway -> Order Service -> MongoDB
- Order Service -> Payment Service (HTTP)
- Payment Service -> External Payment API
- Order Service -> Notification Service (Kafka)
For each step:
1. List potential bottleneck factors for that service
2. Analyze what happens at 10,000 requests per second
3. Propose improvements
When CoT is effective:
- Algorithm problem solving
- System design analysis
- Debugging (tracing error causes)
- Performance optimization analysis
Technique 12: Zero-shot CoT
Adding the simple phrase "Let's think step by step" improves reasoning quality.
Analyze why this SQL query is slow and optimize it.
Let's think step by step.
SELECT u.name, COUNT(o.id) as order_count, SUM(o.total) as total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= '2025-01-01'
GROUP BY u.name
HAVING total_spent > 1000
ORDER BY total_spent DESC;
Technique 13: Tree-of-Thought (ToT)
ToT explores multiple reasoning paths and selects the optimal solution.
Design a caching strategy for the following system.
System: News feed service with 10 million daily views
Explore 3 different approaches:
Approach A: Redis-based centralized cache
- Analyze pros and cons
- Provide expected performance numbers
Approach B: CDN + edge caching
- Analyze pros and cons
- Provide expected performance numbers
Approach C: Hybrid (local cache + distributed cache + CDN)
- Analyze pros and cons
- Provide expected performance numbers
Finally, compare all approaches and select the most suitable strategy
for this system. Explain your choice from cost, performance, and
complexity perspectives.
Technique 14: Self-Consistency
Reason multiple times about the same question, then select the most consistent answer.
Analyze the bugs in the following code from 3 different perspectives.
Code:
async function processOrders(orders) {
const results = [];
for (const order of orders) {
const result = await processPayment(order);
results.push(result);
}
return results;
}
Perspective 1 (Performance Engineer): Find performance issues
Perspective 2 (Security Engineer): Find security vulnerabilities
Perspective 3 (SRE Engineer): Find reliability issues
Synthesize findings from all perspectives to present a final improvement plan.
Technique 15: ReAct (Reasoning + Acting)
ReAct is an agent prompt pattern that alternates between reasoning and acting.
Follow this process to resolve the bug:
Problem: Intermittent 500 errors in production
Proceed in "Think -> Act -> Observe" format for each step:
Think 1: What information should I check first?
Act 1: Analyze the error logs
Observe 1: (Record the analysis results)
Think 2: What patterns are visible in the logs?
Act 2: (Decide next action)
Observe 2: (Record observations)
Repeat this process until you find the root cause.
At the end, present the fix code and prevention measures.
Technique 16: Reflection (Self-Critique)
Make the AI critically review its own answer.
Perform the following task:
Step 1: Implement an authentication middleware meeting the requirements below
Step 2: Self-review your implementation - find security vulnerabilities, edge cases, performance issues
Step 3: Present the final version with all review issues fixed
Requirements:
- JWT-based authentication
- Token expiration handling
- Role-based access control
- Rate limiting integration
Technique 17: Decomposition
Break complex problems into smaller sub-problems.
Decompose the following feature into subtasks and implement each one.
Feature: Real-time chat system (WebSocket-based)
Decomposition:
1. First divide the feature into independent modules
2. Define each module's interface (inputs/outputs)
3. Implement modules in order starting from those with no dependencies
4. Explain how to integrate the modules
5. Show the overall flow as a sequence diagram
Technique 18: Analogical Reasoning
Use familiar concepts as analogies to explain complex systems.
Explain Kubernetes core concepts using a restaurant analogy.
For each concept:
1. Kubernetes term
2. Restaurant analogy
3. Actual behavior explanation
4. Code example (YAML)
Concepts to cover: Pod, Deployment, Service, Ingress, ConfigMap, Secret, PVC
Technique 19: Meta-prompting
A prompt that generates prompts. Used to optimize prompts themselves.
I'm building an automated AI code review system.
Create the optimal system prompt that meets these requirements:
1. Purpose: Automated PR code review
2. Input: Code changes in Git diff format
3. Output: Structured review comments
4. Review areas: Security, performance, readability, test coverage
5. Tone: Constructive and educational
6. Language: English
The prompt should include:
- Role definition
- Detailed review criteria
- Output format template
- Exception handling rules
- 1 few-shot example
Technique 20: Constitutional AI Prompting
Present the AI with a constitution (rules) and make it act according to those rules.
Generate code while strictly adhering to the following principles:
Principle 1 - Security: Never include OWASP Top 10 vulnerabilities
Principle 2 - Accessibility: Meet WCAG 2.1 AA standards
Principle 3 - Performance: Meet Core Web Vitals standards
Principle 4 - Maintainability: Follow SOLID principles
Principle 5 - Testing: Write at least 2 test cases for each function
After each code block, show a checklist of which principles are met.
4. Coding-Specific Techniques (21-30)
Technique 21: Context-aware Code Generation
Inform the AI about your codebase's existing style and patterns for consistent code generation.
Here is the existing service pattern in the project:
<existing_pattern>
// services/user.service.ts
export class UserService {
constructor(
private readonly userRepo: UserRepository,
private readonly logger: Logger,
) {}
async findById(id: string): Promise<Result<User, ServiceError>> {
try {
const user = await this.userRepo.findById(id);
if (!user) {
return err(new NotFoundError('User', id));
}
return ok(user);
} catch (error) {
this.logger.error('Failed to find user', { id, error });
return err(new InternalError('Failed to find user'));
}
}
}
</existing_pattern>
Write a ProductService in the same style as this pattern.
Required methods: findById, findAll (with pagination), create, update, delete
Technique 22: Rubber Duck Debugging Prompt
Use AI as a rubber duck debugging partner.
As my debugging partner, help me solve the following problem.
Symptom: User automatically logged out 3 minutes after login
What I know:
- JWT token expiration is set to 1 hour
- Cannot reproduce in local environment
- Only occurs in production
- Started after March 14th deployment
What I've tried:
- Checked token expiration time -> normal
- Checked browser cookies -> token disappears
Guide me with questions:
1. What possible causes haven't I checked yet?
2. What specific steps would verify each cause?
3. What do you reason is the most likely cause?
Technique 23: Code Review Prompt Template
A systematic code review template.
Review the following code according to this checklist.
Review checklist:
1. Correctness: Does it work as intended?
2. Security: Are there SQL injection, XSS, CSRF vulnerabilities?
3. Performance: Are there unnecessary computations, N+1 queries, memory leaks?
4. Error handling: Are all failure paths properly handled?
5. Readability: Do variable and function names convey meaning well?
6. Testability: Is the structure easy to test?
7. Extensibility: Is it flexible to requirement changes?
Output format:
Mark each item as Pass/Fail/Warning.
For Fail or Warning, provide specific improved code.
Severity: Critical > Major > Minor > Suggestion
Technique 24: Test Generation from Implementation
Automatically generate tests based on implementation code.
Write comprehensive tests for the following function.
Function:
```typescript
export function calculateDiscount(
originalPrice: number,
membershipTier: 'basic' | 'silver' | 'gold' | 'platinum',
couponCode?: string,
): { finalPrice: number; discountRate: number; appliedDiscounts: string[] } {
// ... implementation
}
Test requirements:
- Test framework: Vitest
- Discount tests for each membership tier
- Coupon code application tests
- Boundary value tests (price 0, negative, very large)
- Error cases (invalid coupon, invalid tier)
- Combined discount (membership + coupon) tests
- Structured with describe/it pattern
- Descriptive test names
### Technique 25: Refactoring with Specific Goals
Provide specific refactoring goals.
```text
Refactor the following code.
Refactoring goals:
1. Function separation: One function = one responsibility
2. Remove magic numbers: Replace with meaningful constants
3. Apply early return pattern: Eliminate nested if statements
4. Strengthen type safety: Use union types and type guards
Refactoring process:
- Show before and after side by side
- Explain the reason for each change
- Confirm that behavior has not changed
Technique 26: Architecture Design Prompts
Design system architecture together with AI.
Design a system architecture for the following requirements.
Service: Real-time auction platform
- Concurrent users: up to 100,000
- Real-time bid updates (latency under 100ms)
- Payment processing (payment gateway integration)
- Image upload (up to 10 per product)
Deliverables:
1. High-level architecture diagram (Mermaid)
2. Tech stack selection with rationale for each component
3. Data flow diagram
4. Scalability strategy (horizontal scaling points)
5. Failure response strategy (SPOF identification and alternatives)
6. Estimated monthly cost (AWS-based)
Technique 27: Documentation Generation
Automatically generate documentation from code.
Create API documentation based on the following endpoint code.
Format: OpenAPI 3.0 YAML
Include:
1. Endpoint description
2. Request parameters (path, query, body)
3. Response schema (both success and failure)
4. Authentication method
5. Rate limit information
6. Usage examples (curl)
7. Error code table
Technique 28: Error Explanation and Fix
Analyze error messages and provide fixes.
Analyze the following error and fix it.
Error message:
TypeError: Cannot read properties of undefined (reading 'map')
at UserList (UserList.tsx:15:23)
at renderWithHooks (react-dom.development.js:16305:18)
Context:
- React 18 + TypeScript project
- Component that fetches user list from API and renders it
- Occurs intermittently (when network is slow)
Include:
1. Root cause analysis (why it is undefined)
2. Fix code
3. General guidelines to prevent the same pattern of errors
4. How to catch this error at compile time with types
Technique 29: Performance Optimization Prompts
Systematically perform performance optimization.
Optimize the performance of the following API endpoint.
Current state:
- Average response time: 2.5 seconds
- P99 response time: 8 seconds
- Requests per second: 500 RPS
- Target: average under 200ms, P99 under 500ms
Analysis order:
1. Identify performance bottleneck points in the current code
2. Propose optimization strategies for each bottleneck
3. Show expected improvement in numbers
4. Present optimized code
5. Write benchmark code comparing before and after
Technique 30: Security Audit Prompts
Perform security audits with AI assistance.
Perform a security audit on the following code.
Audit items:
1. OWASP Top 10 (2021) vulnerabilities
2. Authentication/authorization vulnerabilities
3. Data exposure risks
4. Potential dependency vulnerabilities
5. Configuration errors
Output format:
For each finding:
- Vulnerability type: (e.g., A01 Broken Access Control)
- Severity: Critical / High / Medium / Low
- Location: filename and line number
- Description: how the vulnerability can be exploited
- Fix code: secure code example
- Reference: CWE number or related documentation link
5. Model-Specific Optimization
Claude vs GPT-4 vs Gemini Comparison
| Technique | Claude | GPT-4 | Gemini |
|---|---|---|---|
| XML tag delimiters | Very effective | Moderate | Moderate |
| JSON mode | Supported | Native support | Supported |
| System prompt | Very important | Important | Important |
| Long context | 200K | 128K | 2M |
| Multimodal | Image analysis | Image+DALL-E | Image+Video+Audio |
| Code execution | None | Code Interpreter | Code execution |
| Function calling | Tool Use | Function Calling | Function Calling |
Claude Optimization Tips
Tips for getting the best results from Claude:
1. Use XML tags extensively
<context>Project background and tech stack</context>
<task>Specific task description</task>
<constraints>Constraints</constraints>
<examples>Reference examples</examples>
<output_format>Desired output format</output_format>
2. Explicitly request "Think step by step"
Analyze this problem step by step.
Show your reasoning process at each stage.
3. Make full use of the system prompt
Claude responds particularly strongly to system prompts. Put roles, rules, and formats in the system prompt for consistent results.
GPT-4 Optimization Tips
1. Use JSON mode
Please respond in JSON format.
Return only pure JSON without any other text.
2. Leverage Function Calling
GPT-4's native Function Calling is highly effective for structured output. It is especially useful for API integration.
3. Use Code Interpreter
For data analysis, visualization, and complex calculations, Code Interpreter delivers accurate results.
Gemini Optimization Tips
1. Leverage the long context
Gemini's 2M token context window is advantageous for analyzing entire codebases at once.
Here is the project's entire source code.
(attach full code)
Analyze the entire codebase and suggest architecture improvements.
2. Use multimodal input
You can use screenshots, whiteboard photos, and diagram images as inputs.
3. Use Grounding
Google Search-based grounding provides responses that leverage the latest information.
6. Prompt Anti-patterns
Anti-pattern 1: Vague Instructions
# Bad
Fix the code
# Good
Fix the N+1 query problem in the following Python function.
Optimize using SQLAlchemy's joinedload.
Anti-pattern 2: Information Overload
# Bad
(paste 10,000 lines of code)
Review all this code
# Good
Here is the core logic of the payment processing module (relevant parts only).
I suspect a floating-point error in the amount calculation.
Please focus your review on that section.
Anti-pattern 3: Conflicting Constraints
# Bad
Make it fast while using minimum memory
and write the code as readable as possible
handle all edge cases but keep it under 20 lines
# Good
Priorities:
1. (Required) Memory usage under 100MB
2. (Important) Response time under 200ms
3. (Nice-to-have) Code readability (where feasible)
Anti-pattern 4: Hallucination-inducing Prompts
# Bad
Tell me about React 25's new Server Actions API
(asking about a nonexistent version/feature)
# Good
Explain React's latest Server Actions API to the extent you know.
If you're unsure about anything, let me know.
Anti-pattern 5: Over-prompting Simple Tasks
# Bad (verbose prompt for a simple variable rename)
You are a software architect with 20 years of experience.
Following clean code principles, please improve the
name of the following variable.
Variable name: x
Context: A variable that stores the user's age.
# Good
Rename variable x to something meaningful. (stores user age)
7. Prompt Chaining and Agents
Prompt Chaining Overview
Prompt chaining connects multiple prompts sequentially to perform complex tasks. The output of one prompt becomes the input of the next.
Example: Code refactoring chain
Chain 1: Analysis
"List the code smells in the following code. Output as a JSON array."
Chain 2: Prioritization
"Sort the following code smell list by severity. (Input: Chain 1 output)"
Chain 3: Fix
"Fix the 3 most severe code smells and present the corrected code. (Input: Chain 2 output)"
Chain 4: Verification
"Verify that the corrected code behaves identically to the original. (Input: Chain 3 output)"
Agent Loop (Observe - Think - Act)
AI agents perform complex tasks by repeating the Observe-Think-Act loop.
Use the following agent loop to resolve a production incident:
Loop:
1. OBSERVE: Check current state (logs, metrics, alerts)
2. THINK: Analyze causes and plan actions
3. ACT: Execute specific measures
4. VERIFY: Confirm the results of the action
Incident: Database connection pool exhaustion
Show each loop iteration explicitly.
Repeat the loop until the problem is resolved at the VERIFY step.
MCP (Model Context Protocol) Integration
MCP connects AI to external tools.
Perform a code quality check using the following tools:
Available tools:
1. file_read: Read files
2. file_write: Write files
3. terminal: Execute terminal commands
4. git: Execute Git commands
Task sequence:
1. Check changed files with git diff
2. Read each file
3. Run ESLint
4. Run TypeScript compile check
5. Run tests
6. Generate a consolidated report
Memory and Context Management
How to efficiently manage context in long conversations.
Previous conversation summary (context compression):
Project: Next.js e-commerce
Completed: Product listing API, Cart API
Current task: Payment processing API
Technical decisions: Using Stripe, managing payment status via Webhook
Based on the context above, proceed with the next step of the payment processing API.
8. Practical Templates (10)
Template 1: New Feature Implementation
## Feature Request
[Feature name and brief description]
## Background
- Why is this feature needed?
- What problem does it solve?
## Tech Stack
- Framework:
- Language:
- Database:
- Existing pattern reference:
## Requirements
1. [Must-have requirement]
2. [Must-have requirement]
3. [Nice-to-have requirement]
## Constraints
- [Performance requirements]
- [Security requirements]
## Output
1. Implementation code
2. Unit tests
3. API documentation (if applicable)
Template 2: Bug Fix Request
## Bug Description
[What symptoms are occurring]
## Reproduction Steps
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Expected Behavior
[How it should work]
## Actual Behavior
[How it currently works]
## Related Code
[Paste code]
## Environment
- OS:
- Node.js:
- Browser:
## Request
1. Root cause analysis
2. Fix code
3. Tests to prevent recurrence
Template 3: Code Review Request
## PR Summary
[What this PR changes]
## Changed Code
[diff or code]
## Review Perspectives
- [ ] Logic correctness
- [ ] Security
- [ ] Performance
- [ ] Error handling
- [ ] Test coverage
- [ ] Coding conventions
## Please Specifically Check
[Particular concerns about specific sections]
Template 4: Architecture Design
## System Overview
[System purpose and core features]
## Non-functional Requirements
- Concurrent users:
- Response time:
- Availability:
- Data retention:
## Existing Infrastructure
[Current tech and infrastructure in use]
## Request
1. Architecture diagram
2. Tech stack selection with rationale
3. Data model
4. API design
5. Scaling strategy
6. Cost estimation
Template 5: Database Schema Design
## Domain
[Business domain description]
## Entities
[Key entities and relationships]
## Requirements
- Read/write ratio:
- Expected data size:
- Query patterns:
## Request
1. ERD (Mermaid)
2. SQL DDL
3. Index strategy
4. Migration scripts
Template 6: API Design
## API Purpose
[Functionality the API provides]
## RESTful Design
- Resource definitions
- HTTP method mapping
- URL structure
## Request
1. OpenAPI 3.0 spec
2. Request/response examples
3. Error code definitions
4. Authentication/authorization
5. Rate limiting policy
6. Versioning strategy
Template 7: CI/CD Pipeline
## Project Info
- Language/Framework:
- Deployment target:
- Branch strategy:
## Requirements
- Build stage
- Test stages (unit, integration, E2E)
- Security scanning
- Deployment strategy (Blue-Green / Canary / Rolling)
## Request
1. Pipeline YAML (GitHub Actions / GitLab CI)
2. Description of each stage
3. Secret management approach
4. Rollback strategy
Template 8: Performance Optimization
## Current State
- Measured metrics: [response time, throughput, error rate]
- Suspected bottleneck: [description]
## Target
- Response time: [current] -> [target]
- Throughput: [current] -> [target]
## Code
[Code to optimize]
## Request
1. Bottleneck analysis
2. Optimization strategies (in priority order)
3. Optimized code
4. Benchmark code
Template 9: Migration Guide
## Migration Target
- FROM: [current technology/version]
- TO: [target technology/version]
## Current Code
[Code to migrate]
## Requirements
- Backward compatibility required?
- Gradual migration possible?
- Acceptable downtime range
## Request
1. Migration plan (step-by-step)
2. Changed code
3. Compatibility verification tests
4. Rollback plan
Template 10: Incident Response
## Incident Info
- Time occurred:
- Impact scope:
- Severity:
## Current Symptoms
[Error logs, metric screenshots, alert content]
## System Architecture
[Related service architecture]
## Request
1. Immediate response (mitigation measures)
2. Root cause analysis
3. Fix plan
4. Prevention measures
5. Postmortem draft
Quiz
Let's test what you have learned.
Quiz 1: Which of the following correctly describes Few-shot prompting?
Answer: A technique where a small number of examples are included in the prompt so the AI learns the desired pattern
Zero-shot gives instructions without examples, while Few-shot includes 3-5 examples. More examples are not always better -- you must consider token cost and context window.
Quiz 2: What kind of output do you get with Temperature set to 0.0?
Answer: Deterministic output -- always the same result for the same input
Temperature 0.0 is suitable for tasks where accuracy matters, such as code generation and data parsing. For creative tasks, 0.7 or higher is recommended.
Quiz 3: What is the difference between Chain-of-Thought and Tree-of-Thought?
Answer:
- CoT: Progresses step by step along a single reasoning path (linear)
- ToT: Explores multiple reasoning paths simultaneously and selects the optimal one (branching)
CoT is sequential like "Analyzing A gives B, and from B we can determine C." ToT is a comparative approach like "Compare approaches A, B, and C, then select the best one."
Quiz 4: What is the most effective way to structure prompts in Claude?
Answer: Use XML tags
Claude responds particularly well to XML tags. Structuring prompts with tags like context, task, constraints, and output_format yields more accurate responses.
Quiz 5: What are the 3 stages of the ReAct pattern?
Answer: Reasoning - Acting - Observation
ReAct is an agent pattern that alternates between reasoning and acting. The AI thinks about the problem, takes an action, observes the result, and then thinks again. This loop repeats until the task is complete. This pattern is highly effective for complex debugging and system problem resolution.
References
Papers and Academic Resources
- Chain-of-Thought Prompting Elicits Reasoning in Large Language Models - Wei et al., 2022
- Tree of Thoughts: Deliberate Problem Solving with Large Language Models - Yao et al., 2023
- ReAct: Synergizing Reasoning and Acting in Language Models - Yao et al., 2022
- Self-Consistency Improves Chain of Thought Reasoning - Wang et al., 2022
- Constitutional AI: Harmlessness from AI Feedback - Bai et al., 2022
Official Documentation
- Anthropic Prompt Engineering Guide - docs.anthropic.com
- OpenAI Prompt Engineering Guide - platform.openai.com
- Google AI Prompt Engineering - ai.google.dev
- GitHub Copilot Best Practices - docs.github.com
Practical Guides
- Prompt Engineering Guide - promptingguide.ai
- LangChain Documentation - docs.langchain.com
- LlamaIndex Documentation - docs.llamaindex.ai
- Brex Prompt Engineering - GitHub (brexhq/prompt-engineering)
Tools and Frameworks
- LangSmith - Prompt testing and evaluation tool
- PromptLayer - Prompt management platform
- Weights and Biases Prompts - Prompt version control
- Helicone - LLM monitoring and prompt analysis
Community
- r/PromptEngineering - Reddit community
- Awesome Prompt Engineering - GitHub curation
- AI Developer Discord Communities - Real-time knowledge exchange