Lunos logoLunos

Structured Outputs

Fitur Structured Outputs membantu Anda meminta model untuk menghasilkan output berupa JSON yang dapat langsung di-parse dengan format yang konsisten. Alih-alih menerima teks bebas, Anda cukup mendefinisikan sebuah JSON Schema, dan model akan mengembalikan data yang mengikuti skema tersebut secara ketat.

Fitur ini sangat berguna apabila Anda membutuhkan output yang stabil untuk:

  • Form dan tampilan UI yang memerlukan struktur data baku.
  • Input untuk tool, pipeline, dan otomatisasi workflow.
  • Penulisan data ke database yang menuntut format yang ketat dan terprediksi.

Lunos kompatibel dengan format OpenAI, sehingga Anda dapat langsung menggunakan field response_format pada request POST /v1/chat/completions.

Ringkasan Fitur

Dengan Structured Outputs, Anda dapat:

  • Membatasi format respons model agar sesuai dengan JSON Schema tertentu.
  • Mengurangi risiko error parsing akibat format teks yang tidak terduga dari model.
  • Mencegah field penting hilang atau munculnya field tambahan yang tidak diinginkan di luar skema.

Cara Penggunaan

Untuk mengaktifkan Structured Outputs, sertakan parameter response_format di dalam body request Anda. Atur:

  • type: "json_schema"
  • json_schema yang berisi name, strict, dan schema

Contoh request:

{
  "model": "openai/gpt-4o",
  "messages": [
    { "role": "user", "content": "Return a weather summary for London." }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "weather",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "City or location name"
          },
          "temperature": {
            "type": "number",
            "description": "Temperature in Celsius"
          },
          "conditions": {
            "type": "string",
            "description": "Weather conditions description"
          }
        },
        "required": ["location", "temperature", "conditions"],
        "additionalProperties": false
      }
    }
  }
}

Jika model yang Anda pilih mendukung fitur ini, konten respons akan berupa objek JSON yang sesuai dengan skema yang telah Anda definisikan.

Contoh output:

{
  "location": "London",
  "temperature": 18,
  "conditions": "Partly cloudy with light drizzle"
}

Dukungan Model

Fitur Structured Outputs hanya tersedia pada model yang kompatibel.

Untuk memastikan apakah model tertentu mendukung fitur ini di Lunos:

  1. Panggil endpoint GET /v1/models.
  2. Pastikan properti supportedParameters pada model tersebut memuat response_format.
  3. Gunakan response_format dengan type: "json_schema".

Jika response_format tidak tercantum di daftar parameter yang didukung, Lunos akan menolak request tersebut dan mengembalikan error parameter tidak didukung.

Praktik Terbaik (Best Practices)

  • Gunakan description yang jelas dan informatif pada setiap properti skema agar model memahami konteks data yang diharapkan.
  • Atur "strict": true jika Anda membutuhkan respons yang benar-benar patuh terhadap skema tanpa penyimpangan.
  • Jaga skema Anda tetap ringkas dan ketat:
    • Gunakan required untuk menandai field yang wajib ada.
    • Gunakan additionalProperties: false untuk memastikan tidak ada field tak terduga yang muncul di output.

Contoh Request di Lunos

curl -X POST "https://api.lunos.tech/v1/chat/completions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o",
    "messages": [
      { "role": "user", "content": "Return a weather summary for London." }
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "weather",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City or location name"
            },
            "temperature": {
              "type": "number",
              "description": "Temperature in Celsius"
            },
            "conditions": {
              "type": "string",
              "description": "Weather conditions description"
            }
          },
          "required": ["location", "temperature", "conditions"],
          "additionalProperties": false
        }
      }
    }
  }'
import requests

url = "https://api.lunos.tech/v1/chat/completions"
headers = {
  "Authorization": "Bearer YOUR_API_KEY",
  "Content-Type": "application/json",
}
payload = {
  "model": "openai/gpt-4o",
  "messages": [
    { "role": "user", "content": "Return a weather summary for London." }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "weather",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "location": { "type": "string", "description": "City or location name" },
          "temperature": { "type": "number", "description": "Temperature in Celsius" },
          "conditions": { "type": "string", "description": "Weather conditions description" }
        },
        "required": ["location", "temperature", "conditions"],
        "additionalProperties": false
      }
    }
  }
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
const response = await fetch("https://api.lunos.tech/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "openai/gpt-4o",
    messages: [
      { role: "user", content: "Return a weather summary for London." },
    ],
    response_format: {
      type: "json_schema",
      json_schema: {
        name: "weather",
        strict: true,
        schema: {
          type: "object",
          properties: {
            location: { type: "string", description: "City or location name" },
            temperature: { type: "number", description: "Temperature in Celsius" },
            conditions: { type: "string", description: "Weather conditions description" },
          },
          required: ["location", "temperature", "conditions"],
          additionalProperties: false,
        },
      },
    },
  }),
});

const data = await response.json();
console.log(data);

Streaming dengan Structured Outputs

Fitur Structured Outputs juga dapat digunakan bersamaan dengan mode streaming. Cukup tambahkan stream: true pada request Anda:

{
  "stream": true,
  "model": "openai/gpt-4o",
  "messages": [
    { "role": "user", "content": "Return a weather summary for London." }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "weather",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "location": { "type": "string" },
          "temperature": { "type": "number" },
          "conditions": { "type": "string" }
        },
        "required": ["location", "temperature", "conditions"],
        "additionalProperties": false
      }
    }
  }
}

Dalam mode ini, client Anda akan menerima chunk data secara bertahap. Namun, konten akhir yang sudah lengkap tetap dijamin membentuk JSON yang valid dan sesuai dengan skema.

Penanganan Error

Beberapa kondisi error yang mungkin Anda temui:

  1. Model tidak mendukung response_formatrequest akan ditolak oleh Lunos.
  2. Skema JSON tidak validrequest akan ditolak atau model akan mengembalikan pesan error.

Jika ini terjadi, coba ganti model yang Anda gunakan atau periksa kembali validitas skema JSON Anda.

Validasi Respons

Meskipun model sudah mengikuti skema, tetap disarankan untuk memvalidasi ulang JSON hasil akhir di sisi aplikasi Anda sebelum digunakan lebih lanjut.

  • Lakukan parsing menggunakan JSON parser standar.
  • Secara opsional, validasi lagi hasilnya terhadap skema yang sama sebelum menyimpan ke database atau mengeksekusi aksi tertentu.