SoFunction
Updated on 2025-04-13

Add APIs of multiple AI models based on Flask framework and interact

1. Overview

This application is an AI model API management system based on the Flask framework, allowing users to add and delete API keys of different AI models (such as DeepSeek, Alibaba Cloud, Zhipu, Baidu, iFLYTEK, etc.), and interact with the corresponding AI models through these configured APIs to obtain replies. The application includes the backend Flask service and the frontend HTML pages and JavaScript scripts.

2. Backend code description

2.1 Dependency library import

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

Flask: A lightweight framework for building web applications.

request: Used to process HTTP requests and get data in the request.

render_template: Used to render HTML templates.

jsonify: Used to convert Python objects to JSON format and return as HTTP response.

requests: Used to send HTTP requests and interact with external APIs.

2.2 Application Initialization

app = Flask(__name__)

Create a Flask application instance, and the __name__ parameter is used to specify the name of the application.

2.3 API storage dictionary

# Store user-configured APIapis = {
    "deepseek": None,
    "aliyun": None,
    "zhipu": None,
    "baidu": None,
    "iflytek": None
}

Define a dictionary apis to store API keys for different AI models, with the initial values ​​of None.

2.4 Routing functions

1. Homepage routing:

@('/')
def index():
    return render_template('', apis=apis)

When the user accesses the root path, the template is rendered and the apis dictionary is passed to the template for display and manipulation on the page.

2. Add API 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 = ('model')
        api_key = ('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

Process POST request, get JSON data from the request, and extract model and api_key.

Check the integrity of the data. If the necessary parameters are missing or the model is illegal, the corresponding error message will be returned.

If the model exists in the apis dictionary, the corresponding API key is stored in the dictionary and a success message is returned; otherwise, an error message is returned.

If an exception occurs, return the exception information and 500 status code.

3. Delete API routes:

@('/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 = ('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

Process POST request, get JSON data from the request, and extract the model.

Check the integrity of the data. If the model parameters are missing or the model is illegal, the corresponding error message will be returned.

If the model exists in the apis dictionary, set its API key to None and returns a success message; otherwise, an error message is returned.

If an exception occurs, return the exception information and 500 status code.

4. Get the response 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 = ('model')
        prompt = ('prompt')
        
        if not model or not prompt:
            return jsonify({"status": "error", "message": "Missing required parameters"}), 400
            
        if model in apis and apis[model]:
            try:
                # Here we call the corresponding API according to different models                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 = (
                        "/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 = (
                        "/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 = (
                        "/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 = (
                        f"/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",  # Need to be replaced with the actual AppID                        "X-CurTime": str(int(())),
                        "X-Param": ({"scene": "main"}),
                        "X-CheckSum": ""  # Checksum needs to be calculated                    }
                    payload = {
                        "text": prompt
                    }
                    response = (
                        "/v1/aiui/v1/text",
                        headers=headers,
                        json=payload
                    )
                
                if response.status_code == 200:
                    response_data = ()
                    # Extract reply according to response format of different APIs                    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": ,
                        "request_payload": payload  # Add request load for debugging                    }), response.status_code
            except  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

Process POST request, get JSON data from the request, and extract model and propt.

Check the integrity of the data, and return the corresponding error message if the necessary parameters are missing or the model does not configure the API key.

According to different models, the corresponding request header and request load are constructed, and the POST request is sent to the corresponding API endpoint.

If the API call is successful (status code is 200), the reply content is extracted according to the response format of different models and a success message is returned; otherwise, an error message is returned, including the status code, response text, and request load (for debugging).

If a network error or other exception occurs, the corresponding error message and status code will be returned.

2.5 Application run

if __name__ == '__main__':
    (debug=True)

When the script is run directly, start the Flask application and set debug mode to True to view error messages and automatically reload the application during development.

3. Front-end code description

3.1 HTML Structure

Head part:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Model API Manager</title>
    <link href="/npm/[email protected]/dist/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>

Set basic information such as character encoding, viewport, etc. of the page.

Introduces Bootstrap's CSS stylesheet for page layout and styles.

Customize some CSS styles for chat windows, message display, error message display, etc.

Main part:

<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  class="mb-3">
                            <div class="mb-3">
                                <label for="addModel" class="form-label">Model:</label>
                                <select  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"  name="api_key" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-primary">Add API</button>
                        </form>
                        <form >
                            <div class="mb-3">
                                <label for="removeModel" class="form-label">Model:</label>
                                <select  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" ></div>
                        <form >
                            <div class="mb-3">
                                <label for="chatModel" class="form-label">Model:</label>
                                <select  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"  name="prompt" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-success">Get Response</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

The main part of the page uses Bootstrap's raster system layout.

The left section is for API management, which contains forms for adding and removing APIs, with the form containing model selection and API key input boxes.

The right part is used to chat with AI, which contains the chat window and the form to send requests, with the model selection and prompt input boxes.

3.2 JavaScript Script

Add API features:

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

Listen to the submission event for adding API forms to prevent the default submission behavior of the form.

Gets the user-selected model and input API key.

Use fetch to send POST requests to the /add_api endpoint, passing JSON data for the model and API keys.

Process the response. If the response fails, an error will be thrown; if successful, a prompt message will be displayed and the API key input box will be cleared; if an exception occurs, an error message will be displayed.

Code

from flask import Flask, request, render_template, jsonify
import requests
 
app = Flask(__name__)
 
# Store user-configured APIapis = {
    "deepseek": None,
    "aliyun": None,
    "zhipu": None,
    "baidu": None,
    "iflytek": None
}
 
@('/')
def index():
    return render_template('', apis=apis)
 
@('/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 = ('model')
        api_key = ('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
 
@('/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 = ('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
 
@('/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 = ('model')
        prompt = ('prompt')
        
        if not model or not prompt:
            return jsonify({"status": "error", "message": "Missing required parameters"}), 400
            
        if model in apis and apis[model]:
            try:
                # Here we call the corresponding API according to different models                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 = (
                        "/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 = (
                        "/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 = (
                        "/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 = (
                        f"/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",  # Need to be replaced with the actual AppID                        "X-CurTime": str(int(())),
                        "X-Param": ({"scene": "main"}),
                        "X-CheckSum": ""  # Checksum needs to be calculated                    }
                    payload = {
                        "text": prompt
                    }
                    response = (
                        "/v1/aiui/v1/text",
                        headers=headers,
                        json=payload
                    )
                
                if response.status_code == 200:
                    response_data = ()
                    # Extract reply according to response format of different APIs                    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": ,
                        "request_payload": payload  # Add request load for debugging                    }), response.status_code
            except  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__':
    (debug=True)

Code

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;AI Model API Manager&lt;/title&gt;
    &lt;link href="/npm/[email protected]/dist/css/" rel="external nofollow"  rel="external nofollow"  rel="stylesheet"&gt;
    &lt;style&gt;
        .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;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class="container mt-5"&gt;
        &lt;h1 class="text-center mb-4"&gt;AI Model API Manager&lt;/h1&gt;
        &lt;div class="row"&gt;
            &lt;div class="col-md-6"&gt;
                &lt;div class="card mb-3"&gt;
                    &lt;div class="card-header"&gt;API Management&lt;/div&gt;
                    &lt;div class="card-body"&gt;
                        &lt;form  class="mb-3"&gt;
                            &lt;div class="mb-3"&gt;
                                &lt;label for="addModel" class="form-label"&gt;Model:&lt;/label&gt;
                                &lt;select  name="model" class="form-select"&gt;
                                    &lt;option value="deepseek"&gt;DeepSeek&lt;/option&gt;
                                    &lt;option value="aliyun"&gt;Aliyun&lt;/option&gt;
                                    &lt;option value="zhipu"&gt;Zhipu&lt;/option&gt;
                                    &lt;option value="baidu"&gt;Baidu&lt;/option&gt;
                                    &lt;option value="iflytek"&gt;Iflytek&lt;/option&gt;
                                &lt;/select&gt;
                            &lt;/div&gt;
                            &lt;div class="mb-3"&gt;
                                &lt;label for="api_key" class="form-label"&gt;API Key:&lt;/label&gt;
                                &lt;input type="text"  name="api_key" class="form-control" required&gt;
                            &lt;/div&gt;
                            &lt;button type="submit" class="btn btn-primary"&gt;Add API&lt;/button&gt;
                        &lt;/form&gt;
                        &lt;form &gt;
                            &lt;div class="mb-3"&gt;
                                &lt;label for="removeModel" class="form-label"&gt;Model:&lt;/label&gt;
                                &lt;select  name="model" class="form-select"&gt;
                                    &lt;option value="deepseek"&gt;DeepSeek&lt;/option&gt;
                                    &lt;option value="aliyun"&gt;Aliyun&lt;/option&gt;
                                    &lt;option value="zhipu"&gt;Zhipu&lt;/option&gt;
                                    &lt;option value="baidu"&gt;Baidu&lt;/option&gt;
                                    &lt;option value="iflytek"&gt;Iflytek&lt;/option&gt;
                                &lt;/select&gt;
                            &lt;/div&gt;
                            &lt;button type="submit" class="btn btn-danger"&gt;Remove API&lt;/button&gt;
                        &lt;/form&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="col-md-6"&gt;
                &lt;div class="card"&gt;
                    &lt;div class="card-header"&gt;Chat with AI&lt;/div&gt;
                    &lt;div class="card-body"&gt;
                        &lt;div class="chat-window" &gt;&lt;/div&gt;
                        &lt;form &gt;
                            &lt;div class="mb-3"&gt;
                                &lt;label for="chatModel" class="form-label"&gt;Model:&lt;/label&gt;
                                &lt;select  name="model" class="form-select"&gt;
                                    &lt;option value="deepseek"&gt;DeepSeek&lt;/option&gt;
                                    &lt;option value="aliyun"&gt;Aliyun&lt;/option&gt;
                                    &lt;option value="zhipu"&gt;Zhipu&lt;/option&gt;
                                    &lt;option value="baidu"&gt;Baidu&lt;/option&gt;
                                    &lt;option value="iflytek"&gt;Iflytek&lt;/option&gt;
                                &lt;/select&gt;
                            &lt;/div&gt;
                            &lt;div class="mb-3"&gt;
                                &lt;label for="prompt" class="form-label"&gt;Prompt:&lt;/label&gt;
                                &lt;input type="text"  name="prompt" class="form-control" required&gt;
                            &lt;/div&gt;
                            &lt;button type="submit" class="btn btn-success"&gt;Get Response&lt;/button&gt;
                        &lt;/form&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
 
&lt;!-- Keep the previous oneHTMLThe structure remains unchanged,Modify onlyJavaScriptpart --&gt;
&lt;script&gt;
    // Add API    ('addApiForm').addEventListener('submit', function(e) {
        ();
        const model = ('addModel').value;
        const apiKey = ('api_key').value;
        
        fetch('/add_api', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: ({
                model: model,
                api_key: apiKey
            })
        })
        .then(response =&gt; {
            if (!) {
                return ().then(err =&gt; { throw err; });
            }
            return ();
        })
        .then(data =&gt; {
            alert();
            ('api_key').value = '';
        })
        .catch(error =&gt; {
            alert(`Error: ${ || 'Failed to add API'}`);
        });
    });
 
    // Remove API    ('removeApiForm').addEventListener('submit', function(e) {
        ();
        const model = ('removeModel').value;
        
        fetch('/remove_api', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: ({
                model: model
            })
        })
        .then(response =&gt; {
            if (!) {
                return ().then(err =&gt; { throw err; });
            }
            return ();
        })
        .then(data =&gt; {
            alert();
        })
        .catch(error =&gt; {
            alert(`Error: ${ || 'Failed to remove API'}`);
        });
    });
 
    // Get the response    ('getResponseForm').addEventListener('submit', function(e) {
        ();
        const model = ('chatModel').value;
        const prompt = ('prompt').value;
        const chatWindow = ('chatWindow');
        
        // Add user message         += `
            &lt;div class="message user-message"&gt;
                &lt;strong&gt;You:&lt;/strong&gt; ${prompt}
            &lt;/div&gt;
        `;
        
        const submitBtn = ('#getResponseForm button[type="submit"]');
         = true;
        
        fetch('/get_response', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: ({
                model: model,
                prompt: prompt
            })
        })
        .then(response =&gt; {
            if (!) {
                return ().then(err =&gt; { throw err; });
            }
            return ();
        })
        .then(data =&gt; {
            if ( === "success") {
                 += `
                    &lt;div class="message bot-message"&gt;
                        &lt;strong&gt;Bot (${}):&lt;/strong&gt; ${}
                    &lt;/div&gt;
                `;
            } else {
                // Show more detailed error messages                let errorMsg = ;
                if (data.response_text) {
                    try {
                        const errorData = (data.response_text);
                        errorMsg += ` - ${ ||  || ''}`;
                    } catch (e) {
                        errorMsg += ` - ${data.response_text}`;
                    }
                }
                
                 += `
                    &lt;div class="message error-message"&gt;
                        &lt;strong&gt;Error:&lt;/strong&gt; ${errorMsg}
                    &lt;/div&gt;
                `;
            }
             = ;
            ('prompt').value = '';
        })
        .catch(error =&gt; {
            let errorMsg =  || 'Failed to get response';
            if (error.response_text) {
                errorMsg += ` - ${error.response_text}`;
            }
            
             += `
                &lt;div class="message error-message"&gt;
                    &lt;strong&gt;Error:&lt;/strong&gt; ${errorMsg}
                &lt;/div&gt;
            `;
             = ;
        })
        .finally(() =&gt; {
             = false;
        });
    });
&lt;/script&gt;
 
&lt;/body&gt;
&lt;/html&gt;

This is the article about adding multiple AI models APIs based on the Flask framework and interacting. For more related Flask AI model API management content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!