package com.aiup.chatgptserver.service.impl;

import com.aiup.chatgptserver.service.GptChatQuery;
import com.aiup.chatgptserver.service.OpenAiService;
import com.aiup.chatgptserver.service.openai.ChatRequest;
import com.aiup.chatgptserver.service.openai.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class OpenAiServiceImpl implements OpenAiService {

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

    @Value("${openai.api.url}")
    private String apiUrl;
    @Autowired
    private RestTemplate restTemplate;
     /**
     * ChatGPT聊天
     * @param query
     * @return
     */
     @Override
    public ChatResponse chat(GptChatQuery query) throws Exception {
         log.warn("aaaaaaa");
        // create a request
        ChatRequest request = new ChatRequest(model, query.getPrompt());
        // call the API
        ChatResponse response = restTemplate.postForObject(apiUrl, request, ChatResponse.class);
        if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
            throw new Exception("服务忙，请重试");
        }
        // return the first response
        return response;
    }
}
