frontend.py 3.64 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

16
import logging
17
import subprocess
18
from pathlib import Path
19

20
21
from components.processor import Processor
from components.worker import VllmWorker
22
from fastapi import FastAPI
23
24
from pydantic import BaseModel

25
from dynamo import sdk
26
from dynamo.sdk import async_on_shutdown, depends, service
27
from dynamo.sdk.lib.config import ServiceConfig
28
from dynamo.sdk.lib.image import DYNAMO_IMAGE
29

30
31
logger = logging.getLogger(__name__)

32

33
def get_http_binary_path():
34
    """Find the HTTP binary path in SDK or fallback to 'http' command."""
35
36
37
38
39
40
41
42
    sdk_path = Path(sdk.__file__)
    binary_path = sdk_path.parent / "cli/bin/http"
    if not binary_path.exists():
        return "http"
    else:
        return str(binary_path)


43
class FrontendConfig(BaseModel):
44
45
    """Configuration for the Frontend service including model and HTTP server settings."""

46
    served_model_name: str
47
48
49
50
    endpoint: str
    port: int = 8080


51
# todo this should be called ApiServer
52
@service(
53
54
55
56
    dynamo={
        "enabled": True,
        "namespace": "dynamo",
    },
57
58
    resources={"cpu": "10", "memory": "20Gi"},
    workers=1,
59
    image=DYNAMO_IMAGE,
60
    app=FastAPI(title="LLM Example"),
61
62
63
64
65
66
)
class Frontend:
    worker = depends(VllmWorker)
    processor = depends(Processor)

    def __init__(self):
67
        """Initialize Frontend service with HTTP server and model configuration."""
68
69
        config = ServiceConfig.get_instance()
        frontend_config = FrontendConfig(**config.get("Frontend", {}))
70
71
72
73
74
75
76
        self.frontend_config = frontend_config
        self.process = None

        self.setup_model()
        self.start_http_server()

    def setup_model(self):
77
        """Configure the model for HTTP service using llmctl."""
78
        subprocess.run(
79
80
81
82
83
            [
                "llmctl",
                "http",
                "remove",
                "chat-models",
84
                self.frontend_config.served_model_name,
85
86
            ],
            check=False,
87
88
89
90
91
92
93
        )
        subprocess.run(
            [
                "llmctl",
                "http",
                "add",
                "chat-models",
94
95
                self.frontend_config.served_model_name,
                self.frontend_config.endpoint,
96
97
            ],
            check=False,
98
99
        )

100
    def start_http_server(self):
101
        """Start the HTTP server on the configured port."""
102
        logger.info("Starting HTTP server")
103
        http_binary = get_http_binary_path()
104

105
106
107
108
        self.process = subprocess.Popen(
            [http_binary, "-p", str(self.frontend_config.port)],
            stdout=None,
            stderr=None,
109
        )
110

111
    @async_on_shutdown
112
    def cleanup(self):
113
114
115
        """Clean up resources before shutdown."""

        # circusd manages shutdown of http server process, we just need to remove the model using the on_shutdown hook
116
117
118
119
120
121
122
        subprocess.run(
            [
                "llmctl",
                "http",
                "remove",
                "chat-models",
                self.frontend_config.served_model_name,
123
124
            ],
            check=False,
125
        )