import requests
import json
# import pandas as pd
from time import sleep
import time
import re
import os
from tqdm import tqdm
import time
import backoff  # for exponential backoff
from loguru import logger




def request_gpt_unsave(prompt: str, model: str="gpt-3.5-turbo", last_message_ids=None, curiosity: str="lv1",temperature = 0.0) -> (int, str):

    logger.critical("intput")
    if last_message_ids:
        logger.critical(last_message_ids)
    else:
        logger.critical(prompt)
    body = {
        "model": 'gpt-4-turbo-128k',
        "messages": last_message_ids,
        "prompt": prompt,
        "stream": False,
        "temperature": temperature,
    }
    header = {
        "Content-Type": "application/json",
        "accept":"*/*",
        "X-AK": api_key
    }
    FLAG = 1
    while FLAG:
        # print('Requested.')
        print('Requested.')
        # requests.exceptions.ConnectionError
        resp = requests.post(api, json=body, headers=header)
        if resp.status_code == 200:
            respData = json.loads(resp.text)
            if respData['success']:
                messageId = respData['data']['messageId']
                content = respData['data']['content']
                token_prompt = respData['data']['promptTokens']
                token_compli = respData['data']['totalTokens'] - respData['data']['promptTokens']
                FLAG = 0
            # else:
            #     raise requests.exceptions.ConnectionError
    return messageId, content, token_prompt, token_compli


@backoff.on_exception(backoff.expo, (requests.exceptions.ConnectionError)) #json.decoder.JSONDecodeError
def request_gpt(prompt: str, model: str="gpt-3.5-turbo", last_messages=None, temperature = 0.0):
    return request_gpt_unsave(
        prompt = prompt, 
        model = model, 
        last_message_ids = last_messages, 
        # curiosity = curiosity,
        temperature = temperature,
        )



if __name__ == "__main__":
    test = "Teach me about love"
    # messages = [
    messages=[
        {"role": "system", "content": "Answer in a consistent style."},
        {"role": "user", "content": "Teach me about patience."},
        {"role": "assistant", "content": "The river that carves the deepest valley flows from a modest spring. The grandest symphony originates from a single note. The most intricate tapestry begins with a solitary thread"},
        {"role":"user","content":test}

    ]
    print(request_gpt_unsave(test,"gpt-4 8K",last_message_ids=messages))