|
| 1 | +import com.cjcrafter.openai.chat.ChatBot; |
| 2 | +import com.cjcrafter.openai.chat.ChatMessage; |
| 3 | +import com.cjcrafter.openai.chat.ChatRequest; |
| 4 | +import com.cjcrafter.openai.chat.ChatResponse; |
| 5 | +import okhttp3.Response; |
| 6 | + |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.InputStream; |
| 9 | +import java.util.List; |
| 10 | +import java.util.Scanner; |
| 11 | + |
| 12 | +public class JavaTest { |
| 13 | + |
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + Scanner scan = new Scanner(System.in); |
| 16 | + String key = getToken(); |
| 17 | + |
| 18 | + // Create the initial prompt, we will reuse it later. |
| 19 | + String initialPrompt = "You are a customer support chat-bot. Write brief summaries of the user's questions so that agents can easily find the answer in a database."; |
| 20 | + List<ChatMessage> messages = List.of(new ChatMessage("system", initialPrompt)); |
| 21 | + ChatRequest request = new ChatRequest("gpt-3.5-turbo", messages); |
| 22 | + ChatBot bot = new ChatBot(key); |
| 23 | + |
| 24 | + // ChatCompletionRequest copies the list, so let's modify the request's |
| 25 | + // copy of the list. |
| 26 | + messages = request.getMessages(); |
| 27 | + |
| 28 | + while (true) { |
| 29 | + System.out.println("Enter text below:\n\n"); |
| 30 | + String input = scan.nextLine(); |
| 31 | + |
| 32 | + // Generate a response, and print it to the user. |
| 33 | + messages.add(new ChatMessage("user", input)); |
| 34 | + ChatResponse response = bot.generateResponse(request); |
| 35 | + System.out.println("\n" + response.getChoices().get(0).getMessage().getContent()); |
| 36 | + |
| 37 | + // Save the generated message to the bot's conversational memory |
| 38 | + messages.add(response.getChoices().get(0).getMessage()); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public static String getToken() { |
| 43 | + try (InputStream stream = JavaTest.class.getResourceAsStream("token.txt")) { |
| 44 | + Scanner scan = new Scanner(stream); |
| 45 | + return scan.nextLine(); |
| 46 | + } catch (Throwable ex) { |
| 47 | + throw new RuntimeException(ex); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments