Files
reiheAPicker/src/logic_reiheAPicker/ChatGPTApiCallerClass.java

104 lines
4.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package logic_reiheAPicker;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class ChatGPTApiCallerClass {
public static String chatGPT(String prompt) {
String url = "https://api.openai.com/v1/chat/completions";
String apiKey = var_reiheAPicker.Constants.ChatGPTApiKey;
String model = "gpt-4o";
prompt = "You are assessing the relevance of books for a school-focused educational library. " +
"The target audience includes students and educators in all school-related disciplines (such as mathematics, science, languages, history, geography, social studies, arts, physical education, computer science, etc.). " +
"Your task is to rate each book's relevance using this fixed output format: " +
"'87; highly relevant but in English.' " +
"Format rules: " +
"- First, a number from 0 to 100 indicating the relevance. " +
"- Then, a short explanation in plain language. " +
"- Only use German or English titles. " +
"- German books are preferred. " +
"- English books are acceptable only if highly relevant. " +
"- Ignore books in other languages (output: '0; not in German or English.') " +
"Always follow this format. Dont include anything else. " +
"Now evaluate the following title: " + prompt; try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection connection = null;
try {
URL obj = new URL(url);
connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
connection.setRequestProperty("Content-Type", "application/json");
// The request body
String body = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}";
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(body);
writer.flush();
writer.close();
// Response from ChatGPT
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
// Call the method to extract the message
return extractMessageFromJSONResponse(response.toString());
} catch (IOException e) {
// Handle errors and print the API response if available
if (connection != null) {
try {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
StringBuilder errorResponse = new StringBuilder();
String line;
while ((line = errorReader.readLine()) != null) {
errorResponse.append(line);
}
errorReader.close();
System.err.println("Error response from OpenAI API: " + errorResponse.toString());
// Log and continue without throwing
return "skipped due to error"; // Or handle it gracefully based on your program's needs
}
} catch (IOException ex) {
System.err.println("Failed to read error stream from OpenAI API");
ex.printStackTrace();
// Log and continue without throwing
return "skipped due to error"; // Or handle it gracefully
}
}
System.err.println("Error occurred while connecting to OpenAI API: " + e.getMessage());
e.printStackTrace();
// Log and continue without throwing
return "skipped due to error"; // Or handle it gracefully
}
}
public static String extractMessageFromJSONResponse(String response) {
int start = response.indexOf("content")+ 11;
int end = response.indexOf("\"", start);
return response.substring(start, end);
}
}