[OpenAI] 스프링을 활용해 API 요청 보내기

류재성's avatar
Jun 30, 2024
[OpenAI] 스프링을 활용해 API 요청 보내기
 
notion image
 
기본 세팅
 
dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' developmentOnly 'org.springframework.boot:spring-boot-devtools' annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.0' implementation 'org.apache.httpcomponents.client5:httpclient5:5.1' implementation 'org.springframework.boot:spring-boot-starter-json' }
 
의존성 설정
 
application.yml
openai: api: key: YOUR_OPENAI_API_KEY
 
 
_core/WebConfig
💡
한글 깨지는 것을 막기 위해 설정
package org.example.openaitest._core; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); filter.setForceEncoding(true); return filter; } }
 
 
ai/OpenAIController
package org.example.openaitest.ai; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; @RequiredArgsConstructor @Controller public class OpenAIController { private final OpenAIService openAIService; @GetMapping("/") public String index() { return "index"; } @PostMapping("/api/openai/generate-poem") @ResponseBody public String generatePoem(@RequestBody OpenAIRequest.RequestDTO request) throws IOException { return openAIService.getResponse(request.getContent()); } }
 
ai/OpenAIService
package org.example.openaitest.ai; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.io.entity.StringEntity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.charset.StandardCharsets; @Service public class OpenAIService { @Value("${openai.api.key}") private String apiKey; private final ObjectMapper objectMapper; public OpenAIService(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public String getResponse(String prompt) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost request = new HttpPost("https://api.openai.com/v1/chat/completions"); request.setHeader("Content-Type", "application/json; charset=UTF-8"); request.setHeader("Authorization", "Bearer " + apiKey); String json = "{ \"model\": \"gpt-3.5-turbo\", \"messages\": [" + "{\"role\": \"system\", \"content\": \"당신은 음악 스트리밍 관리자입니다. 모든 응답을 한국어로 해주세요.\"}," + "{\"role\": \"user\", \"content\": \"" + prompt + "\"}] }"; request.setEntity(new StringEntity(json, StandardCharsets.UTF_8)); try (CloseableHttpResponse response = httpClient.execute(request)) { JsonNode jsonNode = objectMapper.readTree(response.getEntity().getContent()); return jsonNode.get("choices").get(0).get("message").get("content").asText(); } } } }
 
ai/OpenAIRequest
package org.example.openaitest.ai; import lombok.Data; public class OpenAIRequest { @Data public static class RequestDTO{ private String content; } }
 
index.mustache
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <title>OpenAI API 테스트</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h1>OpenAI API 사용</h1> <form id="prompt-form"> <label for="prompt">프롬프트 입력:</label><br> <textarea id="prompt" name="prompt" rows="4" cols="50"></textarea><br><br> <input type="button" value="제출" onclick="submitPrompt()"> </form> <h2>응답:</h2> <pre id="response"></pre> <script> function submitPrompt() { var prompt = $('#prompt').val(); $.ajax({ url: '/api/openai/generate-poem', type: 'POST', contentType: 'application/json', data: JSON.stringify({ prompt: prompt }), success: function(response) { $('#response').text(response); }, error: function(error) { $('#response').text('Error: ' + error.responseText); } }); } </script> </body> </html>
 
 
notion image
Share article
RSSPowered by inblog