chatGPT API 사용

안민기·2024년 6월 8일

개요

프로젝트 중 openAI에서 제공하는 API를 사용하여 chatGPT 서비스를 이용하고자 했다.

사용법

  1. openAI 사이트(https://platform.openai.com/docs/overview)에 접속후 회원가입을 해준다.

  2. 키 발급 페이지(https://platform.openai.com/account/api-keys)에 들어간 후 Billing을 눌러 결제한다.

  3. Creat new secret key를 눌러 키를 생성받는다.

openAI API는 JSON을 이용해 통신하는데, 스프링부트에 정보를 등록 후 자유롭게 통신할 수 있다.

application.properties

openai.model = [모델 명]
openai.secret-key = [발급받은 키]
openai.api.url = [api url]

ServiceImpl.class

@Service
public class GptServiceImpl implements GptService{
	 @Value("${openai.secret-key}")
    private String apiKey;

    public JsonNode callChatGpt(String userMsg) throws JsonProcessingException {
        final String url = "주소";

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        ObjectMapper objectMapper = new ObjectMapper();

        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("model", "gpt-4");

        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", userMsg);
        messages.add(userMessage);

        Map<String, String> assistantMessage = new HashMap<>();
        assistantMessage.put("role", "system");
        assistantMessage.put("content", "너는 친절한 AI야");
        messages.add(assistantMessage);

        bodyMap.put("messages", messages);

        String body = objectMapper.writeValueAsString(bodyMap);

        HttpEntity<String> request = new HttpEntity<>(body, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);

        return objectMapper.readTree(response.getBody());
    }

    @Override
    public String getAssistantMsg(String userMsg) throws JsonProcessingException {
        JsonNode jsonNode = callChatGpt(userMsg);
        String content = jsonNode.path("choices").get(0).path("message").path("content").asText();

        return content;
    }
}

Service.class

public interface GptService {
	String getAssistantMsg(String userMsg) throws JsonProcessingException;
}

Controller

//답변(param = 질문)
String.valueOf(gptService.getAssistantMsg(param))
profile
개발 블로그

0개의 댓글