- how to see every model call your app makes;
- how to stop a job before it spends too much;
- how to give your request’s state to code on the gem’s threads;
- what a budget needs once calls run at once.
See every model call
on_call: runs a listener after each model call in its block, as in Another reply. This one logs each call:
Output
Logger rescues its own write errors, so this listener never raises.
Stop a job before it spends too much
A gate,before_call:, runs before each call is sent, and refuses it by raising. This job’s limit is a hundredth of a cent, so one call reaches it:
Output
- The gate checks only what calls have already cost, so a job can go over its limit by one call.
- A call DSPy’s cache answered was never billed, so it adds nothing. One with no price,
costnil, counts as the whole limit, since unknown is never free.
Give the gem’s threads your request’s state
Gates, tools and some listeners run on the gem’s own threads, which don’t see your thread’s variables.around: wraps that code, so it can set them there:
Output
account = Current.account taken first, the hook is ->(&run) { Current.set(account:, &run) }, for Current attributes.
A listener for OpenTelemetry records each call as a span that began duration_ms ago and ends now. Take your current span when you make the listener, and give it as each span’s parent, since a call can reach the listener on the gem’s thread, where your current span isn’t set.
Beyond the simple budget
The simple budget is enough for a job that makes its calls one at a time. Calls that run at once. Calls that start together, such asDSPyRb::Evaluate’s, all pass the gate before any has cost anything, and can go over the limit together. So hold an estimate for each call before it’s sent, and swap it for the cost once it ends:
- A gate gets the pending call, whose
idis theidits listener gets. - A
nilcost counts as the whole limit, as in the simple budget. - A call that’s never sent still reaches the listener, with
cost0.0, which releases its estimate. - Gates and listeners then run on several threads at once, so the budget’s figures sit under a lock.
timeout: and num_retries: bound.
Work on a thread pool. A thread your job starts with Thread.new takes the job’s context with it. A pool’s thread keeps the context of the code it first ran for, so wrap the work you hand one in DSPyRb.capture { ... }.
Jobs. In Rails, open each job’s budget in ApplicationJob’s around_perform. Add discard_on OverBudget for the gate’s error: each perform gets a new budget, so a retry would pay for the job’s calls again.
Next
The README
The whole API.