Yapılandırılmış çıktılar
response_format ile modelin yanıtını bir JSON Schema'ya ya da geçerli bir JSON nesnesine uydurun ve yanıtı doğrudan kodunuzda kullanın.
MarkdownModelin yanıtını bir programda kullanacaksanız serbest metin yerine belirli bir yapıda JSON istersiniz. response_format alanı bunu sağlar. Lykia alanı OpenAI biçiminde alır. OpenAI uyumlu sağlayıcılara olduğu gibi iletilir; Anthropic ve Google AI Studio için Lykia onu bu sağlayıcıların kendi biçimine çevirir (Anthropic'te json_object karşılığı olmadığı için bu kip orada atılır). Modelin desteği varsa yanıt verdiğiniz şemaya uyar.
İki kip vardır:
json_schema: Yanıt verdiğiniz JSON Schema'ya uyar. Alan adları, türler ve zorunlu alanlar şemadan gelir.json_object: Yanıt geçerli bir JSON nesnesidir ama yapısı şemayla sınırlanmaz; yapıyı istemde anlatırsınız.
Destekleyen bir model seçin
Bir modelin supported_parameters listesinde structured_outputs varsa model json_schema kipini destekler; response_format varsa model response_format alanını kabul eder. Modelleri bu değerlerle süzün:
# Models whose supported_parameters include "structured_outputs"
curl "https://api.getlykia.com/v1/models?supported_parameters=structured_outputs" \
-H "Authorization: Bearer $LYKIA_API_KEY"Desteklemeyen bir modele response_format gönderdiğinizde ne olacağı modele ve sağlayıcıya bağlıdır. Modeli baştan bu listeden seçin; yedek modeller kullanıyorsanız onların da desteklediğini doğrulayın.
JSON Schema ile
response_format.type alanına "json_schema" yazın ve şemayı json_schema.schema altına koyun:
curl https://api.getlykia.com/v1/chat/completions \
-H "Authorization: Bearer $LYKIA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-4o-mini",
"messages": [
{ "role": "user", "content": "Extract the order: two large lattes and one croissant, to go." }
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "order",
"strict": true,
"schema": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"quantity": { "type": "integer" },
"size": { "type": ["string", "null"] }
},
"required": ["name", "quantity", "size"],
"additionalProperties": false
}
},
"takeaway": { "type": "boolean" }
},
"required": ["items", "takeaway"],
"additionalProperties": false
}
}
}
}'import json
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])
schema = {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"quantity": {"type": "integer"},
"size": {"type": ["string", "null"]},
},
"required": ["name", "quantity", "size"],
"additionalProperties": False,
},
},
"takeaway": {"type": "boolean"},
},
"required": ["items", "takeaway"],
"additionalProperties": False,
}
completion = client.chat.completions.create(
model="openai/gpt-4o-mini",
messages=[{"role": "user", "content": "Extract the order: two large lattes and one croissant, to go."}],
response_format={"type": "json_schema", "json_schema": {"name": "order", "strict": True, "schema": schema}},
)
order = json.loads(completion.choices[0].message.content)
print(order["items"], order["takeaway"])import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });
const schema = {
type: "object",
properties: {
items: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
quantity: { type: "integer" },
size: { type: ["string", "null"] },
},
required: ["name", "quantity", "size"],
additionalProperties: false,
},
},
takeaway: { type: "boolean" },
},
required: ["items", "takeaway"],
additionalProperties: false,
};
const completion = await client.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [{ role: "user", content: "Extract the order: two large lattes and one croissant, to go." }],
response_format: { type: "json_schema", json_schema: { name: "order", strict: true, schema } },
});
const order = JSON.parse(completion.choices[0].message.content ?? "{}");
console.log(order.items, order.takeaway);{
"id": "gen-1795373697-8Qya37ShK5Hzkwlz",
"object": "chat.completion",
"created": 1795373697,
"model": "openai/gpt-4o-mini",
"provider": "openai",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\"items\":[{\"name\":\"latte\",\"quantity\":2,\"size\":\"large\"},{\"name\":\"croissant\",\"quantity\":1,\"size\":null}],\"takeaway\":true}"
},
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 96,
"completion_tokens": 31,
"total_tokens": 127,
"cost": 0.000033,
"is_byok": false,
"cost_details": {
"upstream_cost": 0.000033,
"platform_fee": 0,
"is_byok": false
},
"prompt_tokens_details": {
"cached_tokens": 0,
"cache_write_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0
}
},
"system_fingerprint": "fp_560af6e559"
}Yanıtta JSON, message.content içinde bir dizgi olarak gelir; kullanmadan önce ayrıştırın.
response_formatobjectYanıtın biçimi.
typestringzorunlu"json_schema" ya da "json_object".
json_schemaobjecttype "json_schema" olduğunda zorunlu.
namestringzorunluŞemanın adı; harf, rakam, alt çizgi ve tire.
strictbooleantrue olduğunda model şemaya tam olarak uyar. Katı kipte her nesnede bütün alanlar required listesinde olmalı ve additionalProperties: false verilmelidir; isteğe bağlı bir alanı ["string", "null"] gibi bir türle anlatın.
schemaobjectJSON Schema.
JSON nesnesi kipi
Belirli bir şemaya ihtiyacınız yoksa { "type": "json_object" } ile yalnız geçerli bir JSON nesnesi isteyin. Bu kipte modele istemde JSON yanıt beklediğinizi ve hangi alanları istediğinizi açıkça söyleyin:
curl https://api.getlykia.com/v1/chat/completions \
-H "Authorization: Bearer $LYKIA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-4o-mini",
"messages": [
{ "role": "system", "content": "Reply with a JSON object with the keys \"language\" and \"confidence\"." },
{ "role": "user", "content": "Bugün hava çok güzel." }
],
"response_format": { "type": "json_object" }
}'Pratik notlar
- Yanıtı yine de doğrulayın. Model desteklese bile yanıt,
max_tokenssınırına takıldığında yarım kalabilir (finish_reason: "length"). JSON'u ayrıştırırken hatayı yakalayın ve şemanızla doğrulayın. - Şemayı küçük tutun. Derin iç içe yapılar ve uzun
enumlisteleri istem token'larını artırır. - Açıklama ekleyin. Şemadaki
descriptionalanları modelin alanları doğru doldurmasına yardım eder. - Araçlarla karıştırmayın. Modelin bir fonksiyon çalıştırmanızı istemesini bekliyorsanız araç çağırma, yanıtın kendisinin belirli bir yapıda olmasını istiyorsanız yapılandırılmış çıktı kullanın.
Sonraki adımlar
- Araç çağırma: Modelin kendi fonksiyonlarınızı çağırmasını sağlayın.
- Modeller: Model yeteneklerini katalogdan okuyun.
POST /chat/completions:response_formatalanının başvurusu.