欢迎来到海上华帆的博客园子

记录一些学习过程中的心得体会,供自己和有缘人参考!

大模型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.pyLLMapi.py同属项目文件根目录下,apis.html在项目文件的子文件夹templates中。

posted @   海上华帆  阅读(190)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示