|
| 1 | +package com.google.adk.samples.stale; |
| 2 | + |
| 3 | +import com.google.adk.runner.InMemoryRunner; |
| 4 | +import com.google.adk.samples.stale.agent.StaleAgent; |
| 5 | +import com.google.adk.samples.stale.config.StaleBotSettings; |
| 6 | +import com.google.adk.samples.stale.utils.GitHubUtils; |
| 7 | +import com.google.genai.types.Content; |
| 8 | +import com.google.genai.types.Part; |
| 9 | +import java.util.List; |
| 10 | +import java.util.UUID; |
| 11 | +import java.util.concurrent.CompletableFuture; |
| 12 | +import java.util.logging.Level; |
| 13 | +import java.util.logging.Logger; |
| 14 | +import java.util.stream.Collectors; |
| 15 | + |
| 16 | +public class StaleBotApp { |
| 17 | + |
| 18 | + private static final Logger logger = Logger.getLogger(StaleBotApp.class.getName()); |
| 19 | + private static final String USER_ID = "stale_bot_user"; |
| 20 | + |
| 21 | + record IssueResult(long issueNumber, double durationSeconds, int apiCalls) {} |
| 22 | + |
| 23 | + public static void main(String[] args) { |
| 24 | + |
| 25 | + try { |
| 26 | + runBot(); |
| 27 | + } catch (Exception e) { |
| 28 | + logger.log(Level.SEVERE, "Unexpected fatal error", e); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + public static void runBot() { |
| 33 | + logger.info(" Starting Stale Bot for " + StaleBotSettings.OWNER + "/" + StaleBotSettings.REPO); |
| 34 | + logger.info("Concurrency level set to " + StaleBotSettings.CONCURRENCY_LIMIT); |
| 35 | + |
| 36 | + GitHubUtils.resetApiCallCount(); |
| 37 | + |
| 38 | + double filterDays = StaleBotSettings.STALE_HOURS_THRESHOLD / 24.0; |
| 39 | + logger.fine(String.format("Fetching issues older than %.2f days...", filterDays)); |
| 40 | + |
| 41 | + List<Integer> allIssues; |
| 42 | + try { |
| 43 | + allIssues = |
| 44 | + GitHubUtils.getOldOpenIssueNumbers( |
| 45 | + StaleBotSettings.OWNER, StaleBotSettings.REPO, filterDays); |
| 46 | + } catch (Exception e) { |
| 47 | + logger.log(Level.SEVERE, "Failed to fetch issue list", e); |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + int totalCount = allIssues.size(); |
| 52 | + int searchApiCalls = GitHubUtils.getApiCallCount(); |
| 53 | + |
| 54 | + if (totalCount == 0) { |
| 55 | + logger.info("No issues matched the criteria. Run finished."); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + logger.info( |
| 60 | + String.format( |
| 61 | + "Found %d issues to process. (Initial search used %d API calls).", |
| 62 | + totalCount, searchApiCalls)); |
| 63 | + |
| 64 | + double totalProcessingTime = 0.0; |
| 65 | + int totalIssueApiCalls = 0; |
| 66 | + int processedCount = 0; |
| 67 | + |
| 68 | + InMemoryRunner runner = new InMemoryRunner(StaleAgent.create()); |
| 69 | + |
| 70 | + for (int i = 0; i < totalCount; i += StaleBotSettings.CONCURRENCY_LIMIT) { |
| 71 | + int end = Math.min(i + StaleBotSettings.CONCURRENCY_LIMIT, totalCount); |
| 72 | + List<Integer> chunk = allIssues.subList(i, end); |
| 73 | + int currentChunkNum = (i / StaleBotSettings.CONCURRENCY_LIMIT) + 1; |
| 74 | + |
| 75 | + logger.info( |
| 76 | + String.format("Starting chunk %d: Processing issues %s ", currentChunkNum, chunk)); |
| 77 | + |
| 78 | + // Create a list of Futures (Async Tasks) |
| 79 | + List<CompletableFuture<IssueResult>> futures = |
| 80 | + chunk.stream().map(issueNum -> processSingleIssue(issueNum)).collect(Collectors.toList()); |
| 81 | + |
| 82 | + // Wait for all tasks in this chunk to complete |
| 83 | + CompletableFuture<Void> allFutures = |
| 84 | + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); |
| 85 | + |
| 86 | + try { |
| 87 | + allFutures.join(); |
| 88 | + |
| 89 | + // Aggregate results |
| 90 | + for (CompletableFuture<IssueResult> f : futures) { |
| 91 | + IssueResult result = f.get(); |
| 92 | + if (result != null) { |
| 93 | + totalProcessingTime += result.durationSeconds(); |
| 94 | + totalIssueApiCalls += result.apiCalls(); |
| 95 | + } |
| 96 | + } |
| 97 | + } catch (Exception e) { |
| 98 | + logger.log(Level.SEVERE, "Error gathering chunk results", e); |
| 99 | + } |
| 100 | + |
| 101 | + processedCount += chunk.size(); |
| 102 | + logger.info( |
| 103 | + String.format( |
| 104 | + "Finished chunk %d. Progress: %d/%d ", currentChunkNum, processedCount, totalCount)); |
| 105 | + |
| 106 | + // Sleep between chunks if not finished |
| 107 | + if (end < totalCount) { |
| 108 | + logger.fine( |
| 109 | + "Sleeping for " |
| 110 | + + StaleBotSettings.SLEEP_BETWEEN_CHUNKS |
| 111 | + + "s to respect rate limits..."); |
| 112 | + try { |
| 113 | + Thread.sleep((long) (StaleBotSettings.SLEEP_BETWEEN_CHUNKS * 1000)); |
| 114 | + } catch (InterruptedException e) { |
| 115 | + Thread.currentThread().interrupt(); |
| 116 | + logger.warning("Sleep interrupted."); |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + int totalApiCallsForRun = searchApiCalls + totalIssueApiCalls; |
| 122 | + double avgTimePerIssue = totalCount > 0 ? totalProcessingTime / totalCount : 0; |
| 123 | + |
| 124 | + logger.info("Successfully processed " + processedCount + " issues."); |
| 125 | + logger.info("Total API calls made this run: " + totalApiCallsForRun); |
| 126 | + logger.info(String.format("Average processing time per issue: %.2f seconds.", avgTimePerIssue)); |
| 127 | + } |
| 128 | + |
| 129 | + private static CompletableFuture<IssueResult> processSingleIssue(int issueNumber) { |
| 130 | + return CompletableFuture.supplyAsync( |
| 131 | + () -> { |
| 132 | + long startNano = System.nanoTime(); |
| 133 | + int startApiCalls = GitHubUtils.getApiCallCount(); |
| 134 | + |
| 135 | + logger.info("Processing Issue #" + issueNumber + "..."); |
| 136 | + |
| 137 | + InMemoryRunner localRunner = new InMemoryRunner(StaleAgent.create()); |
| 138 | + |
| 139 | + String sessionId = "session-" + issueNumber + "-" + UUID.randomUUID().toString(); |
| 140 | + |
| 141 | + try { |
| 142 | + |
| 143 | + localRunner |
| 144 | + .sessionService() |
| 145 | + .createSession(localRunner.appName(), USER_ID, null, sessionId) |
| 146 | + .blockingGet(); |
| 147 | + |
| 148 | + logger.fine("Session created successfully: " + sessionId); |
| 149 | + |
| 150 | + String promptText = "Audit Issue #" + issueNumber + "."; |
| 151 | + Content promptMessage = Content.fromParts(Part.fromText(promptText)); |
| 152 | + StringBuilder fullResponse = new StringBuilder(); |
| 153 | + |
| 154 | + localRunner |
| 155 | + .runAsync(USER_ID, sessionId, promptMessage) |
| 156 | + .blockingSubscribe( |
| 157 | + event -> { |
| 158 | + try { |
| 159 | + if (event.content() != null && event.content().isPresent()) { |
| 160 | + event |
| 161 | + .content() |
| 162 | + .get() |
| 163 | + .parts() |
| 164 | + .get() |
| 165 | + .forEach( |
| 166 | + p -> { |
| 167 | + p.text().ifPresent(text -> fullResponse.append(text)); |
| 168 | + }); |
| 169 | + } |
| 170 | + } catch (Exception ignored) { |
| 171 | + } |
| 172 | + }, |
| 173 | + error -> { |
| 174 | + logger.severe( |
| 175 | + "Stream failed for Issue #" + issueNumber + ": " + error.getMessage()); |
| 176 | + }); |
| 177 | + |
| 178 | + String decision = fullResponse.toString().replace("\n", " "); |
| 179 | + if (decision.length() > 150) decision = decision.substring(0, 150); |
| 180 | + |
| 181 | + logger.info("#" + issueNumber + " Decision: " + decision + "..."); |
| 182 | + |
| 183 | + } catch (Exception e) { |
| 184 | + logger.log(Level.SEVERE, "Error processing issue #" + issueNumber, e); |
| 185 | + } |
| 186 | + |
| 187 | + double durationSeconds = (System.nanoTime() - startNano) / 1_000_000_000.0; |
| 188 | + int issueApiCalls = Math.max(0, GitHubUtils.getApiCallCount() - startApiCalls); |
| 189 | + |
| 190 | + return new IssueResult(issueNumber, durationSeconds, issueApiCalls); |
| 191 | + }); |
| 192 | + } |
| 193 | +} |
0 commit comments