text.rs 6.74 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
5
use crate::request_template::RequestTemplate;
use crate::types::openai::chat_completions::{
6
    NvCreateChatCompletionRequest, OpenAIChatCompletionsStreamingEngine,
7
};
8
9
use dynamo_runtime::DistributedRuntime;
use dynamo_runtime::pipeline::Context;
10
use futures::StreamExt;
11
use std::io::{ErrorKind, Write};
12

13
use crate::entrypoint::EngineConfig;
14
use crate::entrypoint::input::common;
15
16

/// Max response tokens for each single query. Must be less than model context size.
17
/// TODO: Cmd line flag to overwrite this
Paul Hendricks's avatar
Paul Hendricks committed
18
const MAX_TOKENS: u32 = 8192;
19
20

pub async fn run(
21
    distributed_runtime: DistributedRuntime,
22
    single_prompt: Option<String>,
23
24
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
25
26
    let prepared_engine =
        common::prepare_engine(distributed_runtime.clone(), engine_config).await?;
27
    // TODO: Pass prepared_engine directly
28
    main_loop(
29
        distributed_runtime,
30
31
        &prepared_engine.service_name,
        prepared_engine.engine,
32
        single_prompt,
33
        prepared_engine.inspect_template,
34
        prepared_engine.request_template,
35
36
    )
    .await
37
38
39
}

async fn main_loop(
40
    distributed_runtime: DistributedRuntime,
41
42
    service_name: &str,
    engine: OpenAIChatCompletionsStreamingEngine,
43
    mut initial_prompt: Option<String>,
Paul Hendricks's avatar
Paul Hendricks committed
44
    _inspect_template: bool,
45
    template: Option<RequestTemplate>,
46
) -> anyhow::Result<()> {
47
    let cancel_token = distributed_runtime.primary_token();
48
49
50
    if initial_prompt.is_none() {
        tracing::info!("Ctrl-c to exit");
    }
51
52
    let theme = dialoguer::theme::ColorfulTheme::default();

53
54
55
    // Initial prompt is the pipe case: `echo "Hello" | dynamo-run ..`
    // We run that single prompt and exit
    let single = initial_prompt.is_some();
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    let mut history = dialoguer::BasicHistory::default();
    let mut messages = vec![];
    while !cancel_token.is_cancelled() {
        // User input
        let prompt = match initial_prompt.take() {
            Some(p) => p,
            None => {
                let input_ui = dialoguer::Input::<String>::with_theme(&theme)
                    .history_with(&mut history)
                    .with_prompt("User");
                match input_ui.interact_text() {
                    Ok(prompt) => prompt,
                    Err(dialoguer::Error::IO(err)) => {
                        match err.kind() {
                            ErrorKind::Interrupted => {
                                // Ctrl-C
                                // Unfortunately I could not make dialoguer handle Ctrl-d
                            }
                            k => {
                                tracing::info!("IO error: {k}");
                            }
                        }
                        break;
                    }
                }
            }
        };
Paul Hendricks's avatar
Paul Hendricks committed
83
84

        // Construct messages
85
86
87
88
89
        let user_message = dynamo_async_openai::types::ChatCompletionRequestMessage::User(
            dynamo_async_openai::types::ChatCompletionRequestUserMessage {
                content: dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                    prompt,
                ),
Paul Hendricks's avatar
Paul Hendricks committed
90
91
92
93
                name: None,
            },
        );
        messages.push(user_message);
94
        // Request
95
        let inner = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
Paul Hendricks's avatar
Paul Hendricks committed
96
            .messages(messages.clone())
97
98
99
100
101
            .model(
                template
                    .as_ref()
                    .map_or_else(|| service_name.to_string(), |t| t.model.clone()),
            )
102
            .stream(true)
103
104
105
106
107
108
            .max_completion_tokens(
                template
                    .as_ref()
                    .map_or(MAX_TOKENS, |t| t.max_completion_tokens),
            )
            .temperature(template.as_ref().map_or(0.7, |t| t.temperature))
109
            .n(1) // only generate one response
Paul Hendricks's avatar
Paul Hendricks committed
110
111
            .build()?;

112
113
        let req = NvCreateChatCompletionRequest {
            inner,
114
            common: Default::default(),
115
            nvext: None,
116
            chat_template_args: None,
117
            media_io_kwargs: None,
118
            unsupported_fields: Default::default(),
119
        };
120
121

        // Call the model
122
123
124
125
126
127
128
        let mut stream = match engine.generate(Context::new(req)).await {
            Ok(stream) => stream,
            Err(err) => {
                tracing::error!(%err, "Request failed.");
                continue;
            }
        };
129
130
131
132
133

        // Stream the output to stdout
        let mut stdout = std::io::stdout();
        let mut assistant_message = String::new();
        while let Some(item) = stream.next().await {
134
135
136
            if cancel_token.is_cancelled() {
                break;
            }
137
138
139
            match (item.data.as_ref(), item.event.as_deref()) {
                (Some(data), _) => {
                    // Normal case
140
                    let entry = data.choices.first();
141
142
143
144
145
146
                    let chat_comp = entry.as_ref().unwrap();
                    if let Some(c) = &chat_comp.delta.content {
                        let _ = stdout.write(c.as_bytes());
                        let _ = stdout.flush();
                        assistant_message += c;
                    }
147
148
                    if let Some(reason) = chat_comp.finish_reason {
                        tracing::trace!("finish reason: {reason:?}");
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
                        break;
                    }
                }
                (None, Some("error")) => {
                    // There's only one error but we loop in case that changes
                    for err in item.comment.unwrap_or_default() {
                        tracing::error!("Engine error: {err}");
                    }
                }
                (None, Some(annotation)) => {
                    tracing::debug!("Annotation. {annotation}: {:?}", item.comment);
                }
                _ => {
                    unreachable!("Event from engine with no data, no error, no annotation.");
                }
164
165
166
167
            }
        }
        println!();

Paul Hendricks's avatar
Paul Hendricks committed
168
        let assistant_content =
169
            dynamo_async_openai::types::ChatCompletionRequestAssistantMessageContent::Text(
Paul Hendricks's avatar
Paul Hendricks committed
170
171
172
                assistant_message,
            );

173
174
        let assistant_message = dynamo_async_openai::types::ChatCompletionRequestMessage::Assistant(
            dynamo_async_openai::types::ChatCompletionRequestAssistantMessage {
Paul Hendricks's avatar
Paul Hendricks committed
175
                content: Some(assistant_content),
176
                ..Default::default()
Paul Hendricks's avatar
Paul Hendricks committed
177
178
179
            },
        );
        messages.push(assistant_message);
180
181
182
183

        if single {
            break;
        }
184
185
    }
    println!();
186
187
188
189
190

    // Stop the runtime and wait for it to stop
    distributed_runtime.shutdown();
    cancel_token.cancelled().await;

191
192
    Ok(())
}