import json

from zhipuai import ZhipuAI
import flask

# client = ZhipuAI(api_key="73bdeed728677bc80efc6956478a2315.VerNWJMCwN9L5gTi")  # 请填写您自己的APIKey
# response = client.chat.completions.create(
#     model="glm-4",  # 请填写您要调用的模型名称
#     messages=[
#         {"role": "user", "content": "你好"},
#     ],
# )
# print(response.choices[0].message)
app = flask.Flask(__name__)


@app.route("/chat", methods=['POST'])
def app_chat():
    data = json.loads(flask.globals.request.get_data())
    # print(data)
    uid = data["user_id"]
    if not data["text"][-1] in ['?', '？', '.', '。', ',', '，', '!', '！']:
        data["text"] += "。"
    data["text"] += ""

    # 使用ZhipuAI库调用模型生成回复
    client = ZhipuAI(api_key="73bdeed728677bc80efc6956478a2315.VerNWJMCwN9L5gTi")  # 请填写您自己的APIKey
    response = client.chat.completions.create(
        model="glm-4-flash",  # 请填写您要调用的模型名称
        messages=[
            {"role": "user", "content": data["text"]},
        ],
    )

    # 获取模型的回复
    resp = response.choices[0].message.content

    if resp:
        return json.dumps({"user_id": data["user_id"], "text": resp, "error": False, "error_msg": ""})
    else:
        return json.dumps({"user_id": data["user_id"], "text": "", "error": True, "error_msg": "模型未返回回复"})


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=11111)
