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

# Triage

> Label each new ticket with a category and an urgent flag, and show them on its page

After reading this guide, you will know:

* how a description tells the model what an output means;
* how to run a predictor when a ticket is created, and save what it returns;
* how to test model calls without calling a model.

A support team's first questions about a new ticket are what it's about and whether it can wait. In this chapter, the model answers both for every new ticket: it gives the ticket a category and an urgent flag, and the ticket's page shows them.

## 1. A signature for triage

Chapter 1's signature, `"ticket -> summary"`, let the model answer in any words it liked. Triage needs more than that. The category has to come from a fixed list the app can rely on, urgent has to be a real `true` or `false`, and the model needs to know what the team counts as urgent.

For that, you write the signature as a class, like the [Introduction](https://ruby-on-dspy.ralak.co/index.md)'s, and give urgent a description.

Create `app/signatures/triage_ticket.rb`:

```ruby app/signatures/triage_ticket.rb theme={"theme":"one-dark-pro"}
class TriageTicket < DSPyRb::Signature
  CATEGORIES = %w[ billing shipping returns account bug other ]

  instructions "Triage a customer's support ticket for the support team."

  input :subject, String
  input :body, String

  output :category, DSPyRb::Types::Literal[*CATEGORIES]
  output :urgent, DSPyRb::Types::Boolean, desc: "Needs a reply today"
end
```

`desc:` gives an output a description, which tells the model what it means. That's where the team's idea of urgent goes.

As in the Introduction, a reply that doesn't fit the types raises an error: `DSPyRb::AdapterParseError`.

`app/signatures` is a new folder, so restart any running server or console for Rails to load it.

## 2. Try it in the console

Before wiring the signature into the app, try it on a 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::Predict[TriageTicket].call(subject:, body:).to_h
=> {category: "billing", urgent: true}
```

`to_h` shows all of a prediction's outputs at once, which suits the console. The app reads each one by name instead, as in `result.category`.

## 3. Columns for the results

Give tickets a column for each output, with the same name, so each assignment reads plainly, as in `category: result.category`:

```bash theme={"theme":"one-dark-pro"}
bin/rails generate migration AddTriageToTickets category:string urgent:boolean
bin/rails db:migrate
```

## 4. Triage each new ticket

Run the predictor whenever a ticket is created. Replace `app/models/ticket.rb` with:

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

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

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

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

`process` runs the ticket through each step, then saves it once. For now `triage` is the only step; chapter 3 adds a second.

The model call runs inline, in the request, so creating a ticket now waits for the model.

## 5. Show the results

Show the category on the ticket's page, and mark the ticket when it's urgent. 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>
</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). Try 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 the category the model chose, `shipping` for this one, with an "Urgent" mark.

## 7. Tests without a real model

Creating a ticket now calls the model, but tests shouldn't depend on one: a real model costs money and needs your key, and no test can know its answer in advance. So the tests use `DSPyRb::DummyLM`, DSPy's own stand-in model. It returns the answers you give it, one per call, in order, and never calls a provider.

A test hands its `DummyLM` to the code it tests with `DSPyRb.context(lm: ...)`, which runs its block with that model in place of `config.lm`.

So that no test reaches the real model by mistake, even with your key set, take the default model away in tests. Add these lines after `require "rails/test_help"` in `test/test_helper.rb`, so it reads:

```ruby test/test_helper.rb theme={"theme":"one-dark-pro"}
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

# No real model in tests: each model call runs on a DSPyRb::DummyLM given by DSPyRb.context.
DSPyRb.configure do |config|
  config.lm = nil
end

module ActiveSupport
  class TestCase
    # Run tests in parallel with specified workers
    parallelize(workers: :number_of_processors)

    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
    fixtures :all

    # Add more helper methods to be used by all tests here...
  end
end
```

A model call outside `DSPyRb.context` now raises `DSPyRb::Error` ("no LM") at once, and sends nothing.

## 8. Test a new ticket

A new ticket should arrive with the category and urgent flag the model gave it. To test that, `DummyLM` needs an answer to give, and the next step's test uses the same one, so keep it in a fixture file. Create `test/fixtures/files/ticket_answers.yml`:

```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.
- category: billing
  urgent: true
```

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

  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
```

## 9. Test what a support agent sees

The `Ticket` test checks what triage saves. This test checks what a support agent sees: it logs a ticket through the app and reads its page. Create `test/integration/ticket_submission_test.rb`:

```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

  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
```

This replaces the scaffold's controller test. Its create test now calls the model outside `DSPyRb.context`, so it fails, and its six other tests cover only code the scaffold generated. Delete it:

```bash theme={"theme":"one-dark-pro"}
rm test/controllers/tickets_controller_test.rb
```

## 10. Run the tests on any machine

`DummyLM` runs inside DSPy, so a new machine, or GitHub's, needs DSPy installed before the tests can run. Add the install to `bin/setup`, after its `bundle install` line:

```ruby bin/setup theme={"theme":"one-dark-pro"}
  puts "== Installing dependencies =="
  system("bundle check") || system!("bundle install")
  system! "bundle exec ruby-on-dspy setup"
```

Then add it to the `test` job in `.github/workflows/ci.yml`, before "Run tests":

```yaml .github/workflows/ci.yml theme={"theme":"one-dark-pro"}
      - name: Install DSPy
        run: bundle exec ruby-on-dspy setup

      - name: Run tests
```

## 11. Check your work

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

Both should pass, with no offenses and 2 tests.

## If something goes wrong

> [!WARNING]
>
> If creating a ticket shows `DSPyRb::LMNotConfiguredError`, no key reached DSPy. Add the key as in [chapter 1, step 4](https://ruby-on-dspy.ralak.co/helpdesk/new-rails-app.md#4-the-model-and-your-key), then restart the server. The ticket is still saved, since triage runs after the commit; it has no category.

## Comparing with the tag

The [`chapter-2` tag](https://github.com/samuelralak/dspy-tutorial/tree/chapter-2) 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-2 --stat
```

Expect the same files to differ as in chapter 1.

## Next

> [card] [Extraction](https://ruby-on-dspy.ralak.co/helpdesk/extraction.md)
>
> Pull the order numbers and products out of each ticket, as lists.


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