A platform for community discussion. Free, open, simple.
FEATURE: Use evals to compare LLMs and Personas' prompts (#36027)
Roman Rizzi3a647c8e50ce
diff --git a/plugins/discourse-ai/README.md b/plugins/discourse-ai/README.mdindex b25e704b750..6af3c42d029 100644--- a/plugins/discourse-ai/README.md+++ b/plugins/discourse-ai/README.md@@ -17,9 +17,15 @@ cd evals```Usage: evals/run [options]-e, --eval NAME Name of the evaluation to run- --list-models List models- -m, --model NAME Model to evaluate (will eval all models if not specified)- -l, --list List evals+ -m, --models NAME Models to evaluate (comma separated, defaults to all)+ -l, --list List eval ids+ --list-models List configured LLMs+ --list-features List feature keys available to evals+ --list-personas List persona definitions under evals/personas+ -f, --feature KEY Filter evals by feature (module_name:feature_name)+ -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)```To run evals you will need to configure API keys in your environment:@@ -27,3 +33,39 @@ To run evals you will need to configure API keys in your environment:OPENAI_API_KEY=your_openai_api_keyANTHROPIC_API_KEY=your_anthropic_api_keyGEMINI_API_KEY=your_gemini_api_key++#### Custom personas for evals++Eval runs can swap the built-in personas with YAML definitions stored in+`plugins/discourse-ai/evals/personas`. Use `--list-personas` to discover available entries; the+special key `default` always refers to the built-in persona prompt. Pass `--persona-keys key1,key2`+(or repeat `--persona-keys key`) to apply them:++```+./run --eval simple_summarization --models gpt-4o-mini --persona-keys topic_summary_eval,another_prompt+```++Each persona file only needs a `system_prompt` (and optional description). When specified, that+prompt replaces the default system prompt of whichever persona the eval runner would normally use.+Pass multiple keys (including `default`) to rerun the same evals with different prompts without+restarting the CLI. Add new files under that directory to compare alternate prompts without touching+the database.++When running persona comparisons (`--compare personas`) the CLI automatically prepends the built-in+`default` persona so you can benchmark your YAML prompts against the stock behavior. Non-comparison+runs still execute only the personas you list.++#### Comparison matrix++Use the `--compare` flag to ask the CLI to judge multiple runs together:++- `--compare personas`: require a single `--models` value and at least one persona key (the+ built-in `default` persona is implicitly added). Each eval is executed for every persona; the+ judge LLM scores them side-by-side and announces the winner plus individual ratings.+- `--compare llms`: require at least two `--models` and exactly one persona (default unless you pass+ `--persona-keys custom_persona`). Every eval runs once and the judge compares the outputs from each+ LLM. Logs include the persona key (or `default`) so you can correlate recordings.++Both modes reuse the rubric declared under the eval’s `judge` block and stream the comparison summary+to STDOUT. The structured log files continue to be written for each underlying run so you can drill+into the raw outputs if the judge’s reasoning needs inspection.diff --git a/plugins/discourse-ai/evals/lib/cli.rb b/plugins/discourse-ai/evals/lib/cli.rbindex 4df20acc534..c8e35db5afc 100644--- a/plugins/discourse-ai/evals/lib/cli.rb+++ b/plugins/discourse-ai/evals/lib/cli.rb@@ -1,57 +1,68 @@# frozen_string_literal: true-require "optparse"+require_relative "features"+require_relative "persona_prompt_loader"class DiscourseAi::Evals::Cli- class Options- attr_accessor :eval_name, :models, :list, :list_models, :list_features, :feature_key-- def initialize(- eval_name: nil,- models: nil,- list: false,- list_models: false,- list_features: false,- feature_key: nil- )- @eval_name = eval_name- @models = models- @list = list- @list_models = list_models- @list_features = list_features- @feature_key = feature_key- end- end+ DEFAULT_JUDGE = "gpt-4o"++ attr_reader :persona_keys++ attr_accessor :eval_name,+ :models,+ :list,+ :list_models,+ :list_features,+ :list_personas,+ :feature_key,+ :judge_name,+ :comparison_modedef self.parse_options!(features_registry)- options = Options.new+ cli = newparser =OptionParser.new do |opts|opts.banner = "Usage: evals/run [options]"opts.on("-e", "--eval NAME", "Name of the evaluation to run") do |eval_name|- options.eval_name = eval_name+ cli.eval_name = eval_nameend- opts.on("--list-models", "List models") { |model| options.list_models = true }- opts.on("--list-features", "List features available for evals") do- options.list_features = true+ opts.on("--list-models", "List models") { cli.list_models = true }+ opts.on("--list-features", "List features available for evals") { cli.list_features = true }+ opts.on("--list-personas", "List persona definitions available to evals") do+ cli.list_personas = trueendopts.on("-m","--models NAME",- "Models to evaluate (will eval all valid models if not specified)",- ) { |models| options.models = models }+ "Models to evaluate (comma separated, defaults to all)",+ ) { |models| cli.models = models }- opts.on("-l", "--list", "List evals") { |model| options.list = true }+ opts.on("-l", "--list", "List evals") { cli.list = true }opts.on("-f","--feature KEY","Feature key to evaluate (module_name:feature_name)",- ) { |key| options.feature_key = key }+ ) { |key| cli.feature_key = key }++ opts.on(+ "-j",+ "--judge NAME",+ "LLM config used to judge eval outputs (defaults to gpt-4o when available)",+ ) { |judge| cli.judge_name = judge }++ opts.on(+ "--persona-keys KEYS",+ "Comma-separated list of persona keys to run sequentially",+ ) { |keys| keys.split(",").each { |key| cli.add_persona_key(key) } }++ opts.on("--compare MODE", "Comparison mode (personas or llms)") do |mode|+ cli.comparison_mode = mode+ endendshow_help = ARGV.empty?@@ -62,13 +73,65 @@ class DiscourseAi::Evals::Cliexit 0end- if options.feature_key && !features_registry.valid_feature_key?(options.feature_key)+ if cli.feature_key && !features_registry.valid_feature_key?(cli.feature_key)STDERR.puts(- "Unknown feature '#{options.feature_key}'. Run with --list-features to view valid keys.",+ "Unknown feature '#{cli.feature_key}'. Run with --list-features to view valid keys.",)exit 1end- options+ if cli.comparison_mode.present?+ normalized = cli.comparison_mode.to_s.downcase.strip+ cli.comparison_mode =+ case normalized+ when "persona", "personas"+ :personas+ when "llms", "models"+ :llms+ else+ STDERR.puts("Unknown comparison mode '#{cli.comparison_mode}'. Use Personas or LLMs.")+ exit 1+ end++ if cli.comparison_mode == :personas+ cli.add_persona_key(DiscourseAi::Evals::PersonaPromptLoader::DEFAULT_PERSONA_KEY)+ end+ end++ cli.judge_name ||= DEFAULT_JUDGE++ cli+ end++ def initialize+ @persona_keys = Set.new+ end++ def judge_provided?+ judge_name.present?+ end++ def add_persona_key(key)+ trimmed = key.to_s.strip+ return if trimmed.empty?++ @persona_keys << trimmed+ end++ def select_evals(available_evals)+ evals = available_evals+ evals = evals.select { |eval_case| eval_case.feature == feature_key } if feature_key.present?+ evals = evals.select { |eval_case| eval_case.id == eval_name } if eval_name.present?++ if evals.empty?+ if feature_key+ puts "Error: No evaluations registered for feature '#{feature_key}'"+ else+ puts "Error: Unknown evaluation '#{eval_name}'"+ end+ exit 1+ end++ evalsendenddiff --git a/plugins/discourse-ai/evals/lib/comparison_runner.rb b/plugins/discourse-ai/evals/lib/comparison_runner.rbnew file mode 100644index 00000000000..760d617a69a--- /dev/null+++ b/plugins/discourse-ai/evals/lib/comparison_runner.rb@@ -0,0 +1,175 @@+# 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+enddiff --git a/plugins/discourse-ai/evals/lib/features.rb b/plugins/discourse-ai/evals/lib/features.rbindex dd08262bce3..e0a6d50b241 100644--- a/plugins/discourse-ai/evals/lib/features.rb+++ b/plugins/discourse-ai/evals/lib/features.rb@@ -37,6 +37,16 @@ module DiscourseAifeature_keys.include?(key)end+ def validate_feature!(feature_key)+ return if feature_key.blank?+ return if valid_feature_key?(feature_key)++ STDERR.puts(+ "Unknown feature '#{feature_key}'. Run with --list-features to view valid keys.",+ )+ exit 1+ end+privateattr_reader :modules, :outputdiff --git a/plugins/discourse-ai/evals/lib/judge.rb b/plugins/discourse-ai/evals/lib/judge.rbnew file mode 100644index 00000000000..f8602fc2e94--- /dev/null+++ b/plugins/discourse-ai/evals/lib/judge.rb@@ -0,0 +1,297 @@+# frozen_string_literal: true++module DiscourseAi+ module Evals+ # Evaluates model outputs using the criteria embedded in the eval.+ #+ # Today it supports the single-output flow that scores one result against a+ # rubric. It encapsulates prompt construction and rating parsing so future+ # comparison judges can reuse the same entry point.+ class Judge+ RESPONSE_FORMAT = {+ type: "json_schema",+ json_schema: {+ name: "judgeVerdict",+ schema: {+ type: "object",+ additionalProperties: false,+ required: %w[rating explanation],+ properties: {+ rating: {+ type: "integer",+ minimum: 1,+ maximum: 10,+ },+ explanation: {+ type: "string",+ },+ },+ },+ },+ }.freeze++ COMPARISON_RESPONSE_FORMAT = {+ type: "json_schema",+ json_schema: {+ name: "judgeComparisonVerdict",+ schema: {+ type: "object",+ additionalProperties: false,+ required: %w[winner winner_explanation ratings],+ properties: {+ winner: {+ type: "string",+ },+ winner_explanation: {+ type: "string",+ },+ ratings: {+ type: "array",+ minItems: 2,+ items: {+ type: "object",+ additionalProperties: false,+ required: %w[candidate rating explanation],+ properties: {+ candidate: {+ type: "string",+ },+ rating: {+ type: "integer",+ minimum: 1,+ maximum: 10,+ },+ explanation: {+ type: "string",+ },+ },+ },+ },+ },+ },+ },+ }.freeze++ def initialize(eval_case:, judge_llm:)+ judge_config = eval_case.judge || {}+ @eval_case = eval_case+ @judge_llm = judge_llm+ @criteria = judge_config[:criteria].presence || judge_config[:prompt].to_s+ @pass_rating = judge_config[:pass_rating] || 10+ end++ def evaluate(result)+ prompt = build_prompt(result)+ response =+ judge_llm.to_llm.generate(+ prompt,+ user: Discourse.system_user,+ temperature: 0,+ response_format: RESPONSE_FORMAT,+ )++ parsed = parse_response(response)+ rating = parsed[:rating]+ explanation = parsed[:explanation]+ raw = parsed[:raw]++ if rating >= pass_rating+ { result: :pass, context: explanation.presence || raw }+ else+ {+ result: :fail,+ message: "LLM Rating below threshold, it was #{rating}, expecting #{pass_rating}",+ context: explanation.presence || raw,+ }+ end+ end++ def compare(candidates)+ prompt = build_comparison_prompt(candidates)+ response =+ judge_llm.to_llm.generate(+ prompt,+ user: Discourse.system_user,+ temperature: 0,+ response_format: COMPARISON_RESPONSE_FORMAT,+ )++ parse_comparison_response(response)+ end++ private++ attr_reader :eval_case, :judge_llm, :criteria, :pass_rating++ def build_prompt(result)+ output_text, metadata = normalize_result(result)+ sections = []+ rubric_text =+ if criteria.present?+ criteria.strip+ else+ "Score the output purely on accuracy, completeness, and adherence to the task instructions."+ end++ sections << "Grading rubric:\n#{rubric_text}"+ sections << "Candidate output:\n#{output_text}"+ sections.concat(metadata)++ sections << prompt_suffix++ DiscourseAi::Completions::Prompt.new(+ "You are an expert judge evaluating LLM outputs.",+ messages: [{ type: :user, content: sections.join("\n\n") }],+ )+ end++ def build_comparison_prompt(candidates)+ sections = []+ rubric_text =+ if criteria.present?+ criteria.strip+ else+ "Score the output purely on accuracy, completeness, and adherence to the task instructions."+ end++ sections << "Grading rubric:\n#{rubric_text}"+ sections.concat(formatted_args)++ candidates.each_with_index do |candidate, index|+ label = candidate[:label].to_s.strip+ label = "candidate #{index + 1}" if label.empty?+ sections << "Candidate #{index + 1} (#{label}):\n#{format_placeholder_value(candidate[:output])}"+ end++ sections << comparison_suffix++ DiscourseAi::Completions::Prompt.new(+ "You are an expert judge evaluating LLM outputs.",+ messages: [{ type: :user, content: sections.join("\n\n") }],+ )+ end++ def normalize_result(result)+ if result.is_a?(String)+ [result, formatted_args]+ elsif result.is_a?(Hash)+ output = result[:result].to_s+ other_metadata =+ result+ .except(:result)+ .map { |key, value| "extra #{key}:\n#{format_placeholder_value(value)}" }+ [output, formatted_args + other_metadata]+ else+ [result.to_s, formatted_args]+ end+ end++ def formatted_args+ args = eval_case.args+ return [] unless args.is_a?(Hash)++ args.map { |key, value| "Source #{key}:\n#{format_placeholder_value(value)}" }+ end++ def format_placeholder_value(value)+ case value+ when Array+ value.join("\n\n")+ else+ value.to_s+ end+ end++ def prompt_suffix+ <<~SUFFIX++ Evaluate the candidate output using the criteria above. Respond with JSON matching:++ {+ "rating": <integer between 1 and 10, where 10 is perfect>,+ "explanation": "brief sentence explaining the score"+ }+ SUFFIX+ end++ def comparison_suffix+ <<~SUFFIX++ Compare every candidate using the rubric above. Respond with JSON that matches:++ {+ "winner": "<candidate label or tie>",+ "winner_explanation": "<brief justification of the decision>",+ "ratings": [+ {+ "candidate": "<candidate label>",+ "rating": <integer between 1 and 10>,+ "explanation": "<short reason describing strengths or issues>"+ }+ ]+ }++ If there is no clear winner, set "winner" to "tie" and explain why.+ SUFFIX+ end++ def parse_response(response)+ rating = explanation = nil++ if response.respond_to?(:read_buffered_property)+ rating = response.read_buffered_property(:rating)+ explanation = response.read_buffered_property(:explanation)+ raw = response.to_s+ else+ raw_text = response.to_s+ begin+ parsed = JSON.parse(raw_text)+ rating = parsed["rating"]+ explanation = parsed["explanation"]+ rescue JSON::ParserError+ # leave rating nil+ end+ raw = raw_text+ end++ { rating: rating.to_i, explanation: explanation.to_s.strip, raw: raw }+ end++ def parse_comparison_response(response)+ raw_text = response.to_s++ parsed =+ begin+ JSON.parse(raw_text)+ rescue JSON::ParserError+ {}+ end++ winner_label = parsed["winner"].to_s.strip+ normalized_winner =+ if winner_label.blank? || winner_label.casecmp("tie").zero?+ nil+ else+ winner_label+ end++ ratings =+ Array(parsed["ratings"]).map do |entry|+ {+ candidate: entry["candidate"].to_s,+ rating: entry["rating"].to_i,+ explanation: entry["explanation"].to_s.strip,+ }+ end++ {+ winner: normalized_winner,+ winner_label: winner_label,+ winner_explanation: parsed["winner_explanation"].to_s.strip,+ ratings: ratings,+ raw: raw_text,+ }+ end+ end+ end+enddiff --git a/plugins/discourse-ai/evals/lib/persona_prompt_loader.rb b/plugins/discourse-ai/evals/lib/persona_prompt_loader.rbnew file mode 100644index 00000000000..bfe29baa0b1--- /dev/null+++ b/plugins/discourse-ai/evals/lib/persona_prompt_loader.rb@@ -0,0 +1,80 @@+# frozen_string_literal: true++require "yaml"++module DiscourseAi+ module Evals+ class PersonaPromptLoader+ DEFAULT_PERSONA_KEY = "default"+ PERSONA_GLOB = File.join(__dir__, "../personas/**/*.yml")++ def list+ entries.map { |entry| [entry[:key], entry[:description]] }+ end++ def find_prompt(key)+ entry = entries.find { |definition| definition[:key] == key }+ entry && entry[:system_prompt]+ end++ def entries+ @entries ||= Dir.glob(PERSONA_GLOB).sort.map { |path| load_entry(path) }.compact+ end++ def variants_for(keys, comparison_mode: nil)+ keys_array = Array(keys)+ variants = []++ if keys_array.empty? || comparison_mode == :personas+ variants << { key: DEFAULT_PERSONA_KEY, prompt: nil }+ end++ keys_array.each do |key|+ next if key == DEFAULT_PERSONA_KEY++ prompt = find_prompt(key)+ if prompt.to_s.strip.empty?+ puts "Error: Unknown persona key '#{key}'. Run --list-personas to view options."+ exit 1+ end++ variants << { key: key, prompt: prompt }+ end++ variants+ end++ def print(output: $stdout)+ output.puts("#{DEFAULT_PERSONA_KEY}: built-in persona prompt")+ list.each do |key, description|+ if description && !description.empty?+ output.puts("#{key}: #{description}")+ else+ output.puts(key)+ end+ end+ end++ def load_entry(path)+ yaml = YAML.load_file(path) || {}++ key = yaml["key"]+ key = File.basename(path, ".yml") if key.nil? || key.to_s.strip.empty?+ return nil if key.nil?++ system_prompt = yaml["system_prompt"]+ system_prompt = system_prompt.to_s+ return nil if system_prompt.strip.empty?++ description = yaml["description"]+ description = description.to_s.strip+ description = nil if description.empty?++ { key: key.to_s.strip, system_prompt: system_prompt, description: description }+ rescue Psych::SyntaxError => e+ warn "Warning: failed to load persona prompt from #{path}: #{e.message}"+ nil+ end+ end+ end+enddiff --git a/plugins/discourse-ai/evals/lib/recorder.rb b/plugins/discourse-ai/evals/lib/recorder.rbindex 6876bfb581a..4b1475169d2 100644--- a/plugins/discourse-ai/evals/lib/recorder.rb+++ b/plugins/discourse-ai/evals/lib/recorder.rb@@ -7,13 +7,16 @@ require_relative "structured_logger"module DiscourseAimodule Evalsclass Recorder- def self.with_cassette(an_eval, output: $stdout)+ def self.with_cassette(an_eval, persona_key: nil, output: $stdout)logs_dir = File.join(__dir__, "../log")FileUtils.mkdir_p(logs_dir)now = Time.now.strftime("%Y%m%d-%H%M%S")- structured_log_filename = "#{an_eval.id}-#{now}.json"- log_filename = "#{an_eval.id}-#{now}.log"+ normalized_key = normalize_persona_key(persona_key)+ persona_segment = sanitized_persona_key(normalized_key)+ base_filename = [an_eval.id, persona_segment, now].compact.join("-")+ structured_log_filename = "#{base_filename}.json"+ log_filename = "#{base_filename}.log"log_path = File.expand_path(File.join(logs_dir, log_filename))structured_log_path = File.expand_path(File.join(logs_dir, structured_log_filename))@@ -21,23 +24,33 @@ module DiscourseAilogger = Logger.new(File.open(log_path, "a"))structured_logger = StructuredLogger.new(structured_log_path)- new(an_eval, logger, log_path, structured_logger, output: output).tap do |recorder|- recorder.running- end+ new(+ an_eval,+ logger,+ log_path,+ structured_logger,+ persona_key: normalized_key,+ output: output,+ ).tap { |recorder| recorder.running }end- def initialize(an_eval, logger, log_path, structured_logger, output: $stdout)+ def initialize(an_eval, logger, log_path, structured_logger, persona_key:, output: $stdout)@an_eval = an_eval@logger = logger@log_path = log_path@structured_logger = structured_logger@output = output+ normalized = persona_key.to_s.strip+ @persona_key = normalized.empty? ? "default" : normalizedenddef runningattach_thread_loggers- logger.info("Starting evaluation '#{an_eval.id}'")- structured_logger.start_root(name: "Evaluating #{an_eval.id}", args: an_eval.to_json)+ logger.info("Starting evaluation '#{an_eval.id}' (persona: #{persona_key})")+ structured_logger.start_root(+ name: "Evaluating #{an_eval.id} (persona: #{persona_key})",+ args: an_eval.to_json.merge(persona_key: persona_key),+ )enddef record_llm_skip(llm_name, reason)@@ -105,7 +118,21 @@ module DiscourseAiprivate- attr_reader :an_eval, :logger, :structured_logger, :output, :log_path+ attr_reader :an_eval, :logger, :structured_logger, :output, :log_path, :persona_key++ def self.normalize_persona_key(key)+ stripped = key.to_s.strip+ stripped = "default" if stripped.empty?+ stripped+ end++ def self.sanitized_persona_key(key)+ stripped = key.to_s.strip+ stripped = "default" if stripped.empty?++ slug = stripped.gsub(/[^a-zA-Z0-9]+/, "-").gsub(/-+/, "-").gsub(/^-|-$/, "")+ slug.empty? ? "default" : slug.downcase+ enddef attach_thread_loggers@previous_thread_loggers = {diff --git a/plugins/discourse-ai/evals/lib/runners/ai_helper.rb b/plugins/discourse-ai/evals/lib/runners/ai_helper.rbindex 0b168ee3483..0556157991d 100644--- a/plugins/discourse-ai/evals/lib/runners/ai_helper.rb+++ b/plugins/discourse-ai/evals/lib/runners/ai_helper.rb@@ -27,12 +27,12 @@ module DiscourseAifeature_name&.start_with?("ai_helper:")end- def initialize(helper_mode)- @helper_mode = helper_mode+ def initialize(feature_name, persona_prompt_override = nil)@persona_class =- PERSONA_MAP.fetch(helper_mode) do- raise ArgumentError, "Unsupported AI Helper mode '#{helper_mode}'"+ PERSONA_MAP.fetch(feature_name) do+ raise ArgumentError, "Unsupported AI Helper mode '#{feature_name}'"end+ super(feature_name, persona_prompt_override)enddef run(eval_case, llm)@@ -49,12 +49,12 @@ module DiscourseAi)formatted = format_response(response)- wrap_result(formatted, { helper_mode: helper_mode })+ wrap_result(formatted, { feature_name: feature_name })endprivate- attr_reader :helper_mode, :persona_class+ attr_reader :feature_name, :persona_classdef build_user(locale)return Discourse.system_user if locale.blank?@@ -72,9 +72,9 @@ module DiscourseAiDiscourseAi::Personas::BotContext.new(user: user,skip_show_thinking: true,- feature_name: "ai_helper:#{helper_mode}",+ feature_name: "ai_helper:#{feature_name}",messages: [{ type: :user, content: user_input }],- format_dates: helper_mode == "smart_dates",+ format_dates: feature_name == "smart_dates",custom_instructions: custom_locale_instructions(user, force_default_locale),)context = attach_user_context(context, user, force_default_locale: force_default_locale)@@ -83,7 +83,7 @@ module DiscourseAienddef build_user_input(input, custom_prompt)- if helper_mode == "custom_prompt" && custom_prompt.present?+ if feature_name == "custom_prompt" && custom_prompt.present?return "<input>#{custom_prompt}:\n#{input}</input>"enddiff --git a/plugins/discourse-ai/evals/lib/runners/base.rb b/plugins/discourse-ai/evals/lib/runners/base.rbindex 60e64c43829..dc026467b9a 100644--- a/plugins/discourse-ai/evals/lib/runners/base.rb+++ b/plugins/discourse-ai/evals/lib/runners/base.rb@@ -9,7 +9,7 @@ module DiscourseAiraise NotImplementedend- def find_runner(feature)+ def find_runner(feature, persona_prompt)registry = [DiscourseAi::Evals::Runners::AiHelper,DiscourseAi::Evals::Runners::Translation,@@ -20,30 +20,32 @@ module DiscourseAiDiscourseAi::Evals::Runners::Inference,]klass = registry.find { |runner| runner.can_handle?(feature) }- klass&.new(feature.split(":").last) if klass+ klass&.new(feature.split(":").last, persona_prompt) if klassendend- attr_reader :feature+ attr_reader :feature_name, :persona_prompt_override- def initialize(feature)- @feature = feature+ def initialize(feature, persona_prompt_override = nil)+ @feature_name = feature+ @persona_prompt_override = persona_prompt_overrideendprivatedef resolve_persona(persona_class: nil)- persona_id ||=- DiscourseAi::Personas::Persona.system_personas[persona_class] if persona_class- persona_record = persona_id && AiPersona.find_by_id_from_cache(persona_id)+ if persona_class.nil?+ raise ArgumentError, "Unable to resolve persona for runner (#{self.class.name})"+ end- persona_klass = persona_record&.class_instance || persona_class+ persona = persona_class.new- if persona_klass.nil?- raise ArgumentError, "Unable to resolve persona for runner (#{self.class.name})"+ if persona_prompt_override.present?+ override = persona_prompt_override+ persona.define_singleton_method(:system_prompt) { override }end- persona_klass.new+ personaenddef capture_plain_response(bot, context)diff --git a/plugins/discourse-ai/evals/lib/runners/discoveries.rb b/plugins/discourse-ai/evals/lib/runners/discoveries.rbindex c51e2e6b62d..6a43bdef96b 100644--- a/plugins/discourse-ai/evals/lib/runners/discoveries.rb+++ b/plugins/discourse-ai/evals/lib/runners/discoveries.rb@@ -10,9 +10,6 @@ module DiscourseAifeature_name&.start_with?("search:discoveries")end- def initialize(_operation)- end-def run(eval_case, llm)args = normalize_args(eval_case.args)case_defs = Array(args.delete(:cases)).presencediff --git a/plugins/discourse-ai/evals/lib/runners/hyde.rb b/plugins/discourse-ai/evals/lib/runners/hyde.rbindex 96cf667f335..32b52b2b5c4 100644--- a/plugins/discourse-ai/evals/lib/runners/hyde.rb+++ b/plugins/discourse-ai/evals/lib/runners/hyde.rb@@ -10,10 +10,6 @@ module DiscourseAifeature_name&.start_with?("embeddings:hyde")end- def initialize(operation)- @operation = operation- end-def run(eval_case, llm)args = normalize_args(eval_case.args)case_defs = Array(args.delete(:cases)).presence@@ -27,8 +23,6 @@ module DiscourseAiprivate- attr_reader :operation-def run_case(case_args, llm)query = case_args[:query].presence || case_args[:input].presenceraise ArgumentError, "HyDE evals require :query or :input" if query.blank?diff --git a/plugins/discourse-ai/evals/lib/runners/inference.rb b/plugins/discourse-ai/evals/lib/runners/inference.rbindex 61f514a18fa..261a8ccb98c 100644--- a/plugins/discourse-ai/evals/lib/runners/inference.rb+++ b/plugins/discourse-ai/evals/lib/runners/inference.rb@@ -28,15 +28,11 @@ module DiscourseAifeature_name&.start_with?("inference:")end- def initialize(feature)- @operation = feature- end-def run(eval_case, llm)args = eval_case.args || {}response =- case operation+ case feature_namewhen "generate_concepts"generate_concepts(args, llm)when "match_concepts"@@ -44,7 +40,7 @@ module DiscourseAiwhen "deduplicate_concepts"deduplicate_concepts(args, llm)else- raise ArgumentError, "Unsupported inference feature '#{operation}'"+ raise ArgumentError, "Unsupported inference feature '#{feature_name}'"endresponse@@ -52,20 +48,18 @@ module DiscourseAiprivate- attr_reader :operation-def generate_concepts(args, llm)content = conversation_to_text(args)raise ArgumentError, "Missing input for generate concepts eval" if content.blank?- persona, user = persona_bundle(operation)+ persona, user = persona_bundle(feature_name)context =build_ctx.tap do |ctx|ctx.messages = [{ type: :user, content: content }]ctx.inferred_concepts = args[:existing_concepts] || []end- values = capture_structured_output(persona, user, llm, context, operation)+ values = capture_structured_output(persona, user, llm, context, feature_name)wrap_result(format_response(values), { query: content })end@@ -76,7 +70,7 @@ module DiscourseAiraise ArgumentError, "Match concepts eval requires :input/:conversation and :concepts"end- persona, user = persona_bundle(operation)+ persona, user = persona_bundle(feature_name)context =build_ctx.tap do |ctx|@@ -84,7 +78,7 @@ module DiscourseAictx.inferred_concepts = candidatesend- values = capture_structured_output(persona, user, llm, context, operation)+ values = capture_structured_output(persona, user, llm, context, feature_name)wrap_result(format_response(values), { query: content, concepts: candidates })end@@ -92,12 +86,12 @@ module DiscourseAicandidates = args[:concepts].to_a.map(&:to_s)raise ArgumentError, "Deduplicate concepts eval requires :concepts" if candidates.empty?- persona, user = persona_bundle(operation)+ persona, user = persona_bundle(feature_name)context =build_ctx.tap { |ctx| ctx.messages = [{ type: :user, content: candidates.join(", ") }] }- values = capture_structured_output(persona, user, llm, context, operation)+ values = capture_structured_output(persona, user, llm, context, feature_name)wrap_result(format_response(values), { concepts: candidates })end@@ -142,7 +136,7 @@ module DiscourseAiDiscourseAi::Personas::BotContext.new(user: Discourse.system_user,skip_show_thinking: true,- feature_name: "evals/inference/#{operation}",+ feature_name: "evals/inference/#{feature_name}",)endenddiff --git a/plugins/discourse-ai/evals/lib/runners/spam.rb b/plugins/discourse-ai/evals/lib/runners/spam.rbindex 213728cf457..5f24291af15 100644--- a/plugins/discourse-ai/evals/lib/runners/spam.rb+++ b/plugins/discourse-ai/evals/lib/runners/spam.rb@@ -10,10 +10,6 @@ module DiscourseAifull_feature_name&.start_with?("spam:")end- def initialize(feature_name)- @feature_name = feature_name- end-def run(eval_case, llm)args = eval_case.argspersona = resolve_persona(persona_class: DiscourseAi::Personas::SpamDetector)@@ -40,8 +36,6 @@ module DiscourseAiprivate- attr_reader :feature_name-def capture_verdict(persona, user, llm, context)bot = DiscourseAi::Personas::Bot.as(user, persona: persona, model: llm)schema = persona.response_format&.firstdiff --git a/plugins/discourse-ai/evals/lib/runners/summarization.rb b/plugins/discourse-ai/evals/lib/runners/summarization.rbindex 9c5ad08512f..a2e0baf1747 100644--- a/plugins/discourse-ai/evals/lib/runners/summarization.rb+++ b/plugins/discourse-ai/evals/lib/runners/summarization.rb@@ -10,10 +10,6 @@ module DiscourseAifull_feature_name&.start_with?("summarization:")end- def initialize(feature_name)- @feature_name = feature_name- end-def run(eval_case, llm)args = eval_case.argsconversation = extract_conversation(args)@@ -32,7 +28,7 @@ module DiscourseAiendpersona_class, strategy = persona_and_strategy(topic)- persona, = resolve_persona(persona_class: persona_class)+ persona = resolve_persona(persona_class: persona_class)context =DiscourseAi::Personas::BotContext.new(@@ -50,8 +46,6 @@ module DiscourseAiprivate- attr_reader :feature_name-def persona_and_strategy(topic)if regular_summaries?[diff --git a/plugins/discourse-ai/evals/lib/workbench.rb b/plugins/discourse-ai/evals/lib/workbench.rbindex 8d1d7b95c50..dd356186427 100644--- a/plugins/discourse-ai/evals/lib/workbench.rb+++ b/plugins/discourse-ai/evals/lib/workbench.rb@@ -11,6 +11,7 @@ require_relative "runners/discoveries"require_relative "runners/inference"require_relative "runners/spam"require_relative "runners/summarization"+require_relative "judge"module DiscourseAimodule Evals@@ -22,8 +23,12 @@ module DiscourseAi# keeps higher-level scripts (`evals/run`) simple while centralizing# instrumentation and error handling.class Workbench- def initialize(output: $stdout)+ def initialize(output: $stdout, judge_llm: nil, persona_prompt: nil, persona_label: "default")@output = output+ @judge_llm = judge_llm+ @persona_prompt = persona_prompt+ label = persona_label.to_s.strip+ @persona_label = label.empty? ? "default" : labelend# Iterate through the provided LLM adapters and execute the eval case for@@ -31,8 +36,8 @@ module DiscourseAi## @param eval_case [DiscourseAi::Evals::Eval] the scenario to run.# @param llms [Array<LlmModel>] LLMs selected by the CLI.- def run(eval_case:, llms:)- recorder = Recorder.with_cassette(eval_case, output: output)+ 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@@ -43,8 +48,18 @@ module DiscourseAinextend- results = execute_eval(eval_case, llm)- recorder.record_llm_results(llm_name, results, start_time)+ 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],+ )+ endrescue DiscourseAi::Evals::Eval::EvalError => erecorder.record_llm_results(llm_name,@@ -78,20 +93,24 @@ module DiscourseAiraise ArgumentError, "Unsupported eval feature '#{feature}'"end- classify_results(eval_case, raw)+ entries = normalize_entries(raw)++ { raw: raw, raw_entries: entries, classified: classify_results(eval_case, entries) }endprivate- attr_reader :output+ attr_reader :output, :judge_llm, :persona_prompt, :persona_labeldef find_runner(feature)- DiscourseAi::Evals::Runners::Base.find_runner(feature)+ DiscourseAi::Evals::Runners::Base.find_runner(feature, persona_prompt)end- def classify_results(eval_case, result)- entries = result.is_a?(Array) ? result : [result]+ def normalize_entries(raw)+ raw.is_a?(Array) ? raw : [raw]+ end+ def classify_results(eval_case, entries)entries.map do |entry|raw_value = entry.is_a?(Hash) && entry.key?(:raw) ? entry[:raw] : entrymetadata = entry.is_a?(Hash) ? entry[:metadata] : nil@@ -146,56 +165,14 @@ module DiscourseAienddef judge_result(eval_case, result)- prompt = eval_case.judge[:prompt].dup-- if result.is_a?(String)- prompt.sub!("{{output}}", result)- eval_case.args.each do |key, value|- prompt.sub!("{{#{key}}}", format_placeholder_value(value))- end- else- prompt.sub!("{{output}}", result[:result])- result.each { |key, value| prompt.sub!("{{#{key}}}", value.to_s) }+ if judge_llm.nil?+ raise DiscourseAi::Evals::Eval::EvalError.new(+ "Evaluation '#{eval_case.id}' requires the --judge option to specify an LLM.",+ { eval_id: eval_case.id },+ )end- prompt += <<~SUFFIX-- Reply with a rating from 1 to 10, where 10 is perfect and 1 is terrible.-- example output:-- [RATING]10[/RATING] perfect output-- example output:-- [RATING]5[/RATING]-- the following failed to preserve... etc...- SUFFIX-- judge_llm = DiscourseAi::Evals::LlmRepository.new.hydrate(eval_case.judge[:llm])-- DiscourseAi::Completions::Prompt.new(- "You are an expert judge tasked at testing LLM outputs.",- messages: [{ type: :user, content: prompt }],- )-- judge_result =- judge_llm.to_llm.generate(prompt, user: Discourse.system_user, temperature: 0)-- rating_match = judge_result.match(%r{\[RATING\](\d+)\[/RATING\]})- rating = rating_match ? rating_match[1].to_i : 0-- if rating >= eval_case.judge[:pass_rating]- { result: :pass }- else- {- result: :fail,- message:- "LLM Rating below threshold, it was #{rating}, expecting #{eval_case.judge[:pass_rating]}",- context: judge_result,- }- end+ DiscourseAi::Evals::Judge.new(eval_case: eval_case, judge_llm: judge_llm).evaluate(result)end# Extract text from an image upload by delegating to the ImageToText helper.@@ -321,15 +298,6 @@ module DiscourseAirescue StandardErrorfalseend-- def format_placeholder_value(value)- case value- when Array- value.join("\n\n")- else- value.to_s- end- endendendenddiff --git a/plugins/discourse-ai/evals/personas/topic_summary_eval.yml b/plugins/discourse-ai/evals/personas/topic_summary_eval.ymlnew file mode 100644index 00000000000..30a5e7b5135--- /dev/null+++ b/plugins/discourse-ai/evals/personas/topic_summary_eval.yml@@ -0,0 +1,17 @@+key: topic_summary_eval+description: Variant of the built-in summarizer persona tuned for eval comparisons+system_prompt: |+ You are an AI specialized in summarizing Discourse forum topics for busy staff members.+ Produce a single paragraph that highlights the most important actions, open questions,+ and decisions mentioned in the conversation you receive.++ Requirements:+ - Stay under 250 words.+ - Preserve the original language of the posts.+ - When referencing noteworthy posts, cite them using Markdown links in the format+ [short description]({resource_url}/POST_NUMBER).+ - Do not repeat the original wording verbatim; synthesize the intent.+ - Omit greetings, sign-offs, and any meta commentary about the task.++ Respond with JSON matching the schema below:+ {"summary": "<text>"}diff --git a/plugins/discourse-ai/evals/run b/plugins/discourse-ai/evals/runold mode 100755new mode 100644index 7f9111bd0a4..aa4b7efabbc--- a/plugins/discourse-ai/evals/run+++ b/plugins/discourse-ai/evals/run@@ -9,57 +9,122 @@ require_relative "lib/prompts/single_test_runner"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 =DiscourseAi::Evals::Features.new(modules: DiscourseAi::Configuration::Module.all)-playground = DiscourseAi::Evals::Workbench.new(output: $stdout)--options = DiscourseAi::Evals::Cli.parse_options!(features_registry)+cli = DiscourseAi::Evals::Cli.parse_options!(features_registry)llm_repository = DiscourseAi::Evals::LlmRepository.new-if options.list_models+if cli.list_modelsllm_repository.printexit 0end-if options.list_features+if cli.list_featuresfeatures_registry.printexit 0end+persona_loader = DiscourseAi::Evals::PersonaPromptLoader.new++if cli.list_personas+ persona_loader.print+ exit 0+end+available_evals = DiscourseAi::Evals::Eval.available_cases-if options.list+if cli.listavailable_evals.each(&:print)exit 0end-llms = llm_repository.choose(options.models)+llms = llm_repository.choose(cli.models)if llms.empty?- puts "Error: Unknown models '#{options.models}'"+ puts "Error: Unknown models '#{cli.models}'"exit 1end-selected_evals = available_evals-selected_evals =- selected_evals.select do |eval_case|- eval_case.feature == options.feature_key- end if options.feature_key.present?-selected_evals =- selected_evals.select do |eval_case|- eval_case.id == options.eval_name- end if options.eval_name.present?--if selected_evals.empty?- if options.feature_key- puts "Error: No evaluations registered for feature '#{options.feature_key}'"+selected_evals = cli.select_evals(available_evals)++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++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? }++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_errorelse- puts "Error: Unknown evaluation '#{options.eval_name}'"+ message += " Pass --judge with an LLM config name."end+ puts messageexit 1end-selected_evals.each { |eval_case| playground.run(eval_case: eval_case, llms: llms) }+if cli.comparison_mode+ 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+ 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++ puts "\n=== Persona: #{label} ==="+ end++ 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++ playground.run(eval_case: eval_case, llms: llms)+ end+enddiff --git a/plugins/discourse-ai/lib/completions/endpoints/canned_response.rb b/plugins/discourse-ai/lib/completions/endpoints/canned_response.rbindex f64bb3b7f52..2ed892552fc 100644--- a/plugins/discourse-ai/lib/completions/endpoints/canned_response.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/canned_response.rb@@ -44,33 +44,24 @@ module DiscourseAiraise response if response.is_a?(StandardError)@completions += 1+ response_enum = response.is_a?(Array) ? response : [response]if block_given?cancelled = falsecancel_fn = lambda { cancelled = true }- # We buffer and return tool invocations in one go.- as_array = response.is_a?(Array) ? response : [response]- as_array.each do |_response|- if is_tool?(_response)- yield(_response, cancel_fn)- elsif is_thinking?(_response)- yield(_response, cancel_fn)- elsif model_params[:response_format].present?- structured_output = as_structured_output(_response)- yield(structured_output, cancel_fn)- else- _response.each_char do |char|- break if cancelled- yield(char, cancel_fn)- end- end+ response_enum.each do |chunk|+ handle_response_chunk(chunk, cancel_fn) { |val| yield(val, cancel_fn) if !cancelled }endend- response = response.first if response.is_a?(Array) && response.length == 1- response = as_structured_output(response) if model_params[:response_format].present?+ final_response =+ if model_params[:response_format].present?+ aggregate_structured_response(response_enum)+ else+ response_enum.length == 1 ? response_enum.first : response_enum+ end- response+ final_responseenddef tokenizer@@ -79,6 +70,44 @@ module DiscourseAiprivate+ def handle_response_chunk(chunk, cancel_fn)+ if is_tool?(chunk)+ yield chunk+ elsif is_thinking?(chunk)+ yield chunk+ elsif model_params[:response_format].present?+ structured =+ (+ if chunk.is_a?(DiscourseAi::Completions::StructuredOutput)+ chunk+ else+ as_structured_output(chunk)+ end+ )+ yield structured+ else+ chunk.to_s.each_char { |char| yield char }+ end+ end++ def aggregate_structured_response(response_enum)+ schema_properties = model_params[:response_format].dig(:json_schema, :schema, :properties)+ output = DiscourseAi::Completions::StructuredOutput.new(schema_properties)++ response_enum.each do |chunk|+ structured =+ if chunk.is_a?(DiscourseAi::Completions::StructuredOutput)+ chunk+ else+ as_structured_output(chunk)+ end+ output << structured.to_s+ end++ output.finish+ output+ end+def is_thinking?(response)response.is_a?(DiscourseAi::Completions::Thinking)end@@ -91,11 +120,40 @@ module DiscourseAischema_properties = model_params[:response_format].dig(:json_schema, :schema, :properties)return response if schema_properties.blank?+ parsed = parse_structured_response(response)++ payload =+ if parsed.is_a?(Hash)+ parsed = parsed.stringify_keys+ schema_properties+ .keys+ .each_with_object({}) do |key, memo|+ string_key = key.to_s+ memo[key] = parsed[string_key] if parsed.key?(string_key)+ end+ else+ { schema_properties.keys.first => response }+ end+output = DiscourseAi::Completions::StructuredOutput.new(schema_properties)- output << { schema_properties.keys.first => response }.to_json+ output << payload.to_json+ output.finishoutputend++ def parse_structured_response(response)+ case response+ when Hash+ response+ when String+ JSON.parse(response)+ else+ nil+ end+ rescue JSON::ParserError+ nil+ endendendenddiff --git a/plugins/discourse-ai/lib/completions/json_streaming_tracker.rb b/plugins/discourse-ai/lib/completions/json_streaming_tracker.rbindex 21cd6b2ffee..b4de6424fa6 100644--- a/plugins/discourse-ai/lib/completions/json_streaming_tracker.rb+++ b/plugins/discourse-ai/lib/completions/json_streaming_tracker.rb@@ -40,7 +40,7 @@ module DiscourseAi@parser.start_array donext if @broken- next unless @current_key+ next if !@current_key@tracking_array = true@current_value = []diff --git a/plugins/discourse-ai/spec/evals/comparison_runner_spec.rb b/plugins/discourse-ai/spec/evals/comparison_runner_spec.rbnew file mode 100644index 00000000000..ce491328687--- /dev/null+++ b/plugins/discourse-ai/spec/evals/comparison_runner_spec.rb@@ -0,0 +1,163 @@+# 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+enddiff --git a/plugins/discourse-ai/spec/evals/judge_spec.rb b/plugins/discourse-ai/spec/evals/judge_spec.rbnew file mode 100644index 00000000000..7ed718e7a49--- /dev/null+++ b/plugins/discourse-ai/spec/evals/judge_spec.rb@@ -0,0 +1,82 @@+# frozen_string_literal: true++require_relative "../../evals/lib/judge"+require_relative "../../evals/lib/eval"++RSpec.describe DiscourseAi::Evals::Judge do+ subject(:judge) { described_class.new(eval_case: eval_case, judge_llm: judge_llm) }++ let(:eval_case) do+ instance_double(+ DiscourseAi::Evals::Eval,+ id: "example",+ args: {+ input: "Source text",+ },+ judge: {+ criteria: "Score the candidate output based on how well it explains the input.",+ pass_rating: 7,+ },+ )+ end++ let(:llm_proxy) { instance_spy(DiscourseAi::Completions::Llm) }+ let(:judge_llm) { instance_double(LlmModel, to_llm: llm_proxy) }+ let(:judge_response) { { "rating" => 8, "explanation" => "Looks good" }.to_json }++ before { allow(llm_proxy).to receive(:generate).and_return(judge_response) }++ it "returns a passing result when the rating meets the threshold" do+ expect(judge.evaluate("great output")[:result]).to eq(:pass)+ end++ it "returns a failing result when the rating is below the threshold" do+ allow(llm_proxy).to receive(:generate).and_return(+ { "rating" => 5, "explanation" => "bad" }.to_json,+ )++ result = judge.evaluate("bad output")++ expect(result[:result]).to eq(:fail)+ expect(result[:message]).to include("below threshold")+ end++ it "substitutes placeholders from hash results" do+ judge.evaluate({ result: "hash-output" })++ expect(llm_proxy).to have_received(:generate).with(+ satisfy { |prompt| prompt.messages.any? { |msg| msg[:content].include?("hash-output") } },+ user: Discourse.system_user,+ temperature: 0,+ response_format: DiscourseAi::Evals::Judge::RESPONSE_FORMAT,+ )+ end++ describe "#compare" do+ it "requests a structured comparison and returns parsed ratings" do+ comparison_payload = {+ "winner" => "default",+ "winner_explanation" => "more accurate",+ "ratings" => [+ { "candidate" => "default", "rating" => 9, "explanation" => "complete" },+ { "candidate" => "custom", "rating" => 6, "explanation" => "missed details" },+ ],+ }.to_json++ allow(llm_proxy).to receive(:generate).and_return(comparison_payload)++ result = judge.compare([{ label: "default", output: "A" }, { label: "custom", output: "B" }])++ expect(llm_proxy).to have_received(:generate).with(+ satisfy do |prompt|+ prompt.messages.any? { |msg| msg[:content].include?("Candidate 2 (custom):") }+ end,+ user: Discourse.system_user,+ temperature: 0,+ response_format: DiscourseAi::Evals::Judge::COMPARISON_RESPONSE_FORMAT,+ )+ expect(result[:winner]).to eq("default")+ expect(result[:ratings].map { |entry| entry[:candidate] }).to match_array(%w[default custom])+ end+ end+enddiff --git a/plugins/discourse-ai/spec/evals/persona_prompt_loader_spec.rb b/plugins/discourse-ai/spec/evals/persona_prompt_loader_spec.rbnew file mode 100644index 00000000000..b9794976ec6--- /dev/null+++ b/plugins/discourse-ai/spec/evals/persona_prompt_loader_spec.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++require_relative "../../evals/lib/persona_prompt_loader"++RSpec.describe DiscourseAi::Evals::PersonaPromptLoader do+ subject(:loader) { described_class.new }++ let(:tmpdir) { Dir.mktmpdir }+ let(:yaml_path) { File.join(tmpdir, "custom.yml") }++ before do+ File.write(yaml_path, <<~YAML)+ key: custom_eval_persona+ description: Custom prompt for evals+ system_prompt: "Always summarize in one sentence."+ YAML++ allow(Dir).to receive(:glob).and_return([yaml_path])+ end++ after { FileUtils.remove_entry(tmpdir) }++ it "lists persona keys" do+ expect(loader.list).to eq([["custom_eval_persona", "Custom prompt for evals"]])+ end++ it "returns the system prompt for a key" do+ expect(loader.find_prompt("custom_eval_persona")).to eq("Always summarize in one sentence.")+ end++ it "returns nil when the key is missing" do+ expect(loader.find_prompt("missing")).to be_nil+ end+enddiff --git a/plugins/discourse-ai/spec/evals/recorder_spec.rb b/plugins/discourse-ai/spec/evals/recorder_spec.rbindex 8a96c9bd30a..efa357cf263 100644--- a/plugins/discourse-ai/spec/evals/recorder_spec.rb+++ b/plugins/discourse-ai/spec/evals/recorder_spec.rb@@ -6,13 +6,21 @@ require_relative "../../evals/lib/eval"RSpec.describe DiscourseAi::Evals::Recorder dosubject(:recorder) do- described_class.new(eval_case, logger, "/tmp/example.json", structured_logger, output: output)+ described_class.new(+ eval_case,+ logger,+ "/tmp/example.json",+ structured_logger,+ persona_key: persona_key,+ output: output,+ )endlet(:eval_case) doinstance_double("DiscourseAi::Evals::Eval", id: "example-eval", to_json: { foo: "bar" })endlet(:logger) { instance_double(Logger, info: nil, error: nil) }+ let(:persona_key) { "default" }let(:structured_logger) doinstance_double(DiscourseAi::Evals::StructuredLogger,@@ -39,12 +47,15 @@ RSpec.describe DiscourseAi::Evals::Recorder dorecorder.runningexpect(structured_logger).to have_received(:start_root).with(- name: "Evaluating example-eval",+ name: "Evaluating example-eval (persona: default)",args: {foo: "bar",+ persona_key: "default",},)- expect(logger).to have_received(:info).with("Starting evaluation 'example-eval'")+ expect(logger).to have_received(:info).with(+ "Starting evaluation 'example-eval' (persona: default)",+ )endenddiff --git a/plugins/discourse-ai/spec/evals/runners/ai_helper_spec.rb b/plugins/discourse-ai/spec/evals/runners/ai_helper_spec.rbindex 4cbdeeccfc0..64e53468c48 100644--- a/plugins/discourse-ai/spec/evals/runners/ai_helper_spec.rb+++ b/plugins/discourse-ai/spec/evals/runners/ai_helper_spec.rb@@ -26,7 +26,7 @@ RSpec.describe DiscourseAi::Evals::Runners::AiHelper dolines = result[:raw].split("\n")expect(lines).to contain_exactly("Title One", "Title Two ignored")- expect(result[:metadata]).to include(helper_mode: "title_suggestions")+ expect(result[:metadata]).to include(feature_name: "title_suggestions")endendenddiff --git a/plugins/discourse-ai/spec/evals/workbench_spec.rb b/plugins/discourse-ai/spec/evals/workbench_spec.rbindex 5a354f2b289..97608451d90 100644--- a/plugins/discourse-ai/spec/evals/workbench_spec.rb+++ b/plugins/discourse-ai/spec/evals/workbench_spec.rb@@ -49,12 +49,16 @@ RSpec.describe DiscourseAi::Evals::Workbench dodescribe "#run" doit "records results for each llm" do- allow(workbench).to receive(:execute_eval).and_return([{ result: :pass }]) # rubocop:disable RSpec/SubjectStub+ # rubocop:disable RSpec/SubjectStub+ allow(workbench).to receive(:execute_eval).and_return(+ { raw: "output", raw_entries: ["output"], classified: [{ result: :pass }] },+ )workbench.run(eval_case: 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(@@ -65,6 +69,24 @@ RSpec.describe DiscourseAi::Evals::Workbench doexpect(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" dolet(:requires_vision) { true }let(:llm_supports_vision) { false }@@ -143,7 +165,7 @@ RSpec.describe DiscourseAi::Evals::Workbench doworkbench.execute_eval(eval_case, llm)end- expect(results.first[:result]).to eq(:pass)+ expect(results[:classified].first[:result]).to eq(:pass)endit "flags spam posts via the spam inspection eval feature" do@@ -166,7 +188,7 @@ RSpec.describe DiscourseAi::Evals::Workbench doworkbench.execute_eval(eval_case, llm)end- expect(results.first[:result]).to eq(:pass)+ expect(results[:classified].first[:result]).to eq(:pass)endend@@ -193,4 +215,55 @@ RSpec.describe DiscourseAi::Evals::Workbench dopersona.save!(validate: false)endend++ describe "#judge_result" do+ let(:judge_eval_case) do+ OpenStruct.new(+ id: "judge-eval",+ args: {+ input: "Source content",+ },+ judge: {+ criteria: "Score the output against the provided input, rewarding accuracy and clarity.",+ pass_rating: 7,+ },+ )+ end++ it "raises a helpful error when no judge llm is configured" do+ expect { workbench.send(:judge_result, judge_eval_case, "answer") }.to raise_error(+ DiscourseAi::Evals::Eval::EvalError,+ /requires the --judge option/,+ )+ end++ it "returns a passing result when the rating meets the threshold" do+ judge_llm = Fabricate(:fake_model)+ workbench_with_judge = described_class.new(output: output, judge_llm: judge_llm)++ response = { "rating" => 8, "explanation" => "good" }.to_json++ result =+ DiscourseAi::Completions::Llm.with_prepared_responses([response], llm: judge_llm) do+ workbench_with_judge.send(:judge_result, judge_eval_case, "answer")+ end++ expect(result[:result]).to eq(:pass)+ end++ it "returns a failure when the rating is below the threshold" do+ judge_llm = Fabricate(:fake_model)+ workbench_with_judge = described_class.new(output: output, judge_llm: judge_llm)++ response = { "rating" => 5, "explanation" => "needs work" }.to_json++ result =+ DiscourseAi::Completions::Llm.with_prepared_responses([response], llm: judge_llm) do+ workbench_with_judge.send(:judge_result, judge_eval_case, "answer")+ end++ expect(result[:result]).to eq(:fail)+ expect(result[:message]).to include("LLM Rating below threshold")+ end+ endend