KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Structured Output with response_format for Consistent AI Responses
PRODUCT: 4D | VERSION: 21 | PLATFORM: Mac & Win
Published On: January 7, 2026
AI in business software has evolved beyond creating text for people to read, it also focuses on generating consistent, structured data that applications can directly process.

Within 4D applications, AI-generated outputs serve critical functions such as filling database fields, powering business workflows, and etc.

When AI responses lack structure or consistency, they create operational risks. Inconsistent formatting, unexpected variations in output, or missing data elements can disrupt application processes and create debugging challenges.

To solve this problem, 4D 21 introduces structured AI outputs using the response_format parameter attribute in 4D AIKit. This capability lets developers specify the precise structure they need from AI models, guaranteeing predictable, reliable results that integrate smoothly with 4D application logic.

Example:
var $client : cs.AIKit.OpenAI
var $result : Object
var $messages : Collection
var $schema : Object
var $data : Variant

$client:=cs.AIKit.OpenAI.new("API Key")

// Build messages
$messages:=New collection
$messages.push(New object("role"; "system"; "content"; "Extract product data"))
$messages.push(New object("role"; "user"; "content"; "Laptop RTX 4060 for $999.99 in stock"))

// Define expected JSON schema
$schema:=New object
$schema.type:="object"
$schema.properties:=New object
$schema.properties.product_name:=New object("type"; "string")
$schema.properties.price:=New object("type"; "number")
$schema.properties.in_stock:=New object("type"; "boolean")

// Set parameters
$params:=cs.AIKit.OpenAIChatCompletionsParameters.new()
$params.model:="gpt-4o-mini"
$params.response_format:=New object
$params.response_format.type:="json_schema"
$params.response_format.json_schema:=New object("name"; "test"; "schema"; $schema)

// Request with response_format
$result:=$client.chat.completions.create($messages; $params)

// Direct structured result
$data:=$result.choice.message.content
var $json:=JSON Parse($data)


As a result, AI outputs can be safely parsed and integrated directly into 4D application logic, reducing operational risks and making AI-driven features more robust and production-ready.