개인프로젝트/기능프로그램_오늘뭐입지

20240518_GPT 답변 구현하기(MSA(3))

일일일코_장민기 2024. 5. 18. 07:44
728x90

 

 

 

더보기

GptController

package org.gpt.ask;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.gpt.GptanswervoDto;
import org.gpt.saveAnswer.SaveAnswerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequiredArgsConstructor
@Slf4j
@Controller
public class GptController {

    private final GptService gptService;
    private final SaveAnswerService saveAnswerService;

    @CrossOrigin(origins = "http://localhost:9001")
    @ResponseBody
    @PostMapping("/askToGpt")
    public String askToGpt(@RequestBody List<Object> questionData) throws JsonProcessingException {

        String dustData = questionData.get(0).toString();
        String weatherData = questionData.get(1).toString();
        String clothData = questionData.get(2).toString();
        String username = questionData.get(3).toString();
//        log.info("dust {}", dustData);
//        log.info("weather {}", weatherData);
//        log.info("cloth {}", clothData);
//        log.info("username {}", username);

        String question =
                "1.오늘의 날씨를 보고 입을 옷을 옷 데이터 중에서 골라 " +
                "모자, 겉옷, 상의, 하의, 양말, 신발이 서로 조화가 잘 되도록 골라 " +
                "모자, 겉옷은 제외 가능 " +
                "상의, 하의, 양말, 신발는 필수 포함 " +
                "2.미세먼지 상태를 보고 마스크 착용 여부 출력 " +
                "3.답변은 List<map>형태로 출력 " +
                "4.답변은 어떤 설명도 없이 데이터만 출력 " +
                "5.답변은 어떤 공백, 줄바꿈도 없어야 함" +
                "ex: [" +
                    "{\"모자\": \"다채로운 블랙 볼캡\", \"상의\": \"화이트 심플한 캐주얼한 티셔츠\", \"하의\": \"진청 데일리한 청바지\", \"양말\": \"화이트 베이직한 스니커즈 양말\", \"신발\": \"화이트 심플한 캔버스 스니커즈\"}," +
                    "{\"미세먼지(PM10)\": \"보통 (48)\", \"초미세먼지(PM2.5)\": \"좋음 (15)\", \"마스크 착용 여부\": \"없음\"}\n" +
                "]" +
                "오늘의 날씨: " + weatherData +
                " 오늘의 미세먼지: " + dustData +
                " 옷 데이터: " + clothData;
        log.info("question {}", question);
        String answer = gptService.getGptResponse(question);

        GptanswervoDto gptanswervoDto = new GptanswervoDto(username, question, answer);
        saveAnswerService.saveAnswer(gptanswervoDto);

        return answer;
    }
}

 

MemberRestContoller

PostMapping("/viewGptAnswer")
public List viewGptAnswer(WeatherareavoDTO weatherareavoDTO, Integer userid, String username) throws JsonProcessingException {

    List<CQ> clothForQuestionToGPTDTOS = clothController.selectClothDataForQuestionToGPT(userid);

    String weatherUrl = "http://localhost:9002/selectWeatherDataForQuestionToGPT";
    List<Object> answerByWeatherList = memberRestService.viewWeatherAnswer(weatherUrl, weatherareavoDTO, clothForQuestionToGPTDTOS, username);

    String gptUrl = "http://localhost:9003/askToGpt";
    String answerByGpt = memberRestService.viewGptAnswer(gptUrl, answerByWeatherList);
    return objectMapper.readValue(answerByGpt, List.class);
}

 

MemberRestService

public List<Object> viewWeatherAnswer(String url, Object sendingData, List<CQ> clothForQuestionToGPTDTOS, String username) throws JsonProcessingException {

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    String requestJson = objectMapper.writeValueAsString(sendingData);
    HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
    ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
    List<Object> answerByWeatherList = objectMapper.readValue(response.getBody(), List.class);
        answerByWeatherList.add(clothForQuestionToGPTDTOS);
        answerByWeatherList.add(username);
    return answerByWeatherList;
}

public String viewGptAnswer(String url, Object sendingData) throws JsonProcessingException {

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    String requestJson = objectMapper.writeValueAsString(sendingData);
    HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
    ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
    return response.getBody();
}

 

js

function viewGptAnswer(){
    const userid = $("#userid").val()
    const username = $("#username").val()
    const base_date = $("#base_date").val();
    const base_time = $("#base_time").val();
    const country = $("#country").val();
    const area = $("#area").val();

    const response_gptData = $("#response_gptData")
    const response_dustData = $("#response_dustData")

    $.ajax({
        type: "post",
        url: "/viewGptAnswer",
        data: {
            userid: userid,
            username: username,
            country: country,
            area: area,
            base_date: base_date,
            base_time: base_time
        },
        success: function(response){
            console.log(response)

            const clothData = response[0];
            const dustData = response[1];

            let clothTable = '<table>';
            clothTable += '<tr><th>항목</th><th>내용</th></tr>';
            for (const key in clothData) {
                clothTable += `<tr><td>${key}: </td><td>${clothData[key]}</td></tr>`;
            }
            clothTable += '</table>';

            let dustTable = '<table>';
            dustTable += '<tr><th>항목</th><th>내용</th></tr>';
            for (const key in dustData) {
                dustTable += `<tr><td>${key}: </td><td>${dustData[key]}</td></tr>`;
            }
            dustTable += '</table>';

            response_gptData.html(clothTable);
            response_dustData.html(dustTable);
        },
        error: function(){
            console.log("GPT 답변 ajax 에러")
        }
    })

}

 

GptController

- question 부분

- 사실 효율적인 것은 AI 학습을 통해 원하는 방식대로 답변을 받는 것이지만, 솔직히 그럴만한 여유가 없었다...

--> 조건과 예시를 세세하게 달아서 GPT로부터 원하는 답변을 받도록 만들었다.

 

MemberRestContoller

- url과 서비스를 넘기고 돌아오는 JSON 데이터를 받는다.

- 이걸 2번 반복해서 첫 번째는 weatherData를 받아오고, 두 번째는 gpt답변을 받아온다.

 

MemberRestService

- restful 방식을 통해 데이터를 넘기고 받는다.

- 이전 구글 로그인 방식을 만들때를 참고했다.

 

js

- 일정한 양식을 가진 JSON 데이터를 table 태그를 만들어서 집어넣었다.

 

출력

 

 

 

개선점

1. AI 학습을 통한 효율적인 질문