package cn.iocoder.yudao.module.llm.service.http;

import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.llm.framework.backend.config.LLMBackendProperties;
import cn.iocoder.yudao.module.llm.service.http.vo.*;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ModelService {

    public final static String DEFAULT_MODEL_ID = "qwen2.5-instruct";

    @Resource
    private LLMBackendProperties llmBackendProperties;

    /**
     * 获取模型列表
     */
    public ModelListRespVO modelList(){
        String result = HttpUtils.get(llmBackendProperties.getModelCompletions(), null);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        try {
            ModelList modelList = JSON.parseObject(result, ModelList.class);
            if (StringUtils.isBlank(modelList.getDetail())) {
                // 没有detail，就是没有错误
                ModelListRespVO respVO = new ModelListRespVO();
                respVO.setData(BeanUtils.toBean(modelList.getData(), ModelListRespVO.ModelData.class));
                return respVO;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    public ModelCompletionsRespVO modelCompletions(ModelCompletionsReqVO req) {
        if (StringUtils.isBlank(req.getModel())) {
            req.setModel(DEFAULT_MODEL_ID);
        }
        String result = HttpUtils.post(llmBackendProperties.getModelCompletions(), null, JSON.toJSONString(req));
        if (StringUtils.isBlank(result)) {
            return null;
        }
        try {
            ChatCompletion chatCompletion = JSON.parseObject(result, ChatCompletion.class);
            if (StringUtils.isBlank(chatCompletion.getDetail())) {
                // 没有detail，就是没有错误
                ModelCompletionsRespVO respVO = new ModelCompletionsRespVO();
                respVO.setSystem("助手");
                respVO.setQuestion(req.getMessages().get(req.getMessages().size() - 1).getContent());
                respVO.setAnswer(chatCompletion.getChoices().get(0).getMessage().getContent());
                return respVO;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
}
