ChatGpt Bot 异常

问题描述 投票:0回答:0

我正在尝试使用 springboot 控制器创建一个聊天机器人,并在生成 apiKey 并将其包含到它返回的代码中后调用 chatgpt api:

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

这可能是不正确的 URL 或者我正在使用无效的 API 密钥因为我正在生成秘密的 api 密钥而且我不知道它们是否相同也可以在这里找到任何其他生成的东西:https://platform.openai.com /账户/api-keys

这是我的控制器类:

@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;
        }
    }

}

邮递员也返回 500 内部服务器错误:

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

我试图更改 api url,因为我不确定它是否正确,但仍然得到相同的响应。

java json spring-boot chatbot openai-api
© www.soinside.com 2019 - 2024. All rights reserved.