· 8 months ago · Feb 06, 2025, 04:55 PM
1
2 //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
3
4 import java.net.URI;
5 import java.net.http.HttpClient;
6 import java.net.http.HttpRequest;
7 import java.net.http.HttpResponse;
8 import java.util.Scanner;
9 import org.json.JSONArray;
10 import org.json.JSONObject;
11
12 public class Groq_Chatbot {
13 private static final String API_KEY = "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"; // Replace with your actual API key
14 private static final String API_URL = "https://api.groq.com/v1/chat/completions";
15
16 public static String getAIResponse(String userInput) {
17 try {
18 // Create JSON request body
19 JSONObject requestBody = new JSONObject();
20 requestBody.put("model", "llama3-8b-8192");
21 JSONArray messages = new JSONArray();
22 messages.put(new JSONObject().put("role", "user").put("content", userInput));
23 requestBody.put("messages", messages);
24
25 // Create HTTP request
26 HttpClient client = HttpClient.newHttpClient();
27 HttpRequest request = HttpRequest.newBuilder()
28 .uri(URI.create(API_URL))
29 .header("Authorization", "Bearer " + API_KEY)
30 .header("Content-Type", "application/json")
31 .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
32 .build();
33
34 // Send request and get response
35 HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
36 System.out.println("API Response: " + response.body());
37
38
39 // Parse response
40 JSONObject jsonResponse = new JSONObject(response.body());
41 JSONArray choices = jsonResponse.getJSONArray("choices");
42 return choices.getJSONObject(0).getJSONObject("message").getString("content");
43
44 } catch (Exception e) {
45 return "Error: " + e.getMessage();
46 }
47 }
48
49 public static void main(String[] args) {
50 Scanner scanner = new Scanner(System.in);
51 System.out.println("Welcome to your AI chatbot! Type 'exit' to quit.");
52
53 while (true) {
54 System.out.print("\nYou: ");
55 String userInput = scanner.nextLine(); //abcABC
56
57 if (userInput.equalsIgnoreCase("exit") || userInput.equalsIgnoreCase("quit")) {
58 System.out.println("\nGoodbye! 👋");
59 break;
60 }
61
62 String response = getAIResponse(userInput);
63 System.out.println("AI: " + response);
64 }
65 scanner.close();
66 }
67 }
68