package com.ch.jedge.jbot.knbase.query;

import com.ch.jedge.jbot.agent.JedgeGdeSession;
import com.ch.jedge.jbot.knbase.JedgeGptApp;
import com.ch.jedge.jbot.knbase.JedgeLlmIntent;
import com.ch.jedge.jbot.knbase.intent.JedgeGdeQuery;
import com.ch.jedge.jbot.session.JedgeServiceSession;
import com.changhong.jedge.JMgbusUtil;
import com.changhong.qlib.QData;
import com.changhong.qlib.intf.QIData;

import static com.ch.jedge.jbot.JEJBotLLMConst.sval_module_llm;

public class JedgeGptQueryIntent extends JedgeLlmIntent {

    public JedgeGptQueryIntent(JedgeGptApp app, JedgeServiceSession s, String key) {
        super(app, s, key);
    }

    @Override
    public boolean isQueryIntent() {
        return true;
    }

    @Override
    protected String getQueryPrompt(JedgeGdeQuery query) {
        //提取所有的背景知识:
        String context = gptSession.getGdtSession().getActiveContent(query);

        return super.getQueryPrompt(query);
    }

    @Override
    public boolean call(JedgeGdeSession gs, JedgeGdeQuery gdeQuery) {
        return super.call(gs, gdeQuery) && makeRealGptStreamCall(gs, gdeQuery);
    }

    private boolean makeRealGptStreamCall(JedgeGdeSession gs, JedgeGdeQuery gdeQuery) {
        //发起gpt的stream请求
        QIData gr = new QData();
        //当知识缓存Enable后,就不需要传统的聊天历史模式了
        // // "history":[["你好","你好👋！我是人工智能助手 ChatGLM-6B，很高兴见到你，欢迎问我任何问题。"]
        if(JedgeGptApp.isHistoryEnabled())
            gr.put("history", getGptHistory());
        String realQuery = getQueryPrompt(gdeQuery);
        if(JedgeGptApp.isDebugMode())
            mGdeApp.getMgModule().highLog(String.format("大模型调用：%s", realQuery));
        gr.put("query", realQuery);
        gr.put("cb",  "/gpt/LocalStream");//本地stream返回
        gr.put("sid", gs.getSessionId());
        QIData p = mGdeApp.getBotService().postServiceRequest(sval_module_llm, "/glm6b/stream", gr);
        if (!JMgbusUtil.isMgbusResultOk(p)) {
            gs.returnGptErrorMessage("中转服务器请求GPT数据失败");
            return false;
        }
        return true;
    }
}
