[코디'ing] GPT에 날씨와 위치 api를 연동해보자

마뇽미뇽·2024년 12월 17일

코디'ing 프로젝트

목록 보기
6/7

gpt에 날씨와 위치정보를 줌으로써 위치기반 날씨에 따른 옷차림을 추천받을 수 있도록 구현하였다.

WeatherService.java

@Service
public class WeatherService {

    @Value("${weather.api.url}")
    private String apiUrl;

    @Value("${weather.api.key}")
    private String apiKey;

    private final RestTemplate restTemplate;

    public WeatherService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getWeatherByCoordinates(double latitude, double longitude) {
        String url = String.format("%s?lat=%f&lon=%f&appid=%s", apiUrl, latitude, longitude, apiKey);
        return restTemplate.getForObject(url, String.class);
    }
}

controller 수정

@RestController
@RequestMapping("/bot")
public class ChatGptController {

    @Value("${openai.model}")
    private String model;

    @Value("${openai.api.url}")
    private String apiURL;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private HashTagGenerator hashTagGenerator;

    @Autowired
    private PostService postService;

    @Autowired
    private WeatherService weatherService;

    @PostMapping("/chat")
    public @ResponseBody ChatResponseDto handleChat(@RequestBody ChatRequestDto chatRequestDto) {
        try {
            double latitude = chatRequestDto.getLatitude();
            double longitude = chatRequestDto.getLongitude();
            String prompt = chatRequestDto.getPrompt();

            // 날씨 정보 가져오기
            String weatherInfo = weatherService.getWeatherByCoordinates(latitude, longitude);

            // 프롬프트와 날씨 정보를 결합
            String extendedPrompt = prompt + "\n\n현재 날씨 정보: " + weatherInfo;

            ChatGptRequest request = new ChatGptRequest(model, extendedPrompt);
            ChatGptResponse chatGptResponse = restTemplate.postForObject(apiURL, request, ChatGptResponse.class);

            if (chatGptResponse == null || chatGptResponse.getChoices() == null || chatGptResponse.getChoices().isEmpty()) {
                return new ChatResponseDto("에러: API로부터 응답이 없습니다.");
            }

            String gptResult = chatGptResponse.getChoices().get(0).getMessage().getContent();

            // 해시태그 생성 (선택 사항)
            String hashtags = hashTagGenerator.generateHashTagsFromBoldText(gptResult);

            // 해시태그를 포함한 결과 문자열 생성
            String resultWithHashtags = gptResult + "\n\n #코디'ing #GPT픽 " + hashtags;

            // 게시물 저장 (선택 사항)
            postService.savePost(resultWithHashtags);

            return new ChatResponseDto(resultWithHashtags);
        } catch (Exception e) {
            return new ChatResponseDto("에러가 발생했습니다. " + e.getMessage());
        }
    }
}

ChatRequestDto.java

@Getter
@Setter
public class ChatRequestDto {
    private double latitude;
    private double longitude;
    private String prompt;
}

ChatResponseDto.java

@Getter
@Setter
@AllArgsConstructor
public class ChatResponseDto {
    private String response;
}
profile
Que sera, sera

0개의 댓글