Session 5· 06· 10 min
Refusal Detection
What you'll learn
- ▸Understand when the model refuses to answer
- ▸Check the .refusal field on structured output responses
- ▸Handle refusals gracefully in production code
What is a refusal?
When the model decides it cannot or should not answer (safety, policy, edge case), structured-output responses return a .refusal field with a message INSTEAD of the usual parsed content. Your code must check for it.
06_refusal_detection_structured_output.py
msg = response.choices[0].message
if msg.refusal: ①
print("Refusal:", msg.refusal)
else:
data = json.loads(msg.content) ②
print("Parsed:", data)①Always check .refusal BEFORE trying to parse .content.
②If refusal is None, content is safe to parse.
$ python 06_refusal_detection_structured_output.py
Refusal behavior varies across models and may change as policies evolve. Never rely on "it never refuses" — always code the refusal path.
Knowledge Check
Why check msg.refusal before msg.content?
Recap — what you just learned
- ✓Structured output responses may have .refusal set instead of .content
- ✓Always check .refusal first in production code
- ✓Refusal behaviour drifts with policy updates — code defensively