> ## Documentation Index
> Fetch the complete documentation index at: https://dspy-rb.ralak.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Another reply

> Get a fresh suggestion past DSPy's cache, with a rollout ID on a copy of the model

After reading this guide, you will know:

* why this chapter keeps DSPy's cache on;
* what a rollout ID is, and how it gets a fresh reply past DSPy's cache;
* how to call a copy of the model, with other options, for one block of code;
* why a double click would be billed twice, and how Turbo prevents it.

At the end of chapter 7, asking again for a reply to the same ticket brought back the first one, from DSPy's cache. In this chapter, each new suggestion asks the model afresh.

## 1. Past the cache

The first fix to reach for is Installation's [`cache: false`](https://dspy-rb.ralak.co/installation#make-a-first-call). On the app's model, it turns off the cache for every call, triage's too.

DSPy's [way to get a different answer](https://github.com/stanfordnlp/dspy/blob/3.5.0/docs/docs/learn/programming/language_models.md) and keep the cache on is a rollout ID, its [`rollout_id`](https://github.com/stanfordnlp/dspy/blob/3.5.0/dspy/clients/lm.py). A rollout ID is part of each call's [cache](https://github.com/stanfordnlp/dspy/blob/3.5.0/docs/docs/tutorials/cache/index.md) key: a new one reaches the model, and the same one again is answered from the cache. DSPy's own `BestOfN` and `Refine`, which run a module several times and keep the best answer, use it this way.

Temperature sets how much a model's replies vary. A rollout ID changes the reply only when temperature is above 0, and the app's model leaves temperature to the provider, so set `temperature: 1.0` with it.

## 2. A copy of the model for one block

Every call uses the app's one model, so a suggestion needs a copy of it with a rollout ID and a temperature, used only for its own calls.

`DSPyRb.lm` is the model your calls use: the app's model, or in a test, the test's `DummyLM`. Its `kwargs` are its options, and `nil` means the provider's default:

```irb theme={"theme":"one-dark-pro"}
$ bin/rails console
helpdesk(dev)> DSPyRb.lm.kwargs
=> {temperature: nil, max_tokens: nil}
```

`copy` makes a new model with some options changed. The original keeps its own:

```irb theme={"theme":"one-dark-pro"}
helpdesk(dev)> first_try = DSPyRb.lm.copy(rollout_id: 1, temperature: 1.0);
helpdesk(dev)> first_try.kwargs
=> {temperature: 1.0, max_tokens: nil, rollout_id: 1}
helpdesk(dev)> DSPyRb.lm.kwargs
=> {temperature: nil, max_tokens: nil}
```

`DSPyRb.context(lm: ...)`, which your tests have used since chapter 2, makes the calls in its block use another model. After the block, they use the app's model again:

```irb theme={"theme":"one-dark-pro"}
helpdesk(dev)> DSPyRb.context(lm: first_try) { DSPyRb.lm.kwargs }
=> {temperature: 1.0, max_tokens: nil, rollout_id: 1}
helpdesk(dev)> DSPyRb.lm.kwargs
=> {temperature: nil, max_tokens: nil}
```

None of this calls the model. In DSPy, these are [`dspy.settings.lm`](https://github.com/stanfordnlp/dspy/blob/3.5.0/dspy/dsp/utils/settings.py), [`lm.copy`](https://github.com/stanfordnlp/dspy/blob/3.5.0/dspy/clients/base_lm.py) and [`dspy.context`](https://github.com/stanfordnlp/dspy/blob/3.5.0/dspy/dsp/utils/settings.py).

## 3. Try a rollout ID

In the same console, run chapter 7's program on its ticket, twice with the same rollout ID, then with a new one:

```irb theme={"theme":"one-dark-pro"}
helpdesk(dev)> subject = "Charged twice"
=> "Charged twice"
helpdesk(dev)> body = "I was charged twice for order 4417."
=> "I was charged twice for order 4417."
helpdesk(dev)> first = DSPyRb.context(lm: first_try) { ReplyWriter.new.call(subject:, body:) };
helpdesk(dev)> first.reply
=> "We apologize for the inconvenience of being charged twice for your order #4417. According to our policy, the extra charge will be refunded to your card within 5 business days. If you do not see the refund by then, please contact us again for further assistance."
helpdesk(dev)> again = DSPyRb.context(lm: first_try) { ReplyWriter.new.call(subject:, body:) };
helpdesk(dev)> again.reply == first.reply
=> true
helpdesk(dev)> again.spend.calls.map(&:cache_hit)
=> [true, true]
helpdesk(dev)> second_try = DSPyRb.lm.copy(rollout_id: 2, temperature: 1.0);
helpdesk(dev)> another = DSPyRb.context(lm: second_try) { ReplyWriter.new.call(subject:, body:) };
helpdesk(dev)> another.reply
=> "We understand that you were charged twice for order 4417. If you were charged twice for one order, we refund the extra charge to your card within 5 business days. Please check your bank statement after this period, and let us know if the refund has not appeared.\n\nThank you for your patience."
helpdesk(dev)> another.spend.calls.map(&:cache_hit)
=> [false, false]
```

So each suggestion needs a new rollout ID.

## 4. A rollout ID for each suggestion

Replace `app/models/ticket.rb` with:

```ruby app/models/ticket.rb theme={"theme":"one-dark-pro"}
class Ticket < ApplicationRecord
  has_many :suggested_replies, dependent: :destroy

  # After the commit, so slow model calls never hold a database transaction open.
  after_create_commit :process

  def suggest_reply
    result = DSPyRb.context(lm: model_for_next_suggestion) do
      ReplyWriter.new.call(subject:, body:)
    end

    suggested_replies.create!(reply: result.reply, article_ids: result.article_ids)
  end

  private
    def process
      result = TicketDesk.new.call(subject:, body:)
      billed = result.spend.calls.reject(&:cache_hit)

      update!(
        reasoning: result.reasoning,
        category: result.category,
        urgent: result.urgent,
        order_numbers: result.order_numbers,
        products: result.products,
        model_calls: billed.size,
        tokens: total_tokens(billed),
        cost: total_cost(billed)
      )
    end

    def total_tokens(calls)
      calls.sum do |call|
        call.usage.prompt_tokens + call.usage.completion_tokens
      end
    end

    def total_cost(calls)
      calls.sum(&:cost) if calls.all?(&:cost)
    end

    def model_for_next_suggestion
      DSPyRb.lm.copy(rollout_id: SecureRandom.random_number(2**31), temperature: 1.0)
    end
end
```

* Each suggestion asks with a random rollout ID, one of about two billion, so each click gets a fresh reply.
* `model_for_next_suggestion` copies `DSPyRb.lm`, not `config.lm`, so in a test it copies the test's `DummyLM`, as step 2 said, and the copy keeps its scripted answers.

## 5. The button asks for another

Once a ticket has a suggestion, its button should offer another. Replace `app/helpers/tickets_helper.rb` with:

```ruby app/helpers/tickets_helper.rb theme={"theme":"one-dark-pro"}
module TicketsHelper
  def suggest_reply_label(ticket)
    ticket.suggested_replies.any? ? "Suggest another reply" : "Suggest a reply"
  end
end
```

A double click would ask for two fresh replies, both billed. Turbo disables a form's button while it submits, so one support agent can't send two by accident; chapter 7's button already did that.

The view adds `data-turbo-submits-with`, which shows "Suggesting a reply..." meanwhile. Replace `app/views/tickets/show.html.erb` with:

```erb app/views/tickets/show.html.erb theme={"theme":"one-dark-pro"}
<p style="color: green"><%= notice %></p>

<%= render @ticket %>

<%= button_to suggest_reply_label(@ticket), ticket_suggested_replies_path(@ticket),
      data: { turbo_submits_with: "Suggesting a reply..." } %>

<%= render @ticket.suggested_replies.order(created_at: :desc) %>

<div>
  <%= link_to "Edit this ticket", edit_ticket_path(@ticket) %> |
  <%= link_to "Back to tickets", tickets_path %>

  <%= button_to "Destroy this ticket", @ticket, method: :delete %>
</div>
```

## 6. See it in the browser

Start the server, and open the "Missing item" ticket you asked for a reply in chapter 7. Its button now reads "Suggest another reply". Click it, and a fresh reply appears above the earlier ones, such as:

> We are sorry to hear that your order 6012 arrived without the charging cable. Please confirm the missing item, and we will send it to you within 2 business days.
>
> **Based on:** Missing items

## 7. Test the fresh reply and the label

A `DummyLM` never caches, so a test can't see a fresh reply. It checks the options each suggestion asks with instead.

`on_call:` runs a listener after each model call in its block.

A context inside another keeps the outer one's listener, so the listener also runs for calls made with the inner one's model.

Try both on the test's scripted answers, for nothing:

```irb theme={"theme":"one-dark-pro"}
$ bin/rails console
helpdesk(dev)> model = DSPyRb::DummyLM[YAML.load_file("test/fixtures/files/reply_answers.yml")];
helpdesk(dev)> first_try = model.copy(rollout_id: 1, temperature: 1.0);
helpdesk(dev)> listener = ->(_call) { puts DSPyRb.lm.kwargs };
helpdesk(dev)> DSPyRb.context(on_call: listener) do
helpdesk(dev)*   DSPyRb.context(lm: first_try) do
helpdesk(dev)*     ReplyWriter.new.call(subject: "Charged twice", body: "I was charged twice for order 4417.")
helpdesk(dev)*   end
helpdesk(dev)* end;
{temperature: 1.0, max_tokens: 1000, rollout_id: 1}
{temperature: 1.0, max_tokens: 1000, rollout_id: 1}
```

The agent made two calls, the outer listener ran after each, and both asked with the copy's options. `max_tokens: 1000` is a `DummyLM`'s own default.

The test does the same: its context gives the `DummyLM` and the listener, and `suggest_reply`'s gives the copy. It checks that two suggestions ask with temperature 1.0 and different rollout IDs. Replace `test/models/ticket_test.rb` with:

```ruby test/models/ticket_test.rb theme={"theme":"one-dark-pro"}
require "test_helper"

class TicketTest < ActiveSupport::TestCase
  test "a new ticket arrives with a category and an urgent flag" do
    ticket = create_ticket

    assert_equal "billing", ticket.category
    assert ticket.urgent?
  end

  test "a new ticket arrives with the order numbers and products it mentions" do
    ticket = create_ticket

    assert_equal [ "1234" ], ticket.order_numbers
    assert_equal [ "coffee grinder" ], ticket.products
  end

  test "a new ticket arrives with the reasoning behind its urgency" do
    ticket = create_ticket

    assert_match "needs a reply today", ticket.reasoning
  end

  test "a new ticket records how many model calls it took" do
    ticket = create_ticket

    assert_equal 2, ticket.model_calls
  end

  test "asking for a reply saves the suggestion with its articles" do
    suggested_reply = DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      tickets(:double_charge).suggest_reply
    end

    assert_equal [ articles(:double_charge).id ], suggested_reply.reload.article_ids
  end

  test "each suggested reply for a ticket is asked for afresh" do
    ticket = tickets(:double_charge)

    first = model_options_during_next_suggestion(ticket)
    second = model_options_during_next_suggestion(ticket)

    assert_equal 1.0, first[:temperature]
    assert_equal 1.0, second[:temperature]
    assert_not_nil first[:rollout_id]
    assert_not_nil second[:rollout_id]
    assert_not_equal first[:rollout_id], second[:rollout_id]
  end

  private
    def model_options_during_next_suggestion(ticket)
      options = []
      listener = ->(_call) { options << DSPyRb.lm.kwargs.slice(:rollout_id, :temperature) }

      DSPyRb.context(lm: scripted_model("reply_answers.yml"), on_call: listener) do
        ticket.suggest_reply
      end

      options.uniq.sole
    end

    def create_ticket
      ticket = DSPyRb.context(lm: scripted_model) do
        Ticket.create!(
          subject: "Refund for order #1234",
          body: "I was charged twice for my coffee grinder."
        )
      end

      ticket.reload
    end
end
```

In `model_options_during_next_suggestion`, `uniq.sole` checks that every call of a suggestion asked with the same options.

Replace `test/integration/ticket_submission_test.rb` with:

```ruby test/integration/ticket_submission_test.rb theme={"theme":"one-dark-pro"}
require "test_helper"

class TicketSubmissionTest < ActionDispatch::IntegrationTest
  test "a support agent logs a ticket and sees its category and urgency" do
    log_ticket

    assert_select "div", /Category:\s+billing/
    assert_select "mark", "Urgent"
  end

  test "a support agent sees the order numbers and products a ticket mentions" do
    log_ticket

    assert_select "div", /Order numbers:\s+1234/
    assert_select "div", /Products:\s+coffee grinder/
  end

  test "a support agent sees why a ticket was marked urgent" do
    log_ticket

    assert_select "div", /Why:\s+A double charge takes the customer's money/
  end

  test "a support agent sees a ticket's model calls, tokens and cost" do
    log_ticket

    assert_select "div", /Model calls:\s+2/
    assert_select "div", /Tokens:\s+0/
    assert_select "div", /Cost:\s+unknown/
  end

  test "a support agent asks for a suggested reply and sees it with its articles" do
    ticket = tickets(:double_charge)

    get ticket_path(ticket)
    assert_select "form[action=?] button", ticket_suggested_replies_path(ticket), text: "Suggest a reply"

    DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      post ticket_suggested_replies_path(ticket)
    end

    follow_redirect!

    assert_select "p", /refund the extra charge within 5 business days/
    assert_select "p", /Based on:\s+Refunds for double charges/
  end

  test "a support agent asks for another reply and sees both" do
    ticket = tickets(:late_parcel)

    get ticket_path(ticket)
    assert_select "form[action=?] button", ticket_suggested_replies_path(ticket), text: "Suggest another reply"

    DSPyRb.context(lm: scripted_model("reply_answers.yml")) do
      post ticket_suggested_replies_path(ticket)
    end

    follow_redirect!

    assert_select "h2", text: /Suggested reply/, count: 2
  end

  test "a support agent deletes a ticket with its suggested replies" do
    assert_difference("SuggestedReply.count", -1) do
      delete ticket_path(tickets(:late_parcel))
    end

    follow_redirect!

    assert_select "p", "Ticket was successfully destroyed."
  end

  private
    def log_ticket
      form = { subject: "Refund for order #1234", body: "I was charged twice for my coffee grinder." }

      DSPyRb.context(lm: scripted_model) do
        post tickets_path, params: { ticket: form }
      end

      follow_redirect!
    end
end
```

Its "another reply" test starts from the ticket that already has a suggestion.

The button's label has a test of its own. Create `test/helpers/tickets_helper_test.rb`:

```ruby test/helpers/tickets_helper_test.rb theme={"theme":"one-dark-pro"}
require "test_helper"

class TicketsHelperTest < ActionView::TestCase
  test "the button asks for a reply on a ticket with none" do
    assert_equal "Suggest a reply", suggest_reply_label(tickets(:double_charge))
  end

  test "the button asks for another reply once a ticket has one" do
    assert_equal "Suggest another reply", suggest_reply_label(tickets(:late_parcel))
  end
end
```

## 8. Check your work

```bash theme={"theme":"one-dark-pro"}
bin/rubocop
bin/rails test
```

Both should pass, with no offenses and 22 tests.

## If something goes wrong

> [!WARNING]
>
> If "Suggest another reply" gives the same reply again, check that `suggest_reply` runs the program inside `DSPyRb.context(lm: model_for_next_suggestion)`.

## Comparing with the tag

The [`chapter-8` tag](https://github.com/samuelralak/dspy-tutorial/tree/chapter-8) holds the app at the end of this chapter. To compare yours with it:

```bash theme={"theme":"one-dark-pro"}
git fetch tutorial --tags --force
git add --all
git diff --cached chapter-8 --stat
```

Expect the same files to differ as in chapter 1.

## Reading DSPy's docs

[DSPy's docs](https://dspy.ai) 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

The gem's [README](https://github.com/samuelralak/ruby-on-dspy) covers the rest of its API.


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