MoonLord-LM / MyJava

MyJava
2 stars 2 forks source link

Chatgpt #319

Open MoonLord-LM opened 5 months ago

MoonLord-LM commented 5 months ago
    String API_URL = "https://api.openai.com/v1/chat/completions";
    String API_KEY = "sk-proj-sGMyQOWDKORjlfpsHGLvT3BlbkFJmzEjUG9AaWpJ0XtMR0ot";
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "application/json");
    headers.set("Authorization", "Bearer " + API_KEY);
    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("model", "gpt-3.5-turbo");
    requestBody.put("max_tokens", "50");
    HashMap<String, String> message1 = new HashMap<>();
    message1.put("role", "system");
    message1.put("content", "You are a helpful assistant.");
    HashMap<String, String> message2 = new HashMap<>();
    message2.put("role", "user");
    message2.put("content", "Who won the world series in 2020?");
    requestBody.put("messages", Arrays.asList(message1, message2));
    HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
    ResponseEntity<String> response = restTemplate.postForEntity(API_URL, entity, String.class);
    if (response.getStatusCode().is2xxSuccessful()) {
        log.info(response.getBody());
    } else {
        log.error(response.getStatusCode() + " " + response.getBody());
    }