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