This article explains how to use structured outputs with the OpenAI API for consistent, machine-readable responses.
Structured outputs ensure your application receives well-defined, machine-readable responses every time. By enforcing formats such as JSON, CSV, or custom Pydantic models, you gain:
Benefit
Description
Type Safety
Guarantees fields are present and correctly typed
Explicit Refusals
Model clearly indicates when it can’t comply
Simpler Prompting
Remove guesswork—just specify the format
Exact Formats
Enforce JSON, CSV, or any structure your application requires
Prompt the model to output strict JSON so downstream services can ingest it without additional parsing.
Copy
Ask AI
from openai import OpenAIclient = OpenAI(api_key="sk-REPLACE_WITH_YOUR_KEY")def recipe_gen(ingredients: list[str]) -> str: messages = [{"role": "user", "content": ing} for ing in ingredients] messages.extend([ {"role": "system", "content": "JSON Format Required"}, {"role": "assistant", "content": "You are a high-end chef. Generate a recipe in JSON!"} ]) response = client.chat.completions.create( model="gpt-4", messages=messages, max_tokens=300, temperature=0.9 ) return response.choices[0].message.contentif __name__ == "__main__": ingredients = [] while True: ing = input("Enter an ingredient (or type done): ") if ing.strip().lower() == "done": break ingredients.append(ing) print(recipe_gen(ingredients))
Run the script:
Copy
Ask AI
$ python recipe_generator.pyEnter an ingredient (or type done): chocolateEnter an ingredient (or type done): grapesEnter an ingredient (or type done): pizza doughEnter an ingredient (or type done): done
Simply update the system prompt to request CSV, then process the comma-separated response.
Copy
Ask AI
from openai import OpenAIclient = OpenAI(api_key="sk-REPLACE_WITH_YOUR_KEY")def recipe_gen_csv(ingredients: list[str]) -> str: messages = [{"role": "user", "content": ing} for ing in ingredients] messages.extend([ {"role": "system", "content": "CSV Format Required"}, {"role": "assistant", "content": "You are a high-end chef. Generate a CSV recipe!"} ]) response = client.chat.completions.create( model="gpt-4", messages=messages, max_tokens=300, temperature=0.9 ) return response.choices[0].message.contentif __name__ == "__main__": ingredients = [] while True: ing = input("Enter an ingredient (or type done): ") if ing.strip().lower() == "done": break ingredients.append(ing) print(recipe_gen_csv(ingredients))
Sample CSV output:
Copy
Ask AI
Ingredient,Quantity,PreparationChicken Breast,2 pieces,Cut into cubesPotatoes,2 medium,Peeled and dicedEggs,4,Hard-boiled and slicedOlive Oil,2 Tbsp,For cookingGarlic,2 cloves,MincedOnion,1 medium,Finely choppedSalt,1 tsp,To tasteBlack Pepper,1/2 tsp,To tastePaprika,1/2 tsp,To tasteFresh Parsley,2 tbsp,Chopped for garnish
You can even mix formats—return cooking steps as CSV:
Copy
Ask AI
Step 1,Heat olive oil in a large pan over medium heat.Step 2,Add chicken and onion; sauté until translucent.Step 3,Add garlic, potatoes, and paprika; cook until tender.Step 4,Stir in eggs until heated through.Step 5,Garnish with parsley and serve.
By specifying your desired output format in the system and assistant messages, you guarantee consistency and simplify downstream processing. For more advanced examples, see the OpenAI Structured Outputs Guide.