Session 5· 20· 10 min

Chat Completions Parse & Refusal

What you'll learn
  • Use chat.completions.parse() (the older endpoint path)
  • Handle message.refusal alongside parsed output
  • Know when to use each parse method

The final Session 5 exercise revisits the Chat Completions endpoint with a parse-style call. Same Pydantic idea, slightly different path. Useful when your codebase is already on Chat Completions.

20_chat_completions_parse_refusal.py
completion = client.chat.completions.parse(                  ①
    model="gpt-4o-2024-08-06",
    messages=[
        {"role": "system", "content": "You are a helpful math tutor..."},
        {"role": "user",   "content": "how can I solve 8x + 7 = -23"},
    ],
    response_format=MathReasoning,                               ②
)

msg = completion.choices[0].message
if msg.refusal:                                                   ③
    print("Refusal:", msg.refusal)
else:
    math = msg.parsed                                             ④
    print(math.final_answer)
chat.completions.parse() — older endpoint, same Pydantic power.
Argument is response_format (not text_format) — this is the naming difference between the two endpoints.
Always check refusal first on structured-output responses.
Typed object lives at message.parsed here, not output_parsed.
$ python 20_chat_completions_parse_refusal.py
responses.parse
lessons 17–19
  • Newer endpoint
  • Argument: text_format
  • Result: response.output_parsed
  • Preferred for new code
chat.completions.parse
this lesson
  • Older endpoint
  • Argument: response_format
  • Result: choice.message.parsed
  • Use when your code is already on Chat Completions
Session 5 complete
You can now produce structured output three ways (JSON mode, schema, Pydantic), call tools in loops, handle parallel calls and errors, and use both parse endpoints. You are ready for LangChain in Session 6.
Code Check
In chat.completions.parse(), where does the typed object live?
Recap — what you just learned
  • Two parse endpoints: responses.parse (new) and chat.completions.parse (old)
  • Argument names differ: text_format vs response_format
  • Result paths differ: output_parsed vs message.parsed
  • Always check refusal before reading parsed
Next up: Session 5 Troubleshooting