I need help with creating a JSON Schema for OpenAI structured outputs where one field depends on another.
Basically I want:
- When field_a equals “yes”, then field_b should be required.
- When field_a equals “no”, then field_b should not exist.
I tried using allOf with if-then conditions but OpenAI rejects my schema. The allOf section seems to be the problem.
What’s the right way to write this conditional schema that OpenAI will accept?
from openai import OpenAI
import json
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_KEY"))
# My schema with conditional logic
response_schema = {
"name": "process_request",
"description": "Process user request with dependent fields",
"parameters": {
"type": "object",
"properties": {
"field_a": {
"type": "string",
"enum": ["yes", "no"],
"description": "Primary response"
},
"field_b": {
"type": "string",
"enum": ["approved", "denied"],
"description": "Secondary response needed when field_a is yes"
}
},
"required": ["field_a"],
"allOf": [
{
"if": {
"properties": {"field_a": {"const": "yes"}}
},
"then": {
"required": ["field_b"]
}
},
{
"if": {
"properties": {"field_a": {"const": "no"}}
},
"then": {
"not": {"required": ["field_b"]}
}
}
]
}
}
def test_schema(prompt_text):
try:
completion = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt_text}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "process_request",
"schema": response_schema["parameters"]
}
}
)
result = completion.choices[0].message.content
data = json.loads(result)
print(f"Success: {data}")
except Exception as error:
print(f"Error occurred: {error}")
if __name__ == "__main__":
test_schema("Answer yes and provide the second field")
test_schema("Answer no without the second field")