基于Flask框架添加多个AI模型的API并进行交互

2025-03-28 15:50

本文主要是介绍基于Flask框架添加多个AI模型的API并进行交互,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下...

1. 概述

该应用是一个基于 Flask 框架的 AI 模型 API 管理系统,允许用户添加、删除不同 AI 模型(如 DeepSeek、阿里云、智谱、百度、科大讯飞等)的 API 密钥,并通过这些配置好的 API 与相应的 AI 模型进行交互,获取回复。应用包含后端的 Flask 服务和前端的 HTML 页面及 javascript 脚本。

2. 后端代码说明

2.1 依赖库导入

from flask import Flask, request, render_template, jsonify
import requests

Flask:用于构建 Web 应用的轻量级框架。

request:用于处理 HTTP 请求,获取请求中的数据。

render_template:用于渲染 HTML 模板。

jsonify:用于将 python 对象转换为 JSON 格式并作为 HTTP 响应返回。

requests:用于发送 HTTP 请求,与外部 API 进行交互。

2.2 应用初始化

app = Flask(__name__)

创建一个 Flask 应用实例,__name__参数用于指定应用的名称。

2.3 API 存储字典

# 存储用户配置的API
apis = {
    "deepseek": None,
    "aliyun": None,
    "zhipu": None,
    "baidu": None,
    "iflytek": None
}

定义一个字典apis,用于存储不同 AI 模型的 API 密钥,初始值均为None。

2.4 路由函数

1.首页路由:

@app.route('/')
def index():
    return render_template('index.html', apis=apis)

当用户访问根路径时,渲染index.html模板,并将apis字典传递给模板,以便在页面上显示和操作。

2.添加 API 路由:

@app.route('/add_api', methods=['POST'])
def add_api():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"status": "error", "message": "No data provided"}), 400
            
        model = data.get('model')
        api_key = data.get('api_key')
        
        if not model or not api_key:
            return jsonify({"status": "error", "message": "Missing required parameters"}), 400
            
        if model in apis:
            apis[model] = api_key
            return jsonify({"status": "success", "message": f"{model} API added successfully!"})
        else:
            return jsonify({"status": "error", "message": "Invalid model specified."}), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

处理POST请求,从请求中获取 JSON 数据,提取model和api_key。

检查数据的完整性,若缺少必要参数或模型不合法,则返回相应的错误信息。

若模型存在于apis字典中,则将对应的 API 密钥存入字典,并返回成功消息;否则返回错误消息。

若发生异常,返回异常信息和 500 状态码。

3.删除 API 路由:

@app.route('/remove_api', methods=['POST'])
def remove_api():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"status": "error", "message": "No data provided"}), 400
            
        model = data.get('model')
        
        if not model:
            return jsonify({"status": "error", "message": "Missing model parameter"}), 400
            
        if model in apis:
            apis[model] = None
            return jsonify({"status": "success", "message": f"{model} API removed successfully!"})
        else:
            return jsonify({"status": "error", "message": "Invalid model specified."}), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

处理POST请求,从请求中获取 JSON 数据,提取model。

检查数据的完整性,若缺少模型参数或模型不合法,则返回相应的错误信息。

若模型存在于apis字典中,则将其 API 密钥设置为None,并返回成功消息;否则返回错误消息。

若发生异常,返回异常信息和 500 状态码。

4.获取响应路由:

@app.route('/get_response', methods=['POST'])
def get_response():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"status": "error", "message": "No data provided"}), 400
            
        model = data.get('model')
        prompt = data.get('prompt')
        
        if not model or not prompt:
            return jsonify({"status": "error", "message": "Missing required parameters"}), 400
            
        if model in apis and apis[model]:
            try:
                # 这里根据不同的模型调用相应的API
                if model == "deepseek":
                    headers = {
                        "Authorization": f"Bearer {apis[model]}",
                        "Content-Type": "application/json"
                    }
                    payload = {
                        "model": "deepseek-chat",
                        "messages": [{"role": "user", "content": prompt}],
                        "temperature": 0.7
                    }
                    response = requests.post(
                        "https://api.deepseek.com/v1/chat/completions",
                        headers=headers,
                        json=payload
                    )
                elif model == "aliyun":
                    headers = {
                        "Authorization": f"Bearer {apis[model]}",
                        "Content-Type": "application/json"
                    }
                    payload = {
                        "model": "bailian",
                        "input": {
                            "messages": [{"role": "user", "content": prompt}]
                        }
                    }
                    response = requests.post(
                        "https://bailian.aliyuncs.com/v2/app/completions",
                        headers=headers,
                        json=payload
                    )
                elif model == "zhipu":
                    headers = {
                        "Authorization": f"Bearer {apis[model]}",
                        "Content-Type": "application/json"
                    }
                    payload = {
                        "model": "chatglm_turbo",
                        "messages": [{"role": "user", "content": prompt}]
                    }
                    response = requests.post(
                        "https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_turbo/invoke",
                        headers=headers,
                        json=payload
                    )
    China编程            elif model == "baidu":
                    headers = {
                        "Content-Type": "application/json",
                        "Accept": "application/json"
                    }
                    payload = {
                        "messages": [{"role": "user", "content": prompt}]
                    }
                    response = requests.post(
                        f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?Access_token={apis[model]}",
                        headers=headers,
                        json=payload
                    )
                elif model == "iflytek":
                    headers = {
                        "Content-Type": "application/json",
                        "X-Appid": "your_app_id",  # 需要替换为实际AppID
                        "X-CurTime": str(int(time.time())),
                        "X-Param": json.dumps({"scene": "main"}),
                        "X-CheckSum": ""  # 需要计算校验和
                    }
                    payload = {
                        "text": prompt
                    }
                    response = requests.post(
                        "https://api.xfyun.cn/v1/aiui/v1/text",
                        headers=headers,
                        json=payload
                    )
                
                if response.status_code == 200:
                    response_data = response.json()
                    # 根据不同API的响应格式提取回复
                    if model == "deepseek":
                        reply = response_data['choices'][0]['message']['content']
                    elif model == "aliyun":
                        reply = response_data['output']['text']
                    elif model == "zhipu":
                        reply = response_data['data']['choices'][0]['content']
                    elif model == "baidu":
                        reply = response_data['result']
                    elif model == "iflytek":
                        reply = response_data['data'][0]['content']
                    
                    return jsonify({
                        "status": "success", 
                        "response": reply,
                        "model": model
                    })
                else:
                    return jsonify({
                        "status": "error", 
                        "message": f"API call failed with status code {response.status_code}",
                        "response_text": response.text,
                        "request_payload": payload  # 添加请求负载用于调试
                    }), response.status_code
            except requests.exceptions.RequestException as e:
                return jsonify({
                    "status": "error", 
                    "message": f"Network error: {str(e)}"
                }), 500
            except Exception as e:
                return jsonify({
                    "status": "error", 
                    "message": str(e),
                    "error_type": type(e).__name__
                }), 500
        else:
            return jsonify({
                "status": "error", 
                "message": "API not configured or invalid model."
            }), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

处理POST请求,从请求中获取 JSON 数据,提取model和prompt。

检查数据的完整性,若缺少必要参数或模型未配置 API 密钥,则返回相应的错误信息。

根据不同的模型,构造相应的请求头和请求负载,发送POST请求到对应的 API 端点。

若 API 调用成功(状态码为 200),根据不同模型的响应格式提取回复内容,并返回成功消息;否则返回错误消息,包括状态码、响应文本和请求负载(用于调试)。

若发生网络错误或其他异常,返回相应的错误信息和状态码。

2.5 应用运行

if __name__ == '__main__':
    app.run(debug=True)

当脚本直接运行时,启动 Flask 应用,并设置debug模式为True,以便在开发过程中查看错误信息和自动重新加载应用。

3. 前端代码说明

3.1 HTML 结构

头部部分:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Model API Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
    <style>
        .chat-window {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 20px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #e3f2fd;
            margin-left: 20%;
        }
        .bot-message {
            background-color: #f1f1f1;
            margin-right: 20%;
        }
        .model-info {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }
        .error-message {
            background-color: #ffebee;
            color: #d32f2f;
        }
    </style>
</head>

设置页面的字符编码、视口等基本信息。

引入 Bootstrap 的 CSS 样式表,用于页面布局和样式。

自定义一些 CSS 样式,用于聊天窗口、消息显示、错误消息显示等。

主体部分:

<body>
    <div class="container mt-5">
        <h1 class="text-center mb-4">AI Model API Manager</h1>
        <div class="row">
            <div class="col-md-6">
                <div class="card mb-3">
                    <div class="card-header">API Management</div>
                    <div class="card-body">
                        <form id="addApiForm" class="mb-3">
                            <div class="mb-3">
                                <label for="addModel" class="form-label">Model:</label>
                                <select id="addModel" name="model" class="form-select">
                                    <option value="deepseek">DeepSeek</option>
                                    <option value="aliyun">Aliyun</option>
                                    <option value="zhipu">Zhipu</option>
                                    <option value="baidu">Baidu</option>
                                    <option value="iflytek">Iflytek</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="api_key" class="form-label">API Key:</label>
                                <input type="text" id="api_key" name="api_key" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-primary">Add API</button>
                        </form>
                        <form id="removeApiForm">
                            <div class="mb-3">
                                <label for="removeModel" class="form-label">Model:</label>
                                <select id="removeModel" name="model" class="form-select">
                                    <option value="deepseek">DeepSeek</option>
                                    <option value="aliyun">Aliyun</option>
                                    <option value="zhipu">Zhipu</option>
                                    <option value="baidu">Baidu</option>
                                    <option value="iflytek">Iflytek</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-danger">Remove API</button>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Chat with AI</div>
                    <div class="card-body">
                        <div class="chat-window" id="chatWindow"></div>
                        <form id="getResponseForm">
                            <div class="mb-3">
                                <label for="chatModel" class="form-label">Model:</label>
                                <select id="chatModel" name="model" class="form-select">
                                    <option value="deepseek">DeepSeek</option>
                                    <option value="aliyun">Aliyun</option>
                                    <option value="zhipu">Zhipu</option>
                                    <option value="baidu">Baidu</option>
                                    <option value="iflytek">Iflytek</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="prompt" class="form-label">Prompt:</label>
                                <input type="text" id="prompt" name="prompt" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-success">Get Response</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

页面主体部分使用 Bootstrap 的栅格系统布局。

左侧部分用于 API 管理,包含添加 API 和移除 API 的表单,表单中包含模型选择和 API 密钥输入框。

右侧部分用于与 AI 聊天,包含聊天窗口和发送请求的表单,表单中包含模型选择和提示输入框。

3.2 JavaScript 脚本

添加 API 功能:

document.getElementById('addApiForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const model = document.getElementById('addModel').value;
    const apiKey = document.getElementById('api_key').value;
    
    fetch('/add_api', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            model: model,
            api_key: apiKey
        })
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(err => { throw err; });
        }
        return response.json();
    })
    .then(data => {
        alert(data.message);
        document.getElementById('api_key').value = '';
    })
    .catch(error => {
        alert(`Error: ${error.message || 'Failed to add API'}`);
    });
});

监听添加 API 表单的提交事件,阻止表单的默认提交行为。

获取用户选择的模型和输入的 API 密钥。

使用fetch发送POST请求到/add_api端点,传递模型和 API 密钥的 JSON 数据。

处理响应,若响应失败,抛出错误;若成功,显示提示信息并清空 API 密钥输入框;若发生异常,显示错误提示。

app.py代码

from flask import Flask, request, render_template, jsonify
import requests
 
app = Flask(__name__)
 
# 存储用户配置的API
apis = {
    "deepseek": None,
    "aliyun": None,
    "zhipu": None,
    "baidu": None,
    "iflytek": None
}
 
@app.route('/')
def index():
    return render_template('index.html', apis=apis)
 
@app.route('/add_api', methods=['POST'])
def add_api():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"status": "error", "message": "No data provided"}), 400
            
        model = data.get('model')
        api_key = data.get('api_key')
        
        if not model or not api_key:
            return jsonify({"status": "error", "message": "Missing required parameters"}), 400
            
        if model in apis:
            apis[model] = api_key
            return jsonify({"status": "success", "message": f"{model} API added successfully!"})
        else:
            return jsonify({"status": "error", "message": "Invalid model specified."}), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500
 
@app.route('/remove_api', methods=['POST'])
def remove_api():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"status": "error", "message": "No data provided"}), 400
            
        model = data.get('model')
        
        if not model:
            return jsonify({"status": "error", "message": "Missing model parameter"}), 400
            
        if model in apis:
            apis[model] = None
            return jsonify({"status": "success", "message": f"{model} API removed successfully!"})
        else:
            return jsonify({"status": "error", "message": "Invalid model specified."}), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500
 
@app.route('/get_response', methods=['POST'])
def get_response():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"status": "error", "message": "No data provided"}), 400
            
        model = data.get('model')
        prompt = data.get('prompt')
        
        if not model or not prompt:
            return jsonify({"status": "error", "message": "Missing required parameters"}), 400
            
        if model in apis and apis[model]:
            try:
                # 这里根据不同的模型调用相应的API
                if model == "deepseek":
                    headers = {
                        "Authorization": f"Bearer {apis[model]}",
                        "Content-Type": "application/json"
                    }
                    payload = {
                        "model": "deepseek-chat",
                        "messages": [{"role": "user", "content": prompt}],
                        "temperature": 0.7
                    }
                    response = requests.post(
                        "https://api.deepseek.com/v1/chat/completions",
                        headers=headers,
                        json=payload
                    )
                elif model == "aliyun":
                    headers = {
                        "Authorization": f"Bearer {apis[model]}",
                        "Content-Type": "application/json"
                    }
                    payload = {
                        "model": "bailian",
                        "input": {
                            "messages": [{"role": "user", "content": prompt}]
                        }
                    }
                    response = requests.post(
                        "https://bailian.aliyuncs.com/v2/app/completions",
                        headers=headers,
                        json=payload
                    )
                elif model == "zhipu":
                    headers = {
                        "Authorization": f"Bearer {apis[model]}",
                        "Content-Type": "application/json"
                    }
                    payload = {
                        "model": "chatglm_turbo",
                        "messages": [{"role": "user", "content": prompt}]
                    }
                    response = requests.post(
                        "https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_turbo/invoke",
                        headers=headers,
                        json=payload
                    )
                elif model == "baidu":
                    headers = {
                        "Content-Type": "application/json",
                        "Accept": "application/json"
                    }
                    payload = {
                        "messages": [{"role": "user", "content": prompt}]
                    }
                    response = requests.post(
                        f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={apis[model]}",
                        headers=headers,
                        json=payload
                    )
                elif model == "iflytek":
                    headers = {
                        "Content-Type": "application/json",
                        "X-Appid": "your_app_id",  # 需要替换为实际AppID
                        "X-CurTime": str(int(time.time())),
                        "X-Param": json.dumps({"scene": "main"}),
                        "X-CheckSum": ""  # 需要计算校验和
                    }
                    payload = {
                        "text": prompt
                    }
                    response = requests.post(
                        "https://api.xfyun.cn/v1/aiui/v1/text",
                        headers=headers,
                        json=payload
                    )
                
                if response.status_code == 200:
                    response_data = response.json()
                    # 根据不同API的响应格式提取回复
                    if model == "deepseek":
                        reply = response_data['choices'][0]['message']['content']
                    elif model == "aliyun":
                        reply = response_data['output']['text']
                    elif model == "zhipu":
                        reply = response_data['data']['choices'][0]['content']
                    elif model == "baidu":
                        reply = response_data['result']
                    elif model == "iflytek":
                        reply = response_data['data'][0]['content']
                    
                    return jsonify({
                        "status": "success", 
                        "response": reply,
                        "model": model
                    })
                else:
                    return jsonify({
                        "status": "error", 
                        "message": f"API call failed with status code {response.status_code}",
                     China编程   "response_text": response.text,
                        "request_payload": payload  # 添加请求负载用于调试
                    }), response.status_code
            except requests.exceptions.RequestException as e:
                return jsonify({
                    "status": "error", 
                    "message": f"Network error: {str(e)}"
                }), 500
            except Exception as e:
                return jsonify({
                    "status": "error", 
                    "message": str(e),
                    "error_type": type(e).__name__
                }), 500
        else:
            return jsonify({
                "status": "error", 
                "message": "API not configured or invalid model."
            }), 400
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500
 
if __name__ == '__main__':
    app.run(debug=True)

index.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Model API Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
    <style>
        .chat-window {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 20px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 5px;
        }
        .jsuser-message {
            background-color: #e3f2fd;
            margin-left: 20%;
        }
        .bot-message {
            background-color: #f1f1f1;
            margin-right: 20%;
        }
        .model-info {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }
        .error-message {
            background-color: #ffebee;
            color: #d32f2f;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center mb-4">AI Model API Manager</h1>
        <div class="row">
            <div class="col-md-6">
                <div class="card mb-3">
                    <div class="card-header">API Management</div>
                    <div class="card-body">
                        <form id="addApiForm" class="mb-3">
                            <div class="mb-3">
                                <label for="addModel" class="form-label">Model:</label>
                                <select id="addModel" name="model" class="form-select">
                                    <option value="deepseek">DeepSeek</option>
                                    <option value="aliyun">Aliyun</option>
                                    <option value="zhipu">Zhipu</option>
                                    <option value="baidu">Baidu</option>
                                    <option value="iflytek">Iflytek</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="api_key" class="form-label">API Key:</label>
                                <input type="text" id="api_key" name="api_key" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-primary">Add API</button>
                        </form>
                        <form id="removeApiForm">
                            <div class="mb-3">
                                <label for="removeModel" class="form-label">Model:</label>
                                <select id="removeModel" name="model" class="form-select">
                                    <option value="deepseek">DeepSeek</option>
                                    <option value="aliyun">Aliyun</option>
                                    <option value="zhipu">Zhipu</option>
                                    <option value="baidu">Baidu</option>
                                    <option value="iflytek">Iflytek</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-danger">Remove API</button>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Chat with AI</div>
                    <div class="card-body">
                        <div class="chat-window" id="chatWindow"></div>
                        <form id="getResponseForm">
                            <div class="mb-3">
                                <label for="chatModel" class="form-label">Model:</label>
                                <select id="chatModel" name="model" class="form-select">
                                    <option value="deepseek">DeepSeek</option>
                                    <option value="aliyun">Aliyun</option>
                                    <option value="zhipu">Zhipu</option>
                                    <option value="baidu">Baidu</option>
                                    <option value="iflytek">Iflytek</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="prompt" class="form-label">Prompt:</label>
                                <input type="text" id="prompt" name="prompt" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-success">Get Response</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
 
<!-- 保持之前的HTML结构不变,只修改JavaScript部分 -->
<script>
    // 添加API
    document.getElementById('addApiForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const model = document.getElementById('addModel').value;
        const apiKey = document.getElementById('api_key').value;
        
        fetch('/add_api', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                model: model,
                api_key: apiKey
            })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => { throw err; });
            }
            return response.json();
        })
        .then(data => {
            alert(data.message);
            document.getElementById('api_key').value = '';
        })
        .catch(error =&javascriptgt; {
            alert(`Error: ${error.message || 'Failed to add API'}`);
        });
    });
 
    // 移除API
    document.getElementById('removeApiForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const model = document.getElementById('removeModel').value;
        
        fetch('/remove_api', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                model: model
            })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => { throw err; });
            }
            return response.json();
        })
        .then(data => {
            alert(data.message);
        })
        .catch(error => {
            alert(`Error: ${error.message || 'Failed to remove API'}`);
        });
    });
 
    // 获取响应
    document.getElementById('getResponseForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const model = document.getElementById('chatModel').value;
        const prompt = document.getElementById('prompt').value;
        const chatWindow = document.getElementById('chatWindow');
        
        // 添加用户消息
        chatWindow.innerHTML += `
            <div class="message user-message">
                <strong>You:</strong> ${prompt}
            </div>
        `;
        
        const submitBtn = document.querySelector('#getResponseForm button[type="submit"]');
        submitBtn.disabled = true;
        
        fetch('/get_response', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                model: model,
                prompt: prompt
            })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => { throw err; });
            }
            return response.json();
        })
        .then(data => {
            if (data.status === "success") {
                chatWindow.innerHTML += `
                    <div class="message bot-message">
                        <strong>Bot (${data.model}):</strong> ${data.response}
                    </div>
                `;
            } else {
                // 显示更详细的错误信息
                let errorMsg = data.message;
                if (data.response_text) {
                    try {
                        const errorData = JSON.parse(data.response_text);
                        errorMsg += ` - ${errorData.error || errorData.message || ''}`;
                    } catch (e) {
                        errorMsg += ` - ${data.response_text}`;
                    }
                }
                
                chatWindow.innerHTML += `
                    <div class="messagewww.chinasem.cn error-message">
                        <strong>Error:</strong> ${errorMsg}
                    </div>
                `;
            }
            chatWindow.scrollTop = chatWindow.scrollHeight;
            document.getElementById('prompt').value = '';
        })
        .catch(error => {
            let errorMsg = error.message || 'Failed to get response';
            if (error.response_text) {
                errorMsg += ` - ${error.response_text}`;
            }
            
            chatWindow.innerHTML += `
                <div class="message error-message">
                    <strong>Error:</strong> ${errorMsg}
                </div>
            `;
            chatWindow.scrollTop = chatWindow.scrollHeight;
        })
        .finally(() => {
            submitBtn.disabled = false;
        });
    });
</script>
 
</body>
</html>

到此这篇关于基于Flask框架添加多个AI模型的API并进行交互的文章就介绍到这了,更多相关Flask AI模型API管理内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于基于Flask框架添加多个AI模型的API并进行交互的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153989

相关文章

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

Nginx中配置使用非默认80端口进行服务的完整指南

《Nginx中配置使用非默认80端口进行服务的完整指南》在实际生产环境中,我们经常需要将Nginx配置在其他端口上运行,本文将详细介绍如何在Nginx中配置使用非默认端口进行服务,希望对大家有所帮助... 目录一、为什么需要使用非默认端口二、配置Nginx使用非默认端口的基本方法2.1 修改listen指令

MySQL按时间维度对亿级数据表进行平滑分表

《MySQL按时间维度对亿级数据表进行平滑分表》本文将以一个真实的4亿数据表分表案例为基础,详细介绍如何在不影响线上业务的情况下,完成按时间维度分表的完整过程,感兴趣的小伙伴可以了解一下... 目录引言一、为什么我们需要分表1.1 单表数据量过大的问题1.2 分表方案选型二、分表前的准备工作2.1 数据评估

Python Flask实现定时任务的不同方法详解

《PythonFlask实现定时任务的不同方法详解》在Flask中实现定时任务,最常用的方法是使用APScheduler库,本文将提供一个完整的解决方案,有需要的小伙伴可以跟随小编一起学习一下... 目录完js整实现方案代码解释1. 依赖安装2. 核心组件3. 任务类型4. 任务管理5. 持久化存储生产环境

Python批量替换多个Word文档的多个关键字的方法

《Python批量替换多个Word文档的多个关键字的方法》有时,我们手头上有多个Excel或者Word文件,但是领导突然要求对某几个术语进行批量的修改,你是不是有要崩溃的感觉,所以本文给大家介绍了Py... 目录工具准备先梳理一下思路神奇代码来啦!代码详解激动人心的测试结语嘿,各位小伙伴们,大家好!有没有想

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

Python用Flask封装API及调用详解

《Python用Flask封装API及调用详解》本文介绍Flask的优势(轻量、灵活、易扩展),对比GET/POST表单/JSON请求方式,涵盖错误处理、开发建议及生产环境部署注意事项... 目录一、Flask的优势一、基础设置二、GET请求方式服务端代码客户端调用三、POST表单方式服务端代码客户端调用四

MySQL进行分片合并的实现步骤

《MySQL进行分片合并的实现步骤》分片合并是指在分布式数据库系统中,将不同分片上的查询结果进行整合,以获得完整的查询结果,下面就来具体介绍一下,感兴趣的可以了解一下... 目录环境准备项目依赖数据源配置分片上下文分片查询和合并代码实现1. 查询单条记录2. 跨分片查询和合并测试结论分片合并(Shardin