@reliya1541 (Taewoong Lim)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

JAVAのproperties 問題

解決したいこと

JAVA17でpropertiesのapikeyを呼ぶ問題について。
apikeyはdataはあるんですが、使うことができないんです。
なぜpropertiesでは@ValueをつっかてRestTemplateの要請が失敗するのか知りたいです。

発生している問題・エラー

    @Value("${openai.api.key}")
    private String apiKey;

propertiesのapiKeyを呼んでrestTeamplateにつかうことができない問題

該当するソースコード

private String sendChatGptRequest(String prompt, String systemMessage, int maxTokens) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "gpt-4o-mini-2024-07-18");
        requestBody.put("messages", new JSONArray()
                .put(new JSONObject().put("role", "system").put("content", systemMessage))
                .put(new JSONObject().put("role", "user").put("content", prompt))
        );
        requestBody.put("max_tokens", maxTokens);

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

        try {
            ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class);
            JSONObject responseBody = new JSONObject(response.getBody());
            return responseBody.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content")
                    .trim();
        } catch (HttpClientErrorException e) {
            log.error("HTTP Status: {}", e.getStatusCode());
            log.error("Response Body: {}", e.getResponseBodyAsString());
            throw new RuntimeException("Failed to process request. Please try again later.");
        }
    }

自分で試したこと

propertiesを使わずに直接キーに入れる=>成功
propertiesをValueを使用して読み込む => 失敗
properties を prefix を使って読み込む => 失敗
ymlに変更してValueを使用して読み込む => 成功

0 likes

No Answers yet.

Your answer might help someone💌