- what a prediction’s
spendrecords 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.
1. Read the spend in the console
Every prediction carries aspend, 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, asprompt_tokensthe model read andcompletion_tokensit wrote;cost: DSPy’s estimate in US dollars, from the price list it ships.
; doesn’t print its result.
2. The cache in the spend
As Installation notes, DSPy answers a repeated call from its cache. Run the same ticket again: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.4. Total each ticket’s cost
dspy-rb reports each call, and the app decides how to total them. Replaceapp/models/ticket.rb with:
app/models/ticket.rb
- They count only billed calls:
billedleaves out calls markedcache_hit, since DSPy doesn’t count cached responses as billed usage. total_costreturnsnilwhen 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. Replaceapp/views/tickets/_ticket.html.erb with:
app/views/tickets/_ticket.html.erb
6. See it in the browser
Start the server, and create a ticket at 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
ADummyLM’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:
test/models/ticket_test.rb
test/integration/ticket_submission_test.rb with:
test/integration/ticket_submission_test.rb
8. Check your work
If something goes wrong
Comparing with the tag
Thechapter-6 tag holds the app at the end of this chapter. To compare yours with it:
Next
An agent suggests a reply
Let DSPy’s ReAct agent search the help center and suggest a reply when a support agent asks.