[코디'ing] GPT 답변을 해시태그화 하자

마뇽미뇽·2024년 12월 17일

코디'ing 프로젝트

목록 보기
5/7

지피티의 답변이 너무 길게 나오니 #으로 해시태그를 사용하면서 피드에 사용할 수 있도록 구현했다.

HashTagConfig.java

@Configuration
public class HashTagConfig {

    @Bean
    public HashTagGenerator hashTagGenerator() {
        return new HashTagGenerator();
    }
}

PostService.java

public interface PostService {
    void savePost(String content);
}

PostServiceImpl.java

@Service
public class PostServiceImpl implements PostService {

    @Override
    public void savePost(String content) {
        // 이 예제에서는 단순히 콘솔에 출력하는 방식으로 구현
        // 실제 애플리케이션에서는 데이터베이스에 저장하거나 다른 저장소에 저장할 수 있습니다.
        System.out.println("게시물 저장: " + content);
    }
}

controller 수정

	@Autowired
    private HashTagGenerator hashTagGenerator;

    @Autowired
    private PostService postService;

    @Operation(summary = "Chat 요청을 처리하고 결과를 반환", description = "ChatGPT에 메시지를 보내고, 날씨 정보를 포함한 결과를 반환합니다.")
    @GetMapping ("/chat")
    public @ResponseBody Response handleChat(@RequestBody ChatRequest chatRequest) {
        try {
            double latitude = chatRequest.getLatitude();
            double longitude = chatRequest.getLongitude();
            String prompt = chatRequest.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 Response("에러: 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 Response(resultWithHashtags);
        } catch (Exception e) {
            return new Response("에러가 발생했습니다. " + e.getMessage());
        }
    }
profile
Que sera, sera

0개의 댓글