Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Run eval comparisons against a dataset (#36223)

Roman Rizzic7ba71bfb3d4
diff --git a/plugins/discourse-ai/README.md b/plugins/discourse-ai/README.md
index 6af3c42d029..8a641dadc56 100644
--- a/plugins/discourse-ai/README.md
+++ b/plugins/discourse-ai/README.md
@@ -26,6 +26,7 @@ Usage: evals/run [options]
-j, --judge NAME LLM config used as a judge (defaults to gpt-4o when available)
--persona-keys KEYS Comma-separated list of persona keys (or repeat the flag) to run sequentially
--compare MODE Run comparisons (MODE: personas or llms)
+ --dataset PATH Path to a CSV dataset file (requires --feature)
```
To run evals you will need to configure API keys in your environment:
@@ -55,6 +56,17 @@ When running persona comparisons (`--compare personas`) the CLI automatically pr
`default` persona so you can benchmark your YAML prompts against the stock behavior. Non-comparison
runs still execute only the personas you list.
+#### Dataset-driven evals
+
+Supply `--dataset path/to/file.csv` along with `--feature module:feature_name` to generate eval cases
+from a CSV instead of YAML files. Each row must include `content` and `expected_output` columns; rows
+are converted into individual eval ids (prefixed with the dataset filename) that reuse the selected
+feature’s runner. Example:
+
+```
+./run --dataset evals/datasets/spam.csv --feature spam:inspect_posts --models gpt-4o-mini
+```
+
#### Comparison matrix
Use the `--compare` flag to ask the CLI to judge multiple runs together:
diff --git a/plugins/discourse-ai/evals/lib/cli.rb b/plugins/discourse-ai/evals/lib/cli.rb
index c8e35db5afc..8391d574637 100644
--- a/plugins/discourse-ai/evals/lib/cli.rb
+++ b/plugins/discourse-ai/evals/lib/cli.rb
@@ -16,7 +16,8 @@ class DiscourseAi::Evals::Cli
:list_personas,
:feature_key,
:judge_name,
- :comparison_mode
+ :comparison_mode,
+ :dataset_path
def self.parse_options!(features_registry)
cli = new
@@ -63,6 +64,10 @@ class DiscourseAi::Evals::Cli
opts.on("--compare MODE", "Comparison mode (personas or llms)") do |mode|
cli.comparison_mode = mode
end
+
+ opts.on("--dataset PATH", "Path to a CSV dataset file (requires --feature)") do |path|
+ cli.dataset_path = path
+ end
end
show_help = ARGV.empty?
@@ -98,7 +103,10 @@ class DiscourseAi::Evals::Cli
end
end
- cli.judge_name ||= DEFAULT_JUDGE
+ if cli.dataset_path.present? && cli.feature_key.blank?
+ STDERR.puts("--dataset requires a --feature flag identifying the eval feature to run.")
+ exit 1
+ end
cli
end
@@ -134,4 +142,47 @@ class DiscourseAi::Evals::Cli
evals
end
+
+ def validate_comparison_requirements!(llms:, persona_variants:)
+ case comparison_mode
+ when :llms
+ if persona_variants.length != 1
+ STDERR.puts("LLM comparison runs against exactly one persona.")
+ exit 1
+ end
+ when :personas
+ if llms.length != 1
+ STDERR.puts("Persona comparison requires exactly one LLM.")
+ exit 1
+ end
+
+ if persona_variants.length < 2
+ STDERR.puts("Persona comparison needs at least two personas.")
+ exit 1
+ end
+ else
+ if persona_variants.length > 1
+ STDERR.puts(
+ "Non-comparison runs accept only one persona. Remove extra --persona-keys or use --compare personas.",
+ )
+ exit 1
+ end
+ end
+ end
+
+ def validate_judge_presence!(requires_judge:, judge_llm:, default_judge_error:)
+ return if !requires_judge || judge_llm
+
+ message = "Error: Selected evaluations require a judge."
+ if default_judge_error
+ message += " Configure '#{judge_name}' or pass --judge with an LLM config name."
+ message += "\n\n"
+ message += default_judge_error
+ else
+ message += " Pass --judge with an LLM config name."
+ end
+
+ puts message
+ exit 1
+ end
end
diff --git a/plugins/discourse-ai/evals/lib/comparison_runner.rb b/plugins/discourse-ai/evals/lib/comparison_runner.rb
deleted file mode 100644
index 760d617a69a..00000000000
--- a/plugins/discourse-ai/evals/lib/comparison_runner.rb
+++ /dev/null
@@ -1,175 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseAi
- module Evals
- class ComparisonRunner
- class ComparisonError < StandardError
- end
-
- SUPPORTED_MODES = {
- "personas" => :personas,
- "persona" => :personas,
- "llms" => :llms,
- "models" => :llms,
- }.freeze
-
- def initialize(mode:, judge_llm:, output: $stdout)
- @mode = normalize_mode(mode)
- @judge_llm = judge_llm
- @output = output
- end
-
- def run(eval_cases:, persona_variants:, llms:)
- case mode
- when :personas
- run_persona_comparison(eval_cases, persona_variants, llms)
- when :llms
- run_llm_comparison(eval_cases, persona_variants, llms)
- else
- raise ComparisonError, "Unsupported comparison mode '#{mode}'"
- end
- end
-
- private
-
- attr_reader :mode, :judge_llm, :output
-
- def run_persona_comparison(eval_cases, persona_variants, llms)
- raise ComparisonError, "Persona comparison requires exactly one LLM" if llms.length != 1
- if persona_variants.length < 2
- raise ComparisonError, "Persona comparison needs at least two personas"
- end
-
- llm = llms.first
- workbenches = persona_variants.map { |variant| [variant, build_workbench(variant)] }
-
- eval_cases.each do |eval_case|
- candidates = []
-
- workbenches.each do |variant, workbench|
- payload = nil
- workbench.run(eval_case: eval_case, llms: [llm]) { |result| payload = result }
- unless payload
- output.puts "Skipping persona '#{variant[:key]}' for #{eval_case.id}: missing output."
- next
- end
-
- candidates << {
- label: variant[:key],
- output: normalize_candidate_output(eval_case, payload[:raw_entries], variant[:key]),
- }
- end
-
- announce_results(eval_case, candidates, :personas)
- end
- end
-
- def run_llm_comparison(eval_cases, persona_variants, llms)
- raise ComparisonError, "LLM comparison needs at least two LLM configs" if llms.length < 2
- if persona_variants.length != 1
- raise ComparisonError, "LLM comparison runs against a single persona"
- end
-
- persona_variant = persona_variants.first
- workbench = build_workbench(persona_variant)
-
- eval_cases.each do |eval_case|
- candidates = []
-
- workbench.run(eval_case: eval_case, llms: llms) do |payload|
- candidates << {
- label: payload[:llm_name],
- output:
- normalize_candidate_output(eval_case, payload[:raw_entries], payload[:llm_name]),
- }
- end
-
- announce_results(eval_case, candidates, :llms, persona_variant[:key])
- end
- end
-
- def announce_results(eval_case, candidates, mode_label, persona_key = nil)
- if candidates.length < 2
- output.puts "Comparison skipped for #{eval_case.id}: need at least two candidates."
- return
- end
-
- result = judge_for(eval_case).compare(candidates)
-
- header = +"=== Comparison (#{mode_label_string(mode_label)}"
- header << ", persona: #{persona_key}" if persona_key && mode_label == :llms
- header << ") #{eval_case.id} ==="
- output.puts
- output.puts header
-
- if result[:winner].present?
- output.puts "Winner: #{result[:winner]}"
- elsif result[:winner_label].to_s.casecmp("tie").zero?
- output.puts "Result: tie"
- else
- output.puts "Result: no winner reported"
- end
- output.puts "Reason: #{result[:winner_explanation]}" if result[:winner_explanation].present?
-
- result[:ratings].each do |rating|
- output.puts " - #{rating[:candidate]}: #{rating[:rating]}/10 — #{rating[:explanation]}"
- end
- end
-
- def mode_label_string(mode_label)
- case mode_label
- when :personas
- "personas"
- when :llms
- "LLMs"
- else
- mode_label.to_s
- end
- end
-
- def normalize_candidate_output(eval_case, raw_entries, label)
- entries = Array(raw_entries).compact
- if entries.length != 1
- raise ComparisonError,
- "Eval '#{eval_case.id}' returned #{entries.length} outputs for #{label}, comparison mode requires exactly one."
- end
-
- entry = entries.first
- value =
- if entry.is_a?(Hash)
- entry[:raw] || entry[:result] || entry[:output]
- else
- entry
- end
-
- string_value = value.to_s.strip
-
- if string_value.empty?
- raise ComparisonError, "Eval '#{eval_case.id}' produced an empty output for #{label}."
- end
-
- string_value
- end
-
- def build_workbench(variant)
- DiscourseAi::Evals::Workbench.new(
- output: output,
- judge_llm: judge_llm,
- persona_prompt: variant[:prompt],
- persona_label: variant[:key],
- )
- end
-
- def judge_for(eval_case)
- DiscourseAi::Evals::Judge.new(eval_case: eval_case, judge_llm: judge_llm)
- end
-
- def normalize_mode(mode)
- normalized = SUPPORTED_MODES[mode.to_s.downcase]
- raise ComparisonError, "Invalid comparison mode '#{mode}'" if normalized.nil?
-
- normalized
- end
- end
- end
-end
diff --git a/plugins/discourse-ai/evals/lib/eval.rb b/plugins/discourse-ai/evals/lib/eval.rb
index 049a84f158b..e27ad3e029f 100644
--- a/plugins/discourse-ai/evals/lib/eval.rb
+++ b/plugins/discourse-ai/evals/lib/eval.rb
@@ -1,5 +1,7 @@
# frozen_string_literal: true
+require "csv"
+
module DiscourseAi
module Evals
# Lightweight data object that loads eval definitions from disk.
@@ -40,8 +42,64 @@ module DiscourseAi
# @param path [String] absolute path to the YAML definition file.
# @raise [ArgumentError] when a required key (like `feature`) is missing.
- def initialize(path:)
- yaml = YAML.load_file(path).symbolize_keys
+ def initialize(path:, initial_data: nil)
+ yaml = initial_data&.symbolize_keys || YAML.load_file(path).symbolize_keys
+ initialize_from_hash(yaml, path: path, base_dir: File.dirname(path))
+ end
+
+ def self.from_dataset_csv(path:, feature:)
+ raise ArgumentError, "Feature is required for datasets" if feature.blank?
+
+ normalized_path = File.expand_path(path)
+ rows = CSV.read(normalized_path, headers: true)
+ raise ArgumentError, "Dataset '#{path}' has no rows" if rows.empty?
+
+ rows.each_with_index.map do |row, index|
+ normalized = normalize_dataset_row(row)
+ content = normalized[:content].to_s.strip
+ expected = normalized[:expected_output].to_s
+
+ if content.blank? || expected.blank?
+ raise ArgumentError, "Dataset rows must define 'content' and 'expected_output'"
+ end
+
+ attrs = {
+ id: "dataset-#{File.basename(path, File.extname(path))}-#{index + 1}",
+ name: "dataset row #{index + 1}",
+ description: "Dataset row #{index + 1} from #{File.basename(path)}",
+ feature: feature,
+ args: {
+ input: content,
+ },
+ expected_output: expected.strip,
+ }
+
+ new(path: normalized_path, initial_data: attrs)
+ end
+ end
+
+ def print
+ puts "#{id}: #{description} (feature: #{feature})"
+ end
+
+ # @return [Hash] plain data used by Recorder and CLI output.
+ def to_json
+ {
+ path: @path,
+ name: @name,
+ description: @description,
+ id: @id,
+ feature: @feature,
+ args: @args,
+ vision: @vision,
+ expected_output: @expected_output,
+ expected_output_regex: @expected_output_regex,
+ }.compact
+ end
+
+ private
+
+ def initialize_from_hash(yaml, path:, base_dir:)
@path = path
@name = yaml[:name]
@id = yaml[:id]
@@ -66,46 +124,36 @@ module DiscourseAi
elsif yaml[:args].is_a?(Array)
yaml[:args].map(&:symbolize_keys)
else
- normalize_args(path, yaml[:args])
+ normalize_args(base_dir, yaml[:args])
end
end
- def print
- puts "#{id}: #{description} (feature: #{feature})"
- end
-
- # @return [Hash] plain data used by Recorder and CLI output.
- def to_json
- {
- path: @path,
- name: @name,
- description: @description,
- id: @id,
- feature: @feature,
- args: @args,
- vision: @vision,
- expected_output: @expected_output,
- expected_output_regex: @expected_output_regex,
- }.compact
- end
-
- private
-
# Converts relative paths (e.g. asset fixtures) into absolute ones so the
# runner can execute from any working directory.
#
- # @param path [String] original yaml file path used as the base directory.
+ # @param base_dir [String] original yaml file directory used as base.
# @param values [Hash] raw args coming from the YAML file.
# @return [Hash] symbolized args with absolute paths when relevant.
- def normalize_args(path, values)
+ def normalize_args(base_dir, values)
args = values.symbolize_keys
args.each do |key, value|
if (key.to_s.include?("_path") || key.to_s == "path") && value.is_a?(String)
- args[key] = File.expand_path(File.join(File.dirname(path), value))
+ args[key] = File.expand_path(File.join(base_dir, value))
end
end
args
end
+
+ def self.normalize_dataset_row(row)
+ row
+ .to_h
+ .each_with_object({}) do |(key, value), memo|
+ next if key.nil?
+
+ normalized_key = key.to_s.strip.downcase.gsub(/\s+/, "_").to_sym
+ memo[normalized_key] = value
+ end
+ end
end
end
end
diff --git a/plugins/discourse-ai/evals/lib/judge.rb b/plugins/discourse-ai/evals/lib/judge.rb
index f8602fc2e94..45caf1684e3 100644
--- a/plugins/discourse-ai/evals/lib/judge.rb
+++ b/plugins/discourse-ai/evals/lib/judge.rb
@@ -116,7 +116,14 @@ module DiscourseAi
response_format: COMPARISON_RESPONSE_FORMAT,
)
- parse_comparison_response(response)
+ parsed = parse_comparison_response(response)
+ mapped_winner = map_candidate_label(parsed[:winner] || parsed[:winner_label], candidates)
+
+ if mapped_winner.present? && !mapped_winner.casecmp("tie").zero?
+ parsed[:winner] = mapped_winner
+ end
+
+ parsed
end
private
@@ -292,6 +299,23 @@ module DiscourseAi
raw: raw_text,
}
end
+
+ def map_candidate_label(winner_label, candidates)
+ return winner_label if winner_label.blank?
+ return winner_label if winner_label.casecmp("tie").zero?
+
+ label_downcased = winner_label.to_s.strip.downcase
+
+ match = label_downcased.match(/candidate\s*(\d+)/i)
+ if match
+ index = match[1].to_i - 1
+ candidate_label = candidates[index]&.dig(:label)
+ return candidate_label if candidate_label.present?
+ end
+
+ candidate = candidates.find { |c| c[:label].to_s.strip.downcase == label_downcased }
+ candidate&.dig(:label) || winner_label
+ end
end
end
end
diff --git a/plugins/discourse-ai/evals/lib/recorder.rb b/plugins/discourse-ai/evals/lib/recorder.rb
index 4b1475169d2..f7cd99dec79 100644
--- a/plugins/discourse-ai/evals/lib/recorder.rb
+++ b/plugins/discourse-ai/evals/lib/recorder.rb
@@ -68,11 +68,10 @@ module DiscourseAi
llm_step = structured_logger.add_child_step(name: "Evaluating with LLM: #{llm_name}")
logger.info("Evaluating with LLM: #{llm_name}")
- output.puts "#{llm_name}: "
results.each do |result|
if result[:result] == :fail
- output.puts "Failed 🔴"
+ output.puts "#{llm_name}: Failed 🔴\n"
output.puts "Error: #{result[:message]}" if result[:message]
# this is deliberate, it creates a lot of noise, but sometimes for debugging it's useful
# output.puts "Context: #{result[:context].to_s[0..2000]}" if result[:context]
@@ -86,7 +85,7 @@ module DiscourseAi
logger.error("Actual: #{result[:actual_output]}") if result[:actual_output]
logger.error("Context: #{result[:context]}") if result[:context]
elsif result[:result] == :pass
- output.puts "Passed 🟢"
+ output.puts "#{llm_name}: Passed 🟢"
logger.info("Evaluation passed with LLM: #{llm_name}")
else
STDERR.puts "Error: Unknown result #{an_eval.inspect}"
@@ -102,6 +101,105 @@ module DiscourseAi
end
end
+ def announce_comparison_judged(eval_case_id:, mode_label:, persona_key: nil, result:)
+ step = start_comparison_step(eval_case_id, mode_label, persona_key)
+
+ output.puts
+ output.puts "#{comparison_header(eval_case_id, mode_label, persona_key)}\n"
+ logger.info(comparison_header(eval_case_id, mode_label, persona_key))
+
+ if result[:winner].present?
+ output.puts "Winner: #{result[:winner]}\n"
+ logger.info("Winner: #{result[:winner]}")
+ append_comparison_entry(step, "winner", result.slice(:winner, :winner_explanation))
+ elsif result[:winner_label].to_s.casecmp("tie").zero?
+ output.puts "Result: tie\n"
+ logger.info("Result: tie")
+ append_comparison_entry(step, "winner", result.slice(:winner_label, :winner_explanation))
+ else
+ output.puts "Result: no winner reported\n"
+ logger.info("Result: no winner reported")
+ append_comparison_entry(step, "winner", result.slice(:winner_label, :winner_explanation))
+ end
+ if result[:winner_explanation].present?
+ output.puts "Reason: #{result[:winner_explanation]}\n"
+ end
+ if result[:winner_explanation].present?
+ logger.info("Reason: #{result[:winner_explanation]}")
+ end
+
+ Array(result[:ratings]).each do |rating|
+ output.puts " - #{rating[:candidate]}: #{rating[:rating]}/10 — #{rating[:explanation]}"
+ logger.info(" - #{rating[:candidate]}: #{rating[:rating]}/10 — #{rating[:explanation]}")
+ append_comparison_entry(step, "rating", rating)
+ end
+
+ finish_comparison_step(step)
+ end
+
+ def announce_comparison_expected(
+ eval_case_id:,
+ mode_label:,
+ persona_key: nil,
+ winner:,
+ status_line: nil,
+ failures: []
+ )
+ step = start_comparison_step(eval_case_id, mode_label, persona_key)
+
+ output.puts
+ output.puts comparison_header(eval_case_id, mode_label, persona_key)
+ logger.info(comparison_header(eval_case_id, mode_label, persona_key))
+
+ if winner == :tie
+ output.puts "Result: tie\n"
+ logger.info("Result: tie")
+ append_comparison_entry(step, "winner", winner: "tie")
+ else
+ output.puts "Winner: #{winner}\n"
+ logger.info("Winner: #{winner}")
+ append_comparison_entry(step, "winner", winner: winner)
+ end
+
+ output.puts " #{status_line}" if status_line.present?
+ logger.info(" #{status_line}") if status_line.present?
+ append_comparison_entry(step, "status", status_line: status_line) if status_line.present?
+
+ failures.each do |failure|
+ output.puts " #{failure[:label]} expected: #{failure[:expected].inspect}, actual: #{failure[:actual].inspect}"
+ logger.info(
+ " #{failure[:label]} expected: #{failure[:expected].inspect}, actual: #{failure[:actual].inspect}",
+ )
+ append_comparison_entry(step, "failure", failure)
+ end
+
+ finish_comparison_step(step)
+ end
+
+ def announce_comparison_aggregate(mode_label:, persona_key: nil, aggregate_scores:)
+ return if aggregate_scores.blank?
+
+ step = start_comparison_step(nil, mode_label, persona_key, summary: true)
+
+ output.puts
+ output.puts "#{comparison_header(nil, mode_label, persona_key, summary: true)}\n"
+ logger.info(comparison_header(nil, mode_label, persona_key, summary: true))
+
+ aggregate_scores.each do |label, stats|
+ output.puts " - #{label}: #{stats[:passes]}/#{stats[:evals]} passed"
+ logger.info(" - #{label}: #{stats[:passes]}/#{stats[:evals]} passed")
+ append_comparison_entry(
+ step,
+ "aggregate",
+ label: label,
+ passes: stats[:passes],
+ evals: stats[:evals],
+ )
+ end
+
+ finish_comparison_step(step)
+ end
+
def finish
structured_logger.finish_root(end_time: Time.now.utc)
@@ -148,6 +246,37 @@ module DiscourseAi
Thread.current[:llm_audit_log] = @previous_thread_loggers[:audit_log]
Thread.current[:llm_audit_structured_log] = @previous_thread_loggers[:structured_log]
end
+
+ def comparison_header(eval_case_id, mode_label, persona_key, summary: false)
+ header = "=== Comparison (#{mode_label}"
+ header << ", persona: #{persona_key}" if persona_key
+ header << ")"
+ header << " #{eval_case_id}" if eval_case_id && !summary
+ header
+ end
+
+ def start_comparison_step(eval_case_id, mode_label, persona_key, summary: false)
+ ensure_root!
+ name = "Comparison (#{mode_label}"
+ name += ", persona: #{persona_key}" if persona_key
+ name += ")"
+ name += " #{eval_case_id}" if eval_case_id && !summary
+ structured_logger.add_child_step(name: name)
+ end
+
+ def finish_comparison_step(step)
+ step[:end_time] = Time.now.utc if step && step[:end_time].nil?
+ end
+
+ def append_comparison_entry(step, name, args)
+ structured_logger.append_entry(step: step, name: name, args: args, started_at: Time.now.utc)
+ end
+
+ def ensure_root!
+ unless structured_logger.root_started?
+ raise ArgumentError, "Structured logger root not started"
+ end
+ end
end
end
end
diff --git a/plugins/discourse-ai/evals/lib/runners/base.rb b/plugins/discourse-ai/evals/lib/runners/base.rb
index dc026467b9a..b69015fe48e 100644
--- a/plugins/discourse-ai/evals/lib/runners/base.rb
+++ b/plugins/discourse-ai/evals/lib/runners/base.rb
@@ -63,9 +63,9 @@ module DiscourseAi
bot.reply(context) do |partial, _, type|
if type == :structured_output
chunk = partial.read_buffered_property(key)
- append_structured_chunk(accumulator, schema_type, chunk)
+ accumulator = append_structured_chunk(accumulator, schema_type, chunk)
elsif type.blank?
- append_structured_chunk(accumulator, schema_type, partial)
+ accumulator = append_structured_chunk(accumulator, schema_type, partial)
end
end
@@ -73,13 +73,16 @@ module DiscourseAi
end
def append_structured_chunk(accumulator, schema_type, chunk)
- return if chunk.nil? || (chunk.respond_to?(:empty?) && chunk.empty?)
+ return accumulator if chunk.nil? || (chunk.respond_to?(:empty?) && chunk.empty?)
case schema_type
when "array"
Array(chunk).each { |item| accumulator << item if accumulator.exclude?(item) }
- else
+ accumulator
+ when "string"
accumulator << chunk.to_s
+ else
+ chunk
end
end
diff --git a/plugins/discourse-ai/evals/lib/workbench.rb b/plugins/discourse-ai/evals/lib/workbench.rb
index dd356186427..da39ea6555e 100644
--- a/plugins/discourse-ai/evals/lib/workbench.rb
+++ b/plugins/discourse-ai/evals/lib/workbench.rb
@@ -12,72 +12,163 @@ require_relative "runners/inference"
require_relative "runners/spam"
require_relative "runners/summarization"
require_relative "judge"
+require_relative "persona_prompt_loader"
module DiscourseAi
module Evals
# Coordinates the execution of eval cases against one or more LLMs.
#
- # The Playground drives the orchestration loop: it prepares the Structured
+ # The Workbench drives the orchestration loop: it prepares the Structured
# Recorder, dispatches work to helpers/utilities based on the eval feature,
# and feeds the aggregated results back to the Recorder. It intentionally
# keeps higher-level scripts (`evals/run`) simple while centralizing
# instrumentation and error handling.
class Workbench
- def initialize(output: $stdout, judge_llm: nil, persona_prompt: nil, persona_label: "default")
+ def initialize(output: $stdout, judge_llm: nil, persona_variants: nil, comparison: nil)
@output = output
@judge_llm = judge_llm
- @persona_prompt = persona_prompt
- label = persona_label.to_s.strip
- @persona_label = label.empty? ? "default" : label
+ @persona_variants = persona_variants
+ @comparison = comparison
end
- # Iterate through the provided LLM adapters and execute the eval case for
- # each one, recording structured logs along the way.
- #
- # @param eval_case [DiscourseAi::Evals::Eval] the scenario to run.
- # @param llms [Array<LlmModel>] LLMs selected by the CLI.
- def run(eval_case:, llms:, &after_run)
- recorder = Recorder.with_cassette(eval_case, persona_key: persona_label, output: output)
-
- llms.each do |llm|
- llm_name = llm.display_name || llm.name
- start_time = Time.now.utc
-
- if eval_case.vision && !llm.vision_enabled?
- recorder.record_llm_skip(llm_name, "LLM does not support vision")
- next
+ def run_evals(eval_cases:, llms: nil, persona_variants: nil)
+ if running_comparisons?
+ compare(eval_cases: eval_cases, llms: llms, persona_variants: persona_variants)
+ else
+ run(eval_cases: eval_cases, llms: llms, persona_variants: persona_variants)
+ end
+ end
+
+ def compare(eval_cases:, llms:, persona_variants: [{ key: :default, prompt: nil }])
+ aggregate_scores = Hash.new { |h, k| h[k] = { passes: 0, evals: eval_cases.length } }
+
+ eval_cases.each do |eval_case|
+ recorder = Recorder.with_cassette(eval_case, output: output)
+ candidates = []
+ persona_compare = persona_variants.length > 1 && llms.length == 1
+
+ persona_variants.each do |variant|
+ llms.each do |llm|
+ llm_name = llm.display_name || llm.name
+ start_time = Time.now.utc
+
+ execution = execute_eval(eval_case, llm, variant, skip_judge: true)
+ classified = Array(execution[:classified])
+
+ if classified.first&.dig(:result) == :skipped
+ recorder.record_llm_skip(
+ llm_name,
+ classified.first[:message] || "LLM does not support vision",
+ )
+ next
+ end
+
+ recorder.record_llm_results(llm_name, classified, start_time)
+
+ candidates << build_candidate(
+ eval_case: eval_case,
+ variant: variant,
+ llm_name: llm_name,
+ execution: execution,
+ persona_compare: persona_compare,
+ )
+ rescue DiscourseAi::Evals::Eval::EvalError => e
+ recorder.record_llm_results(
+ llm_name,
+ [{ result: :fail, message: e.message, context: e.context }],
+ start_time,
+ )
+ rescue StandardError => e
+ puts e.backtrace if !Rails.env.test?
+ recorder.record_llm_results(
+ llm_name,
+ [{ result: :fail, message: e.message }],
+ start_time,
+ )
+ end
end
+ update_aggregate_scores(aggregate_scores, candidates)
+
+ announce_comparison(
+ recorder,
+ eval_case,
+ candidates,
+ persona_variants.first&.dig(:key),
+ aggregate_scores,
+ )
+ ensure
+ recorder&.finish
+ end
+ end
- execution = execute_eval(eval_case, llm)
- recorder.record_llm_results(llm_name, execution[:classified], start_time)
- if after_run
- after_run.call(
- eval_case: eval_case,
- llm: llm,
- llm_name: llm_name,
- persona_label: persona_label,
- raw_entries: execution[:raw_entries],
- classified_entries: execution[:classified],
+ def run(eval_cases:, llms:, persona_variants: [{ key: :default, prompt: nil }])
+ # We only allow one persona at a time here.
+ # If not specified, will contain an element with the default key.
+ variant = persona_variants.first
+
+ eval_cases.each do |eval_case|
+ recorder = Recorder.with_cassette(eval_case, output: output)
+
+ llms.each do |llm|
+ llm_name = llm.display_name || llm.name
+ start_time = Time.now.utc
+
+ if eval_case.vision && !llm.vision_enabled?
+ recorder.record_llm_skip(llm_name, "LLM does not support vision")
+ next
+ end
+
+ execution = execute_eval(eval_case, llm, variant)
+ classified = Array(execution[:classified])
+
+ if classified.first&.dig(:result) == :skipped
+ recorder.record_llm_skip(
+ llm_name,
+ classified.first[:message] || "LLM does not support vision",
+ )
+ next
+ end
+
+ recorder.record_llm_results(llm_name, classified, start_time)
+ rescue DiscourseAi::Evals::Eval::EvalError => e
+ recorder.record_llm_results(
+ llm_name,
+ [{ result: :fail, message: e.message, context: e.context }],
+ start_time,
+ )
+ rescue StandardError => e
+ puts e.backtrace if !Rails.env.test?
+ recorder.record_llm_results(
+ llm_name,
+ [{ result: :fail, message: e.message }],
+ start_time,
)
end
- rescue DiscourseAi::Evals::Eval::EvalError => e
- recorder.record_llm_results(
- llm_name,
- [{ result: :fail, message: e.message, context: e.context }],
- start_time,
- )
- rescue StandardError => e
- puts e.backtrace if !Rails.env.test?
- recorder.record_llm_results(llm_name, [{ result: :fail, message: e.message }], start_time)
+ ensure
+ recorder&.finish
end
- ensure
- recorder&.finish
end
- def execute_eval(eval_case, llm)
+ def execute_eval(
+ eval_case,
+ llm,
+ persona_variant = { key: :default, prompt: nil },
+ skip_judge: false
+ )
feature = eval_case.feature
- runner = find_runner(feature)
+ if eval_case.vision && !llm.vision_enabled?
+ return(
+ {
+ raw: nil,
+ raw_entries: [],
+ classified: [{ result: :skipped, message: "LLM does not support vision" }],
+ }
+ )
+ end
+
+ runner = DiscourseAi::Evals::Runners::Base.find_runner(feature, persona_variant[:prompt])
+
raw =
if runner
runner.run(eval_case, llm)
@@ -95,27 +186,31 @@ module DiscourseAi
entries = normalize_entries(raw)
- { raw: raw, raw_entries: entries, classified: classify_results(eval_case, entries) }
+ {
+ raw: raw,
+ raw_entries: entries,
+ classified: classify_results(eval_case, entries, skip_judge: skip_judge),
+ }
end
- private
+ def running_comparisons?
+ comparison.present?
+ end
- attr_reader :output, :judge_llm, :persona_prompt, :persona_label
+ private
- def find_runner(feature)
- DiscourseAi::Evals::Runners::Base.find_runner(feature, persona_prompt)
- end
+ attr_reader :output, :judge_llm, :persona_variants, :comparison
def normalize_entries(raw)
raw.is_a?(Array) ? raw : [raw]
end
- def classify_results(eval_case, entries)
+ def classify_results(eval_case, entries, skip_judge: false)
entries.map do |entry|
raw_value = entry.is_a?(Hash) && entry.key?(:raw) ? entry[:raw] : entry
metadata = entry.is_a?(Hash) ? entry[:metadata] : nil
- classification = classify_result(eval_case, raw_value)
+ classification = classify_result(eval_case, raw_value, skip_judge: skip_judge)
classification[:metadata] = metadata if metadata.present?
@@ -123,7 +218,136 @@ module DiscourseAi
end
end
- def classify_result(eval_case, result)
+ def announce_comparison(recorder, eval_case, candidates, persona_key, aggregate_scores)
+ return if candidates.length < 2
+
+ mode_label = comparison_mode_label(persona_key, candidates)
+
+ if judge_llm.present? || eval_case.judge.present?
+ judged = judge_for(eval_case).compare(candidates.map { |c| c.slice(:label, :output) })
+ recorder.announce_comparison_judged(
+ eval_case_id: eval_case.id,
+ mode_label: mode_label,
+ persona_key: persona_key,
+ result: judged,
+ )
+ recorder.announce_comparison_aggregate(
+ mode_label: mode_label,
+ persona_key: persona_key,
+ aggregate_scores: aggregate_scores,
+ )
+ else
+ failures = []
+
+ candidates.each do |candidate|
+ entries = Array(candidate[:classified_entries])
+ entries.each do |entry|
+ next if entry[:result] == :pass
+
+ failures << {
+ label: candidate[:label],
+ expected: entry[:expected_output] || entry[:expected_output_regex],
+ actual: entry[:actual_output] || entry[:result],
+ }
+ end
+ end
+
+ winner = pick_winner(aggregate_scores)
+ status_line = build_status_line(candidates)
+
+ recorder.announce_comparison_expected(
+ eval_case_id: eval_case.id,
+ mode_label: mode_label,
+ persona_key: persona_key,
+ winner: winner,
+ status_line: status_line,
+ failures: failures,
+ )
+ recorder.announce_comparison_aggregate(
+ mode_label: mode_label,
+ persona_key: persona_key,
+ aggregate_scores: aggregate_scores,
+ )
+ end
+ end
+
+ def pick_winner(aggregate_scores)
+ best = aggregate_scores.max_by { |_label, stats| stats[:passes] }&.first
+ return :tie if best.nil?
+
+ top_passes = aggregate_scores[best][:passes]
+ tied = aggregate_scores.count { |_label, stats| stats[:passes] == top_passes }
+ tied > 1 ? :tie : best
+ end
+
+ def build_status_line(candidates)
+ entries =
+ candidates.map do |candidate|
+ entries = candidate[:classified_entries]
+ emoji = entries.all? { |e| e[:result] == :pass } ? "🟢" : "🔴"
+ "#{candidate[:label]} #{emoji}"
+ end
+ entries.join(" -- ")
+ end
+
+ def comparison_mode_label(persona_key, candidates)
+ unique_personas = candidates.map { |c| c[:persona_label] }.compact.uniq
+ unique_personas.length > 1 ? "personas" : "LLMs"
+ end
+
+ def update_aggregate_scores(aggregate_scores, candidates)
+ candidates.each do |candidate|
+ entries = Array(candidate[:classified_entries])
+ pass_eval = entries.all? { |e| e[:result] == :pass }
+ # Init score if not present.
+ score = aggregate_scores[candidate[:label]][:passes].to_i
+ score += 1 if pass_eval
+ aggregate_scores[candidate[:label]][:passes] = score
+ end
+ end
+
+ def build_candidate(eval_case:, variant:, llm_name:, execution:, persona_compare:)
+ output =
+ normalize_candidate_output(
+ eval_case,
+ execution[:raw_entries],
+ persona_compare ? variant[:key] : llm_name,
+ )
+ {
+ label: persona_compare ? variant[:key] : llm_name,
+ persona_label: variant[:key],
+ classified_entries: execution[:classified],
+ output: output,
+ }
+ end
+
+ def normalize_candidate_output(eval_case, raw_entries, label)
+ entries = Array(raw_entries).compact
+ entry = entries.find { |e| value_from_entry(e).present? }
+ value = value_from_entry(entry)
+
+ string_value = value.to_s.strip
+
+ raise "Eval '#{eval_case.id}' produced an empty output for #{label}." if string_value.empty?
+
+ string_value
+ end
+
+ def value_from_entry(entry)
+ return if entry.nil?
+
+ if entry.is_a?(Hash)
+ entry[:raw] || entry[:result] || entry[:output]
+ else
+ entry
+ end
+ end
+
+ def judge_for(eval_case)
+ DiscourseAi::Evals::Judge.new(eval_case: eval_case, judge_llm: judge_llm)
+ end
+
+ def classify_result(eval_case, result, skip_judge: false)
if eval_case.expected_output
if result == eval_case.expected_output
{ result: :pass }
@@ -142,7 +366,7 @@ module DiscourseAi
end
elsif eval_case.expected_tool_call
classify_tool_call(eval_case.expected_tool_call, result)
- elsif eval_case.judge
+ elsif eval_case.judge && !skip_judge
judge_result(eval_case, result)
else
{ result: :pass }
@@ -164,6 +388,19 @@ module DiscourseAi
end
end
+ def print_persona_heading(variant)
+ return unless variant[:key]
+
+ label =
+ if variant[:key] == DiscourseAi::Evals::PersonaPromptLoader::DEFAULT_PERSONA_KEY
+ "default (built-in)"
+ else
+ variant[:key]
+ end
+
+ output.puts "\n=== Persona: #{label} ==="
+ end
+
def judge_result(eval_case, result)
if judge_llm.nil?
raise DiscourseAi::Evals::Eval::EvalError.new(
diff --git a/plugins/discourse-ai/evals/run b/plugins/discourse-ai/evals/run
index aa4b7efabbc..31f00ebaedf 100644
--- a/plugins/discourse-ai/evals/run
+++ b/plugins/discourse-ai/evals/run
@@ -10,7 +10,6 @@ require_relative "lib/features"
require_relative "lib/recorder"
require_relative "lib/workbench"
require_relative "lib/persona_prompt_loader"
-require_relative "lib/comparison_runner"
require_relative "lib/cli"
features_registry =
@@ -50,81 +49,49 @@ if llms.empty?
exit 1
end
-selected_evals = cli.select_evals(available_evals)
+selected_evals =
+ if cli.dataset_path.present?
+ DiscourseAi::Evals::Eval.from_dataset_csv(path: cli.dataset_path, feature: cli.feature_key)
+ else
+ cli.select_evals(available_evals)
+ end
judge_llm = nil
default_judge_error = nil
-begin
- judge_llm = llm_repository.hydrate(cli.judge_name)
-rescue StandardError => e
- if cli.judge_provided
- puts "Error: #{e.message}"
- exit 1
- else
- judge_llm = nil
- default_judge_error = e.message
- end
-end
+requires_judge = selected_evals.any? { |eval_case| eval_case.judge.present? }
-persona_variants =
- persona_loader.variants_for(cli.persona_keys, comparison_mode: cli.comparison_mode)
-
-requires_judge =
- cli.comparison_mode.present? || selected_evals.any? { |eval_case| eval_case.judge.present? }
+judge_name = cli.judge_name.presence
+judge_name = DiscourseAi::Evals::Cli::DEFAULT_JUDGE if requires_judge && judge_name.blank?
-if requires_judge && judge_llm.nil?
- message = "Error: Selected evaluations require a judge."
- if default_judge_error
- message += " Configure '#{cli.judge}' or pass --judge with an LLM config name."
- message += "\n\n"
- message += default_judge_error
- else
- message += " Pass --judge with an LLM config name."
- end
- puts message
- exit 1
-end
-
-if cli.comparison_mode
+if judge_name.present?
begin
- DiscourseAi::Evals::ComparisonRunner.new(
- mode: cli.comparison_mode,
- judge_llm: judge_llm,
- output: $stdout,
- ).run(eval_cases: selected_evals, persona_variants: persona_variants, llms: llms)
- rescue DiscourseAi::Evals::ComparisonRunner::ComparisonError => e
- puts "Error: #{e.message}"
- exit 1
+ judge_llm = llm_repository.hydrate(judge_name)
+ rescue StandardError => e
+ if cli.judge_provided?
+ puts "Error: #{e.message}"
+ exit 1
+ else
+ judge_llm = nil
+ default_judge_error = e.message
+ end
end
- exit 0
end
-persona_variants.each do |variant|
- if variant[:key]
- label =
- if variant[:key] == default_persona_key
- "default (built-in)"
- else
- variant[:key]
- end
+persona_variants =
+ persona_loader.variants_for(cli.persona_keys, comparison_mode: cli.comparison_mode)
- puts "\n=== Persona: #{label} ==="
- end
+cli.validate_comparison_requirements!(llms: llms, persona_variants: persona_variants)
- playground =
- DiscourseAi::Evals::Workbench.new(
- output: $stdout,
- judge_llm: judge_llm,
- persona_prompt: variant[:prompt],
- persona_label: variant[:key],
- )
-
- selected_evals.each do |eval_case|
- if cli.judge_provided && eval_case.judge.blank?
- puts "Notice: Eval '#{eval_case.id}' has no judge block. --judge is ignored for this eval."
- end
+cli.validate_judge_presence!(
+ requires_judge: requires_judge,
+ judge_llm: judge_llm,
+ default_judge_error: default_judge_error,
+)
- playground.run(eval_case: eval_case, llms: llms)
- end
-end
+DiscourseAi::Evals::Workbench.new(
+ output: $stdout,
+ judge_llm: judge_llm,
+ persona_variants: persona_variants,
+ comparison: cli.comparison_mode,
+).run_evals(eval_cases: selected_evals, llms: llms, persona_variants: persona_variants)
diff --git a/plugins/discourse-ai/spec/evals/comparison_runner_spec.rb b/plugins/discourse-ai/spec/evals/comparison_runner_spec.rb
deleted file mode 100644
index ce491328687..00000000000
--- a/plugins/discourse-ai/spec/evals/comparison_runner_spec.rb
+++ /dev/null
@@ -1,163 +0,0 @@
-# frozen_string_literal: true
-
-require_relative "../../evals/lib/comparison_runner"
-require_relative "../../evals/lib/judge"
-require_relative "../../evals/lib/workbench"
-
-RSpec.describe DiscourseAi::Evals::ComparisonRunner do
- subject(:runner) { described_class.new(mode: mode, judge_llm: judge_llm, output: output) }
-
- let(:mode) { :personas }
- let(:judge_llm) { Fabricate(:fake_model) }
- let(:output) { StringIO.new }
- let(:eval_case) do
- OpenStruct.new(
- id: "topic-summary",
- args: {
- source: "input",
- },
- judge: {
- criteria: "Score accuracy",
- pass_rating: 8,
- },
- )
- end
-
- before { freeze_time }
-
- describe "#run in persona mode" do
- let(:mode) { :personas }
- let(:llm) { Fabricate(:fake_model) }
- let(:persona_variants) do
- [{ key: "default", prompt: nil }, { key: "topic_summary_eval", prompt: "custom prompt" }]
- end
- let(:workbench_default) { instance_double(DiscourseAi::Evals::Workbench) }
- let(:workbench_custom) { instance_double(DiscourseAi::Evals::Workbench) }
- let(:judge_double) do
- instance_double(
- DiscourseAi::Evals::Judge,
- compare: {
- winner: "topic_summary_eval",
- winner_label: "topic_summary_eval",
- winner_explanation: "custom captured more detail",
- ratings: [
- { candidate: "default", rating: 6, explanation: "missed details" },
- { candidate: "topic_summary_eval", rating: 9, explanation: "accurate" },
- ],
- raw: '{"winner":"topic_summary_eval"}',
- },
- )
- end
-
- before do
- allow(DiscourseAi::Evals::Workbench).to receive(:new).and_return(
- workbench_default,
- workbench_custom,
- )
-
- allow(workbench_default).to receive(:run).and_yield(
- eval_case: eval_case,
- llm: llm,
- llm_name: "Default LLM",
- persona_label: "default",
- raw_entries: ["Default output"],
- classified_entries: [{ result: :pass }],
- )
- allow(workbench_custom).to receive(:run).and_yield(
- eval_case: eval_case,
- llm: llm,
- llm_name: "Default LLM",
- persona_label: "topic_summary_eval",
- raw_entries: ["Custom output"],
- classified_entries: [{ result: :pass }],
- )
-
- allow(DiscourseAi::Evals::Judge).to receive(:new).and_return(judge_double)
- end
-
- it "collects persona outputs and sends them to the judge" do
- runner.run(eval_cases: [eval_case], persona_variants: persona_variants, llms: [llm])
-
- expect(DiscourseAi::Evals::Judge).to have_received(:new).with(
- eval_case: eval_case,
- judge_llm: judge_llm,
- )
- expect(judge_double).to have_received(:compare).with(
- [
- { label: "default", output: "Default output" },
- { label: "topic_summary_eval", output: "Custom output" },
- ],
- )
-
- expect(output.string).to include("Winner: topic_summary_eval")
- expect(output.string).to include("default: 6/10")
- expect(output.string).to include("topic_summary_eval: 9/10")
- end
- end
-
- describe "#run in llm mode" do
- let(:mode) { :llms }
- let(:llm_one) { Fabricate(:fake_model, display_name: "LLM One") }
- let(:llm_two) { Fabricate(:fake_model, display_name: "LLM Two") }
- let(:persona_variants) { [{ key: "default", prompt: nil }] }
- let(:workbench) { instance_double(DiscourseAi::Evals::Workbench) }
- let(:judge_double) do
- instance_double(
- DiscourseAi::Evals::Judge,
- compare: {
- winner: "LLM Two",
- winner_label: "LLM Two",
- winner_explanation: "Fewer hallucinations",
- ratings: [
- { candidate: "LLM One", rating: 5, explanation: "missed context" },
- { candidate: "LLM Two", rating: 8, explanation: "accurate" },
- ],
- raw: '{"winner":"LLM Two"}',
- },
- )
- end
-
- before do
- allow(DiscourseAi::Evals::Workbench).to receive(:new).and_return(workbench)
- call_sequence = [
- {
- eval_case: eval_case,
- llm: llm_one,
- llm_name: "LLM One",
- persona_label: "default",
- raw_entries: ["Output One"],
- classified_entries: [{ result: :pass }],
- },
- {
- eval_case: eval_case,
- llm: llm_two,
- llm_name: "LLM Two",
- persona_label: "default",
- raw_entries: ["Output Two"],
- classified_entries: [{ result: :pass }],
- },
- ]
- allow(workbench).to receive(:run) do |**kwargs, &block|
- expect(kwargs[:llms]).to match_array([llm_one, llm_two])
- expect(kwargs[:eval_case]).to eq(eval_case)
- call_sequence.each { |payload| block.call(payload) }
- end
- allow(DiscourseAi::Evals::Judge).to receive(:new).and_return(judge_double)
- end
-
- it "compares outputs from multiple llms for the same persona" do
- runner.run(
- eval_cases: [eval_case],
- persona_variants: persona_variants,
- llms: [llm_one, llm_two],
- )
-
- expect(judge_double).to have_received(:compare).with(
- [{ label: "LLM One", output: "Output One" }, { label: "LLM Two", output: "Output Two" }],
- )
-
- expect(output.string).to include("Winner: LLM Two")
- expect(output.string).to include("persona: default")
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/evals/eval_spec.rb b/plugins/discourse-ai/spec/evals/eval_spec.rb
index 95e684c4027..0a746313e56 100644
--- a/plugins/discourse-ai/spec/evals/eval_spec.rb
+++ b/plugins/discourse-ai/spec/evals/eval_spec.rb
@@ -10,6 +10,25 @@ RSpec.describe DiscourseAi::Evals::Eval do
end
end
+ describe ".from_dataset_csv" do
+ let(:csv_path) { File.join(@cases_dir, "dataset.csv") }
+
+ before { File.write(csv_path, <<~CSV) }
+ content,expected_output
+ call this number for free money,true
+ hey there is a bug on version 3,false
+ CSV
+
+ it "builds evals for each row with expected outputs" do
+ evals = described_class.from_dataset_csv(path: csv_path, feature: "spam:inspect_posts")
+
+ expect(evals.length).to eq(2)
+ expect(evals.first.args[:input]).to include("free money")
+ expect(evals.first.expected_output).to eq("true")
+ expect(evals.last.expected_output).to eq("false")
+ end
+ end
+
describe ".available_cases" do
it "loads eval instances sorted by file path" do
write_case("set-one", "second", "id" => "second", "feature" => "mod:second")
diff --git a/plugins/discourse-ai/spec/evals/judge_spec.rb b/plugins/discourse-ai/spec/evals/judge_spec.rb
index 7ed718e7a49..053d314c7f7 100644
--- a/plugins/discourse-ai/spec/evals/judge_spec.rb
+++ b/plugins/discourse-ai/spec/evals/judge_spec.rb
@@ -55,7 +55,7 @@ RSpec.describe DiscourseAi::Evals::Judge do
describe "#compare" do
it "requests a structured comparison and returns parsed ratings" do
comparison_payload = {
- "winner" => "default",
+ "winner" => "Candidate 2",
"winner_explanation" => "more accurate",
"ratings" => [
{ "candidate" => "default", "rating" => 9, "explanation" => "complete" },
@@ -75,7 +75,7 @@ RSpec.describe DiscourseAi::Evals::Judge do
temperature: 0,
response_format: DiscourseAi::Evals::Judge::COMPARISON_RESPONSE_FORMAT,
)
- expect(result[:winner]).to eq("default")
+ expect(result[:winner]).to eq("custom")
expect(result[:ratings].map { |entry| entry[:candidate] }).to match_array(%w[default custom])
end
end
diff --git a/plugins/discourse-ai/spec/evals/workbench_compare_spec.rb b/plugins/discourse-ai/spec/evals/workbench_compare_spec.rb
new file mode 100644
index 00000000000..062604bc6e3
--- /dev/null
+++ b/plugins/discourse-ai/spec/evals/workbench_compare_spec.rb
@@ -0,0 +1,144 @@
+# frozen_string_literal: true
+
+require_relative "../../evals/lib/workbench"
+require_relative "../../evals/lib/judge"
+
+RSpec.describe DiscourseAi::Evals::Workbench do
+ let(:output) { StringIO.new }
+ let(:eval_case) do
+ OpenStruct.new(
+ id: "topic-summary",
+ judge: {
+ criteria: "accuracy",
+ pass_rating: 8,
+ },
+ feature: "dummy",
+ args: {
+ },
+ )
+ end
+ let(:llm_one) { Fabricate(:fake_model, display_name: "LLM One") }
+ let(:llm_two) { Fabricate(:fake_model, display_name: "LLM Two") }
+ let(:persona_variants) { [{ key: "default", prompt: nil }, { key: "custom", prompt: "prompt" }] }
+
+ describe "#compare with judge in persona mode" do
+ let(:judge_llm) { Fabricate(:fake_model) }
+ let(:workbench) { described_class.new(output: output, judge_llm: judge_llm, comparison: true) }
+ let(:recorder) do
+ instance_double(
+ DiscourseAi::Evals::Recorder,
+ record_llm_results: nil,
+ record_llm_skip: nil,
+ announce_comparison_judged: nil,
+ announce_comparison_expected: nil,
+ announce_comparison_aggregate: nil,
+ finish: nil,
+ )
+ end
+
+ before do
+ allow(DiscourseAi::Evals::Recorder).to receive(:with_cassette).and_return(recorder)
+ allow(workbench).to receive(:execute_eval).and_return(
+ { raw: "default out", raw_entries: ["default out"], classified: [{ result: :pass }] },
+ { raw: "custom out", raw_entries: ["custom out"], classified: [{ result: :pass }] },
+ )
+ allow_any_instance_of(DiscourseAi::Evals::Judge).to receive(:compare).and_return(
+ winner: "custom",
+ winner_label: "Candidate 2",
+ ratings: [
+ { candidate: "default", rating: 6, explanation: "ok" },
+ { candidate: "custom", rating: 9, explanation: "great" },
+ ],
+ winner_explanation: "better",
+ )
+ end
+
+ it "announces judged comparison with resolved winner labels" do
+ workbench.compare(
+ eval_cases: [eval_case],
+ llms: [llm_one],
+ persona_variants: persona_variants,
+ )
+
+ expect(recorder).to have_received(:announce_comparison_judged).with(
+ eval_case_id: "topic-summary",
+ mode_label: "personas",
+ persona_key: "default",
+ result:
+ a_hash_including(
+ winner: "custom",
+ winner_label: "Candidate 2",
+ winner_explanation: "better",
+ ratings: [
+ { candidate: "default", rating: 6, explanation: "ok" },
+ { candidate: "custom", rating: 9, explanation: "great" },
+ ],
+ ),
+ )
+ end
+ end
+
+ describe "#compare expected-output aggregate" do
+ let(:workbench) { described_class.new(output: output, judge_llm: nil, comparison: :llms) }
+ let(:recorder) do
+ instance_double(
+ DiscourseAi::Evals::Recorder,
+ record_llm_results: nil,
+ record_llm_skip: nil,
+ announce_comparison_judged: nil,
+ announce_comparison_expected: nil,
+ announce_comparison_aggregate: nil,
+ finish: nil,
+ )
+ end
+
+ let(:eval_case) { OpenStruct.new(id: "spam_eval", judge: nil, args: nil, feature: "dummy") }
+
+ before do
+ allow(DiscourseAi::Evals::Recorder).to receive(:with_cassette).and_return(recorder)
+ allow(DiscourseAi::Evals::Judge).to receive(:new).and_raise("judge should not be called")
+ allow(workbench).to receive(:execute_eval).and_return(
+ { raw: "out one", raw_entries: ["out one"], classified: [{ result: :pass }] },
+ {
+ raw: "out two",
+ raw_entries: ["out two"],
+ classified: [
+ { result: :pass },
+ { result: :fail, expected_output: "true", actual_output: "false" },
+ ],
+ },
+ )
+ end
+
+ it "announces expected comparison and aggregates totals across evals" do
+ workbench.compare(
+ eval_cases: [eval_case],
+ llms: [llm_one, llm_two],
+ persona_variants: [{ key: "default", prompt: nil }],
+ )
+
+ expect(recorder).to have_received(:announce_comparison_expected).with(
+ eval_case_id: "spam_eval",
+ mode_label: "LLMs",
+ persona_key: "default",
+ winner: "LLM One",
+ status_line: "LLM One 🟢 -- LLM Two 🔴",
+ failures: [{ label: "LLM Two", expected: "true", actual: "false" }],
+ )
+ expect(recorder).to have_received(:announce_comparison_aggregate).with(
+ mode_label: "LLMs",
+ persona_key: "default",
+ aggregate_scores: {
+ "LLM One" => {
+ evals: 1,
+ passes: 1,
+ },
+ "LLM Two" => {
+ evals: 1,
+ passes: 0,
+ },
+ },
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/evals/workbench_spec.rb b/plugins/discourse-ai/spec/evals/workbench_spec.rb
index 97608451d90..cd82b4023fe 100644
--- a/plugins/discourse-ai/spec/evals/workbench_spec.rb
+++ b/plugins/discourse-ai/spec/evals/workbench_spec.rb
@@ -54,11 +54,10 @@ RSpec.describe DiscourseAi::Evals::Workbench do
{ raw: "output", raw_entries: ["output"], classified: [{ result: :pass }] },
)
- workbench.run(eval_case: eval_case, llms: [llm])
+ workbench.run(eval_cases: [eval_case], llms: [llm])
expect(DiscourseAi::Evals::Recorder).to have_received(:with_cassette).with(
eval_case,
- persona_key: "default",
output: output,
)
expect(recorder).to have_received(:record_llm_results).with(
@@ -69,30 +68,12 @@ RSpec.describe DiscourseAi::Evals::Workbench do
expect(recorder).to have_received(:finish)
end
- it "yields execution payloads to the provided block" do
- execution_payload = {
- raw: "output",
- raw_entries: ["output"],
- classified: [{ result: :pass }],
- }
- allow(workbench).to receive(:execute_eval).and_return(execution_payload) # rubocop:disable RSpec/SubjectStub
-
- yielded = nil
-
- workbench.run(eval_case: eval_case, llms: [llm]) { |payload| yielded = payload }
-
- expect(yielded[:raw_entries]).to eq(["output"])
- expect(yielded[:classified_entries]).to eq([{ result: :pass }])
- expect(yielded[:llm_name]).to eq("gpt-4")
- expect(yielded[:eval_case]).to eq(eval_case)
- end
-
context "when the eval requires vision but the llm does not support it" do
let(:requires_vision) { true }
let(:llm_supports_vision) { false }
it "skips the llm and records the reason" do
- workbench.run(eval_case: eval_case, llms: [llm])
+ workbench.run(eval_cases: [eval_case], llms: [llm])
expect(recorder).to have_received(:record_llm_skip).with(
"gpt-4",
@@ -107,7 +88,7 @@ RSpec.describe DiscourseAi::Evals::Workbench do
error = DiscourseAi::Evals::Eval::EvalError.new("boom", { foo: "bar" })
allow(workbench).to receive(:execute_eval).and_raise(error) # rubocop:disable RSpec/SubjectStub
- workbench.run(eval_case: eval_case, llms: [llm])
+ workbench.run(eval_cases: [eval_case], llms: [llm])
expect(recorder).to have_received(:record_llm_results).with(
"gpt-4",
@@ -122,7 +103,7 @@ RSpec.describe DiscourseAi::Evals::Workbench do
it "records the failure with the exception message" do
allow(workbench).to receive(:execute_eval).and_raise(StandardError.new("kaboom")) # rubocop:disable RSpec/SubjectStub
- workbench.run(eval_case: eval_case, llms: [llm])
+ workbench.run(eval_cases: [eval_case], llms: [llm])
expect(recorder).to have_received(:record_llm_results).with(
"gpt-4",