Bad Request 400 OpenAi API

Hi OpenAI Developer Community, I’m a developer using openai api.

I’ve been encountering error via postman bad request 400 but its says 200 OK. When i’m using other query or unpredicted query i encounter this error, but when i’m using the query that are pre-defined in my code i didn’t encounter this error and the result will give the value in my database. It suppose to be when the query of the user if not in the pre-defined queries it should be pass to openAi API so that it can be flexible in other queries, in short to become dynamic response. this will be use as a chatbot for banking.

here is my updated code and classes use in java

MAIN CONTROLLER

@RestController
@RequestMapping("/api")
public class MainController {
private static final Logger logger = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DatabaseQueryService databaseQueryService;

    @Autowired
    private AppConfig appConfig;

    @PostMapping("/processQuery")
    public ResponseEntity<?> processQuery(@RequestBody Map<String, String> userQuery) {
        String queryContent = userQuery.get("content");
        String userId = userQuery.get("userId");

        try {
            if (queryContent == null || queryContent.isEmpty()) {
                return ResponseEntity.badRequest().body("Invalid request: content is missing.");
            }

            String responseContent = handleQuery(queryContent, userId);
            return ResponseEntity.ok(responseContent);
        } catch (HttpClientErrorException e) {
            logger.error("HTTP error: {} - {}", e.getStatusCode(), e.getResponseBodyAsString());
            return ResponseEntity.status(e.getStatusCode()).body("An error occurred: " + e.getResponseBodyAsString());
        } catch (Exception e) {
            logger.error("An error occurred: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
        }
    }

    private String handleQuery(String queryContent, String userId) {
        String standardizedQuery = standardizeQuery(queryContent);

        logger.info("Standardized query: {}", standardizedQuery);

        switch (standardizedQuery) {
            case "GROUP_TRANSACTIONS_BY_MONTH":
                logger.info("Handling 'GROUP_TRANSACTIONS_BY_MONTH' query.");
                return handleGroupTransactionsByMonth(userId);
            case "TOTAL_AMOUNT":
                logger.info("Handling 'TOTAL_AMOUNT' query.");
                return handleTotalAmount();
            case "RUNNING_BALANCE":
                logger.info("Handling 'RUNNING_BALANCE' query.");
                return handleRunningBalance(userId);
            default:
                logger.info("No specific handler for query. Using OpenAI API fallback.");
                return callOpenAiApi(queryContent);
        }
}

    private String handleTotalAmount() {
        Double totalAmount = databaseQueryService.getTotalAmount();
        return "The total amount is " + totalAmount + ".";
    }

    private String callOpenAiApi(String queryContent) {
        try {
            JSONObject payload = new JSONObject();
            payload.put("model", appConfig.getOpenAiModel());

            JSONArray messages = new JSONArray();
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", queryContent);
            messages.put(userMessage);

            payload.put("messages", messages);

            String apiUrl = appConfig.getOpenAiApiUrl();
            String apiKey = appConfig.getOpenAiApiKey();

            logger.info("Payload to OpenAI API: {}", payload.toString(2));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            HttpEntity<String> entity = new HttpEntity<>(payload.toString(), headers);

            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    apiUrl, HttpMethod.POST, entity, String.class);

            logger.info("OpenAI API full response: {}", responseEntity.getBody());

            return extractContentFromResponse(responseEntity.getBody());
        } catch (HttpClientErrorException e) {
            logger.error("HTTP error: {} - {}", e.getStatusCode(), e.getResponseBodyAsString());
            return "An error occurred while calling OpenAI API: " + e.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error("An error occurred while calling OpenAI API: {}", e.getMessage());
            return "I'm sorry, I didn't understand your request.";
        }
    }

    private String standardizeQuery(String query) {
        query = query.toLowerCase().trim();

        if (query.contains("group") && query.contains("transactions") && query.contains("month")) {
            return "GROUP_TRANSACTIONS_BY_MONTH";
        } else if (query.contains("summary") && query.contains("transactions") && query.contains("month")) {
            return "GROUP_TRANSACTIONS_BY_MONTH"; // Standardize similar intents
        } else if (query.contains("total") && query.contains("amount")) {
            return "TOTAL_AMOUNT";
        } else if (query.contains("running") && query.contains("balance")) {
            return "RUNNING_BALANCE";
        }

        // Handle other queries
        return "UNKNOWN_QUERY";
    }

    private String handleGroupTransactionsByMonth(String userId) {
        if (userId != null) {
            logger.info("User ID provided: {}. Fetching grouped transactions.", userId);
            List<Map<String, Object>> groupedTransactions = databaseQueryService.getTransactionsGroupedByDate(userId);

            if (groupedTransactions.isEmpty()) {
                logger.warn("No transactions found for user ID: {}", userId);
                return "No transactions found for the specified user.";
            } else {
                logger.info("Transactions retrieved successfully. Constructing summary.");
                // Construct a response based on the retrieved data
                return constructTransactionSummaryResponse(groupedTransactions);
            }
        } else {
            logger.warn("User ID is missing for transaction grouping request.");
            return "To group your transactions by date, please provide your user ID.";
        }
    }

    private String handleRunningBalance(String userId) {
        if (userId != null) {
            Double runningBalance = databaseQueryService.getRunningBalanceByUserId(userId);
            return "Your running balance is " + runningBalance + ".";
        } else {
            return "To get your running balance, please provide your user ID.";
        }
    }

    private String constructTransactionSummaryResponse(List<Map<String, Object>> groupedTransactions) {
        StringBuilder transactionsSummary = new StringBuilder("Here's a summary of your transactions per month:\n\n");
        for (Map<String, Object> transaction : groupedTransactions) {
            transactionsSummary.append("Date: ").append(transaction.get("DATE"))
                    .append(", Total Amount: $").append(String.format("%.2f", transaction.get("TOTAL_AMOUNT")))
                    .append("\n");
        }
        logger.info("Transaction summary constructed successfully.");
        return transactionsSummary.toString();
    }

    private String extractContentFromResponse(String responseBody) {
        try {
            JSONObject jsonResponse = new JSONObject(responseBody);
            JSONArray choices = jsonResponse.getJSONArray("choices");
            if (choices.length() > 0) {
                JSONObject choice = choices.getJSONObject(0);
                JSONObject message = choice.getJSONObject("message");
                return message.getString("content");
            } else {
                return "No response content available.";
            }
        } catch (JSONException e) {
            logger.error("Error parsing OpenAI API response: {}", e.getMessage());
            return "Error parsing response.";
        }
    }
}

APP CONFIG


@Configuration
public class AppConfig {
 @Value("${openai.api.key}")
    private String openaiApiKey;

    @Value("${openai.api.url}")
    private String openaiApiUrl;

    @Value("${openai.api.model}")
    private String openaiModel;

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        // Add an interceptor to add the Authorization header to every request
        restTemplate.setInterceptors(Collections.singletonList((request, body, execution) -> {
            request.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + openaiApiKey);
            return execution.execute(request, body);
        }));

        return restTemplate;
    }

    public String getOpenAiApiUrl() {
        return openaiApiUrl;
    }

    public String getOpenAiApiKey() {
        return openaiApiKey;
    }

    public String getOpenAiModel() {
        return openaiModel;
    }
}

APPLICATION YML

openai:
  api:
    key:""
    url: https://api.openai.com/v1/chat/completions
    timeout: 5000  # Added timeout in milliseconds
    model: ft:gpt-3.5-turbo-0125:testgpt:sample-txn7:A30IEzql

ERROR LOGS IN INTELLIJ

2024-09-04T16:57:39.430+08:00  INFO 21656 --- [openaiSpring] [nio-8080-exec-3] c.o.o.Controller.MainController          : Standardized query: UNKNOWN_QUERY
2024-09-04T16:57:39.430+08:00  INFO 21656 --- [openaiSpring] [nio-8080-exec-3] c.o.o.Controller.MainController          : No specific handler for query. Using OpenAI API fallback.
2024-09-04T16:57:39.435+08:00  INFO 21656 --- [openaiSpring] [nio-8080-exec-3] c.o.o.Controller.MainController          : Payload to OpenAI API: {
  "messages": [{
    "role": "user",
    "content": "Give me a breakdown of my transactions for each month."
  }],
  "model": "ft:gpt-3.5-turbo-0125:testgpt:sample-txn7:A30IEzql"
}
2024-09-04T16:57:39.969+08:00 ERROR 21656 --- [openaiSpring] [nio-8080-exec-3] c.o.o.Controller.MainController          : HTTP error: 400 BAD_REQUEST - <html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare</center>
</body>
</html>

ERROR LOGS IN MY POSTMAN

An error occurred while calling OpenAI API: <html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare</center>
</body>
</html>

I hope you can help me to resolve my problem with this. Thank you!!!

Same here. This has been happening for the past 2 days. Before that I did not get this error.