|
| 1 | +/* Licensed under MIT 2025. */ |
| 2 | +package edu.kit.kastel.sdq.lissa.ratlr.promptoptimizer; |
| 3 | + |
| 4 | +import static edu.kit.kastel.sdq.lissa.ratlr.Statistics.getTraceLinksFromGoldStandard; |
| 5 | +import static edu.kit.kastel.sdq.lissa.ratlr.classifier.SimpleClassifier.PROMPT_TEMPLATE_KEY; |
| 6 | +import static edu.kit.kastel.sdq.lissa.ratlr.promptoptimizer.SimpleOptimizer.DEFAULT_OPTIMIZATION_TEMPLATE; |
| 7 | +import static edu.kit.kastel.sdq.lissa.ratlr.promptoptimizer.SimpleOptimizer.ORIGINAL_PROMPT_KEY; |
| 8 | +import static edu.kit.kastel.sdq.lissa.ratlr.promptoptimizer.SimpleOptimizer.PROMPT_END; |
| 9 | +import static edu.kit.kastel.sdq.lissa.ratlr.promptoptimizer.SimpleOptimizer.PROMPT_START; |
| 10 | + |
| 11 | +import java.util.List; |
| 12 | +import java.util.Map; |
| 13 | +import java.util.Set; |
| 14 | +import java.util.regex.Matcher; |
| 15 | +import java.util.regex.Pattern; |
| 16 | +import java.util.stream.Collectors; |
| 17 | + |
| 18 | +import edu.kit.kastel.mcse.ardoco.metrics.ClassificationMetricsCalculator; |
| 19 | +import edu.kit.kastel.sdq.lissa.ratlr.cache.Cache; |
| 20 | +import edu.kit.kastel.sdq.lissa.ratlr.cache.CacheKey; |
| 21 | +import edu.kit.kastel.sdq.lissa.ratlr.cache.CacheManager; |
| 22 | +import edu.kit.kastel.sdq.lissa.ratlr.classifier.ChatLanguageModelProvider; |
| 23 | +import edu.kit.kastel.sdq.lissa.ratlr.classifier.ClassificationResult; |
| 24 | +import edu.kit.kastel.sdq.lissa.ratlr.classifier.Classifier; |
| 25 | +import edu.kit.kastel.sdq.lissa.ratlr.configuration.GoldStandardConfiguration; |
| 26 | +import edu.kit.kastel.sdq.lissa.ratlr.configuration.ModuleConfiguration; |
| 27 | +import edu.kit.kastel.sdq.lissa.ratlr.elementstore.ElementStore; |
| 28 | +import edu.kit.kastel.sdq.lissa.ratlr.knowledge.Element; |
| 29 | +import edu.kit.kastel.sdq.lissa.ratlr.knowledge.TraceLink; |
| 30 | +import edu.kit.kastel.sdq.lissa.ratlr.postprocessor.TraceLinkIdPostprocessor; |
| 31 | +import edu.kit.kastel.sdq.lissa.ratlr.resultaggregator.ResultAggregator; |
| 32 | +import edu.kit.kastel.sdq.lissa.ratlr.utils.KeyGenerator; |
| 33 | + |
| 34 | +import dev.langchain4j.model.chat.ChatModel; |
| 35 | + |
| 36 | +public class IterativeOptimizer extends AbstractPromptOptimizer { |
| 37 | + |
| 38 | + private static final double THRESHOLD_F1_SCORE = 1.0; |
| 39 | + |
| 40 | + /** |
| 41 | + * The maximum number of iterations/requests for the optimization process. |
| 42 | + */ |
| 43 | + private static final int MAXIMUM_ITERATIONS = 10; |
| 44 | + /** |
| 45 | + * The size of the training data used for optimization. |
| 46 | + * This is the number of training examples provided to the language model. |
| 47 | + */ |
| 48 | + private static final int TRAINING_DATA_SIZE = 5; |
| 49 | + |
| 50 | + private final Cache cache; |
| 51 | + |
| 52 | + /** |
| 53 | + * Provider for the language model used in classification. |
| 54 | + */ |
| 55 | + private final ChatLanguageModelProvider provider; |
| 56 | + |
| 57 | + /** |
| 58 | + * The language model instance used for classification. |
| 59 | + */ |
| 60 | + private final ChatModel llm; |
| 61 | + |
| 62 | + /** |
| 63 | + * The template used for classification requests. |
| 64 | + */ |
| 65 | + private final String template; |
| 66 | + |
| 67 | + private String optimizationPrompt; |
| 68 | + |
| 69 | + private ResultAggregator aggregator; |
| 70 | + private TraceLinkIdPostprocessor traceLinkIdPostProcessor; |
| 71 | + private final Set<TraceLink> validTraceLinks; |
| 72 | + private ClassificationMetricsCalculator cmc; |
| 73 | + /** |
| 74 | + * Creates a new iterative optimizer with the specified configuration. |
| 75 | + * |
| 76 | + * @param configuration The module configuration containing optimizer settings |
| 77 | + */ |
| 78 | + public IterativeOptimizer(ModuleConfiguration configuration, GoldStandardConfiguration goldStandard) { |
| 79 | + super(ChatLanguageModelProvider.threads(configuration)); |
| 80 | + this.provider = new ChatLanguageModelProvider(configuration); |
| 81 | + this.template = configuration.argumentAsString("optimization_template", DEFAULT_OPTIMIZATION_TEMPLATE); |
| 82 | + this.cache = CacheManager.getDefaultInstance() |
| 83 | + .getCache(this.getClass().getSimpleName() + "_" + provider.modelName() + "_" + provider.seed()); |
| 84 | + this.llm = provider.createChatModel(); |
| 85 | + this.validTraceLinks = getTraceLinksFromGoldStandard(goldStandard); |
| 86 | + setup(); |
| 87 | + } |
| 88 | + |
| 89 | + private IterativeOptimizer( |
| 90 | + int threads, |
| 91 | + Cache cache, |
| 92 | + ChatLanguageModelProvider provider, |
| 93 | + String template, |
| 94 | + Set<TraceLink> validTraceLinks) { |
| 95 | + super(threads); |
| 96 | + this.cache = cache; |
| 97 | + this.provider = provider; |
| 98 | + this.template = template; |
| 99 | + this.llm = provider.createChatModel(); |
| 100 | + this.validTraceLinks = validTraceLinks; |
| 101 | + setup(); |
| 102 | + } |
| 103 | + /** |
| 104 | + * TODO: Configure in actual configuration file. Decide whether they should be args or adapted |
| 105 | + * Req2Req Example: |
| 106 | + * "result_aggregator" : { |
| 107 | + * "name" : "any_connection", |
| 108 | + * "args" : {} |
| 109 | + * }, |
| 110 | + * "tracelinkid_postprocessor" : { |
| 111 | + * "name" : "req2req", |
| 112 | + * "args" : {} |
| 113 | + */ |
| 114 | + private void setup() { |
| 115 | + cmc = ClassificationMetricsCalculator.getInstance(); |
| 116 | + this.aggregator = ResultAggregator.createResultAggregator(new ModuleConfiguration("any_connection", Map.of())); |
| 117 | + |
| 118 | + this.traceLinkIdPostProcessor = |
| 119 | + TraceLinkIdPostprocessor.createTraceLinkIdPostprocessor(new ModuleConfiguration("req2req", Map.of())); |
| 120 | + } |
| 121 | + |
| 122 | + @Override |
| 123 | + public String optimize(ElementStore sourceStore, ElementStore targetStore, String prompt) { |
| 124 | + Element source = sourceStore.getAllElements(true).getFirst().first(); |
| 125 | + Element target = targetStore |
| 126 | + .findSimilar(sourceStore.getAllElements(true).getFirst().second()) |
| 127 | + .getFirst(); |
| 128 | + optimizationPrompt = |
| 129 | + template.replace("{source_type}", source.getType()).replace("{target_type}", target.getType()); |
| 130 | + ElementStore trainingSourceStore = |
| 131 | + new ElementStore(sourceStore.getAllElements(false).subList(0, TRAINING_DATA_SIZE), -1); |
| 132 | + |
| 133 | + return optimizeIntern(trainingSourceStore, targetStore, prompt); |
| 134 | + } |
| 135 | + |
| 136 | + private String optimizeIntern(ElementStore sourceStore, ElementStore targetStore, String prompt) { |
| 137 | + double[] f1Scores = new double[MAXIMUM_ITERATIONS]; |
| 138 | + int i = 0; |
| 139 | + double f1Score; |
| 140 | + String modifiedPrompt = prompt; |
| 141 | + do { |
| 142 | + logger.debug("Iteration {}: RequestPrompt = {}", i, modifiedPrompt); |
| 143 | + f1Score = scorePrompt(sourceStore, targetStore, modifiedPrompt); |
| 144 | + logger.info("Iteration {}: F1-Score = {}", i, f1Score); |
| 145 | + f1Scores[i] = f1Score; |
| 146 | + modifiedPrompt = optimize(prompt); |
| 147 | + prompt = modifiedPrompt; |
| 148 | + i++; |
| 149 | + } while (i < MAXIMUM_ITERATIONS && f1Score < THRESHOLD_F1_SCORE); |
| 150 | + logger.info("Iterations {}: F1-Scores = {}", i, f1Scores); |
| 151 | + return prompt; |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Optimizes the given prompt using the language model. |
| 156 | + * This method is used for a single iterative optimization step. |
| 157 | + * |
| 158 | + * @param prompt The original prompt to be optimized |
| 159 | + * @return The optimized prompt |
| 160 | + */ |
| 161 | + private String optimize(String prompt) { |
| 162 | + String request = optimizationPrompt.replace(ORIGINAL_PROMPT_KEY, prompt); |
| 163 | + |
| 164 | + String key = KeyGenerator.generateKey(request); |
| 165 | + CacheKey cacheKey = new CacheKey(provider.modelName(), provider.seed(), CacheKey.Mode.CHAT, request, key); |
| 166 | + String response = cache.get(cacheKey, String.class); |
| 167 | + if (response == null) { |
| 168 | + logger.info("Optimizing ({}): {}", provider.modelName(), request); |
| 169 | + response = llm.chat(request); |
| 170 | + cache.put(cacheKey, response); |
| 171 | + } |
| 172 | + logger.debug("Response: {}", response); |
| 173 | + Pattern pattern = Pattern.compile(PROMPT_START + "(?s).*?" + PROMPT_END, Pattern.CASE_INSENSITIVE); |
| 174 | + Matcher matcher = pattern.matcher(response); |
| 175 | + if (matcher.find()) { |
| 176 | + response = matcher.group(0).strip(); |
| 177 | + } else { |
| 178 | + logger.warn("No prompt found in response: {}", response); |
| 179 | + // Fallback to original prompt if no match found |
| 180 | + response = prompt; |
| 181 | + } |
| 182 | + return response; |
| 183 | + } |
| 184 | + |
| 185 | + private double scorePrompt(ElementStore trainingStore, ElementStore targetStore, String prompt) { |
| 186 | + ModuleConfiguration classifierConfig = new ModuleConfiguration( |
| 187 | + "simple_" + provider.platform(), Map.of("model", provider.modelName(), PROMPT_TEMPLATE_KEY, prompt)); |
| 188 | + Classifier classifier = Classifier.createClassifier(classifierConfig); |
| 189 | + List<ClassificationResult> results = classifier.classify(trainingStore, targetStore); |
| 190 | + |
| 191 | + Set<TraceLink> traceLinks = |
| 192 | + aggregator.aggregate(trainingStore.getAllElements(), targetStore.getAllElements(), results); |
| 193 | + traceLinks = traceLinkIdPostProcessor.postprocess(traceLinks); |
| 194 | + List<String> traceLinkIds = trainingStore.getAllElements().stream() |
| 195 | + .map(Element::getIdentifier) |
| 196 | + .map(id -> id.substring(0, id.lastIndexOf("."))) |
| 197 | + .toList(); |
| 198 | + Set<TraceLink> possibleTraceLinks = validTraceLinks.stream() |
| 199 | + .filter(tl -> traceLinkIds.contains(tl.sourceId())) |
| 200 | + .collect(Collectors.toSet()); |
| 201 | + var classification = cmc.calculateMetrics(traceLinks, possibleTraceLinks, null); |
| 202 | + return classification.getF1(); |
| 203 | + } |
| 204 | + |
| 205 | + @Override |
| 206 | + protected AbstractPromptOptimizer copyOf(AbstractPromptOptimizer original) { |
| 207 | + return new IterativeOptimizer(threads, cache, provider, template, validTraceLinks); |
| 208 | + } |
| 209 | +} |
0 commit comments