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