获取大模型API的响应内容的函数返回 return response.choices[0].message
from zhipuai import ZhipuAI
def get_response_from_model(question):
client = ZhipuAI(api_key='your_api_key')
response = client.chat.completions.create(
model='glm-4-plus',
messages=[
{'role': 'user', 'content': question}
],
)
return response.choices[0].message
flask项目文件的渲染函数从响应内容获取所需content字符串传递给模版
from flask import Flask, request, render_template
from LLMapi import get_response_from_model
app = Flask(__name__)
@app.route('/apis', methods=['GET', 'POST'])
def apis():
response = None
if request.method == 'POST':
question = request.form['question']
response = get_response_from_model(question).content
print(type(response))
print(response)
return render_template('apis.html', response=response)
return render_template('apis.html', response=response)
if __name__ == '__main__':
app.run(debug=False)
模版文件输入问题,当响应不为空的时候输出响应内容,并用marked.js库对markdown文本进行转换为html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>APIs Interface</title>
<script src="../static/marked.min.js"></script>
</head>
<body>
<h1>Question Submission</h1>
<form action="/apis" method="post">
<label for="question">Enter you question:</label>
<input type="text" id="question" name="question" required>
<button type="submit">Submit</button>
</form>
{% if response %}
<h1>Response:</h1>
<div id="markdownContent"></div>
<hr>
<p>{{response}}</p>
<hr>
<hr>
<!-- 使用 textarea 存储响应内容 -->
<textarea id="responseContent" style="display:none;">{{ response }}</textarea>
<script>
document.addEventListener("DOMContentLoaded", function() {
// 获取存储在 textarea 中的 response 内容
var responseContent = document.getElementById('responseContent').value;
var htmlContent = marked.parse(responseContent);
document.getElementById('markdownContent').innerHTML = htmlContent;
});
</script>
{% endif %}
</body>
</html>
关键步骤
1️⃣获取模型响应并返回response
;
return response.choices[0].message
2️⃣在模版文件中用不显示的textarea
元素接收以markdown
语法书写并有特殊符号的字符串{{ response }}
;
<!-- 使用 textarea 存储响应内容 -->
<textarea id="responseContent" style="display:none;">{{ response }}</textarea>
3️⃣找到textarea
的value值并传递给markde.parse()函数进行转换为html语句,最后在相应位置展示出来。
// 获取存储在 textarea 中的 response 内容
var responseContent = document.getElementById('responseContent').value;
var htmlContent = marked.parse(responseContent);
document.getElementById('markdownContent').innerHTML = htmlContent;
标签:__,markdown,return,responseContent,question,Html,API,document,response
From: https://www.cnblogs.com/aiparallelworld/p/18412973