gradio_openai_chatbot_webserver.py 4.21 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
3
4
"""Example for starting a Gradio OpenAI Chatbot Webserver
Start vLLM API server:
    vllm serve meta-llama/Llama-2-7b-chat-hf
5

6
7
8
9
10
11
12
13
14
15
16
17
18
19
Start Gradio OpenAI Chatbot Webserver:
    python examples/online_serving/gradio_openai_chatbot_webserver.py \
                    -m meta-llama/Llama-2-7b-chat-hf

Note that `pip install --upgrade gradio` is needed to run this example.
More details: https://github.com/gradio-app/gradio

If your antivirus software blocks the download of frpc for gradio,
you can install it manually by following these steps:

1. Download this file: https://cdn-media.huggingface.co/frpc-gradio-0.3/frpc_linux_amd64
2. Rename the downloaded file to: frpc_linux_amd64_v0.3
3. Move the file to this location: /home/user/.cache/huggingface/gradio/frpc
"""
20
import argparse
21

22
import gradio as gr
23
from openai import OpenAI
24

25
26

def format_history_to_openai(history):
27
28
    history_openai_format = [{
        "role": "system",
29
        "content": "You are a great AI assistant."
30
31
32
33
34
35
36
    }]
    for human, assistant in history:
        history_openai_format.append({"role": "user", "content": human})
        history_openai_format.append({
            "role": "assistant",
            "content": assistant
        })
37
38
39
40
41
42
    return history_openai_format


def predict(message, history, client, model_name, temp, stop_token_ids):
    # Format history to OpenAI chat format
    history_openai_format = format_history_to_openai(history)
43
44
    history_openai_format.append({"role": "user", "content": message})

45
    # Send request to OpenAI API (vLLM server)
46
    stream = client.chat.completions.create(
47
48
49
50
        model=model_name,
        messages=history_openai_format,
        temperature=temp,
        stream=True,
51
52
53
        extra_body={
            'repetition_penalty':
            1,
54
55
56
            'stop_token_ids':
            [int(id.strip())
             for id in stop_token_ids.split(',')] if stop_token_ids else []
57
58
        })

59
60
    # Collect all chunks and concatenate them into a full message
    full_message = ""
61
    for chunk in stream:
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        full_message += (chunk.choices[0].delta.content or "")

    # Return the full message as a single response
    return full_message


def parse_args():
    parser = argparse.ArgumentParser(
        description='Chatbot Interface with Customizable Parameters')
    parser.add_argument('--model-url',
                        type=str,
                        default='http://localhost:8000/v1',
                        help='Model URL')
    parser.add_argument('-m',
                        '--model',
                        type=str,
                        required=True,
                        help='Model name for the chatbot')
    parser.add_argument('--temp',
                        type=float,
                        default=0.8,
                        help='Temperature for text generation')
    parser.add_argument('--stop-token-ids',
                        type=str,
                        default='',
                        help='Comma-separated stop token IDs')
    parser.add_argument("--host", type=str, default=None)
    parser.add_argument("--port", type=int, default=8001)
    return parser.parse_args()


def build_gradio_interface(client, model_name, temp, stop_token_ids):

    def chat_predict(message, history):
        return predict(message, history, client, model_name, temp,
                       stop_token_ids)

    return gr.ChatInterface(fn=chat_predict,
                            title="Chatbot Interface",
                            description="A simple chatbot powered by vLLM")


def main():
    # Parse the arguments
    args = parse_args()

    # Set OpenAI's API key and API base to use vLLM's API server
    openai_api_key = "EMPTY"
    openai_api_base = args.model_url

    # Create an OpenAI client
    client = OpenAI(api_key=openai_api_key, base_url=openai_api_base)

    # Define the Gradio chatbot interface using the predict function
    gradio_interface = build_gradio_interface(client, args.model, args.temp,
                                              args.stop_token_ids)

    gradio_interface.queue().launch(server_name=args.host,
                                    server_port=args.port,
                                    share=True)
122
123


124
125
if __name__ == "__main__":
    main()