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 dakikalık okuma
İleri"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 kullanconst 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şimconst 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 (): 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.
response_format: { type: "json_object" }Use Case'ler#
| Senaryo | Schema |
|---|---|
| Müşteri yorumu sınıflandırma | sentiment + topics + rating |
| CV parsing | name, email, experience[] |
| Soru-cevap (FAQ) | question + answer + tags |
| Form veri çıkarma | tüm form alanları |
| Çeviri metadata | source_lang + target_lang + confidence |
| Kod analizi | functions[], imports[], complexity |
| Spec → Test üretme | test_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...
İlgili İçerikler
Modül 1: Başlangıç ve Temeller
ChatGPT Nedir? Tarihçe, Evrim ve Bugünün Manzarası
Öğrenmeye BaşlaModül 1: Başlangıç ve Temeller
Hesap Açma ve Plan Karşılaştırması: Free, Plus, Pro, Team, Enterprise
Öğrenmeye BaşlaModül 1: Başlangıç ve Temeller