package cn.com.poc.thirdparty.service.impl;

import cn.com.poc.thirdparty.resource.demand.ai.aggregate.AIDialogueService;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Function;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Tool;
import cn.com.poc.thirdparty.resource.demand.ai.entity.function.FunctionCallResponse;
import cn.com.poc.thirdparty.resource.demand.ai.entity.function.FunctionCallResult;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelDemandResult;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelResponse;
import cn.com.poc.thirdparty.service.LLMService;
import cn.hutool.core.lang.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author alex.yao
 * @date 2023/11/23
 **/
@Service
public class LLMServiceImpl implements LLMService {

    private final Logger logger = LoggerFactory.getLogger(LLMService.class);

    @Resource
    private AIDialogueService aiDialogueService;

    @Override
    public LargeModelDemandResult chat(LargeModelResponse response) {
        try {
            return aiDialogueService.poly(response);
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        return null;
    }


    @Override
    public BufferedReader chatChunk(LargeModelResponse request) throws Exception {
        return aiDialogueService.polyStream(request);
    }

    @Override
    public FunctionCallResult functionCall(String query, Tool[] tools) {
        Assert.notEmpty(tools);
        FunctionCallResponse response = new FunctionCallResponse();
        response.setQuery(query);
        List<Function> functions = new ArrayList<>();
        for (Tool tool : tools) {
            Function function = new Function();
            function.setName(tool.getFunction().getName());
            function.setDescription(tool.getFunction().getDescription());
            function.setParameters(tool.getFunction().getParameters());
            functions.add(function);
        }
        response.setFunctions(functions);
        return aiDialogueService.functionCall(response);
    }
}
