endpoint.rs 4.37 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
use std::{future::Future, pin::Pin, sync::Arc};
17

Neelay Shah's avatar
Neelay Shah committed
18
use dynamo_llm::{
19
    backend::Backend,
20
    engines::StreamingEngineAdapter,
21
    model_type::ModelType,
22
    preprocessor::{BackendInput, BackendOutput},
23
    types::{
24
25
26
        openai::chat_completions::{
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
        },
27
28
        Annotated,
    },
29
};
30
use dynamo_runtime::engine::AsyncEngineStream;
Neelay Shah's avatar
Neelay Shah committed
31
use dynamo_runtime::pipeline::{
32
    network::Ingress, Context, ManyOut, Operator, SegmentSource, ServiceBackend, SingleIn, Source,
33
};
34
use dynamo_runtime::{protocols::Endpoint as EndpointId, DistributedRuntime};
35

36
use crate::EngineConfig;
37
38

pub async fn run(
39
    distributed_runtime: DistributedRuntime,
40
41
42
    path: String,
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
43
    let cancel_token = distributed_runtime.primary_token().clone();
44
    let endpoint_id: EndpointId = path.parse()?;
45

46
47
48
49
50
51
52
53
54
    let component = distributed_runtime
        .namespace(&endpoint_id.namespace)?
        .component(&endpoint_id.component)?;
    let endpoint = component
        .service_builder()
        .create()
        .await?
        .endpoint(&endpoint_id.name);

55
56
    let (rt_fut, card): (Pin<Box<dyn Future<Output = _> + Send + 'static>>, _) = match engine_config
    {
57
        EngineConfig::StaticFull { engine, mut model } => {
58
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
59
60
61
62
63
            let ingress_chat = Ingress::<
                Context<NvCreateChatCompletionRequest>,
                Pin<Box<dyn AsyncEngineStream<Annotated<NvCreateChatCompletionStreamResponse>>>>,
            >::for_engine(engine)?;

64
65
66
            model.attach(&endpoint, ModelType::Chat).await?;
            let fut_chat = endpoint.endpoint_builder().handler(ingress_chat).start();

67
            (Box::pin(fut_chat), Some(model.card().clone()))
68
        }
69
70
        EngineConfig::StaticCore {
            engine: inner_engine,
71
            mut model,
72
        } => {
73
74
75
            // Pre-processing is done ingress-side, so it should be already done.
            let frontend =
                SegmentSource::<SingleIn<BackendInput>, ManyOut<Annotated<BackendOutput>>>::new();
76
77
78
            let backend = Backend::from_mdc(model.card().clone())
                .await?
                .into_operator();
79
80
81
82
83
84
            let engine = ServiceBackend::from_engine(inner_engine);
            let pipeline = frontend
                .link(backend.forward_edge())?
                .link(engine)?
                .link(backend.backward_edge())?
                .link(frontend)?;
85
            let ingress = Ingress::for_pipeline(pipeline)?;
86
87
88
89

            model.attach(&endpoint, ModelType::Backend).await?;
            let fut = endpoint.endpoint_builder().handler(ingress).start();

90
            (Box::pin(fut), Some(model.card().clone()))
91
92
        }
        EngineConfig::Dynamic(_) => {
93
94
95
96
            // We can only get here for in=dyn out=vllm|sglang`, because vllm and sglang are a
            // subprocess that we talk to like a remote endpoint.
            // That means the vllm/sglang subprocess is doing all the work, we are idle.
            (never_ready(), None)
97
        }
98
99
    };

100
101
102
103
104
105
106
107
108
    tokio::select! {
        _ = rt_fut => {
            tracing::debug!("Endpoint ingress ended");
        }
        _ = cancel_token.cancelled() => {
        }
    }

    // Cleanup on shutdown
109
110
111
112
113
114
115
    if let Some(mut card) = card {
        if let Err(err) = card
            .delete_from_nats(distributed_runtime.nats_client())
            .await
        {
            tracing::error!(%err, "delete_from_nats error on shutdown");
        }
116
117
118
119
    }

    Ok(())
}
120
121
122
123

fn never_ready() -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'static>> {
    Box::pin(std::future::pending::<anyhow::Result<()>>())
}