Skip to content

Commit ac6115c

Browse files
committed
[FEAT] 헤드라인 생성을 위한 GPT API 설정
1 parent 55699e5 commit ac6115c

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.movelog.domain.gpt.application;
2+
3+
import com.fasterxml.jackson.databind.JsonNode;
4+
import lombok.RequiredArgsConstructor;
5+
import lombok.extern.slf4j.Slf4j;
6+
import org.springframework.beans.factory.annotation.Value;
7+
import org.springframework.http.MediaType;
8+
import org.springframework.stereotype.Service;
9+
import org.springframework.web.reactive.function.client.WebClient;
10+
import reactor.core.publisher.Mono;
11+
12+
import java.util.HashMap;
13+
import java.util.List;
14+
import java.util.Map;
15+
16+
@Service
17+
@RequiredArgsConstructor
18+
@Slf4j
19+
public class GptService {
20+
21+
private final WebClient gptWebClient; // @Qualifier 제거하고 빈 이름에 맞는 생성자 주입
22+
@Value("${chatgpt.api-key}")
23+
private String apiKey;
24+
@Value("${chatgpt.model}")
25+
private String model;
26+
@Value("${chatgpt.max-tokens}")
27+
private Integer maxTokens;
28+
@Value("${chatgpt.temperature}")
29+
private Double temperature;
30+
@Value("${chatgpt.top-p}")
31+
private Double topP;
32+
33+
public Mono<JsonNode> callChatGpt(String prompt) {
34+
return gptWebClient.post()
35+
.uri("/chat/completions") // 경로에 대한 수정
36+
.header("Authorization", "Bearer " + apiKey)
37+
.contentType(MediaType.APPLICATION_JSON)
38+
.bodyValue(buildRequestBody(prompt))
39+
.retrieve()
40+
.bodyToMono(JsonNode.class)
41+
.doOnSuccess(response -> log.info("GPT API 응답 성공: {}", response))
42+
.doOnError(error -> log.error("GPT API 호출 중 오류 발생: {}", error.getMessage()))
43+
.onErrorResume(error -> {
44+
log.error("GPT API 호출 중 예외 처리 발생: {}", error.getMessage());
45+
return Mono.error(new RuntimeException("GPT API 호출 실패", error));
46+
});
47+
}
48+
49+
private Map<String, Object> buildRequestBody(String prompt) {
50+
Map<String, Object> bodyMap = new HashMap<>();
51+
bodyMap.put("model", model);
52+
bodyMap.put("max_tokens", maxTokens);
53+
bodyMap.put("temperature", temperature);
54+
bodyMap.put("top_p", topP);
55+
bodyMap.put("messages", List.of(
56+
Map.of(
57+
"role", "user",
58+
"content", prompt
59+
)
60+
));
61+
return bodyMap;
62+
}
63+
}

0 commit comments

Comments
 (0)