const axios = require("axios");
const { hash, formatPrompt, randomIpv4, sleep } = require("./util");
const marked = require("marked");

const gpt4o = async ({
    messages = [],
    markdown = false
}, result) => {
    let datagpt = {
        messages: [],
        markdown: false
    }

    let msgss = [];

    try {
        if(markdown != undefined && markdown != null && (typeof markdown).toString().toLowerCase() === "Boolean".toLowerCase() && markdown === true){
            datagpt.markdown = true;
        } else {
            datagpt.markdown = false;
        }
    } catch(e){
        datagpt.markdown = false;
    }

    try {
        if(messages != undefined && messages != null && (typeof messages).toString().toLowerCase() === "Object".toLowerCase() && Array.isArray(messages)){
            messages.forEach(e => {
                if(e.role != undefined && e.role != null && (typeof e.role).toString().toLowerCase() === "String".toLowerCase() && e.role.toString().trim().length > 0){
                    if((e.role.toString().toLowerCase() === "user" || e.role.toString().toLowerCase() === "assistant") && e.content != undefined && e.content != null && (typeof e.content).toString().toLowerCase() === "String".toLowerCase()){
                        msgss.push({
                            role: e.role.toString().toLowerCase(),
                            content: e.content.toString()
                        });
                    }
                }
            });

            if(msgss.length <= 0){
                msgss = [];
            }
        } else {
            msgss = [];
        }
    } catch(e){
        msgss = [];
    }

    if(msgss.length <= 0){
        return result({
            "message": null,
            "original": null,
            "finish": true,
            "error": true
        });
    }

    datagpt.messages = msgss;
    datagpt.messages = formatPrompt(datagpt.messages);

    let count = 0;

    async function goGPT4() {
        try {
            await sleep(100);
            let chat = "";
            let sess = hash();
            let request = null;
            const ip4 = randomIpv4();

            request = await axios.post("https://yuntian-deng-o1mini.hf.space/queue/join?__theme=dark", {
                "data": [
                    datagpt.messages,
                    1,
                    1,
                    0,
                    [],
                    []
                ],
                "event_data": null,
                "fn_index": 3,
                "trigger_id": 5,
                "session_hash": sess
            }, {
                headers: {
                    "accept": "*/*",
                    "accept-encoding": "gzip, deflate, br, zstd",
                    "accept-language": 'en-US,en;q=0.5',
                    "cache-control": "no-cache",
                    "content-type": "application/json",
                    "origin": "https://yuntian-deng-o1mini.hf.space",
                    "pragma": "no-cache",
                    "priority": "u=1, i",
                    "referer": "https://yuntian-deng-o1mini.hf.space/?__theme=dark",
                    "sec-ch-ua": "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "\"Windows\"",
                    "sec-fetch-dest": "empty",
                    "sec-fetch-mode": "cors",
                    "sec-fetch-site": "same-origin",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
                    "X-Forwarded-For": `${ip4}`,
                    "X-ProxyUser-Ip": "203.0.113.19"
                }
            });
            
            if(request.status != 200){
                throw new Error("error");
            }

            request = await axios.get("https://yuntian-deng-o1mini.hf.space/queue/data?session_hash=" + encodeURIComponent(sess), {
                headers: {
                    "accept": "text/event-stream",
                    "accept-encoding": "gzip, deflate, br, zstd",
                    "accept-language": 'en-US,en;q=0.5',
                    "cache-control": "no-cache",
                    "content-type": "application/json",
                    "pragma": "no-cache",
                    "priority": "u=1, i",
                    "referer": "https://yuntian-deng-o1mini.hf.space/?__theme=dark",
                    "sec-ch-ua": "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "\"Windows\"",
                    "sec-fetch-dest": "empty",
                    "sec-fetch-mode": "cors",
                    "sec-fetch-site": "same-origin",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
                    "X-Forwarded-For": `${ip4}`,
                    "X-ProxyUser-Ip": "203.0.113.19"
                },
                responseType: "stream"
            });

            if(request.status != 200){
                throw new Error("error");
            }

            let tmp = null;
            request.data.on("data", (chunk) => {
                let data_chk = chunk.toString();

                try {
                    data_chk.split("\n\n").forEach(e => {
                        try {
                            let data = e;

                            try {
                                if(data.startsWith("data: ")){
                                    data = data.slice(6);
                                }

                                data = JSON.parse(data);
                            } catch (error) {
                                if(tmp === null){
                                    tmp = data;
                                } else {
                                    tmp += data;
                                }
                            }

                            try {
                                if(tmp != null){
                                    data = JSON.parse(tmp);
                                    tmp = null;
                                } else {
                                    data = data;
                                }
                            } catch (error) {
                                data = data;
                            }

                            if(data != null && typeof data === "object"){
                                if(data.msg != undefined && data.msg != null){
                                    switch(data.msg){
                                        case "process_generating":
                                        case "process_completed":
                                            if(data.output != undefined && data.output != null && data.output.data != undefined && data.output.data != null){
                                                data.output.data.forEach(e => {
                                                    try {
                                                        if(Array.isArray(e)){
                                                            let ed = e.length - 1;
                                                            e = e[ed];
                                                            
                                                            if(e[e.length - 1] != undefined && e[e.length - 1] != null){
                                                                let chat_tt = e[e.length - 1];

                                                                if(typeof chat_tt === "string"){
                                                                    if(data.msg != "process_completed"){
                                                                        chat += chat_tt;
            
                                                                        if(datagpt.markdown === true){
                                                                            try {
                                                                                let mark = marked.parse(chat);
                                    
                                                                                result({
                                                                                    "message": mark,
                                                                                    "original": chat,
                                                                                    "finish": false,
                                                                                    "error": false
                                                                                });
                                                                            } catch (error) {
                                                                                chat = chat;
                                                                            }
                                                                        } else {
                                                                            result({
                                                                                "message": chat,
                                                                                "original": null,
                                                                                "finish": false,
                                                                                "error": false
                                                                            });
                                                                        }
                                                                    } else {
                                                                        throw new Error("error");
                                                                    }
                                                                } else {
                                                                    throw new Error("error");
                                                                }
                                                            } else {
                                                                throw new Error("error");
                                                            }
                                                        } else {
                                                            throw new Error("error");
                                                        }
                                                    } catch (error) {
                                                        chat = chat;
                                                    }
                                                });
                                            } else {
                                                throw new Error("error");
                                            }
                                            break;
                                        default:
                                            throw new Error("error");
                                            break;
                                    }
                                } else {
                                    throw new Error("error");
                                }
                            } else {
                                chat = chat;
                            }
                        } catch (error) {
                            chat = chat;
                        }
                    });
                } catch (error) {
                    chat = chat;
                }
            });

            request.data.on("end", () => {
                if(chat.trim().length <= 0){
                    count += 1;
                    if(count > 10){
                        return result({
                            "message": null,
                            "original": null,
                            "finish": true,
                            "error": true
                        });
                    } else {
                        setTimeout(function(){goGPT4();});
                    }
                } else {
                    return result({
                        "message": null,
                        "original": null,
                        "finish": true,
                        "error": false
                    });
                }
            });

            request.data.on("error", () => {
                
            });
        } catch (error) {
            count += 1;
            if(count > 10){
                return result({
                    "message": null,
                    "original": null,
                    "finish": true,
                    "error": true
                });
            } else {
                setTimeout(function(){goGPT4();});
            }
        }
    }

    async function goGPT3(){
        try {
            await sleep(100);
            let chat = "";
            let sess = hash();
            let request = null;
            const ip4 = randomIpv4();

            request = await axios.post("https://yuntian-deng-chatgpt4turbo.hf.space/queue/join?", {
                "data": [
                    datagpt.messages,
                    1,
                    1,
                    0,
                    [],
                    []
                ],
                "event_data": null,
                "fn_index": 5,
                "trigger_id": 9,
                "session_hash": sess
            }, {
                headers: {
                    "accept": "*/*",
                    "accept-encoding": "gzip, deflate, br, zstd",
                    "accept-language": 'en-US,en;q=0.5',
                    "content-type": "application/json",
                    "origin": "https://yuntian-deng-chatgpt4turbo.hf.space/",
                    "priority": "u=1, i",
                    "referer": "https://yuntian-deng-chatgpt4turbo.hf.space/",
                    "sec-ch-ua": "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\"",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "\"Windows\"",
                    "sec-fetch-dest": "empty",
                    "sec-fetch-mode": "cors",
                    "sec-fetch-site": "same-origin",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
                    "X-Forwarded-For": `${ip4}`,
                    "X-ProxyUser-Ip": "203.0.113.19"
                }
            });

            if(request.status != 200){
                throw new Error("error");
            }

            request = await axios.get("https://yuntian-deng-chatgpt4turbo.hf.space/queue/data?session_hash=" + encodeURIComponent(sess), {
                headers: {
                    "accept": "*/*",
                    "accept-encoding": "gzip, deflate, br, zstd",
                    "accept-language": 'en-US,en;q=0.5',
                    "content-type": "application/json",
                    "origin": "https://yuntian-deng-chatgpt4turbo.hf.space/",
                    "priority": "u=1, i",
                    "referer": "https://yuntian-deng-chatgpt4turbo.hf.space/",
                    "sec-ch-ua": "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\"",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "\"Windows\"",
                    "sec-fetch-dest": "empty",
                    "sec-fetch-mode": "cors",
                    "sec-fetch-site": "same-origin",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
                    "X-Forwarded-For": `${ip4}`,
                    "X-ProxyUser-Ip": "203.0.113.19"
                },
                responseType: "stream"
            });

            if(request.status != 200){
                throw new Error("error");
            }

            let tmp = null;
            request.data.on("data", (chunk) => {
                let data_chk = chunk.toString();

                try {
                    data_chk.split("\n\n").forEach(e => {
                        try {
                            let data = e;

                            try {
                                if(data.startsWith("data: ")){
                                    data = data.slice(6);
                                }

                                data = JSON.parse(data);
                            } catch (error) {
                                if(tmp === null){
                                    tmp = data;
                                } else {
                                    tmp += data;
                                }
                            }

                            try {
                                if(tmp != null){
                                    data = JSON.parse(tmp);
                                    tmp = null;
                                } else {
                                    data = data;
                                }
                            } catch (error) {
                                data = data;
                            }

                            if(data != null && typeof data === "object"){
                                if(data.msg != undefined && data.msg != null){
                                    switch(data.msg){
                                        case "process_generating":
                                        case "process_completed":
                                            if(data.output != undefined && data.output != null && data.output.data != undefined && data.output.data != null){
                                                data.output.data.forEach(e => {
                                                    try {
                                                        if(Array.isArray(e)){
                                                            let ed = e.length - 1;
                                                            e = e[ed];

                                                            if(e[e.length - 1] != undefined && e[e.length - 1] != null){
                                                                let chat_tt = e[e.length - 1];
                                                                if(typeof chat_tt === "string"){
                                                                    if(data.msg != "process_completed"){
                                                                        chat += chat_tt;
            
                                                                        if(datagpt.markdown === true){
                                                                            try {
                                                                                let mark = marked.parse(chat);
                                    
                                                                                result({
                                                                                    "message": mark,
                                                                                    "original": chat,
                                                                                    "finish": false,
                                                                                    "error": false
                                                                                });
                                                                            } catch (error) {
                                                                                chat = chat;
                                                                            }
                                                                        } else {
                                                                            result({
                                                                                "message": chat,
                                                                                "original": null,
                                                                                "finish": false,
                                                                                "error": false
                                                                            });
                                                                        }
                                                                    } else {
                                                                        throw new Error("error");
                                                                    }
                                                                } else {
                                                                    throw new Error("error");
                                                                }
                                                            } else {
                                                                throw new Error("error");
                                                            }
                                                        } else {
                                                            throw new Error("error");
                                                        }
                                                    } catch (error) {
                                                        chat = chat;
                                                    }
                                                });
                                            } else {
                                                throw new Error("error");
                                            }
                                            break;
                                        default:
                                            throw new Error("error");
                                            break;
                                    }
                                } else {
                                    throw new Error("error");
                                }
                            } else {
                                chat = chat;
                            }
                        } catch (error) {
                            chat = chat;
                        }
                    });
                } catch (error) {
                    chat = chat;
                }
            });

            request.data.on("end", () => {
                if(chat.trim().length <= 0){
                    count += 1;
                    if(count > 10){
                        count = 0;
                        setTimeout(function(){goGPT4();});
                    } else {
                        setTimeout(function(){goGPT3();});
                    }
                } else {
                    return result({
                        "message": null,
                        "original": null,
                        "finish": true,
                        "error": false
                    });
                }
            });

            request.data.on("error", () => {
                
            });
        } catch (error) {
            count += 1;
            if(count > 10){
                count = 0;
                setTimeout(function(){goGPT4();});
            } else {
                setTimeout(function(){goGPT3();});
            }
        }
    }

    async function goGPT2() {
        try {
            await sleep(100);
            let chat = "";
            let sess = hash();
            let request = null;
            const ip4 = randomIpv4();

            request = await axios.post("https://yuntian-deng-chatgpt4.hf.space/queue/join?", {
                "data": [
                    datagpt.messages,
                    1,
                    1,
                    0,
                    [],
                    []
                ],
                "event_data": null,
                "fn_index": 3,
                "trigger_id": 5,
                "session_hash": sess
            }, {
                headers: {
                    "accept": "*/*",
                    "accept-encoding": "gzip, deflate, br, zstd",
                    "accept-language": 'en-US,en;q=0.5',
                    "content-type": "application/json",
                    "origin": "https://yuntian-deng-chatgpt4.hf.space",
                    "priority": "u=1, i",
                    "referer": "https://yuntian-deng-chatgpt4.hf.space/",
                    "sec-ch-ua": "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\"",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "\"Windows\"",
                    "sec-fetch-dest": "empty",
                    "sec-fetch-mode": "cors",
                    "sec-fetch-site": "same-origin",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
                    "X-Forwarded-For": `${ip4}`,
                    "X-ProxyUser-Ip": "203.0.113.19"
                }
            });
            
            if(request.status != 200){
                throw new Error("error");
            }

            request = await axios.get("https://yuntian-deng-chatgpt4.hf.space/queue/data?session_hash=" + encodeURIComponent(sess), {
                headers: {
                    "accept": "*/*",
                    "accept-encoding": "gzip, deflate, br, zstd",
                    "accept-language": 'en-US,en;q=0.5',
                    "content-type": "application/json",
                    "origin": "https://yuntian-deng-chatgpt4.hf.space",
                    "priority": "u=1, i",
                    "referer": "https://yuntian-deng-chatgpt4.hf.space/",
                    "sec-ch-ua": "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\"",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "\"Windows\"",
                    "sec-fetch-dest": "empty",
                    "sec-fetch-mode": "cors",
                    "sec-fetch-site": "same-origin",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
                    "X-Forwarded-For": `${ip4}`,
                    "X-ProxyUser-Ip": "203.0.113.19"
                },
                responseType: "stream"
            });

            if(request.status != 200){
                throw new Error("error");
            }

            let tmp = null;
            request.data.on("data", (chunk) => {
                let data_chk = chunk.toString();

                try {
                    data_chk.split("\n\n").forEach(e => {
                        try {
                            let data = e;

                            try {
                                if(data.startsWith("data: ")){
                                    data = data.slice(6);
                                }

                                data = JSON.parse(data);
                            } catch (error) {
                                if(tmp === null){
                                    tmp = data;
                                } else {
                                    tmp += data;
                                }
                            }

                            try {
                                if(tmp != null){
                                    data = JSON.parse(tmp);
                                    tmp = null;
                                } else {
                                    data = data;
                                }
                            } catch (error) {
                                data = data;
                            }

                            if(data != null && typeof data === "object"){
                                if(data.msg != undefined && data.msg != null){
                                    switch(data.msg){
                                        case "process_generating":
                                        case "process_completed":
                                            if(data.output != undefined && data.output != null && data.output.data != undefined && data.output.data != null){
                                                data.output.data.forEach(e => {
                                                    try {
                                                        if(Array.isArray(e)){
                                                            let ed = e.length - 1;
                                                            e = e[ed];
                                                            
                                                            if(e[e.length - 1] != undefined && e[e.length - 1] != null){
                                                                let chat_tt = e[e.length - 1];

                                                                if(typeof chat_tt === "string"){
                                                                    if(data.msg != "process_completed"){
                                                                        chat += chat_tt;
            
                                                                        if(datagpt.markdown === true){
                                                                            try {
                                                                                let mark = marked.parse(chat);
                                    
                                                                                result({
                                                                                    "message": mark,
                                                                                    "original": chat,
                                                                                    "finish": false,
                                                                                    "error": false
                                                                                });
                                                                            } catch (error) {
                                                                                chat = chat;
                                                                            }
                                                                        } else {
                                                                            result({
                                                                                "message": chat,
                                                                                "original": null,
                                                                                "finish": false,
                                                                                "error": false
                                                                            });
                                                                        }
                                                                    } else {
                                                                        throw new Error("error");
                                                                    }
                                                                } else {
                                                                    throw new Error("error");
                                                                }
                                                            } else {
                                                                throw new Error("error");
                                                            }
                                                        } else {
                                                            throw new Error("error");
                                                        }
                                                    } catch (error) {
                                                        chat = chat;
                                                    }
                                                });
                                            } else {
                                                throw new Error("error");
                                            }
                                            break;
                                        default:
                                            throw new Error("error");
                                            break;
                                    }
                                } else {
                                    throw new Error("error");
                                }
                            } else {
                                chat = chat;
                            }
                        } catch (error) {
                            chat = chat;
                        }
                    });
                } catch (error) {
                    chat = chat;
                }
            });

            request.data.on("end", () => {
                if(chat.trim().length <= 0){
                    count += 1;
                    if(count > 10){
                        count = 0;
                        setTimeout(function(){goGPT3();});
                    } else {
                        setTimeout(function(){goGPT2();});
                    }
                } else {
                    return result({
                        "message": null,
                        "original": null,
                        "finish": true,
                        "error": false
                    });
                }
            });

            request.data.on("error", () => {
                
            });
        } catch (error) {
            count += 1;
            if(count > 10){
                count = 0;
                setTimeout(function(){goGPT3();});
            } else {
                setTimeout(function(){goGPT2();});
            }
        }
    }

    async function goGPT(){
        try {
            await sleep(100);
            const ip4 = randomIpv4();
            let request = null;
            let headers = null;
            let sess = hash();

            headers = {
                "accept": "*/*",
                "accept-encoding": "gzip, deflate, br, zstd",
                "accept-language": 'en-US,en;q=0.5',
                "content-type": "application/json",
                "origin": "https://yuntian-deng-chatgpt.hf.space",
                "priority": "u=1, i",
                "referer": "https://yuntian-deng-chatgpt.hf.space/",
                "sec-ch-ua": "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
                "X-Forwarded-For": `${ip4}`,
                "X-ProxyUser-Ip": "203.0.113.19"
            }

            request = await axios.post("https://yuntian-deng-chatgpt.hf.space/queue/join?", {
                "data": [
                    datagpt.messages,
                    1,
                    1,
                    0,
                    [],
                    []
                ],
                "event_data": null,
                "fn_index": 3,
                "trigger_id": 5,
                "session_hash": sess
            }, {
                headers: headers
            });

            if(request.status != 200){
                throw new Error("error");
            }

            request = await axios.get("https://yuntian-deng-chatgpt.hf.space/queue/data?session_hash=" + encodeURIComponent(sess), {
                headers: headers,
                responseType: "stream"
            });

            if(request.status != 200){
                throw new Error("error");
            }

            let chat = "";
            request.data.on("data", (chunks) => {
                let data_chk = chunks.toString();

                try {
                    data_chk.split("\n\n").forEach(e => {
                        try {
                            let data = e;

                            try {
                                if(data.startsWith("data: ")){
                                    data = data.slice(6);
                                }

                                data = JSON.parse(data);
                            } catch (error) {
                                if(tmp === null){
                                    tmp = data;
                                } else {
                                    tmp += data;
                                }
                            }

                            try {
                                if(tmp != null){
                                    data = JSON.parse(tmp);
                                    tmp = null;
                                } else {
                                    data = data;
                                }
                            } catch (error) {
                                data = data;
                            }

                            if(data != null && typeof data === "object"){
                                if(data.msg != undefined && data.msg != null){
                                    switch(data.msg){
                                        case "process_generating":
                                        case "process_completed":
                                            if(data.output != undefined && data.output != null && data.output.data != undefined && data.output.data != null){
                                                data.output.data.forEach(e => {
                                                    try {
                                                        if(Array.isArray(e)){
                                                            let ed = e.length - 1;
                                                            e = e[ed];

                                                            if(e[e.length - 1] != undefined && e[e.length - 1] != null){
                                                                let chat_tt = e[e.length - 1];
                                                                if(typeof chat_tt === "string"){
                                                                    if(data.msg != "process_completed"){
                                                                        chat += chat_tt;
            
                                                                        if(datagpt.markdown === true){
                                                                            try {
                                                                                let mark = marked.parse(chat);
                                    
                                                                                result({
                                                                                    "message": mark,
                                                                                    "original": chat,
                                                                                    "finish": false,
                                                                                    "error": false
                                                                                });
                                                                            } catch (error) {
                                                                                chat = chat;
                                                                            }
                                                                        } else {
                                                                            result({
                                                                                "message": chat,
                                                                                "original": null,
                                                                                "finish": false,
                                                                                "error": false
                                                                            });
                                                                        }
                                                                    } else {
                                                                        throw new Error("error");
                                                                    }
                                                                } else {
                                                                    throw new Error("error");
                                                                }
                                                            } else {
                                                                throw new Error("error");
                                                            }
                                                        } else {
                                                            throw new Error("error");
                                                        }
                                                    } catch (error) {
                                                        chat = chat;
                                                    }
                                                });
                                            } else {
                                                throw new Error("error");
                                            }
                                            break;
                                        default:
                                            throw new Error("error");
                                            break;
                                    }
                                } else {
                                    throw new Error("error");
                                }
                            } else {
                                chat = chat;
                            }
                        } catch (error) {
                            chat = chat;
                        }
                    });
                } catch (error) {
                    chat = chat;
                }
            });

            request.data.on("end", () => {
                if(chat.toString().trim().length > 0){
                    return result({
                        "message": null,
                        "original": null,
                        "finish": true,
                        "error": false
                    });
                } else {
                    count++;

                    if(count > 10){
                        count = 0;
                        setTimeout(function(){goGPT2();});
                    } else {
                        setTimeout(function(){goGPT();});
                    }
                }
            });

            request.data.on("error", () => {

            });
        } catch(e){
            count++;

            if(count > 10){
                count = 0;
                setTimeout(function(){goGPT2();});
            } else {
                setTimeout(function(){goGPT();});
            }
        }
    }

    goGPT();
}

module.exports = {
    gpt4o
}


const { gpt, gptweb } = require("./API/gpt");
const { dalle } = require("./API/dalle");
const { gpt4o } = require("./API/gpt4o");
const { gpt3 } = require("./API/gpt3.5");
const { prompts } = require("./API/gpt-prompts");
const { blackbox } = require("./API/blackbox");
const { qwen } = require("./API/qwen");
const { gemini } = require("./API/gemini");

async function call() {
    try {
        

        
        gpt4o({
            messages: [
                {
                    role: "user",
                    content: "Привет. Напиши историю США, подробно."
                }
            ],
            markdown: false
        }, (result) => {
            console.log(result);
        });
		
       
    } catch (error) {
        console.log(error)
        console.log("error")
    }
}

call();

Как видишь call выводит ответ частями. Как сделать так, чтобы call вывел на экран весь ответ сразу, пропуская промежуточные выводы?