Skip to content

Structured Outputs: JSON Schema ile Garantili Format

Modül 4'te giriş yaptık; burada API tarafında detayları, Zod entegrasyonu, performans.

Şükrü Yusuf KAYA
9 min read
Advanced
Structured Outputs: JSON Schema ile Garantili Format

"Bu schema'ya uyan JSON dön" = %100 garanti#

OpenAI'nın constrained decoding özelliği: model token üretirken schema'yı ihlal eden seçenekleri filtreler. Sonuç: %100 schema-uyumlu JSON.
typescript
import OpenAI from "openai";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";
 
const openai = new OpenAI();
 
// 1. Schema tanımla (Zod ile, hem TS tipini hem JSON schema'yı bir kerede)
const ArticleAnalysis = z.object({
title: z.string(),
summary: z.string().max(200),
topics: z.array(z.string()).min(1).max(10),
sentiment: z.enum(["pozitif", "negatif", "nötr"]),
reading_time_min: z.number().int().min(1),
key_quotes: z.array(z.object({
text: z.string(),
speaker: z.string().nullable(),
})),
});
 
// 2. API çağrısı — beta.chat.completions.parse kullan
const result = await openai.beta.chat.completions.parse({
model: "gpt-5",
messages: [
{ role: "system", content: "Sen makaleleri analiz eden bir asistansın." },
{ role: "user", content: "Şu makaleyi analiz et: [...]" },
],
response_format: zodResponseFormat(ArticleAnalysis, "analysis"),
});
 
// 3. Tip-güvenli, garanti schema'lı erişim
const analysis = result.choices[0].message.parsed;
// analysis: ArticleAnalysis (TypeScript bilir!)
console.log(analysis.title);
console.log(analysis.topics.join(", "));
Zod + Structured Outputs — tip güvenli, schema-garantili.
💡 JSON mode vs Structured Outputs
JSON mode (
response_format: { type: "json_object" }
): geçerli JSON garantisi var, ama schema'nın hangisi olduğunu bilmez. Model schema'yı yanlış doldurabilir. Structured Outputs: schema'ya uygun garanti. Üretim için her zaman Structured Outputs kullan.

Use Case'ler#

SenaryoSchema
Müşteri yorumu sınıflandırmasentiment + topics + rating
CV parsingname, email, experience[]
Soru-cevap (FAQ)question + answer + tags
Form veri çıkarmatüm form alanları
Çeviri metadatasource_lang + target_lang + confidence
Kod analizifunctions[], imports[], complexity
Spec → Test üretmetest_cases[]

Özet#

✓ Structured Outputs = %100 schema-uyumlu JSON ✓ Zod + zodResponseFormat ile TS tip güvenliği ✓ JSON mode'dan üstün — production'da default ✓ Use case: parsing, sınıflandırma, çıkarım
Sıradaki ders: Assistants API — Threads, Runs, Tools.

Yorumlar & Soru-Cevap

(0)
Yorum yazmak için giriş yap.
Yorumlar yükleniyor...

Related Content