OpenRouter 구조화 출력과 스키마 검증 파이프라인 구현하기
OpenRouter 구조화 출력(json_schema, strict), require_parameters, response-healing 경계와 Python 4단계 JSON Schema 검증 파이프라인 구현을 다룹니다.
OpenRouter 요청에
response_format(json_schema,strict: true)을 지정해도 미지원 엔드포인트 라우팅, 토큰 절단, 구문 결함, 도메인 산술 불일치로 적재 파이프라인은 여전히 실패할 수 있습니다. 공개 API 실측과 Python 4단계 검증 파이프라인을 통해provider.require_parameters,response-healing, 애플리케이션 검증의 역할 경계를 정리합니다.
검증 환경과 범위 안내: 이 글의 모델·엔드포인트 지원 매트릭스(465개 모델,
meta-llama/llama-3.3-70b-instruct7개 엔드포인트)는2026-12-02무인증 공개 REST API(GET /api/v1/models,/endpoints)를 직접 호출한 실시간 실측값입니다. 반면 인보이스 정형 추출 7개 케이스(9회 실행)는OPENROUTER_API_KEY없이 재현한 로컬 OpenRouter 호환 Mock HTTP 서버 + Python3.14.7+jsonschema 4.26.0(Draft202012Validator) 테스트 결과입니다. 실제 원격 추론의 모델별 스키마 준수율과 지연 시간은 측정 범위에 포함되지 않습니다.
json_schema를 넣었는데도 파싱과 적재가 깨지는 4가지 원인
비정형 인보이스(세금계산서·영수증) 텍스트에서 품목 목록, 공급가액, 세액, 합계를 추출해 회계 DB에 적재하는 백엔드 워커를 구성할 때, 흔히 response_format에 type: "json_schema"와 strict: true를 넣으면 JSON 파싱과 데이터 정합성이 모두 보장될 것으로 기대합니다. 그러나 OpenRouter처럼 단일 모델 ID 뒤에 여러 추론 제공업체(Provider)가 붙는 멀티 프로바이더 환경에서는 다음 네 가지 지점에서 파이프라인이 깨집니다.
- 엔드포인트별 파라미터 미지원: 모델 카탈로그가
structured_outputs를 지원하더라도, 실제 요청이 라우팅된 개별 추론 엔드포인트는response_format만 지원하거나 둘 다 지원하지 않을 수 있습니다. 이 경우 파라미터가 무시되어 일반 문장 응답이 돌아옵니다. - 토큰 상한 절단(
finish_reason: "length")과 모델 거절(refusal): 제약 디코딩(constrained decoding)이 켜져 있어도max_completion_tokens에 도달하면 JSON 문자열이 중간에서 끊깁니다. 정책상 거절된 응답은message.content가 비어 있고message.refusal에 사유가 채워집니다. - 구문 결함과 스키마 위반의 혼동: 일부 모델이나 폴백 경로는 JSON 앞뒤에
json` 코드펜스를 붙이거나 후행 쉼표를 남깁니다. 반대로 JSON 문법은 멀쩡하지만 필수 키가 빠지거나 허용하지 않은 키가 추가되는 스키마 위반도 발생합니다. - 도메인 불변식 불일치: JSON Schema는 타입과 필수 필드를 검증할 뿐,
sum(quantity * unit_price) == subtotal이나subtotal + tax == total같은 비즈니스 산술 관계는 검증하지 못합니다. 스키마를 통과한 응답이라도 회계 시스템에 그대로 적재하면 정산 오류가 발생합니다.
공개 API로 structured_outputs 지원 엔드포인트 확인하기
OpenRouter의 공개 REST API는 API 키 없이도 모델별·엔드포인트별 supported_parameters를 조회할 수 있습니다. 여기서 response_format은 JSON 모드(json_object) 수준의 지원을 의미하는 경우가 많고, JSON Schema 기반 제약 디코딩을 쓰려면 structured_outputs가 목록에 포함되어 있는지 확인해야 합니다.
아래 스크립트는 전체 모델 카탈로그와 meta-llama/llama-3.3-70b-instruct의 개별 엔드포인트 지원 현황을 실시간으로 조회합니다. 표준 라이브러리만 사용하므로 Python 3 환경에서 바로 실행할 수 있습니다.
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
# check_structured_support.py
import json
import urllib.request
from datetime import datetime, timezone
MODELS_URL = "https://openrouter.ai/api/v1/models"
ENDPOINTS_URL = "https://openrouter.ai/api/v1/models/meta-llama/llama-3.3-70b-instruct/endpoints"
def fetch_json(url: str) -> dict:
req = urllib.request.Request(
url,
headers={
"Accept": "application/json",
"User-Agent": "openrouter-structured-check/1.0",
},
)
with urllib.request.urlopen(req, timeout=20) as resp:
return json.loads(resp.read().decode("utf-8"))
def main() -> None:
queried_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
models = fetch_json(MODELS_URL).get("data", [])
endpoints = fetch_json(ENDPOINTS_URL).get("data", {}).get("endpoints", [])
rf_count = sum("response_format" in (m.get("supported_parameters") or []) for m in models)
so_count = sum("structured_outputs" in (m.get("supported_parameters") or []) for m in models)
rf_only = sum(
"response_format" in (m.get("supported_parameters") or [])
and "structured_outputs" not in (m.get("supported_parameters") or [])
for m in models
)
print(f"[LIVE API] Queried at: {queried_at}")
print(f"Catalog ({len(models)} models): response_format={rf_count}, structured_outputs={so_count}, response_format_only={rf_only}")
for ep in endpoints:
params = set(ep.get("supported_parameters") or [])
print(ep.get("tag"), ep.get("provider_name"), "response_format" in params, "structured_outputs" in params)
if __name__ == "__main__":
main()
2026-12-02T12:44:31Z에 직접 조회한 결과, 전체 465개 모델 중 response_format 지원은 415개, structured_outputs 지원은 404개였으며 response_format만 지원하고 structured_outputs는 미지원인 모델이 24개였습니다. 같은 모델 ID 안에서도 엔드포인트별 지원 편차가 뚜렷했습니다.
엔드포인트 태그 (tag) | 제공업체 (provider_name) | response_format | structured_outputs |
|---|---|---|---|
deepinfra/turbo | DeepInfra | YES | YES |
akashml/fp8 | AkashML | YES | YES |
parasail/fp8 | Parasail | YES | YES |
cloudflare/fp8 | Cloudflare | YES | NO |
groq | Groq | YES | NO |
coreweave/fp16 | CoreWeave | YES | YES |
amazon-bedrock/us-east-1 | Amazon Bedrock | NO | NO |
7개 엔드포인트 중 둘 다 지원하는 곳은 4개뿐이고, cloudflare/fp8과 groq는 response_format만 지원하며 amazon-bedrock/us-east-1은 둘 다 지원하지 않습니다. 따라서 요청 본문에 provider.require_parameters: true를 설정하지 않으면, response_format(json_schema)을 보냈더라도 미지원 엔드포인트로 라우팅되어 비정형 텍스트가 반환될 수 있습니다.
strict 스키마 요청과 response-healing 플러그인의 역할 경계
엔드포인트 필터링을 마쳤다면 요청 계층의 두 가지 도구인 strict: true와 response-healing 플러그인의 역할을 명확히 구분해야 합니다. OpenRouter의 response-healing 플러그인(plugins: [{ "id": "response-healing" }])은 모델 응답에서 마크다운 코드펜스(json `), 후행 쉼표, 닫는 괄호 누락 같은 JSON 구문 결함을 서버 측에서 자동 복구합니다.
하지만 이 플러그인은 비스트리밍(stream: false) 요청 전용이며, 구문상 유효한 JSON 안의 필수 키 누락·타입 불일치·허용되지 않은 추가 키·산술 오류 같은 스키마 및 의미 위반은 수정하지 않습니다.
| 계층 / 옵션 | 해결하는 문제 | 해결하지 못하는 문제 | 도입하지 말아야 할 상황 |
|---|---|---|---|
response_format: json_object | 유효한 JSON 객체 출력 유도 | 키 이름·타입·필수 여부 강제 불가 | 회계·주문처럼 고정 스키마 적재가 필요한 파이프라인 |
json_schema + strict: true | 엔드포인트 제약 디코딩으로 스키마 준수 유도 | length 절단, refusal, 도메인 산술 불일치 | 제공업체가 미지원하는 복잡한 스키마 키워드 남용 시 |
provider.require_parameters: true | structured_outputs 미지원 엔드포인트 사전 제외 | 가용 엔드포인트가 0개일 때 404/503 실패 | 모든 엔드포인트가 해당 파라미터를 미지원하는 모델 |
plugins: [{ id: "response-healing" }] | 코드펜스·후행 쉼표·닫는 괄호 등 구문 결함 복구 | 필수 키 누락, 추가 키, 타입 오류, 도메인 위반 | 실시간 스트리밍(stream: true) 응답이 필수인 UI |
| 애플리케이션 4단계 검증 | 절단·거절·파싱·스키마·도메인 불변식 최종 차단 | 잘못된 추출 자체를 자동 보정하지는 않음(재시도 필요) | 생략 권장 상황 없음(프로덕션 적재 전 필수) |
response-healing은 JSON 파싱 실패율을 낮추는 안전망이지 스키마 검증의 대체재가 아닙니다. 스트리밍 응답을 써야 하거나, 구문 복구 이후에도 필수 필드 누락을 반드시 막아야 한다면 애플리케이션 계층의 검증을 생략해서는 안 됩니다.
애플리케이션 4단계 검증 파이프라인 구현하기
요청 계층에서 provider.require_parameters: true, json_schema(strict: true, additionalProperties: false), response-healing을 조합하더라도, 애플리케이션이 응답을 DB나 메시지 큐에 적재하기 전에는 반드시 네 단계를 순서대로 검사해야 합니다.
flowchart TD
A["OpenRouter 요청 (require_parameters + strict + response-healing)"] --> B["Stage 1: HTTP/본문 오류, refusal, finish_reason 검사"]
B -->|"finish_reason == stop"| C["Stage 2: json.loads 구문 파싱"]
C -->|"유효 JSON"| D["Stage 3: Draft 2020-12 JSON Schema 검증"]
D -->|"스키마 통과"| E["Stage 4: 도메인 산술 불변식 검증"]
E -->|"일치"| F["회계 시스템 적재 허용"]
핵심은 요청에 실어 보낸 INVOICE_SCHEMA 객체를 애플리케이션의 Draft202012Validator에 그대로 재사용해 스키마 드리프트(요청 스키마와 검증 스키마의 불일치)를 없애는 것입니다. 아래 코드는 Python 3.14.7과 jsonschema 4.26.0으로 구현한 4단계 인보이스 추출 파이프라인의 핵심 발췌입니다. 실행 시 pip install jsonschema가 필요합니다.
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# invoice_pipeline.py
from dataclasses import dataclass
import json
import urllib.error
import urllib.request
from jsonschema import Draft202012Validator
INVOICE_SCHEMA = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"additionalProperties": False,
"required": [
"invoice_number", "vendor", "currency",
"line_items", "subtotal", "tax", "total",
],
"properties": {
"invoice_number": {"type": "string", "minLength": 1},
"vendor": {"type": "string", "minLength": 1},
"currency": {"type": "string", "enum": ["KRW", "USD", "EUR"]},
"line_items": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": False,
"required": ["description", "quantity", "unit_price"],
"properties": {
"description": {"type": "string", "minLength": 1},
"quantity": {"type": "integer", "minimum": 1},
"unit_price": {"type": "integer", "minimum": 0},
},
},
},
"subtotal": {"type": "integer", "minimum": 0},
"tax": {"type": "integer", "minimum": 0},
"total": {"type": "integer", "minimum": 0},
},
}
VALIDATOR = Draft202012Validator(INVOICE_SCHEMA)
@dataclass
class PipelineResult:
ok: bool
failed_stage: str | None # stage1_envelope | stage2_json_parse | stage3_schema | stage4_domain
reason: str
provider: str | None = None
data: dict | None = None
def extract_invoice(
base_url: str,
api_key: str,
invoice_text: str,
*,
require_parameters: bool = True,
use_response_healing: bool = True,
) -> PipelineResult:
payload: dict = {
"model": "meta-llama/llama-3.3-70b-instruct",
"provider": {
"order": ["amazon-bedrock/us-east-1", "deepinfra/turbo"],
"require_parameters": require_parameters,
},
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "invoice_extraction",
"strict": True,
"schema": INVOICE_SCHEMA,
},
},
"messages": [
{"role": "system", "content": "Extract invoice fields strictly matching the JSON schema."},
{"role": "user", "content": invoice_text},
],
}
if use_response_healing:
payload["plugins"] = [{"id": "response-healing"}]
req = urllib.request.Request(
f"{base_url.rstrip('/')}/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
body = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
with exc:
return PipelineResult(False, "stage1_envelope", f"HTTP {exc.code}")
provider = body.get("provider")
# Stage 1: HTTP/본문 오류, refusal, finish_reason 검사
if body.get("error"):
return PipelineResult(False, "stage1_envelope", f"body_error: {body['error']}", provider)
choices = body.get("choices") or []
if not choices:
return PipelineResult(False, "stage1_envelope", "empty_choices", provider)
choice = choices[0]
message = choice.get("message") or {}
if message.get("refusal"):
return PipelineResult(False, "stage1_envelope", f"refusal: {message['refusal']}", provider)
if choice.get("finish_reason") != "stop":
return PipelineResult(False, "stage1_envelope", f"finish_reason={choice.get('finish_reason')}", provider)
# Stage 2: JSON 구문 파싱
raw_content = message.get("content")
if not isinstance(raw_content, str):
return PipelineResult(False, "stage2_json_parse", "content_not_string", provider)
try:
parsed = json.loads(raw_content)
except json.JSONDecodeError as exc:
return PipelineResult(False, "stage2_json_parse", f"json_decode_error: {exc.msg}", provider)
# Stage 3: Draft 2020-12 JSON Schema 검증
errors = sorted(VALIDATOR.iter_errors(parsed), key=lambda e: list(e.path))
if errors:
return PipelineResult(False, "stage3_schema", "; ".join(e.message for e in errors[:2]), provider)
# Stage 4: 도메인 산술 불변식 검증
calc_subtotal = sum(item["quantity"] * item["unit_price"] for item in parsed["line_items"])
if calc_subtotal != parsed["subtotal"]:
return PipelineResult(False, "stage4_domain", f"subtotal_mismatch: expected {calc_subtotal}, got {parsed['subtotal']}", provider)
if parsed["subtotal"] + parsed["tax"] != parsed["total"]:
return PipelineResult(False, "stage4_domain", f"total_mismatch: {parsed['subtotal']}+{parsed['tax']}!={parsed['total']}", provider)
return PipelineResult(True, None, "passed_all_4_stages", provider, parsed)
위 클라이언트는 base_url에 https://openrouter.ai/api/v1을, api_key에 OPENROUTER_API_KEY 환경 변수를 넣으면 코드 변경 없이 실제 OpenRouter API로 바로 전환됩니다.
로컬 호환 서버로 7가지 케이스 검증하기
API 키 없이도 모든 실패 경로와 복구 경계를 결정적으로 재현하기 위해, /api/v1/chat/completions 요청의 provider.require_parameters와 plugins 배열을 해석하는 로컬 OpenRouter 호환 Mock HTTP 서버(127.0.0.1 임시 포트)를 띄우고 7개 케이스(총 9회 실행)를 unittest로 검증했습니다.
1
2
python3 check_structured_support.py
PRINT_TABLE=1 python3 -m unittest -v test_invoice_pipeline.py
| 테스트 케이스 | 결과 | 선택된 제공업체 | 차단 단계 | 관찰된 상세 동작 | | :— | :—: | :— | :— | :— | | C7_req_params_off | FAIL | Amazon Bedrock | stage2_json_parse | 미지원 엔드포인트로 라우팅되어 일반 문장 반환 → 파싱 실패 | | C7_req_params_on | PASS | DeepInfra | - | 미지원 엔드포인트 제외 후 deepinfra/turbo로 라우팅 → 4단계 통과 | | C9_valid_invoice | PASS | DeepInfra | - | 정상 인보이스 JSON 추출(total: 165000) → 4단계 통과 | | C8_syntax_heal_off | FAIL | DeepInfra | stage2_json_parse | json 코드펜스 + 후행 쉼표 포함 응답 → json.loads 실패 | | C8_syntax_heal_on | **PASS** | DeepInfra | - | response-healing이 코드펜스·후행 쉼표 제거 → 4단계 통과 | | C9_length_truncated | FAIL | DeepInfra | stage1_envelope | finish_reason=length로 잘린 JSON을 파싱 전 Stage 1에서 즉시 차단 | | C9_model_refusal | FAIL | DeepInfra | stage1_envelope | message.refusal 감지 → 파싱 시도 없이 Stage 1에서 차단 | | C8_schema_violation | FAIL | DeepInfra | stage3_schema | 필수 키 누락 + extra_unexpected_key 포함 → 구문 유효해 복구 미적용, Stage 3 차단 | | C9_domain_mismatch | FAIL | DeepInfra | stage4_domain | 스키마는 통과했으나 150000+15000!=170000` 산술 불일치 → Stage 4 차단 |
그림 1. 2026-12-02 실시간 공개 API 실측(상단)과 로컬 OpenRouter 호환 Mock 서버 기반 4단계 인보이스 검증 파이프라인 9회 실행 결과(하단).
특히 C8_schema_violation과 C9_domain_mismatch 케이스가 이 구조의 필요성을 잘 보여줍니다. response-healing을 켠 상태에서도 문법적으로 올바른 JSON 안의 추가 키·누락 필드는 그대로 통과하므로 Stage 3 스키마 검증이 필수이며, 타입과 필수 키를 모두 만족하더라도 합계 금액이 틀린 응답은 Stage 4 도메인 불변식 검증만이 막을 수 있습니다.
운영 시 주의사항과 체크리스트
실제 프로덕션 파이프라인에 구조화 출력을 적용할 때는 다음 네 가지를 사전에 점검해야 합니다.
- 제공업체별 JSON Schema 키워드 제한 확인:
strict: true모드에서는 모든 객체에additionalProperties: false와 전체required명시가 요구되는 경우가 많으며, 제공업체에 따라anyOf,$ref, 복잡한pattern정규식 지원 범위가 다릅니다. 배포 전 대상 엔드포인트에서 실제 스키마로 스모크 테스트를 실행합니다. max_completion_tokens여유치 확보: 인보이스 품목 수가 늘어날수록 출력 JSON 길이가 길어집니다.finish_reason: "length"가 발생하면response-healing으로 괄호를 닫더라도 데이터가 유실된 상태이므로, Stage 1에서 즉시 실패로 분류하고 토큰 상한을 높여 재시도해야 합니다.- 스트리밍 필요 시 대안 분리:
response-healing은 비스트리밍 요청에서만 동작합니다. 사용자에게 실시간 스트리밍 UI를 제공해야 한다면 스트리밍 경로와 정형 데이터 적재 경로를 분리하거나, 클라이언트 측 증분 파서와 최종 완료 시점의 4단계 검증을 결합합니다. - 엔드포인트 지원 현황 주기적 점검: OpenRouter의 제공업체 목록과
supported_parameters는 수시로 바뀝니다.require_parameters: true를 켠 상태에서 지원 엔드포인트가 모두 빠지면 요청 자체가 실패하므로, 공개/endpointsAPI 조회를 배포 전 헬스체크에 포함해 두면 장애를 미리 감지할 수 있습니다.