GPT-4 API로 프롬프트 템플릿 시스템 구축하기
배경
고객 문의를 카테고리별로 자동 분류하는 기능을 GPT-4 API로 구축했다. 초기에는 프롬프트를 코드에 하드코딩했는데, 요구사항이 추가될 때마다 코드 수정이 필요했고 프롬프트 버전 관리가 어려웠다.
템플릿 시스템 설계
프롬프트를 별도 파일로 분리하고 변수 치환 방식을 도입했다.
// prompts/classify-inquiry.txt
You are a customer service classifier.
Classify the following inquiry into one of these categories: {{categories}}
Inquiry: {{inquiry}}
Category:
interface PromptTemplate {
load(name: string): string;
render(template: string, variables: Record<string, string>): string;
}
class FilePromptTemplate implements PromptTemplate {
private cache: Map<string, string> = new Map();
load(name: string): string {
if (!this.cache.has(name)) {
const content = fs.readFileSync(`./prompts/${name}.txt`, 'utf-8');
this.cache.set(name, content);
}
return this.cache.get(name)!;
}
render(template: string, variables: Record<string, string>): string {
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => variables[key] || '');
}
}
사용 예시
const promptTemplate = new FilePromptTemplate();
const template = promptTemplate.load('classify-inquiry');
const prompt = promptTemplate.render(template, {
categories: '결제, 배송, 반품, 기타',
inquiry: '주문한 상품이 언제 도착하나요?'
});
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: prompt }],
temperature: 0.3
});
효과
프롬프트 수정이 필요할 때 배포 없이 텍스트 파일만 변경하면 됐다. 프롬프트 엔지니어링 작업을 비개발자도 참여할 수 있게 됐고, Git으로 프롬프트 변경 이력을 추적할 수 있어 A/B 테스트에도 유용했다.
추후 데이터베이스 기반으로 전환하면 런타임 프롬프트 수정도 가능할 것 같다.