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

# What a ticket cost

> Total each ticket's model calls, tokens and cost, and show them on its page

After reading this guide, you will know:

* what a prediction's `spend` records about each model call;
* how DSPy's cache shows in that record;
* how to total a ticket's model calls, tokens and cost, and show them on its page.

Since chapter 3, each new ticket makes two model calls, and the provider bills each one. A support team wants to see what each ticket cost, in tokens and dollars.

In this chapter, the app adds up each ticket's model calls, tokens and cost, and the ticket's page shows them.

## 1. Read the spend in the console

Every prediction carries a `spend`, a record of the model calls behind it. A program's covers every call made inside it, so chapter 5's single call holds what a ticket's whole job cost. Each call in `spend.calls` has:

* `usage`: its tokens, the pieces of text a provider bills by, as `prompt_tokens` the model read and `completion_tokens` it wrote;
* `cost`: DSPy's estimate in US dollars, from the price list it ships.

Run the program on a new ticket, and read both. A line ending in `;` doesn't print its result.

```irb theme={"theme":"one-dark-pro"}
$ bin/rails console
helpdesk(dev)> subject = "Damaged on arrival"
=> "Damaged on arrival"
helpdesk(dev)> body = "The mug in order 8817 arrived cracked."
=> "The mug in order 8817 arrived cracked."
helpdesk(dev)> result = TicketDesk.new.call(subject:, body:);
helpdesk(dev)> result.spend.calls.map(&:cost)
=> [0.00021279999999999997, 0.0001432]
helpdesk(dev)> result.spend.calls.first.usage.to_h.slice(:prompt_tokens, :completion_tokens)
=> {prompt_tokens: 296, completion_tokens: 59}
```

The first call is triage's, and the second the details'.

## 2. The cache in the spend

As [Installation](https://ruby-on-dspy.ralak.co/installation.md#make-a-first-call) notes, DSPy answers a repeated call from its [cache](https://github.com/stanfordnlp/dspy/blob/3.5.0/docs/docs/tutorials/cache/index.md). Run the same ticket again:

```irb theme={"theme":"one-dark-pro"}
helpdesk(dev)> result = TicketDesk.new.call(subject:, body:);
helpdesk(dev)> result.spend.calls.map(&:cache_hit)
=> [true, true]
```

A call answered from the cache is marked `cache_hit`. It has no `usage`, and keeps the cost of the call it repeats, though nothing was billed.

## 3. Columns for the cost

Give tickets a column for each figure the page will show: model calls, tokens and cost.

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

## 4. Total each ticket's cost

Ruby on DSPy reports each call, and the app decides how to total them. 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
      result = TicketDesk.new.call(subject:, body:)
      billed = result.spend.calls.reject(&:cache_hit)

      update!(
        reasoning: result.reasoning,
        category: result.category,
        urgent: result.urgent,
        order_numbers: result.order_numbers,
        products: result.products,
        model_calls: billed.size,
        tokens: total_tokens(billed),
        cost: total_cost(billed)
      )
    end

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

    def total_cost(calls)
      calls.sum(&:cost) if calls.all?(&:cost)
    end
end
```

The three figures follow two rules:

* They count only billed calls: `billed` leaves out calls marked `cache_hit`, since DSPy [doesn't count cached responses](https://github.com/stanfordnlp/dspy/blob/3.5.0/docs/docs/learn/programming/modules.md) as billed usage.
* `total_cost` returns `nil` when DSPy has no price for a billed call, so an unknown cost never shows as free.

## 5. Show the cost

Show the three figures at the end of the ticket's page, with the cost to six decimal places, since a call costs a fraction of a cent. Tickets created before this chapter have none, so show them only when they're there.

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

  <% if ticket.model_calls.present? %>
    <div>
      <strong>Model calls:</strong>
      <%= ticket.model_calls %>
    </div>

    <div>
      <strong>Tokens:</strong>
      <%= ticket.tokens %>
    </div>

    <div>
      <strong>Cost:</strong>
      <%= ticket.cost ? number_to_currency(ticket.cost, precision: 6) : "unknown" %>
    </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 "Missing item" and the body "My order 6012 arrived without the charging cable."

The ticket's page ends with what it cost, such as "Model calls: 2", "Tokens: 628" and "Cost: \$0.000381".

Create the same ticket again, and it shows "Model calls: 0", "Tokens: 0" and "Cost: \$0.000000", since the cache answered both calls, as in step 2.

## 7. The cost in the tests

A `DummyLM`'s calls are in `spend` too, each with 0 tokens and no price, and none is a cache hit. So in the tests, a new ticket shows 2 model calls, 0 tokens and an unknown cost.

Both ticket test files gain a test for the new figures. 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 records how many model calls it took" do
    ticket = create_ticket

    assert_equal 2, ticket.model_calls
  end

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

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

  test "a support agent sees a ticket's model calls, tokens and cost" do
    log_ticket

    assert_select "div", /Model calls:\s+2/
    assert_select "div", /Tokens:\s+0/
    assert_select "div", /Cost:\s+unknown/
  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
```

## 8. Check your work

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

Both should pass, with no offenses and 9 tests.

## If something goes wrong

> [!WARNING]
>
> If the cost shows "unknown" with a real model, DSPy's price list has none for it. The README's [Usage and cost](https://github.com/samuelralak/ruby-on-dspy#usage-and-cost) shows how to give DSPy another list.

## Comparing with the tag

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

Expect the same files to differ as in chapter 1.

## Next

> [card] [An agent suggests a reply](https://ruby-on-dspy.ralak.co/helpdesk/agent.md)
>
> Let DSPy's ReAct agent search the help center and suggest a reply when a support agent asks.


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