[Spring Boot] 스프링 ChatGPT API 활용 예제 ( + postman으로 확인 )

2024. 9. 4. 16:46· Spring Boot
목차
  1. 1. ChatGPT API
  2. 2. api key 발급
  3. 2-1. 회원가입 및 로그인
  4. 2-2. api key 발급
  5. 3. Postman 으로 api 작동 확인
  6. 3-1. curl 커맨드 작성
  7. 3-2. Postman으로 리턴된 결과 확인
  8. 4. 스프링 ChatGPT API 활용 예제
  9.  4-1. 의존 라이브러리
  10. 4-2. config > AppConfig
  11. 4-3. service
  12. 4-4. controller
  13. 4-5. 실행 결과

1. ChatGPT API

  • OpenAi에서 제공하는 언어 모델 API
  • 이 API를 활용하면 개발자가 애플리케이션에 대화형 AI 기능을 쉽게 통합할 수 있음
  • RESTful API
    • HTTP 요청을 통해 쉽게 호출 가능
    • JSON 형식으로 데이터를 주고 받음

 

2. api key 발급

2-1. 회원가입 및 로그인

  • https://platform.openai.com/docs/overview 접속
  • 우측 상단의 버튼으로 로그인(회원가입)진행

 

2-2. api key 발급

  • 우측 상단의 프로필 > Your profile 클릭

 

  • 프로필 페이지에서 User API keys 클릭

 

  • Create new secret key 클릭

 

  • Name과 Permissions 를 생성 의도에 맞게 설정 후 Create secret key 클릭

 

  • 상단에 API key generated! 라는 문구가 뜨며 생성된 api key가 출력됨
생성된 api key는 해당 페이지를 나가게 되면 다시 열람할 수 없음!
따라서 꼭 따로 저장해놓자!!

 

3. Postman 으로 api 작동 확인

3-1. curl 커맨드 작성

https://platform.openai.com/docs/api-reference/introduction

  • 위의 페이지에서 curl 커맨드 매뉴얼을 가져옴
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4o-2024-05-13",
    "messages": [
      {
        "role": "system",
        "content": "너는 스프링 챗지피티 프로젝트 도우미야. 모든 답변은 간단한 자기소개 후에 해줘."
      },
      {
        "role": "user",
        "content": "안녕? 서울의 위도와 경도를 알려줘"
      }
    ]
  }'
  • Authorization : Bearer [위에서 발급받은 api 키]
  • model : 자신이 사용하는 gpt 모델명 작성
    • 모델명 참고 : https://platform.openai.com/docs/models/gpt-4o
  • messages[0] : (챗gpt에게 역할 부여) 프롬프트 엔지니어링, 마크다운 언어 호환
  • messages[1] : 챗gpt에게 입력할 메시지

 

3-2. Postman으로 리턴된 결과 확인

  • 위에서 작성한 curl 을 postman에서 복붙 ⇒ 결과 확인

  • choices[0]의 message 내부의 content 에 답변이 담겨 온 것을 확인!
    • 프롬프트 엔지니어링으로 챗 gpt에게 부여한 역할에 맞게 간단한 자기 소개 후에 답변한 것도 확인 가능

 

4. 스프링 ChatGPT API 활용 예제

 4-1. 의존 라이브러리

  • build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

    // JSON 데이터를 처리하기 위한 라이브러리 추가
    implementation group: 'org.json', name: 'json', version: '20231013'

}

 

4-2. config > AppConfig

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  • RestTemplate을 스프링 컨테이너에 빈으로 등록
  • 애플리케이션의 다른 곳에서도 RESTful API 호출을 쉽게 수행 가능하게 함

 

4-3. service

  • ChatGPTService
@Service
@RequiredArgsConstructor
public class ChatGPTService {

    // RestTemplate 주입받음
    private final RestTemplate restTemplate;

    // 메시지 입력받고 챗gpt의 응답을 리턴하는 메서드
    public ResponseEntity<String> chat(String message) {

        HttpHeaders headers = new HttpHeaders(); // HTTP 헤더 생성
        headers.setContentType(MediaType.APPLICATION_JSON); // 요청 본문 타입 설정
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // 수신할 응답 타입 설정
        String apiKey = ""; // 발급받은 API 키 설정 (여기서는 지움)
        headers.set("Authorization", "Bearer " + apiKey); // 인증 헤더에 API 키 추가

        JSONObject messageSystem = new JSONObject(); // 시스템 메시지 JSON 객체 생성
        messageSystem.put("role", "system");  // 역할 설정
        messageSystem.put("content", "너는 스프링 챗지피티 프로젝트 도우미야. 모든 답변은 간단한 자기소개 후에 해줘."); // 시스템 메시지 추가

        JSONObject messageUser = new JSONObject(); // 사용자 메시지 JSON 객체 생성
        messageUser.put("role", "user"); // 역할 설정
        messageUser.put("content", message); // 사용자 메시지 추가

        JSONObject requestBody = new JSONObject(); // 요청 본문을 위한 JSON 객체 생성
        requestBody.put("model", "gpt-4o-2024-05-13"); // 사용할 모델 설정
        requestBody.put("messages", new JSONArray(Arrays.asList(messageSystem, messageUser))); // 메시지 배열 추가

        HttpEntity<String> request = new HttpEntity<>(requestBody.toString(), headers); // HTTP 요청 엔티티 생성

        String apiEndpoint = "https://api.openai.com/v1/chat/completions"; // API 엔드포인트 설정
        try {
            // REST API 호출을 통해 응답 받기
            ResponseEntity<String> response = restTemplate.postForEntity(apiEndpoint, request, String.class);

            // 응답 상태 코드 확인
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return response;  // 성공적인 응답 반환
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("api 호출 중 오류 발생!"); // 오류 메시지 반환
            }
        } catch (Exception e) {
            e.printStackTrace();

            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("api 호출 중 예외 발생: " + e.getMessage()); // 예외 메시지 반환
        }
    }
}

 

4-4. controller

  • ChatGPTApiController
@RestController
@RequiredArgsConstructor
public class ChatGPTApiController {

    private final ChatGPTService chatGPTService;

    @GetMapping("/api/chatGPT")
    public ResponseEntity<String> chatGPT(@RequestBody String message) {
        return chatGPTService.chat(message);
    }
}

 

4-5. 실행 결과

  • GET localhost:8080/api/chatGPT
    • Body에 메시지에 해당하는 JSON 추가 후 요청 전송

 

저작자표시 변경금지 (새창열림)

'Spring Boot' 카테고리의 다른 글

[Spring Boot] ResponseEntity 사용 이유, 사용 방법  (1) 2024.09.05
[Spring Boot] 스프링 트랜잭션 (@Transactional)  (0) 2024.09.05
[Spring Boot] 스프링 이미지 업로드 예제 (3) - 외부 경로에 업로드  (0) 2024.09.03
[Spring Boot] 스프링 이미지 업로드 예제 (2) - DB에 이미지 직접 저장  (0) 2024.09.02
[Spring Boot] 스프링 이미지 업로드 예제 (1) - 프로젝트 내부 디렉토리에 업로드  (0) 2024.09.02
  1. 1. ChatGPT API
  2. 2. api key 발급
  3. 2-1. 회원가입 및 로그인
  4. 2-2. api key 발급
  5. 3. Postman 으로 api 작동 확인
  6. 3-1. curl 커맨드 작성
  7. 3-2. Postman으로 리턴된 결과 확인
  8. 4. 스프링 ChatGPT API 활용 예제
  9.  4-1. 의존 라이브러리
  10. 4-2. config > AppConfig
  11. 4-3. service
  12. 4-4. controller
  13. 4-5. 실행 결과
'Spring Boot' 카테고리의 다른 글
  • [Spring Boot] ResponseEntity 사용 이유, 사용 방법
  • [Spring Boot] 스프링 트랜잭션 (@Transactional)
  • [Spring Boot] 스프링 이미지 업로드 예제 (3) - 외부 경로에 업로드
  • [Spring Boot] 스프링 이미지 업로드 예제 (2) - DB에 이미지 직접 저장
공대생안씨
공대생안씨
전자공학과 학부생의 코딩 일기
공대생의 코딩 일기전자공학과 학부생의 코딩 일기
티스토리
|
로그인
공대생안씨
공대생의 코딩 일기
공대생안씨
글쓰기
|
관리
전체
오늘
어제
  • All Categories (153)
    • Spring Boot (46)
      • JPA (7)
      • Lombok (2)
    • Java (21)
    • DevOps (3)
      • CI,CD (8)
      • Monitoring (2)
    • Database (7)
      • MySQL (5)
      • MongoDB (1)
      • H2 (1)
    • Trouble Shooting (5)
    • FE (4)
    • IntelliJ (3)
    • Git (3)
    • Algorithm (41)

블로그 메뉴

  • 홈
  • 태그
  • Github

공지사항

인기 글

hELLO · Designed By 정상우.v4.2.2
공대생안씨
[Spring Boot] 스프링 ChatGPT API 활용 예제 ( + postman으로 확인 )
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.