|
| 1 | +package com.apolloconfig.apollo.ai.qabot.markdown; |
| 2 | + |
| 3 | +import com.apolloconfig.apollo.ai.qabot.config.MarkdownFilesConfig; |
| 4 | +import com.apolloconfig.apollo.ai.qabot.config.MarkdownProcessorRetryConfig; |
| 5 | +import com.apolloconfig.apollo.ai.qabot.openai.OpenAiAssistantsService; |
| 6 | +import com.google.common.collect.Maps; |
| 7 | +import java.io.IOException; |
| 8 | +import java.nio.file.Files; |
| 9 | +import java.nio.file.Path; |
| 10 | +import java.nio.file.Paths; |
| 11 | +import java.security.MessageDigest; |
| 12 | +import java.security.NoSuchAlgorithmException; |
| 13 | +import java.util.ArrayList; |
| 14 | +import java.util.List; |
| 15 | +import java.util.Map; |
| 16 | +import java.util.Objects; |
| 17 | +import java.util.function.Function; |
| 18 | +import java.util.stream.Stream; |
| 19 | +import org.slf4j.Logger; |
| 20 | +import org.slf4j.LoggerFactory; |
| 21 | +import org.springframework.stereotype.Service; |
| 22 | +import org.springframework.util.backoff.BackOff; |
| 23 | +import org.springframework.util.backoff.BackOffExecution; |
| 24 | +import org.springframework.util.backoff.ExponentialBackOff; |
| 25 | +import retrofit2.HttpException; |
| 26 | + |
| 27 | +@Service |
| 28 | +public class MarkdownProcessor { |
| 29 | + |
| 30 | + private static final Logger LOGGER = LoggerFactory.getLogger(MarkdownProcessor.class); |
| 31 | + |
| 32 | + private final OpenAiAssistantsService aiService; |
| 33 | + private final MarkdownFilesConfig markdownFilesConfig; |
| 34 | + private final MarkdownProcessorRetryConfig markdownProcessorRetryConfig; |
| 35 | + private final BackOff backOff; |
| 36 | + private final Map<String, String> fileHashValues; |
| 37 | + private final Map<String, String> fileIds; |
| 38 | + |
| 39 | + public MarkdownProcessor(OpenAiAssistantsService aiService, |
| 40 | + MarkdownFilesConfig markdownFilesConfig, |
| 41 | + MarkdownProcessorRetryConfig markdownProcessorRetryConfig) { |
| 42 | + this.aiService = aiService; |
| 43 | + this.markdownFilesConfig = markdownFilesConfig; |
| 44 | + this.markdownProcessorRetryConfig = markdownProcessorRetryConfig; |
| 45 | + this.backOff = initializeBackOff(); |
| 46 | + this.fileHashValues = Maps.newConcurrentMap(); |
| 47 | + this.fileIds = this.aiService.getVectorStoreFileIds(); |
| 48 | + } |
| 49 | + |
| 50 | + private BackOff initializeBackOff() { |
| 51 | + ExponentialBackOff exponentialBackOff = new ExponentialBackOff(); |
| 52 | + exponentialBackOff.setInitialInterval(markdownProcessorRetryConfig.getDelay()); |
| 53 | + exponentialBackOff.setMultiplier(markdownProcessorRetryConfig.getMultiplier()); |
| 54 | + exponentialBackOff.setMaxInterval(markdownProcessorRetryConfig.getMaxDelay()); |
| 55 | + exponentialBackOff.setMaxElapsedTime(markdownProcessorRetryConfig.getMaxElapsedTime()); |
| 56 | + |
| 57 | + return exponentialBackOff; |
| 58 | + } |
| 59 | + |
| 60 | + public void initialize(String location) { |
| 61 | + processWithAction(location, path -> { |
| 62 | + try { |
| 63 | + String markdownContent = Files.readString(path); |
| 64 | + fileHashValues.put(getMarkdownFileRoots(path), computeHash(markdownContent)); |
| 65 | + } catch (IOException e) { |
| 66 | + throw new RuntimeException(e); |
| 67 | + } |
| 68 | + return true; |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + public List<String> loadAndProcessFiles(String location) { |
| 73 | + return this.processWithAction(location, this::processFileWithRetry); |
| 74 | + } |
| 75 | + |
| 76 | + private List<String> processWithAction(String location, Function<Path, Boolean> action) { |
| 77 | + List<String> updatedFiles = new ArrayList<>(); |
| 78 | + Path mdDirectory = Paths.get(location); |
| 79 | + try (Stream<Path> paths = Files.walk(mdDirectory)) { |
| 80 | + paths |
| 81 | + .filter(Files::isRegularFile) |
| 82 | + .filter(path -> path.toString().endsWith(".md")) |
| 83 | + .forEach(mdFile -> { |
| 84 | + try { |
| 85 | + boolean result = action.apply(mdFile); |
| 86 | + if (result) { |
| 87 | + updatedFiles.add(mdFile.toAbsolutePath().toString()); |
| 88 | + } |
| 89 | + } catch (Throwable e) { |
| 90 | + LOGGER.error("Error processing file {}", mdFile.getFileName(), e); |
| 91 | + } |
| 92 | + }); |
| 93 | + } catch (Throwable e) { |
| 94 | + LOGGER.error("Error reading files from location {}", location, e); |
| 95 | + } |
| 96 | + |
| 97 | + return updatedFiles; |
| 98 | + } |
| 99 | + |
| 100 | + private boolean processFileWithRetry(Path mdFile) { |
| 101 | + BackOffExecution backOffExecution = backOff.start(); |
| 102 | + while (!Thread.currentThread().isInterrupted()) { |
| 103 | + try { |
| 104 | + return processFile(mdFile); |
| 105 | + } catch (HttpException exception) { |
| 106 | + if (exception.code() == 429) { |
| 107 | + long sleepTime = backOffExecution.nextBackOff(); |
| 108 | + |
| 109 | + if (sleepTime == BackOffExecution.STOP) { |
| 110 | + LOGGER.error("Retry limit exceeded. Stopping"); |
| 111 | + break; |
| 112 | + } |
| 113 | + |
| 114 | + LOGGER.warn("OpenAI API rate limit exceeded. Retrying in {} ms", sleepTime); |
| 115 | + |
| 116 | + try { |
| 117 | + Thread.sleep(sleepTime); |
| 118 | + } catch (InterruptedException e) { |
| 119 | + LOGGER.error("Interrupted while waiting for retry", e); |
| 120 | + Thread.currentThread().interrupt(); |
| 121 | + break; |
| 122 | + } |
| 123 | + } else { |
| 124 | + throw exception; |
| 125 | + } |
| 126 | + } catch (Throwable e) { |
| 127 | + throw new RuntimeException(e); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + return false; |
| 132 | + } |
| 133 | + |
| 134 | + boolean processFile(Path mdFile) throws IOException { |
| 135 | + String fileRoot = getMarkdownFileRoots(mdFile); |
| 136 | + |
| 137 | + String markdownContent = Files.readString(mdFile); |
| 138 | + String hashValue = computeHash(markdownContent); |
| 139 | + |
| 140 | + String fileHashValue = this.fileHashValues.get(fileRoot); |
| 141 | + |
| 142 | + if (Objects.equals(hashValue, fileHashValue)) { |
| 143 | + return false; |
| 144 | + } |
| 145 | + |
| 146 | + LOGGER.debug("File {} has changed", mdFile.getFileName()); |
| 147 | + |
| 148 | + String fileId = this.fileIds.get(fileRoot); |
| 149 | + if (fileId != null) { |
| 150 | + this.aiService.deleteVectorStoreFile(fileId); |
| 151 | + this.fileIds.remove(fileRoot); |
| 152 | + } |
| 153 | + |
| 154 | + String newFileId = this.aiService.createVectorStoreFile(fileRoot, markdownContent); |
| 155 | + this.fileIds.put(fileRoot, newFileId); |
| 156 | + this.fileHashValues.put(fileRoot, hashValue); |
| 157 | + |
| 158 | + return true; |
| 159 | + } |
| 160 | + |
| 161 | + private String getMarkdownFileRoots(Path mdFile) { |
| 162 | + String fullPath = mdFile.toAbsolutePath().toString(); |
| 163 | + for (String root : markdownFilesConfig.getRoots()) { |
| 164 | + if (fullPath.contains(root)) { |
| 165 | + fullPath = fullPath.substring(fullPath.indexOf(root)); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + return fullPath; |
| 170 | + } |
| 171 | + |
| 172 | + private String computeHash(String input) { |
| 173 | + try { |
| 174 | + MessageDigest md = MessageDigest.getInstance("SHA-256"); |
| 175 | + byte[] hash = md.digest(input.getBytes()); |
| 176 | + StringBuilder hexString = new StringBuilder(2 * hash.length); |
| 177 | + for (byte b : hash) { |
| 178 | + String hex = Integer.toHexString(0xff & b); |
| 179 | + if (hex.length() == 1) { |
| 180 | + hexString.append('0'); |
| 181 | + } |
| 182 | + hexString.append(hex); |
| 183 | + } |
| 184 | + return hexString.toString(); |
| 185 | + } catch (NoSuchAlgorithmException e) { |
| 186 | + throw new RuntimeException(e); |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | +} |
0 commit comments