import requests
import time
import random
import json


def callServer(prompt, model="deepseek-ai/DeepSeek-R1"):
    url = "https://api.siliconflow.cn/v1/chat/completions"
    headers = {
        # "Authorization": f"Bearer ****",
        "Authorization": f"Bearer sk-cgteigkshpgccdbsfzefmvdjpaicjmydidliorsnjorbqclg",
        "Content-Type": "application/json"
    }
    payload = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        # 重要参数
        # 温度越高，答案多样性越好，但是也越容易出问题；
        # 温度越低，答案越稳定，但很相似，比较死板
        "temperature": 0.6,
        "max_tokens": 6000
    }

    success = True
    msg = "OK"
    think = ""
    result = ""
    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()
        # 注意：deepseek的输出结果分为思考和结论两部分
        # 我们想要学习deepseek的风格，需要把两部分都记录下来
        think = response.json()['choices'][0]['message']['reasoning_content']
        result = response.json()['choices'][0]['message']['content']
    except Exception as e:
        success = False
        msg = "API调用异常:" + str(e)
    return success, msg, think, result

def callServerStimu(prompt, model="deepseek-ai/DeepSeek-R1"):
    #这里模拟等待远程服务器的结果
    time.sleep(random.randint(2,5))
    success = True
    msg = "OK"
    think = 'reasoning_content of '+ prompt
    result = 'content of '+prompt
    return success,msg,think,result


def loadRawDataSet(fileName):
    dataList = []
    with open(fileName, "r", encoding="utf-8") as file:
        while True:
            line = file.readline()
            if not line:  # 读取到文件末尾时退出
                break
            line = line.strip()
            if len(line)>0:
                dataList.append(json.loads(line))
    return dataList

def writeData(dataSet,fileName):
    with open(fileName, 'w', encoding='utf-8') as f:
        json.dump(dataSet, f, ensure_ascii=False, indent=2)

def askBatch(fileName, targetName):
    resultList = []
    # 读取生成的问题的文件:queryData.json, 把数据放入列表
    dataList = loadRawDataSet(fileName)
    count = 0
    for data in dataList:
        count += 1
        if count==20:
            break
        # success, msg, think, result = callServerStimu(data["instruction"])
        success, msg, think, result = callServer(data["instruction"])
        if success:
            # deepseek的输出结果分为思考和结论两部分，我们用<think></think>包裹思考部分
            # 大模型非常善于学习各种格式性强的结构，可以充分利用这一点
            data["output"] = "<think>\n" + think + "\n\n</think>\n\n\n" + result
            resultList.append(data)
        else:
            pass
        print(data["id"], success, msg, think, result)
    writeData(resultList, targetName)


if __name__ == "__main__":
    # input = "请给出“wander”这个词的三个近义词？"
    # success, msg, think, result = callServer(input)
    # print(success, msg, think, result) # 输出有两部分, think是思考, result是结果

    fileName = "../data/testDataTemp/queryData.jsonl"
    targetName = "../data/testDataTemp/answerData.jsonl"
    askBatch(fileName, targetName)