hello_world.py 4.35 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
17
import logging

18
from fastapi.responses import StreamingResponse
19
20
from pydantic import BaseModel

21
from dynamo.runtime.logging import configure_dynamo_logging
22
23
24
25
26
27
28
29
30
from dynamo.sdk import (
    DYNAMO_IMAGE,
    api,
    depends,
    endpoint,
    liveness,
    readiness,
    service,
)
31
from dynamo.sdk.lib.config import ServiceConfig
32

33
34
logger = logging.getLogger(__name__)

35

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
Pipeline Architecture:

Users/Clients (HTTP)


┌─────────────┐
│  Frontend   │  HTTP API endpoint (/generate)
└─────────────┘
      │ dynamo/runtime

┌─────────────┐
│   Middle    │
└─────────────┘
      │ dynamo/runtime

┌─────────────┐
│  Backend    │
└─────────────┘
"""


class RequestType(BaseModel):
    text: str


class ResponseType(BaseModel):
    text: str


@service(
    dynamo={
        "namespace": "inference",
    },
70
71
    resource={"cpu": 1, "memory": "500Mi"},
    workers=2,
72
    image=DYNAMO_IMAGE,
73
74
75
)
class Backend:
    def __init__(self) -> None:
76
        logger.info("Starting backend")
77
78
79
        config = ServiceConfig.get_instance()
        self.message = config.get("Backend", {}).get("message", "back")
        logger.info(f"Backend config message: {self.message}")
80

81
    @endpoint()
82
83
84
    async def generate(self, req: RequestType):
        """Generate tokens."""
        req_text = req.text
85
        logger.info(f"Backend received: {req_text}")
86
        text = f"{req_text}-{self.message}"
87
        for token in text.split():
88
            yield f"Backend: {token}"
89
90
91


@service(
92
    dynamo={"namespace": "inference"},
93
    image=DYNAMO_IMAGE,
94
95
96
97
98
)
class Middle:
    backend = depends(Backend)

    def __init__(self) -> None:
99
        logger.info("Starting middle")
100
101
102
        config = ServiceConfig.get_instance()
        self.message = config.get("Middle", {}).get("message", "mid")
        logger.info(f"Middle config message: {self.message}")
103

104
    @endpoint()
105
106
107
    async def generate(self, req: RequestType):
        """Forward requests to backend."""
        req_text = req.text
108
        logger.info(f"Middle received: {req_text}")
109
        text = f"{req_text}-{self.message}"
110
111
        next_request = RequestType(text=text).model_dump_json()
        async for response in self.backend.generate(next_request):
112
            logger.info(f"Middle received response: {response}")
113
            yield f"Middle: {response}"
114
115


116
@service(
117
    dynamo={"namespace": "inference"},
118
    image=DYNAMO_IMAGE,
119
)
120
class Frontend:
121
122
    """A simple frontend HTTP API that forwards requests to the dynamo graph."""

123
124
125
    middle = depends(Middle)

    def __init__(self) -> None:
126
        # Configure logging
127
        configure_dynamo_logging(service_name="Frontend")
128

129
130
131
132
133
134
        logger.info("Starting frontend")
        config = ServiceConfig.get_instance()
        self.message = config.get("Frontend", {}).get("message", "front")
        self.port = config.get("Frontend", {}).get("port", 8000)
        logger.info(f"Frontend config message: {self.message}")
        logger.info(f"Frontend config port: {self.port}")
135

136
137
    # alternative syntax: @endpoint(transports=[DynamoTransport.HTTP])
    @api()
138
    async def generate(self, request: RequestType):
139
        """Stream results from the pipeline."""
140
141
142
143
        logger.info(f"Frontend received: {request.text}")

        async def content_generator():
            async for response in self.middle.generate(request.model_dump_json()):
144
                yield f"Frontend: {response}"
145
146

        return StreamingResponse(content_generator())
147
148
149
150
151
152
153
154

    @liveness
    def is_alive(self):
        return True

    @readiness
    def is_ready(self):
        return True