AI is increasingly present in our applications. It can generate complex JSON, extract data from documents, or provide structured responses. But there is a problem: AI can make mistakes, omit fields, or even invent information.
This is where a JSON Schema becomes essential. It acts as a framework to verify that AI responses strictly follow the expected structure, ensuring that your data remains reliable and usable in your 4D applications.
Why JSON Schema Matters When Using AI
A JSON Schema allows you to:
- Automatically validate responses produced by AI
- Detect errors, inconsistencies, or missing fields
- Send these errors back to the AI for automatic correction
- Guarantee usable data, even if the model evolves or makes mistakes
In practice, the schema acts as a safety net, you continue to benefit from the power of AI while maintaining a predictable and controlled format for your 4D applications.
Using JSON Schema with 4D AI Kit
4D AI Kit includes a very useful feature, the ability to ask the AI to return a JSON response structured according to a specific schema.
This allows you to define exactly:
- the expected fields,
- their types,
- and even certain constraints (allowed values, numeric ranges, etc.).
This approach is detailed in two 4D blog posts: one focused on Structured Outputs, which explicitly instruct the AI to comply with a predefined response format, and another introducing the JSON Schema Draft 2020-12 parser, supporting the latest standard and enabling stricter, more expressive validation of AI-generated JSON.
Example: Text Analysis and Entity Extraction
Imagine you are using a text analysis API to recognize entities in a sentence. An AI response could look like this:
{
"model": "gpt-text-analyzer-v2",
"input": "Steve Jobs founded Apple in Cupertino.",
"entities": [
{ "type": "PERSON", "text": "Steve Jobs", "confidence": 0.98 },
{ "type": "ORG", "text": "Apple", "confidence": 0.95 },
{ "type": "LOCATION", "text": "Cupertino", "confidence": 0.93 }
]
}
The Validation JSON Schema
To ensure that the AI respects this structure, you can define a JSON Schema compatible with Draft 2020-12:
{
"$schema": "https://json-schema.org/draft/2020-12/schema#",
"title": "AI Text Analysis Response",
"type": "object",
"properties": {
"model": { "type": "string" },
"input": { "type": "string" },
"entities": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "type": "string", "enum": ["PERSON", "ORG", "LOCATION"] },
"text": { "type": "string" },
"confidence": { "type": "number", "minimum": 0, "maximum": 1 }
},
"required": ["type", "text", "confidence"]
}
}
},
"required": ["model", "input", "entities"]
}
This schema guarantees the structure of the data returned by the AI. JSON Schema does not validate the semantic relevance of the answers, but it enforces a strict framework that allows your 4D applications to work with reliable and usable data.
The System Prompt: Framing the AI’s Behavior
The system prompt is essential. It defines the role of the AI and enforces strict discipline on the output format.
You are an AI text analysis engine. Your task is to analyze the provided text and extract named entities. You must identify: - people (PERSON) - organizations (ORG) - locations (LOCATION) Return the result strictly as a JSON object that follows the provided JSON Schema. Do not add any extra fields. Do not add explanations or text outside the JSON. If no entity is found, return an empty array for "entities".
This prompt:
- clearly defines the task,
- explicitly restates the constraints,
- strongly limits creative deviations from the model.
Implementation with 4D AI Kit
Let’s now see how to implement this mechanism on the 4D side using 4D AI Kit.
Chat and Schema Configuration
In this example, the JSON Schema and the system prompt are stored in the application resources and explicitly passed to the model during the call.
// Retrieve the system prompt
var $systemPrompt:=File("/RESOURCES/prompt.txt").getText()
// Retrieve the JSON Schema to validate the AI response
var $schema:=JSON Parse(File("/RESOURCES/schema.json").getText())
// Define chat parameters
var $params:=cs.AIKit.OpenAIChatCompletionsParameters.new()
$params.model:="gpt-text-analyzer-v2"
$params.response_format:={\
type: "json_schema"; \
json_schema: {name: "analyse_schema"; schema: $schema}}
// Create AI chat helper
var $ai:=cs.AIKit.OpenAI.new($openAIKey)
var $chatHelper:=$ai.chat.create($systemPrompt; $params)
With this configuration, the AI knows exactly which format it must produce, which significantly reduces errors.
Calling the AI
Once the schema and response format are configured, all that remains is to call the AI and provide the text to analyze.
// Send the user prompt to the AI
var $userPrompt:="Steve Jobs founded Apple in Cupertino."
var $result:=$chatHelper.prompt($userPrompt)
// Convert AI response to object
var $response:=JSON Parse($result.choice.message.text)
Validating the AI Response and Handling Errors
Even when a schema is provided, it is essential to validate the response on the 4D side before using it. The AI can produce an invalid response due to truncation, generation errors, or ambiguous context.
// Validate the JSON against the schema
var $validation:=JSON Validate($response; $schema)
// Handle validation errors
If (Not($validation.success))
// If the JSON is invalid, build an error prompt to send back to the AI
var $errorPrompt:=\
"The JSON you returned does not match the expected schema. "+\
"Here are the validation errors:\n"+\
JSON Stringify($validation.errors)+\
"\nPlease return a corrected JSON that strictly follows the schema."
// Resend the prompt (or send error prompt) to let AI correct its output
$result:=$chatHelper.prompt($userPrompt)
Else
// If the JSON is valid, continue with your processing
// e.g., save to database, display in form, or trigger further actions
End if
This mechanism makes it possible to implement an AI → 4D → AI loop:
- The AI generates a JSON response.
- 4D validates the JSON against the schema.
- If an error is detected, 4D sends the missing or incorrect information back to the AI.
- The AI corrects the response and returns a valid JSON.
This automatic feedback loop ensures that your data remains reliable, even when the AI makes mistakes.
Concrete Benefits
- AI-generated JSON that is reliable and consistent
- Automatic error correction through the validation loop
- Security and control across your API → AI pipelines
- Data that is always usable for your forms, processing, or analysis
Conclusion
Integrating JSON Schema with 4D AI Kit transforms the way you use AI. You move from an “unpredictable AI” workflow to a predictable, controlled, robust, and automated process.
By combining Structured Outputs, JSON Schema, and validation on the 4D side, you fully leverage the power of AI while ensuring reliable, secure, and production-ready data.
This approach goes far beyond simple text analysis. The same pattern can be applied to any scenario where AI-generated data must be safely integrated into a 4D application.
JSON Schema does not make AI “intelligent”, but it makes it predictable.
Comments are not currently available for this post.