import json
import time

import requests


def dsv3_infer_alipay(user_input):
    # url = "https://antchat-prepub.alipay.com/v1/chat/completions"  # 预发
    url = "https://antchat.alipay.com/v1/chat/completions"  # 生产

    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer wRyhVCXm1eBKBgC1jIzXyZchDkMbxWzB",
        # 高保：wRyhVCXm1eBKBgC1jIzXyZchDkMbxWzB
        # 低保：2ZDJjLSLyfWDcw9ollWOFYyTWkAay0OK
        "SOFA-TraceId": "0b46977c17296519321548915ef847",
        "SOFA-RpcId": "0.1"
    }

    data = {
        "model": "DeepSeek-V3",
        "messages": [
            {
                "role": "user",
                "content": user_input
            }
        ],
        'stream': True
    }

    start_time = time.time()
    res_raw = requests.post(url, headers=headers, json=data)
    res_raw.encoding = 'utf-8'
    res_txt = res_raw.text
    res = stream_handle_dsv3(res_txt)
    end_time = time.time()
    # print(f"耗时：{end_time - start_time}秒")
    return res

def stream_handle_dsv3(input_data):
    inp_list = input_data.split('\n\n')
    result = ''
    for line in inp_list:
        if line.startswith('data:'):
            try:
                # 去掉"data:"前缀并解析JSON
                json_data = json.loads(line[5:])
                # 提取content内容
                content = json_data['choices'][0]['delta']['content']
                result += content
            except:
                continue

    return result