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

# A program

> Run a ticket's whole job as one DSPy program, with a single call

After reading this guide, you will know:

* what DSPy means by a module and a program;
* how to write a program as a `DSPyRb::Module`;
* how to run a ticket's whole job with one call;
* how to test a program on its own.

In chapters 3 and 4, the console tried each predictor on its own, never the whole job: the only way to run both is to save a ticket. In this chapter, the two become one program, which you can run on its own. It returns every output in one prediction, and `Ticket` makes a single call to it.

## 1. A program that runs both predictors

A DSPy [module](https://github.com/stanfordnlp/dspy/blob/3.5.0/docs/docs/learn/programming/modules.md) is a building block for programs that use language models, and modules can be composed into bigger modules, called programs.

Triage's `ChainOfThought` and extraction's `Predict` are DSPy's built-in modules, so the two can be composed into one program.

In Ruby, a program is a `DSPyRb::Module`, DSPy's `dspy.Module`: it holds its predictors in instance variables and calls them in `forward`. Create `app/programs/ticket_desk.rb`:

```ruby app/programs/ticket_desk.rb theme={"theme":"one-dark-pro"}
class TicketDesk < DSPyRb::Module
  def initialize
    super

    @triage = DSPyRb::ChainOfThought[TriageTicket, reasoning: :written]
    @details = DSPyRb::Predict[ExtractDetails]
  end

  def forward(subject:, body:)
    triage = @triage.call(subject:, body:)
    details = @details.call(subject:, body:)

    DSPyRb::Prediction[
      reasoning: triage.reasoning,
      category: triage.category,
      urgent: triage.urgent,
      order_numbers: details.order_numbers,
      products: details.products
    ]
  end
end
```

Its predictors are chapter 4's, unchanged, so triage still writes out its reasoning.

In dspy-rb, `forward` must return a prediction, so it builds one with `DSPyRb::Prediction[...]`, naming each output it takes from the two predictors. You run a program with `call`, as you do a predictor: `call` runs `forward` and returns its prediction.

`app/programs` is a new folder, so restart any running server or console, as in chapter 2.

## 2. Try it in the console

Run the program on its own, on a new ticket:

```irb theme={"theme":"one-dark-pro"}
$ bin/rails console
helpdesk(dev)> subject = "Wrong size"
=> "Wrong size"
helpdesk(dev)> body = "Order 5521 came with a medium shirt, but I ordered a large."
=> "Order 5521 came with a medium shirt, but I ordered a large."
helpdesk(dev)> TicketDesk.new.call(subject:, body:).to_h
=> {reasoning: "The customer received the wrong size shirt compared to what they ordered. This issue relates to the contents of the shipment and may require a return or replacement process.", category: "returns", urgent: true, order_numbers: ["5521"], products: ["shirt"]}
```

One call to the program gives all five outputs, though it still makes two model calls, one for each predictor.

## 3. Run the program for each new ticket

Let the program do each new ticket's work. Replace `app/models/ticket.rb` with:

```ruby app/models/ticket.rb theme={"theme":"one-dark-pro"}
class Ticket < ApplicationRecord
  # After the commit, so slow model calls never hold a database transaction open.
  after_create_commit :process

  private
    def process
      result = TicketDesk.new.call(subject:, body:)

      update!(
        reasoning: result.reasoning,
        category: result.category,
        urgent: result.urgent,
        order_numbers: result.order_numbers,
        products: result.products
      )
    end
end
```

The steps now live in the program, so `process` calls it and saves each output in one `update!`.

Nothing changes on the ticket's page, and chapter 4's tests still pass.

## 4. Test the program on its own

The program exists so that a ticket's whole job runs without saving a ticket. Its own test checks that.

Three test files now need the same scripted model, so it becomes a helper they all share. In `test/test_helper.rb`, add `scripted_model` under Rails' comment for helpers, so the file reads:

```ruby test/test_helper.rb theme={"theme":"one-dark-pro"}
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

# No real model in tests: each model call runs on a DSPyRb::DummyLM given by DSPyRb.context.
DSPyRb.configure do |config|
  config.lm = nil
end

module ActiveSupport
  class TestCase
    # Run tests in parallel with specified workers
    parallelize(workers: :number_of_processors)

    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
    fixtures :all

    # Add more helper methods to be used by all tests here...
    def scripted_model
      DSPyRb::DummyLM[YAML.load_file(file_fixture("ticket_answers.yml"))]
    end
  end
end
```

Create `test/programs/ticket_desk_test.rb`, which runs the program with no ticket at all:

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

class TicketDeskTest < ActiveSupport::TestCase
  test "the desk runs a ticket's whole job without saving a ticket" do
    result = assert_no_difference("Ticket.count") do
      DSPyRb.context(lm: scripted_model) do
        TicketDesk.new.call(
          subject: "Refund for order #1234",
          body: "I was charged twice for my coffee grinder."
        )
      end
    end

    assert_match "needs a reply today", result.reasoning
    assert_equal "billing", result.category
    assert result.urgent
    assert_equal [ "1234" ], result.order_numbers
    assert_equal [ "coffee grinder" ], result.products
  end
end
```

The ticket tests now use the helper too. 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

  private
    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
```

And 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

  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
```

## 5. Check your work

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

Both should pass, with no offenses and 7 tests.

## If something goes wrong

> [!WARNING]
>
> If you see a `NameError` naming `TicketDesk`, the server or console started before `app/programs` existed. Restart it.

## Comparing with the tag

The [`chapter-5` tag](https://github.com/samuelralak/dspy-tutorial/tree/chapter-5) 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-5 --stat
```

Expect the same files to differ as in chapter 1.

## Next

> [card] [What a ticket cost](https://dspy-rb.ralak.co/helpdesk/cost.md)
>
> Total each ticket's model calls, tokens and cost, and show them on its page.


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