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

# A ledger of model work

> Record what each piece of a ticket's model work cost, in a ledger whose entries never change

After reading this guide, you will know:

* why a suggestion's cost can't go in chapter 6's columns;
* how a ledger keeps model costs: one entry for each piece of work, never changed;
* how to store DSPy's cost estimate exactly, in whole nano-dollars with its currency;
* how to test the ledger on priced, cached and unpriced calls.

Chapter 6 saved what a ticket's triage and details cost. A suggested reply costs money too, and the app saves its cost nowhere. In this chapter, each piece of a ticket's model work is written to a ledger.

## 1. A suggestion's cost goes nowhere

`suggest_reply` saves the reply and drops `result.spend`, so a suggestion's calls, tokens and cost are lost.

The simplest fix adds each suggestion's figures to the ticket's three columns from chapter 6. Two things go wrong:

* The ticket can no longer tell which work cost what.
* The `cost` column keeps six decimal places, too few to hold one call's cost.

Assign the first cost from chapter 6's console, which calls no model:

```irb theme={"theme":"one-dark-pro"}
$ bin/rails console
helpdesk(dev)> Ticket.new(cost: 0.00021279999999999997).cost
=> 0.213e-3
```

Rails rounds it to the column's six places, and each figure added in would round again. More places wouldn't make it exact: Rails hands SQLite a `decimal` as a floating-point number.

## 2. A ledger

Another approach saves each suggestion's figures on its own `SuggestedReply`. But a ticket's suggestions are deleted with it, and their costs would go too, though the money was spent.

Money is kept in a [ledger](https://stripe.dev/blog/ledger-stripe-system-for-tracking-and-validating-money-movement): a table of entries, each written once and never changed. A total is added up from the entries, never stored.

The app's ledger gets one entry for each piece of model work: a ticket's triage and details, or one suggested reply. An entry holds that work's billed calls, tokens and cost. It also counts the calls DSPy's cache answered, since chapter 6's repeated ticket showed "Model calls: 0" for work that ran.

A payment ledger also corrects a mistake with new entries rather than an edit, and records each movement twice, out of one account and into another. This app corrects no entries and moves no money, so its ledger needs neither.

## 3. The ledger's table

The ledger keeps each cost in nano-dollars, billionths of a dollar. gpt-4.1-mini charges 400 of them for a prompt token and 1,600 for a completion token, so a cost is a whole number, and whole numbers add up exactly.

Step 1's cost, in the same console:

```irb theme={"theme":"one-dark-pro"}
helpdesk(dev)> (0.00021279999999999997.to_d * 1_000_000_000).round
=> 212800
```

The ledger is a table of its own. Generate its model:

```bash theme={"theme":"one-dark-pro"}
bin/rails generate model LedgerEntry
```

Replace the migration it wrote, the file in `db/migrate/` whose name ends in `_create_ledger_entries.rb`, with:

```ruby db/migrate/20261201090938_create_ledger_entries.rb theme={"theme":"one-dark-pro"}
class CreateLedgerEntries < ActiveRecord::Migration[8.1]
  def change
    create_table :ledger_entries do |t|
      t.references :ticket, null: false, foreign_key: false
      t.references :suggested_reply, foreign_key: false, index: { unique: true }
      t.string :work, null: false
      t.integer :billed_calls
      t.integer :cached_calls
      t.integer :tokens
      t.bigint :cost_nanos
      t.string :currency, null: false, default: "USD"
      t.datetime :created_at, null: false
    end

    add_index :ledger_entries, :ticket_id,
      unique: true,
      where: "work = 'triage and details'",
      name: "index_ledger_entries_on_one_triage_per_ticket"
  end
end
```

* `cost_nanos` holds DSPy's estimate of the cost, in nano-dollars. An empty one means the cost is unknown, never 0.
* `currency` names the money: DSPy's costs are in US dollars.
* A ledger never counts the same work twice, so a second entry for it raises `ActiveRecord::RecordNotUnique`. `where:` limits the last index to triage entries, so a ticket has at most one. The unique index on `suggested_reply_id` gives a suggestion at most one, and the triage entries' empty `suggested_reply_id` doesn't count against it.
* An entry is never updated, so it has `created_at` and no `updated_at`.

Then run the migration:

```bash theme={"theme":"one-dark-pro"}
bin/rails db:migrate
```

## 4. Write an entry

An entry's figures come from a piece of work's `spend`, as chapter 6's did. Replace `app/models/ledger_entry.rb` with:

```ruby app/models/ledger_entry.rb theme={"theme":"one-dark-pro"}
class LedgerEntry < ApplicationRecord
  NANOS_PER_DOLLAR = 1_000_000_000
  TRIAGE_AND_DETAILS = "triage and details"
  SUGGESTED_REPLY = "suggested reply"

  belongs_to :ticket
  belongs_to :suggested_reply, optional: true

  validates :work, inclusion: { in: [ TRIAGE_AND_DETAILS, SUGGESTED_REPLY ] }

  def self.record!(work:, spend:, suggested_reply: nil)
    billed = spend.calls.reject(&:cache_hit)

    create!(
      work:,
      suggested_reply:,
      billed_calls: billed.size,
      cached_calls: spend.calls.size - billed.size,
      tokens: total_tokens(billed),
      cost_nanos: total_cost_nanos(billed)
    )
  end

  def self.total_tokens(calls)
    calls.sum do |call|
      call.usage.prompt_tokens + call.usage.completion_tokens
    end
  end

  def self.total_cost_nanos(calls)
    return unless calls.all?(&:cost)

    calls.sum do |call|
      (call.cost.to_d * NANOS_PER_DOLLAR).round
    end
  end

  def readonly?
    persisted?
  end
end
```

* `record!` writes one entry from a `spend`. As in chapter 6, only the calls that reached the model are billed; the rest came from DSPy's cache.
* `total_tokens` is chapter 6's, moved here.
* `total_cost_nanos` is chapter 6's `total_cost` in whole nano-dollars, so a call with no price still leaves it `nil`.
* `readonly?` makes a saved entry read-only: `save`, `update` and `destroy` raise `ActiveRecord::ReadOnlyRecord`. `delete`, `update_all` and `delete_all` skip that check, so the app never calls them on the ledger.

## 5. Record each piece of work

Each piece of work writes its entry as it saves its result. Replace `app/models/ticket.rb` with:

```ruby app/models/ticket.rb theme={"theme":"one-dark-pro"}
class Ticket < ApplicationRecord
  has_many :suggested_replies, dependent: :destroy
  has_many :ledger_entries

  # After the commit, so slow model calls never hold a database transaction open.
  after_create_commit :process

  def suggest_reply
    result = DSPyRb.context(lm: model_for_next_suggestion) do
      ReplyWriter.new.call(subject:, body:)
    end

    transaction do
      suggested_reply = suggested_replies.create!(reply: result.reply, article_ids: result.article_ids)
      ledger_entries.record!(work: LedgerEntry::SUGGESTED_REPLY, suggested_reply:, spend: result.spend)

      suggested_reply
    end
  end

  def ledger_total(figure)
    ledger_entries.sum(figure) unless ledger_entries.where(figure => nil).exists?
  end

  private
    def process
      result = TicketDesk.new.call(subject:, body:)

      transaction do
        update!(
          reasoning: result.reasoning,
          category: result.category,
          urgent: result.urgent,
          order_numbers: result.order_numbers,
          products: result.products
        )

        ledger_entries.record!(work: LedgerEntry::TRIAGE_AND_DETAILS, spend: result.spend)
      end
    end

    def model_for_next_suggestion
      DSPyRb.lm.copy(rollout_id: SecureRandom.random_number(2**31), temperature: 1.0)
    end
end
```

* `ledger_entries.record!` runs `record!` on the ticket's own entries, so each entry gets its ticket.
* The model calls run first, outside any transaction, as the comment from chapter 2 says. Then one transaction saves the work's result with its entry, so both are saved or neither is.
* `process` no longer writes chapter 6's three columns. Its entry holds those figures.
* With no foreign keys and no `dependent:`, a ticket can be deleted, suggestions and all, and their entries stay.
* `ledger_total` asks the database for a figure's total, unless an entry doesn't know it. SQL's `SUM` skips empty values, so a total over an unknown cost would look known, and too low.
* `suggest_reply` still returns the `SuggestedReply`, its transaction block's last value.

Work that fails before its entry is written isn't counted, so the ledger can miss calls the provider billed.

## 6. Show the ledger

The ledger goes on the ticket's page, like chapter 7's suggestions.

`dollars` shows nano-dollars as dollars, to six places as chapter 6 did, and an unknown cost as "unknown". A total adds up whole nano-dollars, so it's rounded only once, for display. Replace `app/helpers/tickets_helper.rb` with:

```ruby app/helpers/tickets_helper.rb theme={"theme":"one-dark-pro"}
module TicketsHelper
  def suggest_reply_label(ticket)
    ticket.suggested_replies.any? ? "Suggest another reply" : "Suggest a reply"
  end

  def dollars(nanos)
    nanos ? number_to_currency(nanos.to_d / LedgerEntry::NANOS_PER_DOLLAR, precision: 6) : "unknown"
  end
end
```

Create `app/views/ledger_entries/_ledger_entry.html.erb`:

```erb app/views/ledger_entries/_ledger_entry.html.erb theme={"theme":"one-dark-pro"}
<tr>
  <td><%= ledger_entry.work.capitalize %></td>
  <td><%= l ledger_entry.created_at, format: :short %></td>
  <td><%= ledger_entry.billed_calls %></td>
  <td><%= ledger_entry.cached_calls %></td>
  <td><%= ledger_entry.tokens %></td>
  <td><%= dollars(ledger_entry.cost_nanos) %></td>
</tr>
```

Replace `app/views/tickets/show.html.erb` with:

```erb app/views/tickets/show.html.erb theme={"theme":"one-dark-pro"}
<p style="color: green"><%= notice %></p>

<%= render @ticket %>

<% if @ticket.ledger_entries.any? %>
  <h2>Model work</h2>

  <table>
    <thead>
      <tr>
        <th>What</th>
        <th>When</th>
        <th>Billed calls</th>
        <th>From DSPy's cache</th>
        <th>Tokens</th>
        <th>Cost</th>
      </tr>
    </thead>

    <tbody>
      <%= render @ticket.ledger_entries.order(:created_at) %>
    </tbody>

    <tfoot>
      <tr>
        <th>Total</th>
        <td></td>
        <td><%= @ticket.ledger_total(:billed_calls) %></td>
        <td><%= @ticket.ledger_total(:cached_calls) %></td>
        <td><%= @ticket.ledger_total(:tokens) %></td>
        <td><%= dollars(@ticket.ledger_total(:cost_nanos)) %></td>
      </tr>
    </tfoot>
  </table>
<% end %>

<%= button_to suggest_reply_label(@ticket), ticket_suggested_replies_path(@ticket),
      data: { turbo_submits_with: "Suggesting a reply..." } %>

<%= render @ticket.suggested_replies.order(created_at: :desc) %>

<div>
  <%= link_to "Edit this ticket", edit_ticket_path(@ticket) %> |
  <%= link_to "Back to tickets", tickets_path %>

  <%= button_to "Destroy this ticket", @ticket, method: :delete %>
</div>
```

"Billed calls" is chapter 6's "Model calls", now that the calls from DSPy's cache are counted beside them.

`_ticket` is the list's partial too, so it loses chapter 6's figures. 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>
```

## 7. Remove chapter 6's columns

No code reads or writes the three columns any more. Generate a migration that removes them, with chapter 6's types so a rollback restores them exactly, and run it:

```bash theme={"theme":"one-dark-pro"}
bin/rails generate migration RemoveSpendFromTickets model_calls:integer tokens:integer 'cost:decimal{10,6}'
bin/rails db:migrate
```

Chapter 6's figures go with its columns, so tickets from before this chapter start with no ledger entries.

## 8. See the ledger and try to change it

Start the server, and create a ticket with the subject "Wrong size" and the body "I ordered a medium jacket in order 7120 and got a small." Click "Suggest a reply", then "Suggest another reply". Its "Model work" table shows figures such as these:

| What | When | Billed calls | From DSPy's cache | Tokens | Cost |
| - | - | - | - | - | - |
| Triage and details | 01 Dec 09:16 | 2 | 0 | 632 | \$0.000378 |
| Suggested reply | 01 Dec 09:16 | 3 | 0 | 1663 | \$0.000789 |
| Suggested reply | 01 Dec 09:16 | 4 | 0 | 2476 | \$0.001151 |
| Total | | 9 | 0 | 4771 | \$0.002318 |

Each suggestion is billed in full, since each asks with a new rollout ID. The agent took a different number of turns each time.

Create the same ticket again. DSPy answers its triage and details from its cache, so its row shows 0 billed calls, 2 from DSPy's cache, 0 tokens and \$0.000000.

A saved entry can't be changed, even from the console:

```irb theme={"theme":"one-dark-pro"}
$ bin/rails console
helpdesk(dev)> LedgerEntry.last.update!(tokens: 0)
(helpdesk):1:in '<main>': LedgerEntry is marked as readonly (ActiveRecord::ReadOnlyRecord)
```

Deleting a ticket leaves its entries, so what it spent stays counted. Try it on `Ticket.last`, the repeated "Wrong size" ticket:

```irb theme={"theme":"one-dark-pro"}
helpdesk(dev)> ticket = Ticket.last;
helpdesk(dev)> ticket.destroy;
helpdesk(dev)> LedgerEntry.where(ticket_id: ticket.id).count
=> 1
```

## 9. Test the ledger

The tests need entries to start from. Replace the generated `test/fixtures/ledger_entries.yml` with:

```yaml test/fixtures/ledger_entries.yml theme={"theme":"one-dark-pro"}
late_parcel_triage:
  ticket: late_parcel
  work: triage and details
  billed_calls: 2
  cached_calls: 0
  tokens: 628
  cost_nanos: 380800

late_parcel_reply:
  ticket: late_parcel
  suggested_reply: late_parcel
  work: suggested reply
  billed_calls: 3
  cached_calls: 0
  tokens: 2100
  cost_nanos: 1200000
```

A `DummyLM`'s calls have 0 tokens and no price, and none is a cache hit. So the ledger's own tests build each `spend` with `DSPyRb::Spend`, from calls that are priced, cached or unpriced, as DSPy gives them.

`DSPyRb::Spend` refuses a call without the fields every real one has, so `priced_call` gives those, plus `usage` and `cost`. The ledger reads only `usage`, `cache_hit` and `cost`. Replace the generated `test/models/ledger_entry_test.rb` with:

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

class LedgerEntryTest < ActiveSupport::TestCase
  test "a piece of work is recorded with its billed calls, tokens and cost" do
    entry = record_triage(DSPyRb::Spend.new(calls: [ priced_call, priced_call ]))

    assert_equal 2, entry.billed_calls
    assert_equal 866, entry.tokens
    assert_equal 425_600, entry.cost_nanos
  end

  test "a piece of work is recorded under the ticket it was done for" do
    entry = record_triage(DSPyRb::Spend.new(calls: [ priced_call ]))

    assert_equal tickets(:double_charge), entry.ticket
  end

  test "calls answered from DSPy's cache are recorded but not billed" do
    entry = record_triage(DSPyRb::Spend.new(calls: [ priced_call, cached_call ]))

    assert_equal 1, entry.billed_calls
    assert_equal 1, entry.cached_calls
    assert_equal 433, entry.tokens
    assert_equal 212_800, entry.cost_nanos
  end

  test "a call with no price leaves the cost unknown" do
    entry = record_triage(DSPyRb::Spend.new(calls: [ priced_call, unpriced_call ]))

    assert_nil entry.cost_nanos
  end

  test "a ticket's triage and details are recorded once" do
    spend = DSPyRb::Spend.new(calls: [ priced_call ])

    assert_raises(ActiveRecord::RecordNotUnique) do
      tickets(:late_parcel).ledger_entries.record!(work: LedgerEntry::TRIAGE_AND_DETAILS, spend:)
    end
  end

  test "a suggested reply is recorded once" do
    spend = DSPyRb::Spend.new(calls: [ priced_call ])

    assert_raises(ActiveRecord::RecordNotUnique) do
      tickets(:late_parcel).ledger_entries.record!(
        work: LedgerEntry::SUGGESTED_REPLY,
        suggested_reply: suggested_replies(:late_parcel),
        spend:
      )
    end
  end

  test "a saved ledger entry can't be updated or destroyed" do
    entry = ledger_entries(:late_parcel_triage)

    assert_raises(ActiveRecord::ReadOnlyRecord) do
      entry.update!(tokens: 0)
    end

    assert_raises(ActiveRecord::ReadOnlyRecord) do
      entry.destroy
    end
  end

  private
    def record_triage(spend)
      tickets(:double_charge).ledger_entries.record!(work: LedgerEntry::TRIAGE_AND_DETAILS, spend:)
    end

    def priced_call
      {
        id: SecureRandom.uuid,
        model: "openai/gpt-4.1-mini",
        messages: [],
        usage: { prompt_tokens: 400, completion_tokens: 33, cached_tokens: 0, cache_creation_tokens: 0, reasoning_tokens: 0 },
        settings: {},
        cache_hit: false,
        duration_ms: 900,
        outcome: "completed",
        cost: 0.00021279999999999997
      }
    end

    def cached_call
      priced_call.except(:usage).merge(cache_hit: true)
    end

    def unpriced_call
      priced_call.except(:cost)
    end
end
```

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

  test "a new ticket's triage and details are written to its ledger" do
    entry = create_ticket.ledger_entries.sole

    assert_equal LedgerEntry::TRIAGE_AND_DETAILS, entry.work
    assert_equal 2, entry.billed_calls
    assert_nil entry.cost_nanos
  end

  test "asking for a reply saves the suggestion with its articles" do
    suggested_reply = DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      tickets(:double_charge).suggest_reply
    end

    assert_equal [ articles(:double_charge).id ], suggested_reply.reload.article_ids
  end

  test "each suggested reply for a ticket is asked for afresh" do
    ticket = tickets(:double_charge)

    first = model_options_during_next_suggestion(ticket)
    second = model_options_during_next_suggestion(ticket)

    assert_equal 1.0, first[:temperature]
    assert_equal 1.0, second[:temperature]
    assert_not_nil first[:rollout_id]
    assert_not_nil second[:rollout_id]
    assert_not_equal first[:rollout_id], second[:rollout_id]
  end

  test "a suggested reply is written to the ledger beside the reply" do
    suggested_reply = DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      tickets(:double_charge).suggest_reply
    end

    entry = LedgerEntry.find_by!(suggested_reply:)

    assert_equal LedgerEntry::SUGGESTED_REPLY, entry.work
    assert_equal 2, entry.billed_calls
  end

  test "a ticket's totals add up its ledger" do
    ticket = tickets(:late_parcel)

    assert_equal 5, ticket.ledger_total(:billed_calls)
    assert_equal 2728, ticket.ledger_total(:tokens)
    assert_equal 1_580_800, ticket.ledger_total(:cost_nanos)
  end

  test "a ticket's total cost is unknown while any of its work has no price" do
    ticket = tickets(:late_parcel)

    DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      ticket.suggest_reply
    end

    assert_nil ticket.ledger_total(:cost_nanos)
  end

  test "a deleted ticket's ledger entries stay" do
    assert_no_difference("LedgerEntry.count") do
      tickets(:late_parcel).destroy
    end
  end

  private
    def model_options_during_next_suggestion(ticket)
      options = []
      listener = ->(_call) { options << DSPyRb.lm.kwargs.slice(:rollout_id, :temperature) }

      DSPyRb.context(lm: scripted_model("reply_answers.yml"), on_call: listener) do
        ticket.suggest_reply
      end

      options.uniq.sole
    end

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

      ticket.reload
    end
end
```

Replace `test/helpers/tickets_helper_test.rb` with:

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

class TicketsHelperTest < ActionView::TestCase
  test "the button asks for a reply on a ticket with none" do
    assert_equal "Suggest a reply", suggest_reply_label(tickets(:double_charge))
  end

  test "the button asks for another reply once a ticket has one" do
    assert_equal "Suggest another reply", suggest_reply_label(tickets(:late_parcel))
  end

  test "a cost shows in dollars to six places" do
    assert_equal "$0.001581", dollars(1_580_800)
  end

  test "an unknown cost shows as unknown" do
    assert_equal "unknown", dollars(nil)
  end
end
```

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

  test "a support agent sees what each piece of work cost and the ticket's total" do
    get ticket_path(tickets(:late_parcel))

    assert_select "tbody tr", text: /Triage and details.*\$0\.000381/m
    assert_select "tbody tr", text: /Suggested reply.*\$0\.001200/m
    assert_select "tfoot tr", text: /Total.*\$0\.001581/m
  end

  test "a support agent asks for a suggested reply and sees it with its articles" do
    ticket = tickets(:double_charge)

    get ticket_path(ticket)
    assert_select "form[action=?] button", ticket_suggested_replies_path(ticket), text: "Suggest a reply"

    DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      post ticket_suggested_replies_path(ticket)
    end

    follow_redirect!

    assert_select "p", /refund the extra charge within 5 business days/
    assert_select "p", /Based on:\s+Refunds for double charges/
  end

  test "a support agent asks for another reply and sees both" do
    ticket = tickets(:late_parcel)

    get ticket_path(ticket)
    assert_select "form[action=?] button", ticket_suggested_replies_path(ticket), text: "Suggest another reply"

    DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      post ticket_suggested_replies_path(ticket)
    end

    follow_redirect!

    assert_select "h2", text: /Suggested reply/, count: 2
  end

  test "a support agent deletes a ticket with its suggested replies" do
    assert_difference("SuggestedReply.count", -1) do
      delete ticket_path(tickets(:late_parcel))
    end

    follow_redirect!

    assert_select "p", "Ticket was successfully destroyed."
  end

  private
    def log_ticket
      form = { subject: "Refund for order #1234", body: "I was charged twice for my coffee grinder." }

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

      follow_redirect!
    end
end
```

"a new ticket's triage and details are written to its ledger" and "a support agent sees what each piece of work cost and the ticket's total" take the place of chapter 6's tests of the three columns.

## 10. Check your work

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

Both should pass, with no offenses and 35 tests.

## If something goes wrong

> [!WARNING]
>
> If `bin/rails test` fails before step 9 with "NOT NULL constraint failed: ledger\_entries.ticket\_id", the fixtures `generate model` wrote are still in place. Step 9 replaces them.

## Comparing with the tag

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

Expect the same files to differ as in chapter 1.

## Reading DSPy's docs

[DSPy's docs](https://dspy.ai) go deeper into signatures, predictors, reasoning, programs and agents. Their code is Python, and its names map to Ruby like this:

* `dspy.LM(...)` is `DSPyRb::LM[...]`
* `dspy.configure(lm=...)` is `DSPyRb.configure do |config| config.lm = ... end`
* `dspy.context(lm=...)` is `DSPyRb.context(lm: ...) do ... end`
* `dspy.settings.lm` is `DSPyRb.lm`
* `lm.copy(rollout_id=..., temperature=...)` is `lm.copy(rollout_id: ..., temperature: ...)`
* `lm.kwargs["rollout_id"]` is `lm.kwargs[:rollout_id]`
* `dspy.Signature` is `DSPyRb::Signature`: its docstring is `instructions`, and `dspy.InputField()` and `dspy.OutputField(desc=...)` are `input` and `output ..., desc:`
* `dspy.Predict` is `DSPyRb::Predict`
* `dspy.ChainOfThought` is `DSPyRb::ChainOfThought`
* `rationale_field_type=str` is `reasoning: :written`
* `dspy.Module`, the class your programs subclass, is `DSPyRb::Module`
* `dspy.Prediction` is `DSPyRb::Prediction`
* `dspy.ReAct(signature, tools=[...], max_iters=...)` is `DSPyRb::ReAct[signature, tools: [...], max_iters: ...]`
* a DSPy tool, a Python function with a docstring, is a `DSPyRb::Tool` subclass: its docstring is `desc`, each parameter an `arg`, and its body `call`
* `result.history.messages` is `result.history["messages"]`
* `dspy.utils.DummyLM` is `DSPyRb::DummyLM`

## Next

> [card] [Hooks around model calls](https://ruby-on-dspy.ralak.co/production/hooks.md)
>
> Check each model call before it's sent, and see it once it ends.


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