public static double getAiPitchCorrection(double currentPitch, double targetPitch) throws Exception {
HttpClient client = HttpClient.newHttpClient();
String prompt = String.format(
"Given currentPitch=%.4f and targetPitch=%.4f, calculate the correction (target - current). " +
"Return ONLY the number with no text.",
currentPitch, targetPitch
);
JSONObject payload = new JSONObject()
.put("model", "gpt-4o-mini")
.put("messages", new org.json.JSONArray()
.put(new JSONObject()
.put("role", "system")
.put("content", "You are a precise calculator that only returns numbers."))
.put(new JSONObject()
.put("role", "user")
.put("content", prompt))
);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.openai.com/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + OPENAI_API_KEY)
.POST(HttpRequest.BodyPublishers.ofString(payload.toString(), StandardCharsets.UTF_8))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONObject jsonResponse = new JSONObject(response.body());
String content = jsonResponse
.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("message")
.getString("content")
.trim();
return Double.parseDouble(content);
}