http.rs 5.04 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// SPDX-FileCopyrightText: Copyright (c) 2024-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;

18
19
use crate::input::common;
use crate::{EngineConfig, Flags};
20
use dynamo_llm::http::service::discovery::LLMRouterMode;
21
use dynamo_llm::http::service::ModelManager;
Neelay Shah's avatar
Neelay Shah committed
22
use dynamo_llm::{
23
    engines::StreamingEngineAdapter,
24
    http::service::{discovery, service_v2},
25
    request_template::RequestTemplate,
26
    types::{
27
28
29
        openai::chat_completions::{
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
        },
30
        openai::completions::{CompletionRequest, CompletionResponse},
31
32
    },
};
33
use dynamo_runtime::component::Component;
34
use dynamo_runtime::transports::etcd;
35
use dynamo_runtime::{DistributedRuntime, Runtime};
36
37
38

/// Build and run an HTTP service
pub async fn run(
39
    runtime: Runtime,
40
    flags: Flags,
41
    engine_config: EngineConfig,
42
    template: Option<RequestTemplate>,
43
) -> anyhow::Result<()> {
44
    let http_service = service_v2::HttpService::builder()
45
        .port(flags.http_port)
46
47
        .enable_chat_endpoints(true)
        .enable_cmpl_endpoints(true)
48
        .with_request_template(template)
49
        .build()?;
50
    match engine_config {
51
        EngineConfig::Dynamic(endpoint) => {
52
            let distributed_runtime = DistributedRuntime::from_settings(runtime.clone()).await?;
53
54
55
            match distributed_runtime.etcd_client() {
                Some(etcd_client) => {
                    // This will attempt to connect to NATS and etcd
56

57
58
59
60
                    let component = distributed_runtime
                        .namespace(endpoint.namespace)?
                        .component(endpoint.component)?;
                    let network_prefix = component.service_name();
61

62
                    // Listen for models registering themselves in etcd, add them to HTTP service
63
                    run_watcher(
64
                        component.clone(),
65
66
67
                        http_service.model_manager().clone(),
                        etcd_client.clone(),
                        &network_prefix,
68
                        flags.router_mode.as_llm(),
69
70
                    )
                    .await?;
71
72
73
74
75
                }
                None => {
                    // Static endpoints don't need discovery
                }
            }
76
        }
77
        EngineConfig::StaticFull { engine, model } => {
78
79
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
            let manager = http_service.model_manager();
80
81
            manager.add_completions_model(model.service_name(), engine.clone())?;
            manager.add_chat_completions_model(model.service_name(), engine)?;
82
        }
83
84
        EngineConfig::StaticCore {
            engine: inner_engine,
85
            model,
86
        } => {
87
88
89
90
91
            let manager = http_service.model_manager();

            let chat_pipeline = common::build_pipeline::<
                NvCreateChatCompletionRequest,
                NvCreateChatCompletionStreamResponse,
92
            >(model.card(), inner_engine.clone())
93
            .await?;
94
            manager.add_chat_completions_model(model.service_name(), chat_pipeline)?;
95

96
            let cmpl_pipeline = common::build_pipeline::<CompletionRequest, CompletionResponse>(
97
                model.card(),
98
99
100
                inner_engine,
            )
            .await?;
101
            manager.add_completions_model(model.service_name(), cmpl_pipeline)?;
102
        }
103
    }
104
105
106
107
108
109
110
111
    tracing::debug!(
        "Supported routes: {:?}",
        http_service
            .route_docs()
            .iter()
            .map(|rd| rd.to_string())
            .collect::<Vec<String>>()
    );
112
113
114
    http_service.run(runtime.primary_token()).await?;
    runtime.shutdown(); // Cancel primary token
    Ok(())
115
}
116
117
118
119

/// Spawns a task that watches for new models in etcd at network_prefix,
/// and registers them with the ModelManager so that the HTTP service can use them.
async fn run_watcher(
120
    component: Component,
121
122
123
    model_manager: ModelManager,
    etcd_client: etcd::Client,
    network_prefix: &str,
124
    router_mode: LLMRouterMode,
125
) -> anyhow::Result<()> {
126
127
128
    let watch_obj = Arc::new(
        discovery::ModelWatcher::new(component, model_manager, network_prefix, router_mode).await?,
    );
129
130
131
    tracing::info!("Watching for remote model at {network_prefix}");
    let models_watcher = etcd_client.kv_get_and_watch_prefix(network_prefix).await?;
    let (_prefix, _watcher, receiver) = models_watcher.dissolve();
132
    let _watcher_task = tokio::spawn(watch_obj.watch(receiver));
133
134
    Ok(())
}