大模型API与前端的结合使用
大模型API与Flask项目示例
一、输入问题交给后台处理
获取表单GET,通过模版表单将问题提交给后台POST
模版文件apis.html
如下:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='initinal-scale=1.0'>
<title> API➕Flask</title>
</head>
<body>
<h1>API➕Flask项目示例</h1>
<form action='/apis' method='POST'>
<label for='question'>请输入问题:</label>
<input type='text' name='question' id='question' required>
<button type='submit'>提交</button>
</form>
{% if response %}
<h1>Assistant's answer:</h1>
{{ response }}
{% endif %}
</body>
</html>
二、后台接入API获得回答
从前端表单的提交request获取问题question
带问题接入大模型API获得回答
LLMapi.py
代码如下:
from zhipuai import ZhipuAI
def get_response_from_model(question):
client = ZhipuAI(api_key='xx')
response = client.chat.completions.create(
model = 'glm-4-plus',
messages = [{'role': 'user', 'content': question}],
)
return response.choices[0].message.content
三、将回答渲染后返回页面
flask项目文件apis.py
如下:
from flask import Flask, request
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)
return render_template('apis.html', response=response)
return render_template('apis.html', response=response)
if __name__ == '__main__':
app.run(debug=False)
备注:flask项目文件结构,apis.py
和LLMapi.py
同属项目文件根目录下,apis.html
在项目文件的子文件夹templates
中。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本