How to specify output format in prompts
PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the openai Python package and set your API key as an environment variable for secure access.
pip install openai>=1.0 Step by step
Use explicit instructions in your prompt to specify the output format. For example, ask the model to return a JSON object with specific keys. This ensures the response is structured and easy to parse.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = '''
Generate a JSON object with the following keys: "name", "age", and "city".
Example:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
'''
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
print(response.choices[0].message.content) {
"name": "Alice",
"age": 30,
"city": "New York"
} Common variations
You can specify other formats like XML or markdown by changing the instructions. For streaming or async calls, adapt the SDK usage accordingly. Different models may interpret format instructions with varying strictness.
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a helpful assistant."
user_prompt = '''
Please provide the output in XML format with tags: <name>, <age>, <city>.
Example:
<person>
<name>Alice</name>
<age>30</age>
<city>New York</city>
</person>
'''
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=500,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}]
)
print(message.content[0].text) <person> <name>Alice</name> <age>30</age> <city>New York</city> </person>
Troubleshooting
If the output format is inconsistent, try adding explicit examples or use delimiters like triple backticks to enforce code blocks. Also, verify the model supports your requested format and check for prompt length limits.
Key Takeaways
- Always include explicit instructions and examples in your prompt to specify output format.
- Use code block delimiters like triple backticks to help the model produce clean, parseable output.
- Different models and SDKs support format instructions differently; test and adjust accordingly.