스프링부트 chatGpt사용해 보기

greenTea·2023년 5월 29일
0

🤔스프링부트를 이용하여 웹을 만드는 중 chagGpt를 이용할 수 있으면 좋지 않을까라는 생각에 chatGpt를 연동해보기로 하였습니다.

1.API-key 발급

먼저 openAi에서 api-key를 발급받아줍니다.

이때 카드를 등록하게 되면 5달러가😭 자동으로 인출되게 됩니다.
(글을 찾아보니 나중에 다시 준다고 하긴 하는데 좀 이상합니다...)!

2. request api

openAi - api reference로 들어가면 스펙을 확인 할 수 있습니다.

아래와 같은 스펙을 요구하고 있습니다. 이에 맞춰서 보내주면 되는 것을 확인 하였습니다.

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'

스프링 부트로 메시지 받아오기

연결을 하기 위해 다양한 방법이 있지만 여기서는 restTemplate을 이용하여 메시지를 주고 받아오겠습니다.

먼저 자신의 api-key를 변수에 저장하여야 합니다. 저는 application.yml에 저장을 하고 @Value를 이용하여 가져왔습니다.

 @Value("${chatGpt.key}")
    private String key;

이제 restTemplate으로 메시지를 보내보겠습니다. 위에서 본 조건에 맞춰 메시지를 보내면 됩니다.

@Controller
public class ChatGptController {

    @Value("${chatGpt.key}")
    private String key;

    @PostMapping("/send")
    public ResponseEntity send(String message) {
        RestTemplate restTemplate = new RestTemplate();

        URI uri = UriComponentsBuilder
                .fromUriString("https://api.openai.com/v1/chat/completions")
                .build()
                .encode()
                .toUri();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "Bearer " + key);

        ArrayList<Message> list = new ArrayList<>();
        list.add(new Message("user",message));


        Body body = new Body("gpt-3.5-turbo", list);

        RequestEntity<Body> httpEntity = new RequestEntity<>(body, httpHeaders, HttpMethod.POST, uri);

        ResponseEntity<String> exchange = restTemplate.exchange(httpEntity, String.class);
        return exchange;
    }

    @AllArgsConstructor
    @Data
    static class Body {
        String model;
        List<Message> messages;
    }

    @AllArgsConstructor
    @Data
    static class Message {
        String role;
        String content;
    }
}
  1. uriComoponentBuilderuri를 만들고 난후 HttpHeadersapi-keyBearer으로 넣어줍니다.
  2. body에 담을 값을 넣어줍니다. api요구 스펙에 맞춰서 값을 담아 넣어줍니다.
  3. RequestEntity를 생성한 후 restTemplate을 통해 값을 넘겨주었습니다.

4. postman을 이용하여 값을 확인

postman을 통해 제대로 값을 전달하고 받아오는지 확인해보겠습니다.

message에 "지구보다 큰 태양계 행성 중 하나만 이름을 알려줘"라는 메시지를 담아보냈습니다.

response

위와 같은 답변이 왔습니다.

추가 할 점

  1. gpt를 이용해서 메시지를 보내게 되면 chunk단위로 비용을 지불해야 하기에 api-key는 절대 공개해서는 안됩니다.😭
  2. gpt를 보내 메시지를 받아오는 과정이 생각이상으로 시간이 걸리기에 이 점도 알아두시면 좋을 것 같습니다.
profile
greenTea입니다.

0개의 댓글