Promptfoo와 로컬 Ollama로 티켓 분류 프롬프트와 JSON 출력 비교하기
외부 API 비용 없이 Promptfoo 0.126.0과 로컬 Ollama qwen2.5:1.5b로 티켓 분류 프롬프트와 format: json 및 JSON Schema 출력 차이를 검증하는 방법을 정리합니다.
프롬프트 문구를 바꿀 때마다 채팅창에 예시를 붙여 넣어 눈으로 확인하면, 이전 케이스에서 깨진 규칙을 놓치기 쉽습니다. Promptfoo와 로컬 Ollama를 연결하면 외부 API 비용 없이 프롬프트 버전과
format: json·JSON Schema 옵션의 차이를 같은 입력으로 정량 비교할 수 있습니다.
이 글의 모든 실행 결과는 macOS(Apple Silicon), Node.js
v22.23.3, Promptfoo0.126.0, Ollama0.40.18(qwen2.5:1.5b) 환경에서 실제 로컬POST /api/chat호출로 확인했습니다.
로컬 모델로 프롬프트 변경을 비교할 때 부딪히는 문제
고객 지원 티켓을 { category, priority, requires_escalation, summary } 형태의 JSON으로 자동 분류하는 백엔드 기능을 만든다고 가정합니다. 프롬프트를 조금 다듬으면 특정 티켓은 잘 분류되지만, 다른 티켓의 category 값이 허용 목록을 벗어나거나 긴급 장애의 requires_escalation이 false로 바뀌는 회귀가 종종 발생합니다.
외부 유료 API로 프롬프트 초안을 반복 실험하면 호출 비용과 속도 제한이 부담됩니다. 반면 로컬 Ollama 서버에 Promptfoo를 붙이면 동일한 티켓 데이터셋을 여러 프롬프트와 출력 옵션에 걸쳐 한 번에 실행하고, 스키마 위반과 도메인 규칙 위반을 별도 지표로 집계할 수 있습니다.
다만 로컬 환경에서 Ollama를 평가 대상으로 붙일 때는 클라우드 API와 다른 세 가지 조건을 먼저 잡아야 합니다.
- 동시 요청 제한: Promptfoo는 기본적으로 여러 테스트를 병렬로 보냅니다. 로컬 GPU·메모리 자원이 넉넉하지 않을 때 요청이 한꺼번에 몰리면 응답 지연이 튀거나 타임아웃이 발생하므로
--max-concurrency 1로 순차 실행하는 편이 안정적입니다. - 메모리 점유 해제: Ollama는 기본 설정에서 요청이 끝난 뒤에도 모델을 메모리에 일정 시간 유지합니다. 평가 직후 다른 개발 도구를 써야 한다면 프로바이더 설정에
keep_alive: 0을 넣어 요청 종료 시점에 바로 언로드하도록 제어할 수 있습니다. - 캐시 비활성화와 시드 고정: 프롬프트나 모델 옵션을 바꿔 비교할 때 디스크 캐시가 끼어들면 실제 모델 응답 대신 이전 결과가 재사용될 수 있습니다. 비교 실행에서는
--no-cache를 붙이고temperature: 0,seed: 42로 샘플링 변동을 줄입니다.
Ollama 프로바이더와 비교 매트릭스 구성
먼저 작업 디렉터리에서 Promptfoo 버전을 고정 설치합니다. 전역 설치 대신 로컬 devDependencies로 두면 팀원이나 다른 머신에서도 같은 버전으로 재현하기 쉽습니다.
1
2
npm init -y
npm install --save-exact promptfoo@0.126.0
비교할 프롬프트는 두 가지입니다. prompts/triage-v1.txt는 필요한 키 이름만 알려 주는 단순 지시문이고, prompts/triage-v2.txt는 허용 enum 값과 에스컬레이션 기준을 명시한 지시문입니다.
1
2
3
4
5
# prompts/triage-v1.txt
Classify this customer support ticket and respond in JSON with category, priority, requires_escalation, and summary.
Ticket:
{{ticket}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# prompts/triage-v2.txt
You are a support ticket triage classifier.
Return ONLY a single JSON object with these exact four keys and no extra keys:
- "category": one of "bug", "billing", "feature"
- "priority": one of "high", "medium", "low"
- "requires_escalation": boolean
- "summary": concise one-sentence summary (non-empty string)
Classification rules:
1. Production outages or HTTP 500 errors affecting orders -> category "bug", priority "high", requires_escalation true.
2. Duplicate charges, refunds, or invoice billing issues -> category "billing", priority "medium", requires_escalation false.
3. New feature or enhancement requests -> category "feature", priority "low", requires_escalation false.
Ticket:
{{ticket}}
이제 promptfooconfig.yaml에서 ollama:chat:qwen2.5:1.5b 프로바이더와 티켓 3건(장애, 중복 결제, 기능 요청)을 연결합니다. 로컬 Ollama 서버가 기본 주소(http://localhost:11434)가 아닌 포트에 떠 있다면 실행 시 OLLAMA_BASE_URL 환경 변수로 주소를 지정합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# promptfooconfig.yaml
description: "Local Ollama ticket triage prompt comparison (v1 vs v2)"
prompts:
- id: file://prompts/triage-v1.txt
label: "v1-basic"
- id: file://prompts/triage-v2.txt
label: "v2-strict"
providers:
- id: ollama:chat:qwen2.5:1.5b
label: "qwen2.5:1.5b (format=json)"
config:
temperature: 0
seed: 42
keep_alive: 0
format: json
defaultTest:
assert:
- type: is-json
value: file://triage.schema.json
metric: JSON schema
- type: javascript
value: file://triage-rules.cjs
metric: Triage rules
tests:
- description: "Checkout HTTP 500 outage"
vars:
ticket: "Checkout returns HTTP 500 for all KR cards since 14:10 KST. Orders are failing."
expectedCategory: "bug"
expectedPriority: "high"
expectedEscalation: true
- description: "Duplicate invoice charge"
vars:
ticket: "I was charged twice for invoice #INV-4092 and need a refund for the duplicate charge."
expectedCategory: "billing"
expectedPriority: "medium"
expectedEscalation: false
- description: "CSV export feature request"
vars:
ticket: "Could you add CSV export to the monthly usage dashboard?"
expectedCategory: "feature"
expectedPriority: "low"
expectedEscalation: false
ollama:chat:<model> 프로바이더의 config.format에는 두 가지 값을 넣을 수 있습니다. 문자열 json은 모델이 문법적으로 유효한 JSON 객체만 생성하도록 제한합니다. 반면 아래처럼 JSON Schema 객체를 직접 넘기면 Ollama가 디코딩 단계에서 지정한 키, 타입, enum 목록에 맞는 토큰만 허용하는 구조화 출력(Structured Outputs) 모드로 동작합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# promptfooconfig-schema.yaml (providers 섹션 발췌)
providers:
- id: ollama:chat:qwen2.5:1.5b
label: "format: json"
config:
temperature: 0
seed: 42
keep_alive: 0
format: json
- id: ollama:chat:qwen2.5:1.5b
label: "format: json-schema"
config:
temperature: 0
seed: 42
keep_alive: 0
format:
type: object
additionalProperties: false
required: [category, priority, requires_escalation, summary]
properties:
category:
type: string
enum: ["bug", "billing", "feature"]
priority:
type: string
enum: ["high", "medium", "low"]
requires_escalation:
type: boolean
summary:
type: string
JSON 스키마와 분류 규칙 assertion 분리
출력이 JSON인지 확인하는 검사와 비즈니스 분류가 맞는지 확인하는 검사를 하나의 assertion에 섞으면, 실패했을 때 프롬프트 형식이 깨진 것인지 판단 기준이 틀린 것인지 한눈에 구분하기 어렵습니다. 그래서 defaultTest.assert에 metric 이름을 달리해 두 단계로 나눕니다.
첫 번째 단계인 is-json은 triage.schema.json을 읽어 추가 키 금지(additionalProperties: false), 필수 필드, 허용 enum, summary 최소 길이를 검증합니다.
1
2
3
4
5
6
7
8
9
10
11
12
// triage.schema.json
{
"type": "object",
"additionalProperties": false,
"required": ["category", "priority", "requires_escalation", "summary"],
"properties": {
"category": { "type": "string", "enum": ["bug", "billing", "feature"] },
"priority": { "type": "string", "enum": ["high", "medium", "low"] },
"requires_escalation": { "type": "boolean" },
"summary": { "type": "string", "minLength": 5 }
}
}
두 번째 단계인 javascript assertion은 응답 JSON을 파싱한 뒤 각 테스트 케이스의 context.vars에 정의한 기대값과 대조합니다. 불일치 항목을 문자열 배열에 모아 { pass, score, reason } 객체로 반환하면, 나중에 웹 UI와 JSON 리포트에서 어떤 필드가 기대값과 달랐는지 바로 읽을 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// triage-rules.cjs
module.exports = (output, context) => {
let data;
try {
data = JSON.parse(output);
} catch (err) {
return { pass: false, score: 0, reason: `Invalid JSON: ${err.message}` };
}
const vars = context.vars || {};
const failures = [];
if (data.category !== vars.expectedCategory) {
failures.push(`category=${JSON.stringify(data.category)} (expected ${JSON.stringify(vars.expectedCategory)})`);
}
const allowedPriorities = String(vars.expectedPriority || '').split('|').filter(Boolean);
if (allowedPriorities.length > 0 && !allowedPriorities.includes(data.priority)) {
failures.push(`priority=${JSON.stringify(data.priority)} (expected ${allowedPriorities.join(' or ')})`);
}
const expectedEsc = vars.expectedEscalation === true || vars.expectedEscalation === 'true';
if (data.requires_escalation !== expectedEsc) {
failures.push(`requires_escalation=${JSON.stringify(data.requires_escalation)} (expected ${expectedEsc})`);
}
if (failures.length > 0) {
return { pass: false, score: 0, reason: failures.join('; ') };
}
return {
pass: true,
score: 1,
reason: `Matched ${data.category}/${data.priority}/escalation=${data.requires_escalation}`,
};
};
로컬 실행 결과와 format: json · JSON Schema 비교
로컬 설정과 캐시가 전역 ~/.promptfoo 디렉터리와 섞이지 않도록 환경 변수를 분리해 평가를 실행했습니다. 첫 번째 실행은 format: json 고정 조건에서 v1-basic과 v2-strict를 비교하는 6셀(프롬프트 2종 × 티켓 3건) 평가입니다.
1
2
3
4
5
6
7
PROMPTFOO_CONFIG_DIR=./.pf-config \
PROMPTFOO_CACHE_PATH=./.pf-cache \
npx promptfoo eval \
-c promptfooconfig.yaml \
--max-concurrency 1 \
--no-cache \
-o results-v1v2.json
로컬 Ollama qwen2.5:1.5b에서 6셀은 에러 없이 6.1초 만에 끝났고 총 1,134토큰(v1-basic 366토큰, v2-strict 768토큰)을 사용했습니다. results-v1v2.json에 기록된 셀별 응답 지연 시간(latencyMs)은 881ms에서 1,301ms 사이였습니다.
실행 결과를 로컬 웹 UI(npx promptfoo view)로 열면 두 프롬프트의 통과율, 토큰 수, 평균 지연 시간, 그리고 실패한 assertion 사유가 같은 표에 나란히 배치됩니다.
그림 1. 로컬 Ollama qwen2.5:1.5b(format: json)로 실행한 v1-basic vs v2-strict 비교 매트릭스 (promptfoo view).
v1-basic은 3건 모두 문법적으로 유효한 JSON을 반환했지만 category에 "Technical Support", "Payment Error", "Feature Request"처럼 임의의 문자열을 만들어 냈습니다. 결과적으로 JSON schema와 Triage rules 모두 0/3 실패였습니다. 반면 허용 값과 분류 규칙을 명시한 v2-strict는 3건 모두 두 지표를 통과했습니다.
여기서 한 가지 의문이 남습니다. 프롬프트(v1-basic)는 그대로 두고 Ollama의 format 옵션만 JSON Schema 객체로 바꾸면 분류 정확도까지 함께 해결될까요? 이를 확인하기 위해 promptfooconfig-schema.yaml로 프로바이더 2종(format: json, format: json-schema) × 프롬프트 2종 × 티켓 3건, 총 12셀을 같은 조건(--max-concurrency 1 --no-cache)으로 실행했습니다.
조합 (qwen2.5:1.5b) | Checkout HTTP 500 장애 | 중복 결제 환불 요청 | CSV 내보내기 기능 요청 | JSON schema | Triage rules | 최종 통과 |
|---|---|---|---|---|---|---|
format: json + v1-basic | FAIL (Technical Support, High, false) | FAIL (Payment Error, High, false) | FAIL (Feature Request, Normal, false) | 0/3 | 0/3 | 0/3 |
format: json-schema + v1-basic | FAIL (billing, high, false) | FAIL (billing, high, false) | PASS (feature, low, false) | 3/3 | 1/3 | 1/3 |
format: json + v2-strict | PASS (bug, high, true) | PASS (billing, medium, false) | PASS (feature, low, false) | 3/3 | 3/3 | 3/3 |
format: json-schema + v2-strict | PASS (bug, high, true) | PASS (billing, medium, false) | PASS (feature, low, false) | 3/3 | 3/3 | 3/3 |
결과가 분명하게 갈렸습니다. format: json-schema를 켜자 v1-basic의 JSON schema 통과율은 0/3에서 3/3으로 올라갔습니다. 디코딩 제약 덕분에 모델이 허용 목록 밖의 문자열을 아예 생성하지 못했기 때문입니다.
그러나 Triage rules는 여전히 1/3에 머물렀습니다. HTTP 500 결제 장애 티켓을 "billing"과 requires_escalation: false로 잘못 분류했고, 중복 결제 티켓도 기대한 "medium" 대신 "high"를 출력했습니다. 스키마 강제 디코딩은 출력 형식과 enum 계약을 지키는 안전장치일 뿐, 어떤 상황을 장애로 보고 에스컬레이션할지 판단하는 도메인 분류 규칙을 대신하지 못합니다.
실패 원인을 CLI나 스크립트에서 바로 확인해야 할 때는 내보낸 results-v1v2.json과 results-schema.json의 latencyMs와 gradingResult.componentResults 배열을 조회하면 됩니다. 아래는 12셀 실행 결과(results-schema.json) 중 format: json-schema + v1-basic의 첫 번째 티켓에서 기록된 실제 필드 요약입니다.
1
2
3
4
5
6
7
8
9
10
11
12
{
"latencyMs": 977,
"output": "{\"category\":\"billing\",\"priority\":\"high\",\"requires_escalation\":false,\"summary\":\"...\"}",
"componentResults": [
{ "metric": "JSON schema", "pass": true, "reason": "Assertion passed" },
{
"metric": "Triage rules",
"pass": false,
"reason": "category=\"billing\" (expected \"bug\"); requires_escalation=false (expected true)"
}
]
}
로컬 평가의 한계와 실무 적용 전 점검 항목
상황에 따라 format: json, format: <JSON Schema>, 프롬프트 규칙 명시를 어떻게 조합할지 정리하면 다음과 같습니다.
| 구성 요소 | 보장하는 범위 | 보장하지 못하는 범위 | 권장 용도 |
|---|---|---|---|
format: json | 문법적으로 파싱 가능한 JSON 객체 | 키 누락, 추가 키, 허용 enum, 도메인 정확도 | 빠른 프로토타이핑, 스키마가 자주 바뀌는 초기 탐색 |
format: <JSON Schema> | 필수 키, 타입, additionalProperties: false, 허용 enum | 입력 맥락에 따른 분류·에스컬레이션 판단 | 파서 장애를 막아야 하는 구조화 출력 파이프라인 |
| 프롬프트 규칙 명시 + assertion | 도메인 분류 기준과 회귀 여부 정량 검증 | 디코딩 수준에서의 출력 토큰 강제 | 운영 배포 전 프롬프트 버전 비교 및 품질 기준선 관리 |
로컬 Ollama 소형 모델(
qwen2.5:1.5b등) 평가는 프롬프트 구조 결함, 스키마 누락, 기본 분류 규칙 회귀를 비용 없이 빠르게 거르는 용도에 적합합니다. 반대로 운영 환경에서 대형 클라우드 모델의 복잡한 추론 품질이나 미묘한 뉘앙스를 최종 판정하는 용도로는 로컬 소형 모델 결과를 그대로 대체해 쓰지 말아야 합니다. 소형 모델은 동일한seed와temperature: 0에서도 모델 태그나 양자화 버전이 바뀌면 출력이 달라질 수 있습니다.
실무 프로젝트에 로컬 Ollama 기반 프롬프트 평가를 붙이기 전에 아래 네 가지를 점검하면 불필요한 시행착오를 줄일 수 있습니다.
- 모델 태그와 실행 옵션을 설정 파일에 고정:
qwen2.5:1.5b처럼 정확한 태그와temperature: 0,seed,keep_alive: 0을promptfooconfig.yaml에 함께 기록합니다. - 형식 검사와 규칙 검사를 별도
metric으로 분리:is-json과 도메인 규칙javascriptassertion을 분리해야 스키마 문제와 분류 로직 문제를 혼동하지 않습니다. - 비교 실행 시 동시성과 캐시 정책 명시: 로컬 장비에서는
--max-concurrency 1 --no-cache를 기본 명령으로 두어 지연 시간 왜곡과 캐시 재사용을 막습니다. - 최종 배포 전 운영 모델 교차 검증: 로컬 모델에서 프롬프트 구조와 규칙을 1차 정리한 뒤, 실제 운영 트래픽을 처리할 타깃 모델에서도 같은 테스트 스위트를 한 번 더 돌려 품질 기준을 확인합니다.