api_server.py 18.5 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
import importlib
import inspect
5
import multiprocessing
6
import multiprocessing.forkserver as forkserver
7
import os
8
import signal
9
import socket
10
import tempfile
11
import warnings
12
from argparse import Namespace
13
from collections.abc import AsyncIterator
14
from contextlib import asynccontextmanager
15
from typing import Any
16

17
import uvloop
18
from fastapi import FastAPI, HTTPException
Zhuohan Li's avatar
Zhuohan Li committed
19
20
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
21
from starlette.datastructures import State
Zhuohan Li's avatar
Zhuohan Li committed
22

23
import vllm.envs as envs
Woosuk Kwon's avatar
Woosuk Kwon committed
24
from vllm.engine.arg_utils import AsyncEngineArgs
25
from vllm.engine.protocol import EngineClient
26
from vllm.entrypoints.chat_utils import load_chat_template
27
from vllm.entrypoints.launcher import serve_http
28
from vllm.entrypoints.logger import RequestLogger
29
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
30
from vllm.entrypoints.openai.models.protocol import BaseModelPath
31
32
33
34
35
36
37
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.openai.server_utils import (
    get_uvicorn_log_config,
    http_exception_handler,
    lifespan,
    log_response,
    validation_exception_handler,
38
)
39
from vllm.entrypoints.sagemaker.api_router import sagemaker_standards_bootstrap
40
41
42
43
from vllm.entrypoints.serve.elastic_ep.middleware import (
    ScalingMiddleware,
)
from vllm.entrypoints.serve.tokenize.serving import OpenAIServingTokenization
44
45
46
from vllm.entrypoints.utils import (
    cli_env_setup,
    log_non_default_args,
47
    log_version_and_model,
48
    process_lora_modules,
49
)
50
from vllm.logger import init_logger
51
from vllm.reasoning import ReasoningParserManager
52
from vllm.tasks import POOLING_TASKS, SupportedTask
53
from vllm.tool_parsers import ToolParserManager
54
from vllm.tracing import instrument
yhu422's avatar
yhu422 committed
55
from vllm.usage.usage_lib import UsageContext
Cyrus Leung's avatar
Cyrus Leung committed
56
from vllm.utils.argparse_utils import FlexibleArgumentParser
57
from vllm.utils.network_utils import is_valid_ipv6_address
58
from vllm.utils.system_utils import decorate_logs, set_ulimit
59
from vllm.version import __version__ as VLLM_VERSION
Zhuohan Li's avatar
Zhuohan Li committed
60

61
prometheus_multiproc_dir: tempfile.TemporaryDirectory
62

63
# Cannot use __name__ (https://github.com/vllm-project/vllm/pull/4765)
64
logger = init_logger("vllm.entrypoints.openai.api_server")
65

66
67
_FALLBACK_SUPPORTED_TASKS: tuple[SupportedTask, ...] = ("generate",)

68

69
@asynccontextmanager
70
async def build_async_engine_client(
71
    args: Namespace,
72
73
    *,
    usage_context: UsageContext = UsageContext.OPENAI_API_SERVER,
74
75
    disable_frontend_multiprocessing: bool | None = None,
    client_config: dict[str, Any] | None = None,
76
) -> AsyncIterator[EngineClient]:
77
78
79
80
    if os.getenv("VLLM_WORKER_MULTIPROC_METHOD") == "forkserver":
        # The executor is expected to be mp.
        # Pre-import heavy modules in the forkserver process
        logger.debug("Setup forkserver with pre-imports")
81
        multiprocessing.set_start_method("forkserver")
82
83
84
85
        multiprocessing.set_forkserver_preload(["vllm.v1.engine.async_llm"])
        forkserver.ensure_running()
        logger.debug("Forkserver setup complete!")

86
    # Context manager to handle engine_client lifecycle
87
88
    # Ensures everything is shutdown and cleaned up on error/exit
    engine_args = AsyncEngineArgs.from_cli_args(args)
89
90
91
    if client_config:
        engine_args._api_process_count = client_config.get("client_count", 1)
        engine_args._api_process_rank = client_config.get("client_index", 0)
92

93
    if disable_frontend_multiprocessing is None:
94
        disable_frontend_multiprocessing = bool(args.disable_frontend_multiprocessing)
95

96
    async with build_async_engine_client_from_engine_args(
97
98
99
100
        engine_args,
        usage_context=usage_context,
        disable_frontend_multiprocessing=disable_frontend_multiprocessing,
        client_config=client_config,
101
    ) as engine:
102
103
104
105
106
107
        yield engine


@asynccontextmanager
async def build_async_engine_client_from_engine_args(
    engine_args: AsyncEngineArgs,
108
109
    *,
    usage_context: UsageContext = UsageContext.OPENAI_API_SERVER,
110
    disable_frontend_multiprocessing: bool = False,
111
    client_config: dict[str, Any] | None = None,
112
) -> AsyncIterator[EngineClient]:
113
    """
114
    Create EngineClient, either:
115
116
117
118
119
120
        - in-process using the AsyncLLMEngine Directly
        - multiprocess using AsyncLLMEngine RPC

    Returns the Client or None if the creation failed.
    """

121
122
123
    # Create the EngineConfig (determines if we can use V1).
    vllm_config = engine_args.create_engine_config(usage_context=usage_context)

124
    if disable_frontend_multiprocessing:
125
        logger.warning("V1 is enabled, but got --disable-frontend-multiprocessing.")
126

127
    from vllm.v1.engine.async_llm import AsyncLLM
128

129
    async_llm: AsyncLLM | None = None
130
131
132
133
134
135

    # Don't mutate the input client_config
    client_config = dict(client_config) if client_config else {}
    client_count = client_config.pop("client_count", 1)
    client_index = client_config.pop("client_index", 0)

136
137
138
139
140
    try:
        async_llm = AsyncLLM.from_vllm_config(
            vllm_config=vllm_config,
            usage_context=usage_context,
            enable_log_requests=engine_args.enable_log_requests,
141
            aggregate_engine_logging=engine_args.aggregate_engine_logging,
142
143
144
            disable_log_stats=engine_args.disable_log_stats,
            client_addresses=client_config,
            client_count=client_count,
145
146
            client_index=client_index,
        )
147
148

        # Don't keep the dummy data in memory
149
        assert async_llm is not None
150
151
152
153
154
155
        await async_llm.reset_mm_cache()

        yield async_llm
    finally:
        if async_llm:
            async_llm.shutdown()
156
157


158
159
160
161
162
163
164
165
166
167
168
169
170
def build_app(
    args: Namespace, supported_tasks: tuple["SupportedTask", ...] | None = None
) -> FastAPI:
    if supported_tasks is None:
        warnings.warn(
            "The 'supported_tasks' parameter was not provided to "
            "build_app and will be required in a future version. "
            "Defaulting to ('generate',).",
            DeprecationWarning,
            stacklevel=2,
        )
        supported_tasks = _FALLBACK_SUPPORTED_TASKS

171
    if args.disable_fastapi_docs:
172
173
174
        app = FastAPI(
            openapi_url=None, docs_url=None, redoc_url=None, lifespan=lifespan
        )
175
176
    elif args.enable_offline_docs:
        app = FastAPI(docs_url=None, redoc_url=None, lifespan=lifespan)
177
178
    else:
        app = FastAPI(lifespan=lifespan)
179
    app.state.args = args
180
181
182
183

    from vllm.entrypoints.openai.basic.api_router import register_basic_api_routers

    register_basic_api_routers(app)
184

185
    from vllm.entrypoints.serve import register_vllm_serve_api_routers
186

187
    register_vllm_serve_api_routers(app)
188

189
190
    from vllm.entrypoints.openai.models.api_router import (
        attach_router as register_models_api_router,
191
192
    )

193
    register_models_api_router(app)
194

195
196
    from vllm.entrypoints.sagemaker.api_router import (
        attach_router as register_sagemaker_api_router,
197
198
    )

199
    register_sagemaker_api_router(app, supported_tasks)
200

201
202
203
204
    if "generate" in supported_tasks:
        from vllm.entrypoints.openai.generate.api_router import (
            register_generate_api_routers,
        )
205

206
        register_generate_api_routers(app)
207

208
    if "transcription" in supported_tasks:
209
210
        from vllm.entrypoints.openai.speech_to_text.api_router import (
            attach_router as register_speech_to_text_api_router,
211
        )
212

213
        register_speech_to_text_api_router(app)
Zhuohan Li's avatar
Zhuohan Li committed
214

215
216
217
218
219
220
221
    if "realtime" in supported_tasks:
        from vllm.entrypoints.openai.realtime.api_router import (
            attach_router as register_realtime_api_router,
        )

        register_realtime_api_router(app)

222
223
    if any(task in POOLING_TASKS for task in supported_tasks):
        from vllm.entrypoints.pooling import register_pooling_api_routers
224

225
        register_pooling_api_routers(app, supported_tasks)
226

227
    app.root_path = args.root_path
Zhuohan Li's avatar
Zhuohan Li committed
228
229
230
231
232
233
234
235
    app.add_middleware(
        CORSMiddleware,
        allow_origins=args.allowed_origins,
        allow_credentials=args.allow_credentials,
        allow_methods=args.allowed_methods,
        allow_headers=args.allowed_headers,
    )

236
237
    app.exception_handler(HTTPException)(http_exception_handler)
    app.exception_handler(RequestValidationError)(validation_exception_handler)
Ethan Xu's avatar
Ethan Xu committed
238

239
    # Ensure --api-key option from CLI takes precedence over VLLM_API_KEY
240
    if tokens := [key for key in (args.api_key or [envs.VLLM_API_KEY]) if key]:
241
242
        from vllm.entrypoints.openai.server_utils import AuthenticationMiddleware

243
        app.add_middleware(AuthenticationMiddleware, tokens=tokens)
244

245
    if args.enable_request_id_headers:
246
247
        from vllm.entrypoints.openai.server_utils import XRequestIdMiddleware

248
        app.add_middleware(XRequestIdMiddleware)
249

250
251
252
    # Add scaling middleware to check for scaling state
    app.add_middleware(ScalingMiddleware)

253
    if envs.VLLM_DEBUG_LOG_API_SERVER_RESPONSE:
254
255
256
257
258
        logger.warning(
            "CAUTION: Enabling log response in the API Server. "
            "This can include sensitive information and should be "
            "avoided in production."
        )
259
        app.middleware("http")(log_response)
260

261
262
263
264
    for middleware in args.middleware:
        module_path, object_name = middleware.rsplit(".", 1)
        imported = getattr(importlib.import_module(module_path), object_name)
        if inspect.isclass(imported):
265
            app.add_middleware(imported)  # type: ignore[arg-type]
266
267
268
        elif inspect.iscoroutinefunction(imported):
            app.middleware("http")(imported)
        else:
269
270
271
            raise ValueError(
                f"Invalid middleware {middleware}. Must be a function or a class."
            )
272

273
    app = sagemaker_standards_bootstrap(app)
Ethan Xu's avatar
Ethan Xu committed
274
275
276
    return app


277
async def init_app_state(
278
    engine_client: EngineClient,
279
    state: State,
280
    args: Namespace,
281
    supported_tasks: tuple["SupportedTask", ...] | None = None,
282
) -> None:
283
    vllm_config = engine_client.vllm_config
284
285
286
287
288
289
290
291
292
    if supported_tasks is None:
        warnings.warn(
            "The 'supported_tasks' parameter was not provided to "
            "init_app_state and will be required in a future version. "
            "Please pass 'supported_tasks' explicitly.",
            DeprecationWarning,
            stacklevel=2,
        )
        supported_tasks = _FALLBACK_SUPPORTED_TASKS
293

294
    if args.served_model_name is not None:
295
        served_model_names = args.served_model_name
296
    else:
297
        served_model_names = [args.model]
298

299
    if args.enable_log_requests:
300
        request_logger = RequestLogger(max_log_len=args.max_log_len)
301
302
    else:
        request_logger = None
303

304
    base_model_paths = [
305
        BaseModelPath(name=name, model_path=args.model) for name in served_model_names
306
307
    ]

308
    state.engine_client = engine_client
309
    state.log_stats = not args.disable_log_stats
310
    state.vllm_config = vllm_config
311
    state.args = args
312
    resolved_chat_template = load_chat_template(args.chat_template)
313

314
    # Merge default_mm_loras into the static lora_modules
315
316
317
318
319
320
    default_mm_loras = (
        vllm_config.lora_config.default_mm_loras
        if vllm_config.lora_config is not None
        else {}
    )
    lora_modules = process_lora_modules(args.lora_modules, default_mm_loras)
321

322
    state.openai_serving_models = OpenAIServingModels(
323
        engine_client=engine_client,
324
        base_model_paths=base_model_paths,
325
        lora_modules=lora_modules,
326
    )
327
    await state.openai_serving_models.init_static_loras()
328
    state.openai_serving_tokenization = OpenAIServingTokenization(
329
        engine_client,
330
        state.openai_serving_models,
331
        request_logger=request_logger,
332
333
        chat_template=resolved_chat_template,
        chat_template_content_format=args.chat_template_content_format,
334
        trust_request_chat_template=args.trust_request_chat_template,
335
        log_error_stack=args.log_error_stack,
336
    )
337
338
339
340
341
342

    if "generate" in supported_tasks:
        from vllm.entrypoints.openai.generate.api_router import init_generate_state

        await init_generate_state(
            engine_client, state, args, request_logger, supported_tasks
343
        )
344
345

    if "transcription" in supported_tasks:
346
        from vllm.entrypoints.openai.speech_to_text.api_router import (
347
            init_transcription_state,
348
        )
349
350
351

        init_transcription_state(
            engine_client, state, args, request_logger, supported_tasks
352
        )
353

354
355
356
357
358
    if "realtime" in supported_tasks:
        from vllm.entrypoints.openai.realtime.api_router import init_realtime_state

        init_realtime_state(engine_client, state, args, request_logger, supported_tasks)

359
360
    if any(task in POOLING_TASKS for task in supported_tasks):
        from vllm.entrypoints.pooling import init_pooling_state
361

362
        init_pooling_state(engine_client, state, args, request_logger, supported_tasks)
363

364
365
366
    state.enable_server_load_tracking = args.enable_server_load_tracking
    state.server_load_metrics = 0

367

368
def create_server_socket(addr: tuple[str, int]) -> socket.socket:
369
370
371
372
373
374
    family = socket.AF_INET
    if is_valid_ipv6_address(addr[0]):
        family = socket.AF_INET6

    sock = socket.socket(family=family, type=socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
375
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
376
377
378
379
380
    sock.bind(addr)

    return sock


381
382
383
384
385
386
def create_server_unix_socket(path: str) -> socket.socket:
    sock = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM)
    sock.bind(path)
    return sock


387
def validate_api_server_args(args):
388
    valid_tool_parses = ToolParserManager.list_registered()
389
390
391
392
393
    if args.enable_auto_tool_choice and args.tool_call_parser not in valid_tool_parses:
        raise KeyError(
            f"invalid tool call parser: {args.tool_call_parser} "
            f"(chose from {{ {','.join(valid_tool_parses)} }})"
        )
394

395
    valid_reasoning_parsers = ReasoningParserManager.list_registered()
396
397
    if (
        reasoning_parser := args.structured_outputs_config.reasoning_parser
398
    ) and reasoning_parser not in valid_reasoning_parsers:
399
        raise KeyError(
400
            f"invalid reasoning parser: {reasoning_parser} "
401
            f"(chose from {{ {','.join(valid_reasoning_parsers)} }})"
402
        )
403

404

405
@instrument(span_name="API server setup")
406
407
408
409
def setup_server(args):
    """Validate API server args, set up signal handler, create socket
    ready to serve."""

410
    log_version_and_model(logger, VLLM_VERSION, args.model)
411
412
413
414
415
    log_non_default_args(args)

    if args.tool_parser_plugin and len(args.tool_parser_plugin) > 3:
        ToolParserManager.import_tool_parser(args.tool_parser_plugin)

416
417
418
    if args.reasoning_parser_plugin and len(args.reasoning_parser_plugin) > 3:
        ReasoningParserManager.import_reasoning_parser(args.reasoning_parser_plugin)

419
420
    validate_api_server_args(args)

421
422
423
    # workaround to make sure that we bind the port before the engine is set up.
    # This avoids race conditions with ray.
    # see https://github.com/vllm-project/vllm/issues/8204
424
425
426
427
428
    if args.uds:
        sock = create_server_unix_socket(args.uds)
    else:
        sock_addr = (args.host or "", args.port)
        sock = create_server_socket(sock_addr)
429

430
431
432
433
    # workaround to avoid footguns where uvicorn drops requests with too
    # many concurrent requests active
    set_ulimit()

434
435
436
437
438
439
    def signal_handler(*_) -> None:
        # Interrupt server on sigterm while initializing
        raise KeyboardInterrupt("terminated")

    signal.signal(signal.SIGTERM, signal_handler)

440
441
442
443
444
    if args.uds:
        listen_address = f"unix:{args.uds}"
    else:
        addr, port = sock_addr
        is_ssl = args.ssl_keyfile and args.ssl_certfile
445
        host_part = f"[{addr}]" if is_valid_ipv6_address(addr) else addr or "0.0.0.0"
446
        listen_address = f"http{'s' if is_ssl else ''}://{host_part}:{port}"
447
448
449
450
451
    return listen_address, sock


async def run_server(args, **uvicorn_kwargs) -> None:
    """Run a single-worker API server."""
452
453

    # Add process-specific prefix to stdout and stderr.
454
    decorate_logs("APIServer")
455

456
457
458
459
    listen_address, sock = setup_server(args)
    await run_server_worker(listen_address, sock, args, **uvicorn_kwargs)


460
461
462
async def run_server_worker(
    listen_address, sock, args, client_config=None, **uvicorn_kwargs
) -> None:
463
464
465
466
467
    """Run a single API server worker."""

    if args.tool_parser_plugin and len(args.tool_parser_plugin) > 3:
        ToolParserManager.import_tool_parser(args.tool_parser_plugin)

468
469
470
    if args.reasoning_parser_plugin and len(args.reasoning_parser_plugin) > 3:
        ReasoningParserManager.import_reasoning_parser(args.reasoning_parser_plugin)

471
472
    # Get uvicorn log config (from file or with endpoint filter)
    log_config = get_uvicorn_log_config(args)
473
    if log_config is not None:
474
        uvicorn_kwargs["log_config"] = log_config
475

476
    async with build_async_engine_client(
477
478
        args,
        client_config=client_config,
479
    ) as engine_client:
480
481
        supported_tasks = await engine_client.get_supported_tasks()
        logger.info("Supported tasks: %s", supported_tasks)
482

483
484
        app = build_app(args, supported_tasks)
        await init_app_state(engine_client, app.state, args, supported_tasks)
485

486
487
        logger.info(
            "Starting vLLM API server %d on %s",
488
            engine_client.vllm_config.parallel_config._api_process_rank,
489
490
            listen_address,
        )
491
492
        shutdown_task = await serve_http(
            app,
493
            sock=sock,
494
            enable_ssl_refresh=args.enable_ssl_refresh,
495
496
497
            host=args.host,
            port=args.port,
            log_level=args.uvicorn_log_level,
498
499
500
            # NOTE: When the 'disable_uvicorn_access_log' value is True,
            # no access log will be output.
            access_log=not args.disable_uvicorn_access_log,
501
            timeout_keep_alive=envs.VLLM_HTTP_TIMEOUT_KEEP_ALIVE,
502
503
504
505
            ssl_keyfile=args.ssl_keyfile,
            ssl_certfile=args.ssl_certfile,
            ssl_ca_certs=args.ssl_ca_certs,
            ssl_cert_reqs=args.ssl_cert_reqs,
506
            ssl_ciphers=args.ssl_ciphers,
507
508
            h11_max_incomplete_event_size=args.h11_max_incomplete_event_size,
            h11_max_header_count=args.h11_max_header_count,
509
510
511
            **uvicorn_kwargs,
        )

512
    # NB: Await server shutdown only after the backend context is exited
513
514
515
516
    try:
        await shutdown_task
    finally:
        sock.close()
517

Ethan Xu's avatar
Ethan Xu committed
518
519
520

if __name__ == "__main__":
    # NOTE(simon):
521
522
    # This section should be in sync with vllm/entrypoints/cli/main.py for CLI
    # entrypoints.
523
    cli_env_setup()
Ethan Xu's avatar
Ethan Xu committed
524
    parser = FlexibleArgumentParser(
525
526
        description="vLLM OpenAI-Compatible RESTful API server."
    )
Ethan Xu's avatar
Ethan Xu committed
527
528
    parser = make_arg_parser(parser)
    args = parser.parse_args()
529
    validate_parsed_serve_args(args)
530

531
    uvloop.run(run_server(args))