> ## 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.

# Extraction

> Pull the order numbers and products out of each ticket, as lists

After reading this guide, you will know:

* how to ask the model for a list;
* how to add a second model call to a ticket's steps;
* how to script two model calls in a test.

Once a ticket is triaged, the team needs its details: which orders and which products it's about. In this chapter, the model finds every order number and product a new ticket mentions, and the ticket's page lists them.

## 1. A signature for the details

Finding details is a task of its own, so it gets its own signature rather than more outputs on `TriageTicket`. That keeps each signature one small task you can try alone in the console. The cost is a second model call for each ticket.

Create `app/signatures/extract_details.rb`:

```ruby app/signatures/extract_details.rb theme={"theme":"one-dark-pro"}
class ExtractDetails < DSPyRb::Signature
  instructions "Find every order number and product a customer's support ticket mentions, " \
               "in its subject and its body."

  input :subject, String
  input :body, String

  output :order_numbers,
         DSPyRb::Types::List[String],
         desc: "Every order number in the subject and the body"
  output :products, DSPyRb::Types::List[String], desc: "Product names, as the customer wrote them"
end
```

A ticket can mention any number of orders and products, so each output is a list. `DSPyRb::Types::List[String]` asks the model for an array of strings, which may be empty.

Customers often put the order number only in the subject, as in "Refund for order #1234". So the instructions and the `order_numbers` description tell the model to look in both the subject and the body.

## 2. Try it in the console

Try it 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::Predict[ExtractDetails].call(subject:, body:).to_h
=> {order_numbers: ["1234"], products: ["coffee grinder"]}
```

## 3. Columns for the lists

Give tickets a JSON column for each list, with the same name as its output:

```bash theme={"theme":"one-dark-pro"}
bin/rails generate migration AddDetailsToTickets order_numbers:json products:json
bin/rails db:migrate
```

## 4. A second step for the details

Add the details after triage. 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::Predict[TriageTicket].call(subject: ticket.subject, body: ticket.body)

      ticket.tap do |t|
        t.assign_attributes(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
```

Creating a ticket now waits for two model calls, one after the other.

## 5. Show the lists

List the order numbers and products on the ticket's page, when it has any. 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.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 the subject "Return for order 7788" and the body "I would like to return the espresso cups, and the milk jug from order 7790."

The ticket's page shows "Order numbers: 7788 and 7790", one from the subject and one from the body, and "Products: espresso cups and milk jug".

## 7. Two answers in the tests

Each new ticket now makes two model calls, triage first, so `DummyLM` needs two answers, in that order. 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.
- category: billing
  urgent: true
- order_numbers: [ "1234" ]
  products: [ "coffee grinder" ]
```

Each test file gains a test for the details. 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

  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

  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 4 tests.

## If something goes wrong

> [!WARNING]
>
> If a test fails with `DSPyRb::AdapterParseError`, a call got an answer that doesn't fit its signature: `ticket_answers.yml` is missing an answer, or has them in the wrong order. Triage's answer comes first.

## Comparing with the tag

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

Expect the same files to differ as in chapter 1.

## Next

> [card] [Reasoning](https://ruby-on-dspy.ralak.co/helpdesk/reasoning.md)
>
> Have the model reason before it triages, and show why on each ticket's page.


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