How Refusal Responses Work with Structured Outputs and Nullable Unions
When a model refuses a request under Structured Outputs, providers often return a refusal string (message.refusal in OpenAI SDKs) or a refusal stop reason rather than JSON matching your data schema. If your code assumes parsed or content is always a valid payload object, it will throw a parse or schema error instead of handling the refusal cleanly.
Adding a nullable union / discriminated outcome makes refusals an explicit, typed branch in your application logic while keeping normal data extraction strict:
- Separate
message.refusalfrommessage.parsed/content: Check refusal fields first so you do not feed a plain-text refusal message intoJSON.parse()or retry loops meant for malformed JSON. - Use a discriminated union with a nullable payload: Modeling
{ outcome: "extracted", payload: PayloadSchema, refusalReason: null } | { outcome: "refused", payload: null, refusalReason: string | null }forces callers to handle both branches explicitly. - Avoid over-broad unions that hide bad extractions: A union of two loose object shapes can let a malformed data object accidentally match the wrong branch—discriminated unions (
outcome/statusliteral tags) keep validation unambiguous.
Steps to Handle Refusals Cleanly
- Check provider refusal fields first: Inspect
message.refusal(orfinish_reason === "refusal") before attempting JSON parsing or schema validation. - Define a discriminated union with nullable fields: Represent successful extraction and refusal as explicit variants, using
.nullable()on optional or non-applicable fields when required by strict JSON Schema. - Validate parsed output with
safeParse(): Run Zod validation on the parsed JSON and route refusals to a dedicated fallback/audit path instead of generic schema-retry prompts. - Preserve clean history for multi-turn chats: If appending a refusal to conversation history, store the refusal text cleanly without fabricating fake JSON tool or data payloads.
TypeScript Example: Discriminated Union + Refusal Guard
import OpenAI from "openai";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";
const openai = new OpenAI();
const InvoicePayloadSchema = z.object({
vendor: z.string().min(1),
totalAmount: z.number().nonnegative(),
currency: z.string().min(3).max(3),
dueDate: z.string().nullable(),
});
// Discriminated union cleanly separates valid extraction from structured refusal
const ExtractionOutcomeSchema = z.discriminatedUnion("outcome", [
z.object({
outcome: z.literal("extracted"),
payload: InvoicePayloadSchema,
refusalReason: z.null(),
}),
z.object({
outcome: z.literal("refused"),
payload: InvoicePayloadSchema.nullable(),
refusalReason: z.string().min(1).nullable(),
}),
]);
export type ExtractionOutcome = z.infer<typeof ExtractionOutcomeSchema>;
export async function extractInvoiceWithRefusalHandling(
documentText: string
): Promise<ExtractionOutcome> {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0,
messages: [
{
role: "system",
content:
"Extract invoice fields into the schema. If you must refuse the request, set outcome to 'refused' and explain why in refusalReason.",
},
{
role: "user",
content: documentText,
},
],
response_format: zodResponseFormat(
ExtractionOutcomeSchema,
"invoice_extraction_outcome"
),
});
const message = completion.choices[0]?.message;
// 1. Handle transport/API-level refusal field directly
if (message?.refusal) {
return {
outcome: "refused",
payload: null,
refusalReason: message.refusal,
};
}
const raw = message?.content ?? "";
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
throw new Error(`Expected JSON output for structured schema, got: \${raw}`);
}
// 2. Validate against the discriminated union schema
const validated = ExtractionOutcomeSchema.safeParse(parsedJson);
if (!validated.success) {
throw new Error(
`Schema validation failed: \${JSON.stringify(validated.error.issues)}`
);
}
return validated.data;
}
Helpful Tips for Production Schemas
- Do not retry safety refusals like JSON syntax bugs: Retrying a genuine safety refusal with the same prompt usually triggers another refusal and wastes tokens; log it, return a safe user message, or route to human review.
- Keep strict JSON Schema rules in mind: When converting Zod schemas to strict JSON Schema, make sure every object property is listed in
requiredand use.nullable()rather than.optional()where strict mode expects explicit keys. - Distinguish false-positive refusals from real policy blocks: Track refusal rates by model and prompt template so over-sensitive classifiers on benign inputs can be tuned or routed to a better-suited model.
You must log in or register to comment.
