- 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.
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
costcolumn keeps six decimal places, too few to hold one call’s cost.
decimal as a floating-point number.
2. A ledger
Another approach saves each suggestion’s figures on its ownSuggestedReply. 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:db/migrate/ whose name ends in _create_ledger_entries.rb, with:
db/migrate/20261201090938_create_ledger_entries.rb
cost_nanosholds DSPy’s estimate of the cost, in nano-dollars. An empty one means the cost is unknown, never 0.currencynames 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 onsuggested_reply_idgives a suggestion at most one, and the triage entries’ emptysuggested_reply_iddoesn’t count against it. - An entry is never updated, so it has
created_atand noupdated_at.
4. Write an entry
An entry’s figures come from a piece of work’sspend, as chapter 6’s did. Replace app/models/ledger_entry.rb with:
app/models/ledger_entry.rb
record!writes one entry from aspend. As in chapter 6, only the calls that reached the model are billed; the rest came from DSPy’s cache.total_tokensis chapter 6’s, moved here.total_cost_nanosis chapter 6’stotal_costin whole nano-dollars, so a call with no price still leaves itnil.readonly?makes a saved entry read-only:save,updateanddestroyraiseActiveRecord::ReadOnlyRecord.delete,update_allanddelete_allskip 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. Replaceapp/models/ticket.rb with:
app/models/ticket.rb
ledger_entries.record!runsrecord!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.
processno 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_totalasks the database for a figure’s total, unless an entry doesn’t know it. SQL’sSUMskips empty values, so a total over an unknown cost would look known, and too low.suggest_replystill returns theSuggestedReply, its transaction block’s last value.
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
app/views/ledger_entries/_ledger_entry.html.erb:
app/views/ledger_entries/_ledger_entry.html.erb
app/views/tickets/show.html.erb with:
app/views/tickets/show.html.erb
_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: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:
Ticket.last, the repeated “Wrong size” ticket:
9. Test the ledger
The tests need entries to start from. Replace the generatedtest/fixtures/ledger_entries.yml with:
test/fixtures/ledger_entries.yml
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
test/models/ticket_test.rb with:
test/models/ticket_test.rb
test/helpers/tickets_helper_test.rb with:
test/helpers/tickets_helper_test.rb
test/integration/ticket_submission_test.rb with:
test/integration/ticket_submission_test.rb
10. Check your work
If something goes wrong
Comparing with the tag
Thechapter-9 tag holds the app at the end of this chapter. To compare yours with it:
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(...)isDSPyRb::LM[...]dspy.configure(lm=...)isDSPyRb.configure do |config| config.lm = ... enddspy.context(lm=...)isDSPyRb.context(lm: ...) do ... enddspy.settings.lmisDSPyRb.lmlm.copy(rollout_id=..., temperature=...)islm.copy(rollout_id: ..., temperature: ...)lm.kwargs["rollout_id"]islm.kwargs[:rollout_id]dspy.SignatureisDSPyRb::Signature: its docstring isinstructions, anddspy.InputField()anddspy.OutputField(desc=...)areinputandoutput ..., desc:dspy.PredictisDSPyRb::Predictdspy.ChainOfThoughtisDSPyRb::ChainOfThoughtrationale_field_type=strisreasoning: :writtendspy.Module, the class your programs subclass, isDSPyRb::Moduledspy.PredictionisDSPyRb::Predictiondspy.ReAct(signature, tools=[...], max_iters=...)isDSPyRb::ReAct[signature, tools: [...], max_iters: ...]- a DSPy tool, a Python function with a docstring, is a
DSPyRb::Toolsubclass: its docstring isdesc, each parameter anarg, and its bodycall result.history.messagesisresult.history["messages"]dspy.utils.DummyLMisDSPyRb::DummyLM
Next
Hooks around model calls
Check each model call before it’s sent, and see it once it ends.