> ## Documentation Index
> Fetch the complete documentation index at: https://dspy-rb.ralak.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Reasoning

> Have the model reason before it triages, and show why on each ticket's page

After reading this guide, you will know:

* how `ChainOfThought` has the model reason before it answers;
* why `reasoning: :written` gets you written reasoning from any model;
* how to script reasoning in a test.

When a ticket is marked urgent, a support agent wants to know why before acting on it. In this chapter, the model reasons before it triages each new ticket, and the ticket's page shows that reasoning under "Why:".

## 1. A predictor that reasons

Until now, triage has used `Predict`, 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:

```irb theme={"theme":"one-dark-pro"}
$ bin/rails console
helpdesk(dev)> subject = "Refund for order #1234"
=> "Refund for order #1234"
helpdesk(dev)> body = "I was charged twice for my coffee grinder."
=> "I was charged twice for my coffee grinder."
helpdesk(dev)> DSPyRb::ChainOfThought[TriageTicket].call(subject:, body:).reasoning
=> "Verify the customer's order and payment details to confirm the double charge, then initiate a refund for the duplicate payment."
```

That's a plan for handling the ticket, not why the model triaged it as it did. What `reasoning` holds depends on the model: with `gpt-4.1-mini`, DSPy's [`ChainOfThought`](https://github.com/stanfordnlp/dspy/blob/3.5.0/dspy/predict/chain_of_thought.py) 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:

```irb theme={"theme":"one-dark-pro"}
helpdesk(dev)> DSPyRb::ChainOfThought[TriageTicket, reasoning: :written].call(subject:, body:).to_h
=> {reasoning: "The customer is reporting an issue with being charged twice for a product, which is a payment-related problem. This falls under the billing category. There is no indication that the issue requires immediate attention today, so it is not urgent.", category: "billing", urgent: false}
```

Reasoning first can change the answer: this time the model judged the ticket not urgent, where chapter 2's `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:

```bash theme={"theme":"one-dark-pro"}
bin/rails generate migration AddReasoningToTickets reasoning:text
bin/rails db:migrate
```

## 4. Triage with reasoning

Triage every new ticket with `ChainOfThought`. Replace `app/models/ticket.rb` with:

```ruby app/models/ticket.rb theme={"theme":"one-dark-pro"}
class Ticket < ApplicationRecord
  # After the commit, so slow model calls never hold a database transaction open.
  after_create_commit :process

  private
    def process
      self
        .then { |ticket| triage(ticket) }
        .then { |ticket| details(ticket) }
        .then(&:save!)
    end

    def triage(ticket)
      result = DSPyRb::ChainOfThought[TriageTicket, reasoning: :written].call(subject: ticket.subject, body: ticket.body)

      ticket.tap do |t|
        t.assign_attributes(
          reasoning: result.reasoning,
          category: result.category,
          urgent: result.urgent
        )
      end
    end

    def details(ticket)
      result = DSPyRb::Predict[ExtractDetails].call(subject: ticket.subject, body: ticket.body)

      ticket.tap do |t|
        t.assign_attributes(order_numbers: result.order_numbers, products: result.products)
      end
    end
end
```

Triage's reply is now longer, so creating a ticket takes a little longer.

## 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. Replace `app/views/tickets/_ticket.html.erb` with:

```erb app/views/tickets/_ticket.html.erb theme={"theme":"one-dark-pro"}
<div id="<%= dom_id ticket %>">
  <div>
    <strong>Subject:</strong>
    <%= ticket.subject %>
    <% if ticket.urgent? %>
      <mark>Urgent</mark>
    <% end %>
  </div>

  <div>
    <strong>Body:</strong>
    <%= ticket.body %>
  </div>

  <div>
    <strong>Category:</strong>
    <%= ticket.category %>
  </div>

  <% if ticket.reasoning.present? %>
    <div>
      <strong>Why:</strong>
      <%= ticket.reasoning %>
    </div>
  <% end %>

  <% if ticket.order_numbers.present? %>
    <div>
      <strong>Order numbers:</strong>
      <%= ticket.order_numbers.to_sentence %>
    </div>
  <% end %>

  <% if ticket.products.present? %>
    <div>
      <strong>Products:</strong>
      <%= ticket.products.to_sentence %>
    </div>
  <% end %>
</div>
```

## 6. See it in the browser

Start the server, and create a ticket at [http://localhost:3000/tickets/new](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 shows `shipping` 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 a `reasoning` too. Replace `test/fixtures/files/ticket_answers.yml` with:

```yaml test/fixtures/files/ticket_answers.yml theme={"theme":"one-dark-pro"}
# The model's scripted answers for a new ticket, one for each call, in order.
- reasoning: A double charge takes the customer's money, so it needs a reply today.
  category: billing
  urgent: true
- order_numbers: [ "1234" ]
  products: [ "coffee grinder" ]
```

The scripted answer keeps chapter 2's verdict: the tests check what the app does with an answer, not which answer a model gives.

Each test file gains a test for the reasoning. Replace `test/models/ticket_test.rb` with:

```ruby test/models/ticket_test.rb theme={"theme":"one-dark-pro"}
require "test_helper"

class TicketTest < ActiveSupport::TestCase
  test "a new ticket arrives with a category and an urgent flag" do
    ticket = create_ticket

    assert_equal "billing", ticket.category
    assert ticket.urgent?
  end

  test "a new ticket arrives with the order numbers and products it mentions" do
    ticket = create_ticket

    assert_equal [ "1234" ], ticket.order_numbers
    assert_equal [ "coffee grinder" ], ticket.products
  end

  test "a new ticket arrives with the reasoning behind its urgency" do
    ticket = create_ticket

    assert_match "needs a reply today", ticket.reasoning
  end

  private
    def create_ticket
      lm = DSPyRb::DummyLM[YAML.load_file(file_fixture("ticket_answers.yml"))]

      ticket = DSPyRb.context(lm:) do
        Ticket.create!(
          subject: "Refund for order #1234",
          body: "I was charged twice for my coffee grinder."
        )
      end

      ticket.reload
    end
end
```

And replace `test/integration/ticket_submission_test.rb` with:

```ruby test/integration/ticket_submission_test.rb theme={"theme":"one-dark-pro"}
require "test_helper"

class TicketSubmissionTest < ActionDispatch::IntegrationTest
  test "a support agent logs a ticket and sees its category and urgency" do
    log_ticket

    assert_select "div", /Category:\s+billing/
    assert_select "mark", "Urgent"
  end

  test "a support agent sees the order numbers and products a ticket mentions" do
    log_ticket

    assert_select "div", /Order numbers:\s+1234/
    assert_select "div", /Products:\s+coffee grinder/
  end

  test "a support agent sees why a ticket was marked urgent" do
    log_ticket

    assert_select "div", /Why:\s+A double charge takes the customer's money/
  end

  private
    def log_ticket
      lm = DSPyRb::DummyLM[YAML.load_file(file_fixture("ticket_answers.yml"))]
      form = { subject: "Refund for order #1234", body: "I was charged twice for my coffee grinder." }

      DSPyRb.context(lm:) do
        post tickets_path, params: { ticket: form }
      end

      follow_redirect!
    end
end
```

## 8. Check your work

```bash theme={"theme":"one-dark-pro"}
bin/rubocop
bin/rails test
```

Both should pass, with no offenses and 6 tests.

## If something goes wrong

> [!WARNING]
>
> If a test fails with `DSPyRb::AdapterParseError`, check that the first answer in `ticket_answers.yml` has a `reasoning`, and that `triage`'s `ChainOfThought` has `reasoning: :written`. Without the option, DSPy asks for a `plan` field, so a scripted `reasoning` doesn't fit.

## Comparing with the tag

The [`chapter-4` tag](https://github.com/samuelralak/dspy-tutorial/tree/chapter-4) holds the app at the end of this chapter. To compare yours with it:

```bash theme={"theme":"one-dark-pro"}
git fetch tutorial --tags --force
git add --all
git diff --cached chapter-4 --stat
```

Expect the same files to differ as in chapter 1.

## Next

> [card] [A program](https://dspy-rb.ralak.co/helpdesk/program.md)
>
> Run a ticket's whole job as one DSPy program, with a single call.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.