endpoint.rs 5.39 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
use std::sync::Arc;

Neelay Shah's avatar
Neelay Shah committed
18
use dynamo_llm::{
19
    backend::Backend,
20
    engines::StreamingEngineAdapter,
21
22
23
    http::service::discovery::{ModelEntry, ModelNetworkName},
    key_value_store::{EtcdStorage, KeyValueStore, KeyValueStoreManager},
    model_card,
24
    model_type::ModelType,
25
26
    preprocessor::OpenAIPreprocessor,
    types::{
27
28
29
        openai::chat_completions::{
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
        },
30
31
        Annotated,
    },
32
};
Neelay Shah's avatar
Neelay Shah committed
33
use dynamo_runtime::pipeline::{
34
35
    network::Ingress, ManyOut, Operator, SegmentSource, ServiceBackend, SingleIn, Source,
};
36
use dynamo_runtime::{protocols::Endpoint, DistributedRuntime};
37

38
use crate::EngineConfig;
39
40

pub async fn run(
41
    distributed_runtime: DistributedRuntime,
42
43
44
45
46
    path: String,
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
    // This will attempt to connect to NATS and etcd

47
    let cancel_token = distributed_runtime.primary_token().clone();
48
    let endpoint_id: Endpoint = path.parse()?;
49

50
51
    let etcd_client = distributed_runtime.etcd_client();

52
    let (ingress, service_name, mut card, requires_preprocessing) = match engine_config {
53
54
55
        EngineConfig::StaticFull {
            service_name,
            engine,
56
            card,
57
58
        } => {
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
59
            (Ingress::for_engine(engine)?, service_name, card, false)
60
        }
61
62
63
64
        EngineConfig::StaticCore {
            service_name,
            engine: inner_engine,
            card,
65
        } => {
66
            let frontend = SegmentSource::<
67
                SingleIn<NvCreateChatCompletionRequest>,
68
                ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
69
70
71
72
73
74
            >::new();
            let preprocessor = OpenAIPreprocessor::new(*card.clone())
                .await?
                .into_operator();
            let backend = Backend::from_mdc(*card.clone()).await?.into_operator();
            let engine = ServiceBackend::from_engine(inner_engine);
75

76
77
78
79
80
81
82
            let pipeline = frontend
                .link(preprocessor.forward_edge())?
                .link(backend.forward_edge())?
                .link(engine)?
                .link(backend.backward_edge())?
                .link(preprocessor.backward_edge())?
                .link(frontend)?;
83

84
85
            // TODO: switch last 'false' to 'true' once we have ingress-side pre-processing
            (Ingress::for_pipeline(pipeline)?, service_name, card, false)
86
87
88
89
        }
        EngineConfig::Dynamic(_) => {
            anyhow::bail!("Cannot use endpoint for both in and out");
        }
90
        EngineConfig::None => unreachable!(),
91
92
93
94
    };

    let model_registration = ModelEntry {
        name: service_name.to_string(),
95
        endpoint: endpoint_id.clone(),
96
        model_type: ModelType::Chat,
97
    };
98

99
    let component = distributed_runtime
100
101
        .namespace(&endpoint_id.namespace)?
        .component(&endpoint_id.component)?;
102
103
104
105
    let endpoint = component
        .service_builder()
        .create()
        .await?
106
107
        .endpoint(&endpoint_id.name);

108
    if let Some(etcd_client) = etcd_client {
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        // Store model config files in NATS object store
        let nats_client = distributed_runtime.nats_client();
        card.move_to_nats(nats_client.clone()).await?;

        // Publish the Model Deployment Card to etcd
        let kvstore: Box<dyn KeyValueStore> =
            Box::new(EtcdStorage::new(etcd_client.clone(), endpoint_id));
        let card_store = Arc::new(KeyValueStoreManager::new(kvstore));
        card.requires_preprocessing = requires_preprocessing; // Not used yet. Soon.
        let key = card.slug().to_string();
        card_store
            .publish(model_card::BUCKET_NAME, None, &key, &mut *card.clone())
            .await?;

        // Publish our ModelEntry to etcd. This allows ingress to find the model card.
        // (Why don't we put the model card directly under this key?)
        let network_name = ModelNetworkName::from_local(&endpoint, etcd_client.lease_id());
126
127
128
        tracing::debug!("Registering with etcd as {network_name}");
        etcd_client
            .kv_create(
129
                network_name.to_string(),
130
                serde_json::to_vec_pretty(&model_registration)?,
131
                None, // use primary lease
132
133
134
            )
            .await?;
    }
135

136
    let rt_fut = endpoint.endpoint_builder().handler(ingress).start();
137
138
139
140
141
142
    tokio::select! {
        _ = rt_fut => {
            tracing::debug!("Endpoint ingress ended");
        }
        _ = cancel_token.cancelled() => {
        }
143
    }
144

145
    // Cleanup on shutdown
146
147
148
149
    if let Err(err) = card
        .delete_from_nats(distributed_runtime.nats_client())
        .await
    {
150
151
        tracing::error!(%err, "delete_from_nats error on shutdown");
    }
152
    Ok(())
153
}