프로젝트에서 Gemini API를 이용해 서비스에 적용해야하는 요건이 있음
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GeminiReqDto {
private List<Content> contents;
@Data
public class Content{
private List<Part> parts;
public Content(String text){
parts = new ArrayList<>();
Part part = new Part(text);
parts.add(part);
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Part{
private String text;
}
}
public void createGeminiReqDto(String text){
this.contents = new ArrayList<>();
Content content = new Content(text);
contents.add(content);
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GeminiResDto {
private List<Candidate> candidates;
@Data
public static class Candidate {
private Content content;
private String finishReason;
}
@Data
public static class Content {
private List<Parts> parts;
private String role;
}
@Data
public static class Parts {
private String text;
}
}
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate geminiRestTemplate(){
return new RestTemplate();
}
}
public ProductDescriptionResDto getAIDescription(String productName){
String geminiURL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key="
+ "{GEMINI-API-KEY}";
String requestText = productName + "에 대한 상품 설명을 50자 이내로 작성해줘.";
GeminiReqDto request = new GeminiReqDto();
request.createGeminiReqDto(requestText);
String description = "";
try{
GeminiResDto response = restTemplate.postForObject(geminiURL, request, GeminiResDto.class);
description = response.getCandidates().get(0).getContent().getParts().get(0).getText();
}catch (Exception e){
log.error("INTERNAL SERVER ERROR");
throw new CoreApiException(ErrorType.DEFAULT_ERROR);
}
return new ProductDescriptionResDto(description);
}