🤔스프링부트를 이용하여 웹을 만드는 중 chagGpt를 이용할 수 있으면 좋지 않을까라는 생각에 chatGpt를 연동해보기로 하였습니다.
먼저 openAi에서 api-key를 발급받아줍니다.
이때 카드를 등록하게 되면 5달러가😭 자동으로 인출되게 됩니다.
(글을 찾아보니 나중에 다시 준다고 하긴 하는데 좀 이상합니다...)!
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;
}
}
uriComoponentBuilder
로 uri를 만들고 난후 HttpHeaders
에 api-key를 Bearer으로 넣어줍니다.RequestEntity
를 생성한 후 restTemplate
을 통해 값을 넘겨주었습니다.postman을 통해 제대로 값을 전달하고 받아오는지 확인해보겠습니다.
message에 "지구보다 큰 태양계 행성 중 하나만 이름을 알려줘"라는 메시지를 담아보냈습니다.
위와 같은 답변이 왔습니다.