|
| 1 | +package com.launchdarkly.sdk.server.ai; |
| 2 | + |
| 3 | +import com.launchdarkly.logging.LDLogger; |
| 4 | +import com.launchdarkly.sdk.server.ai.datamodel.LDAIConfigTypes.Message; |
| 5 | +import com.launchdarkly.sdk.server.ai.datamodel.LDAITrackingTypes.JudgeResult; |
| 6 | + |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | +import java.util.Objects; |
| 10 | +import java.util.concurrent.ThreadLocalRandom; |
| 11 | +import java.util.stream.Collectors; |
| 12 | + |
| 13 | +/** |
| 14 | + * Evaluates an AI model output against a judge prompt, returning a scored {@link JudgeResult}. |
| 15 | + * <p> |
| 16 | + * A {@code Judge} wraps an {@link AIJudgeConfig} and a {@link Runner}. Each call to |
| 17 | + * {@link #evaluate} or {@link #evaluateMessages} invokes the runner with a formatted evaluation |
| 18 | + * prompt and parses the structured {@code {score, reasoning}} response. Evaluation can be sampled |
| 19 | + * to reduce cost: pass a {@code samplingRate} of {@code 0.0} to always skip, or {@code 1.0} to |
| 20 | + * always run. |
| 21 | + * <p> |
| 22 | + * Instances are immutable and thread-safe. |
| 23 | + */ |
| 24 | +public final class Judge { |
| 25 | + /** |
| 26 | + * JSON-Schema fragment sent to the runner as the {@code outputType}, requesting structured |
| 27 | + * {@code {score, reasoning}} output. |
| 28 | + */ |
| 29 | + private static final Map<String, Object> EVALUATION_SCHEMA = Map.of( |
| 30 | + "type", "object", |
| 31 | + "properties", Map.of( |
| 32 | + "score", Map.of("type", "number"), |
| 33 | + "reasoning", Map.of("type", "string")), |
| 34 | + "required", List.of("score", "reasoning")); |
| 35 | + |
| 36 | + private final AIJudgeConfig config; |
| 37 | + private final Runner runner; |
| 38 | + private final LDLogger logger; |
| 39 | + |
| 40 | + /** |
| 41 | + * Constructs a judge. |
| 42 | + * |
| 43 | + * @param config the judge AI Config; must not be {@code null} |
| 44 | + * @param runner the runner to invoke; must not be {@code null} |
| 45 | + * @param logger the logger; must not be {@code null} |
| 46 | + */ |
| 47 | + public Judge(AIJudgeConfig config, Runner runner, LDLogger logger) { |
| 48 | + this.config = Objects.requireNonNull(config, "config"); |
| 49 | + this.runner = Objects.requireNonNull(runner, "runner"); |
| 50 | + this.logger = Objects.requireNonNull(logger, "logger"); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Evaluates the given input/output pair, always running (sampling rate {@code 1.0}). |
| 55 | + * |
| 56 | + * @param input the message history or prompt that was sent to the model |
| 57 | + * @param output the model's response to evaluate |
| 58 | + * @return the evaluation result; never {@code null} |
| 59 | + */ |
| 60 | + public JudgeResult evaluate(String input, String output) { |
| 61 | + return evaluate(input, output, 1.0); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * Evaluates the given input/output pair, subject to the given sampling rate. |
| 66 | + * |
| 67 | + * @param input the message history or prompt that was sent to the model |
| 68 | + * @param output the model's response to evaluate |
| 69 | + * @param samplingRate the fraction of evaluations to actually run; {@code 0.0} always skips, |
| 70 | + * {@code 1.0} always runs |
| 71 | + * @return the evaluation result; never {@code null} |
| 72 | + */ |
| 73 | + public JudgeResult evaluate(String input, String output, double samplingRate) { |
| 74 | + if (ThreadLocalRandom.current().nextDouble() >= samplingRate) { |
| 75 | + return JudgeResult.builder() |
| 76 | + .sampled(false) |
| 77 | + .success(false) |
| 78 | + .judgeConfigKey(config.getKey()) |
| 79 | + .metricKey(config.getEvaluationMetricKey()) |
| 80 | + .build(); |
| 81 | + } |
| 82 | + |
| 83 | + String formatted = "MESSAGE HISTORY:\n" + input + "\n\nRESPONSE TO EVALUATE:\n" + output; |
| 84 | + LDAIConfigTracker tracker = config.createTracker(); |
| 85 | + |
| 86 | + RunnerResult result; |
| 87 | + try { |
| 88 | + result = tracker.trackMetricsOf(RunnerResult::getMetrics, () -> runner.run(formatted, EVALUATION_SCHEMA)); |
| 89 | + } catch (Exception ex) { |
| 90 | + return JudgeResult.builder() |
| 91 | + .sampled(true) |
| 92 | + .success(false) |
| 93 | + .judgeConfigKey(config.getKey()) |
| 94 | + .metricKey(config.getEvaluationMetricKey()) |
| 95 | + .errorMessage(ex.getMessage()) |
| 96 | + .build(); |
| 97 | + } |
| 98 | + |
| 99 | + Map<String, Object> parsed = result.getParsed(); |
| 100 | + if (parsed == null) { |
| 101 | + logger.warn("Judge {}: runner returned null parsed output", config.getKey()); |
| 102 | + return JudgeResult.builder() |
| 103 | + .sampled(true) |
| 104 | + .success(false) |
| 105 | + .judgeConfigKey(config.getKey()) |
| 106 | + .metricKey(config.getEvaluationMetricKey()) |
| 107 | + .build(); |
| 108 | + } |
| 109 | + |
| 110 | + Object scoreRaw = parsed.get("score"); |
| 111 | + if (!(scoreRaw instanceof Number)) { |
| 112 | + logger.warn("Judge {}: parsed output missing numeric score", config.getKey()); |
| 113 | + return JudgeResult.builder() |
| 114 | + .sampled(true) |
| 115 | + .success(false) |
| 116 | + .judgeConfigKey(config.getKey()) |
| 117 | + .metricKey(config.getEvaluationMetricKey()) |
| 118 | + .build(); |
| 119 | + } |
| 120 | + double score = ((Number) scoreRaw).doubleValue(); |
| 121 | + if (score < 0.0 || score > 1.0) { |
| 122 | + logger.warn("Judge {}: score {} is outside [0.0, 1.0]", config.getKey(), score); |
| 123 | + return JudgeResult.builder() |
| 124 | + .sampled(true) |
| 125 | + .success(false) |
| 126 | + .judgeConfigKey(config.getKey()) |
| 127 | + .metricKey(config.getEvaluationMetricKey()) |
| 128 | + .build(); |
| 129 | + } |
| 130 | + |
| 131 | + JudgeResult.Builder resultBuilder = JudgeResult.builder() |
| 132 | + .sampled(true) |
| 133 | + .success(true) |
| 134 | + .judgeConfigKey(config.getKey()) |
| 135 | + .metricKey(config.getEvaluationMetricKey()) |
| 136 | + .score(score); |
| 137 | + |
| 138 | + Object reasoningRaw = parsed.get("reasoning"); |
| 139 | + if (reasoningRaw instanceof String) { |
| 140 | + resultBuilder.reasoning((String) reasoningRaw); |
| 141 | + } else if (reasoningRaw != null) { |
| 142 | + logger.warn("Judge {}: reasoning is not a string, ignoring", config.getKey()); |
| 143 | + } |
| 144 | + |
| 145 | + return resultBuilder.build(); |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Evaluates a message list and runner response, always running (sampling rate {@code 1.0}). |
| 150 | + * <p> |
| 151 | + * Messages are formatted as {@code role: content} lines, joined by newlines. |
| 152 | + * |
| 153 | + * @param messages the messages that were sent to the model |
| 154 | + * @param response the runner result whose {@link RunnerResult#getContent() content} is evaluated |
| 155 | + * @return the evaluation result; never {@code null} |
| 156 | + */ |
| 157 | + public JudgeResult evaluateMessages(List<Message> messages, RunnerResult response) { |
| 158 | + return evaluateMessages(messages, response, 1.0); |
| 159 | + } |
| 160 | + |
| 161 | + /** |
| 162 | + * Evaluates a message list and runner response, subject to the given sampling rate. |
| 163 | + * <p> |
| 164 | + * Messages are formatted as {@code role: content} lines, joined by newlines. |
| 165 | + * |
| 166 | + * @param messages the messages that were sent to the model |
| 167 | + * @param response the runner result whose {@link RunnerResult#getContent() content} is evaluated |
| 168 | + * @param samplingRate the fraction of evaluations to actually run |
| 169 | + * @return the evaluation result; never {@code null} |
| 170 | + */ |
| 171 | + public JudgeResult evaluateMessages(List<Message> messages, RunnerResult response, double samplingRate) { |
| 172 | + String formattedMessages = messages == null ? "" : messages.stream() |
| 173 | + .map(m -> m.getRole().getWireValue() + ": " + m.getContent()) |
| 174 | + .collect(Collectors.joining("\n")); |
| 175 | + return evaluate(formattedMessages, response == null ? "" : response.getContent(), samplingRate); |
| 176 | + } |
| 177 | + |
| 178 | + /** |
| 179 | + * Returns the judge AI Config this instance was constructed with. |
| 180 | + * |
| 181 | + * @return the judge config, never {@code null} |
| 182 | + */ |
| 183 | + public AIJudgeConfig getConfig() { |
| 184 | + return config; |
| 185 | + } |
| 186 | + |
| 187 | + /** |
| 188 | + * Returns the runner this instance was constructed with. |
| 189 | + * |
| 190 | + * @return the runner, never {@code null} |
| 191 | + */ |
| 192 | + public Runner getRunner() { |
| 193 | + return runner; |
| 194 | + } |
| 195 | +} |
0 commit comments