0

I'm trying to create a chatbot using a Spring Boot controller and calling the ChatGPT API after generating apiKey and including it into the code, it’s returning:

Unexpected code Response{protocol=h2, code=400, message=, url=https://api.openai.com/v1/engines/davinci-codex/completions}

It might be incorrect the URL or I'm using an invalid API key, because I’m generating a secret API key, and I don't know if they are the same. Also I can't find anything else to generate here: https://platform.openai.com/account/api-keys

Here is my controller class:

@RestController
@RequestMapping("/api/bot")
public class ChatbotController {
    private final OkHttpClient httpClient = new OkHttpClient();
    private final String apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";

    @GetMapping("/{question}")
    public String getAnswer(@PathVariable("question") String question) throws IOException {
        String prompt = "Q: " + question + "\nA:";
        String response = getChatbotResponse(prompt);
        return response;
    }

    private String getChatbotResponse(String prompt) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");

        String requestBody = "{\"prompt\":\"" + prompt + "\",\"temperature\":0.5,\"max_tokens\":150}";

        RequestBody body = RequestBody.create(mediaType, requestBody);

        Request request = new Request.Builder()
                .url(apiUrl)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer <myapikey>")
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            String[] lines = responseBody.split("\\r?\\n");
            String text = "";
            for (String line : lines) {
                if (line.contains("\"text\"")) {
                    text = line.substring(line.indexOf(":") + 2, line.length() - 1);
                    break;
                }
            }
            return text;
        }
    }

}

Also, in Postman, it is a returning 500 internal server error:

{"timestamp":"2023-03-15T18:16:56.750+00:00","status":500,"error":"Internal Server Error","path":"/api/bot/how%20can%20i%20gain%20weight"}

I tried to change the API URL, because I’m not sure about it that it is the correct one, but I am still getting the same response.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Does this answer your question? [OpenAI GPT-3 API error: "Cannot specify both model and engine"](https://stackoverflow.com/questions/75176667/openai-gpt-3-api-error-cannot-specify-both-model-and-engine) – Rok Benko Mar 15 '23 at 19:19

0 Answers0