Spring & Spring Boot

[Spring&SpringBoot] OpenAI 이미지 생성 API 사용하기

김먼저 2023. 5. 31. 10:31

 

준비물 : OpenAI Secret API Key

 

https://firstws.tistory.com/63

 

[OpenAI] OpenAI API Key 발급 받기(feat.chatGPT)

0. OpenAI API Key OpenAI에서 개발한 인공지능 모델들을 외부에서 사용할 수 있도록 인증하는 역할을 합니다. OpenAI는 다양한 유형의 인공지능 모델을 제공하는데요, 대표적인 모델을 살펴보면 아래와

firstws.tistory.com

 

1. Postman으로 Test 해보기

 

method : POST
url : https://api.openai.com/v1/images/generations

 

Headers Setting

 

Content-Type : application/json
Authorization : ${OpenAI Secret API Key}

 

 

Body-JSON

 

{
    "prompt" : "cute cat Illustrate",
    "n" : 1,
    "size" : "256x256"
}

 

promt : 요청 메세지
n : 이미지 개수(1~10)
size : 이미지 사이즈('128x128', '256x256', '1024x1024'만 가능)
response_format : url(default), b64_json(Base64) 두가지 가능

 

 

'Send' 클릭해서 요청 보내기 - 결과

 

 

 

url링크를 클릭하거나 브라우저에 붙여넣습니다.

 

 

ChatGPT보다 쉽고 적용하는 것은 더욱 쉽습니다.

 

이제 DTO - Config - Controller - Service 순서로 작성해보겠습니다.

 

 

2. DTO 작성하기

 

@Getter
@NoArgsConstructor
//Front단에서 요청하는 DTO
public class CommentRequest implements Serializable {
    private String comment;

    public CommentRequest(String comment) {
        this.comment = comment;
    }
}
@Getter
@NoArgsConstructor
//OpenAI에 요청할 DTO Format('response_format' 추가하셔도됩니다.)
public class ImageGenerationRequest implements Serializable {
    private String prompt;
    private int n;
    private String size;

    @Builder
    public ImageGenerationRequest(String prompt, int n, String size) {
        this.prompt = prompt;
        this.n = n;
        this.size = size;
    }
}
@Getter
@NoArgsConstructor
//요청에 대한 응답을 받을 DTO
public class ImageGenerationResponse {

    private long created;
    private List<ImageURL> data;

    @Getter
    @Setter
    public static class ImageURL {
        private String url;
    }
}

 

 

 

3. Config 작성하기

 

package com.ctrit.c_cocaine.infra.openai.chatGPT;

import org.springframework.context.annotation.Configuration;

@Configuration
public class ChatGptConfig {
    public static final String AUTHORIZATION = "Authorization";
    public static final String BEARER = "Bearer ";
    public static final String MEDIA_TYPE = "application/json; charset=UTF-8";
    public static final String IMAGE_URL = "https://api.openai.com/v1/images/generations";
    public static final int IMAGE_COUNT = 2;//  1~10
    public static final String IMAGE_SIZE = "256x256"; // '256x256', '512x512', '1024x1024'
}

 

 

 

4. Controller 작성하기

 

@RequiredArgsConstructor
@RequestMapping("/chat-gpt")
@RestController
public class ChatGptController {
    private final APIResponse apiResponse;
    private final ChatGptService chatGptService;

    @PostMapping("/image-generation")
    public ResponseEntity sendComment(
            Locale locale,
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody CommentRequest commentRequest) {
        String code = ResponseCode.CD_SUCCESS;
        ImageGenerationResponse imageGenerationResponse = null;
        try {
            imageGenerationResponse = chatGptService.makeImages(commentRequest);
        } catch (Exception e) {
            apiResponse.printErrorMessage(e);
            code = e.getMessage();
        }
        return apiResponse.getResponseEntity(locale, code,
                imageGenerationResponse != null ? imageGenerationResponse.getData() : new ChatGptResponse());
    }
}

 

 

 

 

5. Service 작성하기

 

@Slf4j
@RequiredArgsConstructor
@Service
public class ChatGptService {
    private final RestTemplate restTemplate;

	//api key를 application.yml에 넣어두었습니다.
    @Value("${api-key.chat-gpt}")
    private String apiKey;

    public ImageGenerationResponse makeImages(CommentRequest commentRequest){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType(ChatGptConfig.MEDIA_TYPE));
        httpHeaders.add(ChatGptConfig.AUTHORIZATION, ChatGptConfig.BEARER + apiKey);

        ImageGenerationRequest imageGenerationRequest = ImageGenerationRequest.builder()
                .prompt(commentRequest.getComment())
                .n(ChatGptConfig.IMAGE_COUNT)
                .size(ChatGptConfig.IMAGE_SIZE)
                .build();

        HttpEntity<ImageGenerationRequest> requestHttpEntity = new HttpEntity<>(imageGenerationRequest, httpHeaders);

        ResponseEntity<ImageGenerationResponse> responseEntity = restTemplate.postForEntity(
                ChatGptConfig.IMAGE_URL,
                requestHttpEntity,
                ImageGenerationResponse.class
        );
        return responseEntity.getBody();
    }
}

 

 

 

실행 결과

 

 

 

 

*한글로 요청시 반영이 거의 안되니 영어로 요청하시길 바랍니다!

 

 

Ref : https://platform.openai.com/docs/api-reference/images

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com