- how
ChainOfThoughthas the model reason before it answers; - why
reasoning: :writtengets you written reasoning from any model; - how to script reasoning in a test.
1. A predictor that reasons
Until now, triage has usedPredict, which asks the model for the outputs alone. To see why it answered as it did, you need a predictor that asks for its reasoning too.
DSPyRb::ChainOfThought[signature] makes a predictor that has the model reason before it answers, and adds a reasoning output to the prediction.
2. Try it in the console
TriageTicket needs no change. Try ChainOfThought on chapter 2’s sample ticket:
reasoning holds depends on the model: with gpt-4.1-mini, DSPy’s ChainOfThought asks for a short plan, and with a reasoning model, one that reasons privately before it answers, such as gpt-5-mini, it may be empty.
reasoning: :written asks any model to write out its reasoning instead:
Predict judged it urgent, and its reasoning shows why.
That’s what the reasoning is for: a support agent sees what the model weighed, and can tell when its idea of urgent isn’t the team’s.
3. A column for the reasoning
Give tickets a column for the reasoning, with the same name as its output:4. Triage with reasoning
Triage every new ticket withChainOfThought. Replace app/models/ticket.rb with:
app/models/ticket.rb
5. Show the reasoning
Show the reasoning under the category, as “Why:”. Tickets created before this chapter have none, so show it only when there is some. Replaceapp/views/tickets/_ticket.html.erb with:
app/views/tickets/_ticket.html.erb
6. See it in the browser
Start the server, and create a ticket at http://localhost:3000/tickets/new with chapter 2’s parcel ticket: the subject “Where is my parcel?” and the body “My order 3310 was due on Monday and has not arrived. I need it for a wedding on Saturday.” The ticket’s page showsshipping and the “Urgent” mark, with the model’s reasoning under “Why:”, such as:
The customer is inquiring about the status of their shipment which was expected to arrive earlier in the week but has not yet been delivered. Since the order is urgently needed for an event this Saturday, the issue pertains to the shipping and timely delivery of the parcel.
7. Reasoning in the tests
With reasoning, triage’s scripted answer needs areasoning too. Replace test/fixtures/files/ticket_answers.yml with:
test/fixtures/files/ticket_answers.yml
test/models/ticket_test.rb with:
test/models/ticket_test.rb
test/integration/ticket_submission_test.rb with:
test/integration/ticket_submission_test.rb
8. Check your work
If something goes wrong
Comparing with the tag
Thechapter-4 tag holds the app at the end of this chapter. To compare yours with it:
Next
A program
Run a ticket’s whole job as one DSPy program, with a single call.