in bigquery-antipattern-recognition/src/main/java/com/google/zetasql/toolkit/antipattern/rewriter/gemini/GeminiRewriter.java [66:113]
public static String processPrompt(String prompt, String projectId) throws IOException {
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
credentials.refreshIfExpired();
String accessToken = credentials.getAccessToken().getTokenValue();
// Prepare request
URL url = new URL(String.format(API_URI_TEMPLATE, projectId));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setDoOutput(true);
String body = String.format(GeminiConstants.GEMINI_API_HTTP_POST_BODY, prompt);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// check response
int responseCode = connection.getResponseCode();
logger.info(connection.toString());
logger.info("POST Response Code: " + responseCode);
// get response body
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
String res = response.toString();
String optimizedSQL = getSqlFromRes(res);
Pattern pattern = Pattern.compile("```(?:sql)?(.*?)```", Pattern.DOTALL);
Matcher matcher = pattern.matcher(optimizedSQL);
if (matcher.find()) {
optimizedSQL = matcher.group(1).trim();
} else {
optimizedSQL = optimizedSQL.trim();
}
return optimizedSQL;
}
} else {
logger.info("POST request failed" + connection.getResponseMessage());
}
return null;
}