swimminginthecode DIVE!

BACK/Spring

SpringBoot 환경에서 ChatGpt API 사용해 보기

dazz6 2024. 11. 22. 18:00

지난 프로젝트에서 외부 API 중 카카오 로그인과 네이버 로그인을 적용해 봤는데,

요즈음 ChatGpt를 적용하여 글이나 사진을 생성하여 제공하는 플랫폼이 많이 보여 구현해 보기로 했다.

 

외부와 통신한다는 것이 어렵게 느껴질 수 있는데, 카카오/네이버 로그인에 비해서 간단하게 구현할 수 있었다.

다만 다른 점은 질문하고 답변을 받을 때마다 크레딧이 차감된다.

새로 계정을 생성하면 3개월 동안 쓸 수 있는 크레딧을 준다는데, 가입한 지 3개월이 훌쩍 지난 아이디라 새로 5달러를 충전했다.

하나를 질문하고 답변받는 데 평균적으로 0.01달러 미만이 차감되는 것 같다.

 

공식 문서

https://platform.openai.com/docs/api-reference/introduction

 

구현 전에 OpenAI에서 API Key를 발급받아야 하는데, 이는 도움받은 다른 블로그를 첨부 (감사합니다)

https://www.daleseo.com/chatgpt-api-keys/

 

/* Controller */
@GetMapping("/api/gpt")
public ResponseEntity<String> gpt(@RequestParam String prompt) {
	return ResponseEntity.ok(service.gpt(prompt));
}

/* Service */
@Value("${openai.api-key}")
private String openaiApiKey;
// key를 application.properties 에 openai.api-key=... 로 작성해 주면 자동으로 key가 openaiApiKey 변수에 주입된다.
    
public String gpt(String prompt) {
	WebClient webClient = WebClient.builder()
		.baseUrl("https://api.openai.com/v1/chat/completions")
        .defaultHeader("Authorization", "Bearer " + openaiApiKey)
        .defaultHeader("Content-Type", "application/json")
        .build();

    String response = webClient.post()
        .bodyValue("{\"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}")
        // 모델은 비교적 저렴한 gpt-3.5-turbo로 지정
        .retrieve()
        .bodyToMono(String.class)
        .block();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response);

			// ChatGpt로부터 받은 JSON을 파싱하여 답변 content만 추출하기
            JsonNode contentNode = rootNode
                    .path("choices")
                    .get(0)
                    .path("message")
                    .path("content");

            return contentNode.asText();

        } catch (Exception e) {
            System.out.println("getUseGpt ERROR : " + e.getMessage());
        }

        return null;
    }

 

 

postman으로 확인했을 때 성공적으로 연결할 수 있었다!

 

간단한 질문과 답변 정도만 테스트해 보았는데, 다중 질문이나 이미지 생성도 다음에 구현해 봐야겠다.

'BACK > Spring' 카테고리의 다른 글

SpringBoot 환경에서 ChatGpt API 사용해 보기 - Spring AI  (0) 2024.12.04
Hmac를 사용하여 url 암호화 구현해 보기  (0) 2024.11.25
Spring 12  (0) 2024.08.09
Spring 11  (0) 2024.08.05
Spring 10  (0) 2024.08.01