scripts.py 7.08 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

Ethan Xu's avatar
Ethan Xu committed
3
4
5
6
7
# The CLI entrypoint to vLLM.
import argparse
import os
import signal
import sys
8
from typing import List, Optional
Ethan Xu's avatar
Ethan Xu committed
9

10
import uvloop
Ethan Xu's avatar
Ethan Xu committed
11
from openai import OpenAI
12
from openai.types.chat import ChatCompletionMessageParam
Ethan Xu's avatar
Ethan Xu committed
13

14
import vllm.version
15
from vllm.engine.arg_utils import EngineArgs
Ethan Xu's avatar
Ethan Xu committed
16
from vllm.entrypoints.openai.api_server import run_server
17
18
from vllm.entrypoints.openai.cli_args import (make_arg_parser,
                                              validate_parsed_serve_args)
19
from vllm.logger import init_logger
Ethan Xu's avatar
Ethan Xu committed
20
21
from vllm.utils import FlexibleArgumentParser

22
23
logger = init_logger(__name__)

Ethan Xu's avatar
Ethan Xu committed
24

25
def register_signal_handlers():
Ethan Xu's avatar
Ethan Xu committed
26
27
28
29
30
31
32
33
34

    def signal_handler(sig, frame):
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTSTP, signal_handler)


def serve(args: argparse.Namespace) -> None:
35
36
37
38
39
40
    # The default value of `--model`
    if args.model != EngineArgs.model:
        raise ValueError(
            "With `vllm serve`, you should provide the model as a "
            "positional argument instead of via the `--model` option.")

Ethan Xu's avatar
Ethan Xu committed
41
42
43
    # EngineArgs expects the model name to be passed as --model.
    args.model = args.model_tag

44
    uvloop.run(run_server(args))
Ethan Xu's avatar
Ethan Xu committed
45
46
47


def interactive_cli(args: argparse.Namespace) -> None:
48
    register_signal_handlers()
Ethan Xu's avatar
Ethan Xu committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

    base_url = args.url
    api_key = args.api_key or os.environ.get("OPENAI_API_KEY", "EMPTY")
    openai_client = OpenAI(api_key=api_key, base_url=base_url)

    if args.model_name:
        model_name = args.model_name
    else:
        available_models = openai_client.models.list()
        model_name = available_models.data[0].id

    print(f"Using model: {model_name}")

    if args.command == "complete":
        complete(model_name, openai_client)
    elif args.command == "chat":
        chat(args.system_prompt, model_name, openai_client)


def complete(model_name: str, client: OpenAI) -> None:
    print("Please enter prompt to complete:")
    while True:
        input_prompt = input("> ")

        completion = client.completions.create(model=model_name,
                                               prompt=input_prompt)
        output = completion.choices[0].text
        print(output)


def chat(system_prompt: Optional[str], model_name: str,
         client: OpenAI) -> None:
81
    conversation: List[ChatCompletionMessageParam] = []
Ethan Xu's avatar
Ethan Xu committed
82
83
84
85
86
87
    if system_prompt is not None:
        conversation.append({"role": "system", "content": system_prompt})

    print("Please enter a message for the chat model:")
    while True:
        input_message = input("> ")
88
        conversation.append({"role": "user", "content": input_message})
Ethan Xu's avatar
Ethan Xu committed
89
90
91
92
93
94
95

        chat_completion = client.chat.completions.create(model=model_name,
                                                         messages=conversation)

        response_message = chat_completion.choices[0].message
        output = response_message.content

96
        conversation.append(response_message)  # type: ignore
Ethan Xu's avatar
Ethan Xu committed
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
122
123
        print(output)


def _add_query_options(
        parser: FlexibleArgumentParser) -> FlexibleArgumentParser:
    parser.add_argument(
        "--url",
        type=str,
        default="http://localhost:8000/v1",
        help="url of the running OpenAI-Compatible RESTful API server")
    parser.add_argument(
        "--model-name",
        type=str,
        default=None,
        help=("The model name used in prompt completion, default to "
              "the first model in list models API call."))
    parser.add_argument(
        "--api-key",
        type=str,
        default=None,
        help=(
            "API key for OpenAI services. If provided, this api key "
            "will overwrite the api key obtained through environment variables."
        ))
    return parser


124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def env_setup():
    # The safest multiprocessing method is `spawn`, as the default `fork` method
    # is not compatible with some accelerators. The default method will be
    # changing in future versions of Python, so we should use it explicitly when
    # possible.
    #
    # We only set it here in the CLI entrypoint, because changing to `spawn`
    # could break some existing code using vLLM as a library. `spawn` will cause
    # unexpected behavior if the code is not protected by
    # `if __name__ == "__main__":`.
    #
    # References:
    # - https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
    # - https://pytorch.org/docs/stable/notes/multiprocessing.html#cuda-in-multiprocessing
    # - https://pytorch.org/docs/stable/multiprocessing.html#sharing-cuda-tensors
    # - https://docs.habana.ai/en/latest/PyTorch/Getting_Started_with_PyTorch_and_Gaudi/Getting_Started_with_PyTorch.html?highlight=multiprocessing#torch-multiprocessing-for-dataloaders
    if "VLLM_WORKER_MULTIPROC_METHOD" not in os.environ:
        logger.debug("Setting VLLM_WORKER_MULTIPROC_METHOD to 'spawn'")
        os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"


Ethan Xu's avatar
Ethan Xu committed
145
def main():
146
147
    env_setup()

Ethan Xu's avatar
Ethan Xu committed
148
    parser = FlexibleArgumentParser(description="vLLM CLI")
149
150
151
152
153
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version=vllm.version.__version__)

154
    subparsers = parser.add_subparsers(required=True, dest="subparser")
Ethan Xu's avatar
Ethan Xu committed
155
156
157
158
159
160
161
162

    serve_parser = subparsers.add_parser(
        "serve",
        help="Start the vLLM OpenAI Compatible API server",
        usage="vllm serve <model_tag> [options]")
    serve_parser.add_argument("model_tag",
                              type=str,
                              help="The model tag to serve")
163
164
165
166
167
168
169
    serve_parser.add_argument(
        "--config",
        type=str,
        default='',
        required=False,
        help="Read CLI options from a config file."
        "Must be a YAML with the following options:"
170
        "https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html#cli-reference"
171
    )
172

Ethan Xu's avatar
Ethan Xu committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    serve_parser = make_arg_parser(serve_parser)
    serve_parser.set_defaults(dispatch_function=serve)

    complete_parser = subparsers.add_parser(
        "complete",
        help=("Generate text completions based on the given prompt "
              "via the running API server"),
        usage="vllm complete [options]")
    _add_query_options(complete_parser)
    complete_parser.set_defaults(dispatch_function=interactive_cli,
                                 command="complete")

    chat_parser = subparsers.add_parser(
        "chat",
        help="Generate chat completions via the running API server",
        usage="vllm chat [options]")
    _add_query_options(chat_parser)
    chat_parser.add_argument(
        "--system-prompt",
        type=str,
        default=None,
        help=("The system prompt to be added to the chat template, "
              "used for models that support system prompts."))
    chat_parser.set_defaults(dispatch_function=interactive_cli, command="chat")

    args = parser.parse_args()
199
200
201
    if args.subparser == "serve":
        validate_parsed_serve_args(args)

Ethan Xu's avatar
Ethan Xu committed
202
203
204
205
206
207
208
209
210
    # One of the sub commands should be executed.
    if hasattr(args, "dispatch_function"):
        args.dispatch_function(args)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()