input.rs 3.67 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
// SPDX-License-Identifier: Apache-2.0

//! This module contains tools to gather a prompt from a user, forward it to an engine and return
//! the response.
//! See the Input enum for the inputs available. Input::Http (OpenAI compatible HTTP server)
//! and Input::Text (interactive chat) are good places to start.
//! The main entry point is `run_input`.

use std::{
    fmt,
    io::{IsTerminal as _, Read as _},
13
    str::FromStr,
14
15
16
};

mod common;
17
pub use common::{build_routed_pipeline, build_routed_pipeline_with_preprocessor};
18
pub mod endpoint;
GuanLuo's avatar
GuanLuo committed
19
pub mod grpc;
20
21
22
pub mod http;
pub mod text;

23
use dynamo_runtime::protocols::ENDPOINT_SCHEME;
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

/// The various ways of connecting prompts to an engine
#[derive(PartialEq)]
pub enum Input {
    /// Run an OpenAI compatible HTTP server
    Http,

    /// Single prompt on stdin
    Stdin,

    /// Interactive chat
    Text,

    /// Pull requests from a namespace/component/endpoint path.
    Endpoint(String),

GuanLuo's avatar
GuanLuo committed
40
41
    // Run an KServe compatible gRPC server
    Grpc,
42
43
}

44
45
46
47
48
49
50
51
impl FromStr for Input {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Input::try_from(s)
    }
}

52
53
54
55
56
57
impl TryFrom<&str> for Input {
    type Error = anyhow::Error;

    fn try_from(s: &str) -> anyhow::Result<Self> {
        match s {
            "http" => Ok(Input::Http),
GuanLuo's avatar
GuanLuo committed
58
            "grpc" => Ok(Input::Grpc),
59
60
61
62
63
64
65
66
67
68
69
70
71
72
            "text" => Ok(Input::Text),
            "stdin" => Ok(Input::Stdin),
            endpoint_path if endpoint_path.starts_with(ENDPOINT_SCHEME) => {
                Ok(Input::Endpoint(endpoint_path.to_string()))
            }
            e => Err(anyhow::anyhow!("Invalid in= option '{e}'")),
        }
    }
}

impl fmt::Display for Input {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = match self {
            Input::Http => "http",
GuanLuo's avatar
GuanLuo committed
73
            Input::Grpc => "grpc",
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
            Input::Text => "text",
            Input::Stdin => "stdin",
            Input::Endpoint(path) => path,
        };
        write!(f, "{s}")
    }
}

impl Default for Input {
    fn default() -> Self {
        if std::io::stdin().is_terminal() {
            Input::Text
        } else {
            Input::Stdin
        }
    }
}

/// Run the given engine (EngineConfig) connected to an input.
/// Does not return until the input exits.
94
95
/// For Input::Endpoint pass a DistributedRuntime. For everything else pass either a Runtime or a
/// DistributedRuntime.
96
pub async fn run_input(
97
    drt: dynamo_runtime::DistributedRuntime,
98
99
100
    in_opt: Input,
    engine_config: super::EngineConfig,
) -> anyhow::Result<()> {
101
102
103
104
105
106
107
    // Initialize audit bus + sink workers (off hot path; fan-out supported)
    if crate::audit::config::policy().enabled {
        let cap: usize = std::env::var("DYN_AUDIT_CAPACITY")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(1024);
        crate::audit::bus::init(cap);
108
        crate::audit::sink::spawn_workers_from_env().await?;
109
        tracing::info!(cap, "Audit initialized");
110
111
    }

112
113
    match in_opt {
        Input::Http => {
114
            http::run(drt, engine_config).await?;
115
        }
GuanLuo's avatar
GuanLuo committed
116
        Input::Grpc => {
117
            grpc::run(drt, engine_config).await?;
GuanLuo's avatar
GuanLuo committed
118
        }
119
        Input::Text => {
120
            text::run(drt, None, engine_config).await?;
121
122
123
124
        }
        Input::Stdin => {
            let mut prompt = String::new();
            std::io::stdin().read_to_string(&mut prompt).unwrap();
125
            text::run(drt, Some(prompt), engine_config).await?;
126
127
        }
        Input::Endpoint(path) => {
128
            endpoint::run(drt, path, engine_config).await?;
129
130
131
132
        }
    }
    Ok(())
}