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

# Hooks around model calls

> Check each model call before it's sent, and see it once it ends

After reading this guide, you will know:

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

This guide builds on the tutorial's [What a ticket cost](https://ruby-on-dspy.ralak.co/helpdesk/cost.md), [An agent suggests a reply](https://ruby-on-dspy.ralak.co/helpdesk/agent.md) and [Another reply](https://ruby-on-dspy.ralak.co/helpdesk/another-reply.md). The examples use this model:

```ruby theme={"theme":"one-dark-pro"}
# frozen_string_literal: true

require "ruby-on-dspy"

DSPyRb.configure do |config|
  config.lm = DSPyRb::LM["openai/gpt-4.1-mini"]
end
```

## See every model call

`on_call:` runs a listener after each model call in its block, as in [Another reply](https://ruby-on-dspy.ralak.co/helpdesk/another-reply.md). This one logs each call:

```ruby theme={"theme":"one-dark-pro"}
# frozen_string_literal: true

require "logger"

logger = Logger.new($stdout)
summarize = DSPyRb::Predict["ticket -> summary"]
log_call = ->(call) { logger.info("#{call.model} #{call.outcome}, cost #{call.cost}") }

DSPyRb.context(on_call: log_call) do
  summarize.call(ticket: "Hi, I was charged twice for order 4521. Please refund one of the charges.")
end
```

```text Output theme={"theme":"one-dark-pro"}
I, [2026-12-01T14:09:20.537612 #31220]  INFO -- : openai/gpt-4.1-mini completed, cost 0.0001012
```

A listener that raises stops the work it was made under, and the work raises its error in place of its result. `Logger` [rescues its own write errors](https://github.com/ruby/logger/blob/v1.7.0/lib/logger/log_device.rb#L148-L154), 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:

```ruby theme={"theme":"one-dark-pro"}
# frozen_string_literal: true

class OverBudget < StandardError; end

summarize = DSPyRb::Predict["ticket -> summary"]
ticket = "Hi, I was charged twice for order 4521. Please refund one of the charges."
limit = 0.0001
spent = 0
refuse_over_budget = ->(_pending) { raise OverBudget, "over this job's budget" if spent >= limit }
add_cost = ->(call) { spent += call.cost || limit unless call.cache_hit }

DSPyRb.context(before_call: refuse_over_budget, on_call: add_cost) do
  summarize.call(ticket:)
  puts spent
  summarize.call(ticket:)
rescue OverBudget => e
  puts e.message
end
```

```text Output theme={"theme":"one-dark-pro"}
0.0001012
over this job's budget
```

* 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, `cost` `nil`, 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:

```ruby theme={"theme":"one-dark-pro"}
# frozen_string_literal: true

summarize = DSPyRb::Predict["ticket -> summary"]
print_account = ->(_pending) { p Thread.current[:account] }

Thread.current[:account] = "Acme"

account = Thread.current[:account]

set_account = lambda do |&run|
  Thread.current[:account] = account
  run.call
end

DSPyRb.context(before_call: print_account) do
  summarize.call(ticket: "Where is my order 3310?")
end

DSPyRb.context(before_call: print_account, around: set_account) do
  summarize.call(ticket: "Where is my order 3310?")
end
```

```text Output theme={"theme":"one-dark-pro"}
nil
"Acme"
```

In Rails, with `account = Current.account` taken first, the hook is `->(&run) { Current.set(account:, &run) }`, for [`Current`](https://api.rubyonrails.org/v8.1.4.1/classes/ActiveSupport/CurrentAttributes.html) attributes.

A listener for [OpenTelemetry](https://opentelemetry.io/docs/languages/ruby/instrumentation/) 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 as `DSPyRb::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:

```ruby theme={"theme":"one-dark-pro"}
# frozen_string_literal: true

class OverBudget < StandardError; end

summarize = DSPyRb::Predict["ticket -> summary"]
limit = 0.05
estimate = 0.01
held = {}
spent = 0
lock = Mutex.new

reserve = lambda do |pending|
  lock.synchronize do
    raise OverBudget, "over this job's budget" if spent + held.values.sum + estimate > limit

    held[pending.id] = estimate
  end
end

settle = lambda do |call|
  lock.synchronize do
    held.delete(call.id)
    spent += call.cost || limit unless call.cache_hit
  end
end

DSPyRb.context(before_call: reserve, on_call: settle) do
  summarize.call(ticket: "Hi, I was charged twice for order 4521. Please refund one of the charges.")
end
```

* A gate gets the pending call, whose `id` is the `id` its listener gets.
* A `nil` cost counts as the whole limit, as in the simple budget.
* A call that's never sent still reaches the listener, with `cost` `0.0`, which releases its estimate.
* Gates and listeners then run on several threads at once, so the budget's figures sit under a lock.

**Estimates left waiting.** A few calls never reach their listener, such as those running when DSPy's process is lost. So a budget kept in your database gives each estimate an expiry longer than your slowest call, which the model's `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`](https://guides.rubyonrails.org/v8.1.4.1/active_job_basics.html#callbacks). Add [`discard_on OverBudget`](https://guides.rubyonrails.org/v8.1.4.1/active_job_basics.html#retrying-or-discarding-failed-jobs) for the gate's error: each perform gets a new budget, so a retry would pay for the job's calls again.

## Next

> [card] [The README](https://github.com/samuelralak/ruby-on-dspy)
>
> The whole API.


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