Skip to main content
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:
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: 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:
The ledger is a table of its own. Generate its model:
Replace the migration it wrote, the file in db/migrate/ whose name ends in _create_ledger_entries.rb, with:
db/migrate/20261201090938_create_ledger_entries.rb
  • 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:

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:
app/models/ledger_entry.rb
  • 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:
app/models/ticket.rb
  • 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:
app/helpers/tickets_helper.rb
Create app/views/ledger_entries/_ledger_entry.html.erb:
app/views/ledger_entries/_ledger_entry.html.erb
Replace app/views/tickets/show.html.erb with:
app/views/tickets/show.html.erb
“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:
app/views/tickets/_ticket.html.erb

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:
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: 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:
Deleting a ticket leaves its entries, so what it spent stays counted. Try it on Ticket.last, the repeated “Wrong size” ticket:

9. Test the ledger

The tests need entries to start from. Replace the generated test/fixtures/ledger_entries.yml with:
test/fixtures/ledger_entries.yml
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:
test/models/ledger_entry_test.rb
Replace test/models/ticket_test.rb with:
test/models/ticket_test.rb
Replace test/helpers/tickets_helper_test.rb with:
test/helpers/tickets_helper_test.rb
Replace test/integration/ticket_submission_test.rb with:
test/integration/ticket_submission_test.rb
“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

Both should pass, with no offenses and 35 tests.

If something goes wrong

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 holds the app at the end of this chapter. To compare yours with it:
Expect the same files to differ as in chapter 1.

Reading DSPy’s docs

DSPy’s docs 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

Hooks around model calls

Check each model call before it’s sent, and see it once it ends.