import json
import re

import requests
from openai import OpenAI


def deepseek_api(prompt, content, api_key="sk-xxx",model="deepseek-chat",is_json=True):
    client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")
    if is_json:
        response_format = {
            'type': 'json_object'
        }
    else:
        response_format = {
            'type': 'text'
        }
    if content is not None:
        message = [
            {"role": "system", "content": prompt},
            {"role": "user", "content": content},
        ]
    else:
        message = [
            {"role": "system", "content": prompt},
        ]
    response = client.chat.completions.create(
        model=model,
        messages=message,
        response_format=response_format,
        stream=False
    )

    resp_content = response.choices[0].message.content
    return resp_content


# 本地千问大语言模型
def local_qwen_api(prompt):
    no_think = ""
    # no_think = "/no_think"
    # 定义服务地址 # 构造请求数据
    host = "http://192.168.31.22:11434"
    data = {
        "model": "qwen3:14b",
        "messages": [
            # {"role": "system", "content": prompt},
            {"role": "user", "content": prompt + no_think}  # 这里添加了 {no_think}
        ],
        "stream": False
    }

    # 发送 POST 请求
    response = requests.post(
        url=f"{host}/api/chat",  # 使用 /api/chat 路径
        headers={"Content-Type": "application/json"},
        data=json.dumps(data)
    )

    # 检查响应状态
    if response.status_code == 200:

        response_data = response.json()
        answer = response_data.get("message", "").get("content", "")
        # print(f"answer: {answer}")
        # 使用正则表达式移除<think>标签及其内容 如果是思考模型，就不返回<think>标签及其内容
        pattern = r'<think>.*?</think>'
        cleaned_text = re.sub(pattern, '', answer, flags=re.DOTALL)
        cleaned_text = cleaned_text.strip()
        # print(f"{cleaned_text}")
        return cleaned_text
        # return json.loads(cleaned_text).get('相似度')
    else:
        print(f"请求失败，状态码：{response.status_code}")
        # print(response.text)
        return ''
