WeChatBot/ai.py

46 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)