python代码:
from zhipuai import ZhipuAI
from flask_cors import CORS
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
CORS(app)
@app.route("/")
def index():
return "Welcome to my Flask app!"
@app.route("/getPrompt", methods=["POST"])
def getPrompt():
# print(request.method)
if request.method == "POST":
# print(json.loads(request.get_data()))
data = json.loads(request.get_data())
# print(data)
content = data['content']
# print(content)
# 创建ZhipuAI客户端
###################需要修改下面一行#################
client = ZhipuAI(api_key="你的api_key")
response = client.chat.completions.create(
model="glm-4", # 填写需要调用的模型名称
messages=[
{"role": "user", "content": content}
],
)
answer = response.choices[0].message.content
return jsonify({"answer": answer}) # 返回JSON格式的答案
return jsonify({"error": "Invalid request method"}), 405
if __name__ == "__main__":
app.run(debug=True)
html发送请求(jQuery版):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./js/jquery-1.11.1.min.js"></script>
</head>
<body>
<input type="text">
<button>对话</button>
<div></div>
<script>
$('button').click(function () {
$.post('http://127.0.0.1:5000/getPrompt', JSON.stringify({
content: $('input').val()
}), function (res) {
console.log(res);
// res.answer
})
});
</script>
</body>
</html>
标签:__,Flask,app,request,清言,content,data,智谱
From: https://blog.csdn.net/m0_70071170/article/details/142988331