chat_completions.rs 10.7 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
6
7
use dynamo_runtime::protocols::annotated::AnnotationsProvider;
use serde::{Deserialize, Serialize};
use validator::Validate;

8
9
10
use crate::engines::ValidateRequest;

use super::{
11
    OpenAIOutputOptionsProvider, OpenAISamplingOptionsProvider, OpenAIStopConditionsProvider,
12
    common_ext::{CommonExt, CommonExtProvider},
13
14
    nvext::NvExt,
    nvext::NvExtProvider,
15
    validate,
16
};
17

18
pub mod aggregator;
19
mod delta;
Ryan Olson's avatar
Ryan Olson committed
20
pub mod jail;
21

Paul Hendricks's avatar
Paul Hendricks committed
22
pub use aggregator::DeltaAggregator;
23
24
pub use delta::DeltaGenerator;

25
/// A request structure for creating a chat completion, extending OpenAI's
26
/// `CreateChatCompletionRequest` with [`NvExt`] extensions and common fields.
27
28
29
///
/// # Fields
/// - `inner`: The base OpenAI chat completion request, embedded using `serde(flatten)`.
30
31
32
/// - `common`: Common extension fields (ignore_eos, min_tokens) at root level, embedded using `serde(flatten)`.
/// - `nvext`: The optional NVIDIA extension field. See [`NvExt`] for more details.
///   Note: If ignore_eos is specified in both common and nvext, the common (root-level) value takes precedence.
Paul Hendricks's avatar
Paul Hendricks committed
33
#[derive(Serialize, Deserialize, Validate, Debug, Clone)]
34
pub struct NvCreateChatCompletionRequest {
Paul Hendricks's avatar
Paul Hendricks committed
35
    #[serde(flatten)]
36
    pub inner: dynamo_async_openai::types::CreateChatCompletionRequest,
37

38
39
40
    #[serde(flatten, default)]
    pub common: CommonExt,

41
    #[serde(skip_serializing_if = "Option::is_none")]
42
    pub nvext: Option<NvExt>,
43
44
45
46

    /// Extra args to pass to the chat template rendering context
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_template_args: Option<std::collections::HashMap<String, serde_json::Value>>,
47
48
}

49
50
51
52
53
54
/// A response structure for unary chat completion responses, embedding OpenAI's
/// `CreateChatCompletionResponse`.
///
/// # Fields
/// - `inner`: The base OpenAI unary chat completion response, embedded
///   using `serde(flatten)`.
55
pub type NvCreateChatCompletionResponse = dynamo_async_openai::types::CreateChatCompletionResponse;
56

57
58
59
60
61
62
/// A response structure for streamed chat completions, embedding OpenAI's
/// `CreateChatCompletionStreamResponse`.
///
/// # Fields
/// - `inner`: The base OpenAI streaming chat completion response, embedded
///   using `serde(flatten)`.
63
64
pub type NvCreateChatCompletionStreamResponse =
    dynamo_async_openai::types::CreateChatCompletionStreamResponse;
65

66
67
/// Implements `NvExtProvider` for `NvCreateChatCompletionRequest`,
/// providing access to NVIDIA-specific extensions.
68
impl NvExtProvider for NvCreateChatCompletionRequest {
69
    /// Returns a reference to the optional `NvExt` extension, if available.
70
71
72
73
    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }

74
    /// Returns `None`, as raw prompt extraction is not implemented.
75
76
77
78
79
    fn raw_prompt(&self) -> Option<String> {
        None
    }
}

80
81
/// Implements `AnnotationsProvider` for `NvCreateChatCompletionRequest`,
/// enabling retrieval and management of request annotations.
82
impl AnnotationsProvider for NvCreateChatCompletionRequest {
83
    /// Retrieves the list of annotations from `NvExt`, if present.
Biswa Panda's avatar
Biswa Panda committed
84
85
86
87
88
89
    fn annotations(&self) -> Option<Vec<String>> {
        self.nvext
            .as_ref()
            .and_then(|nvext| nvext.annotations.clone())
    }

90
91
92
93
94
95
96
    /// Checks whether a specific annotation exists in the request.
    ///
    /// # Arguments
    /// * `annotation` - A string slice representing the annotation to check.
    ///
    /// # Returns
    /// `true` if the annotation exists, `false` otherwise.
Biswa Panda's avatar
Biswa Panda committed
97
98
99
100
101
102
103
104
    fn has_annotation(&self, annotation: &str) -> bool {
        self.nvext
            .as_ref()
            .and_then(|nvext| nvext.annotations.as_ref())
            .map(|annotations| annotations.contains(&annotation.to_string()))
            .unwrap_or(false)
    }
}
105

106
107
/// Implements `OpenAISamplingOptionsProvider` for `NvCreateChatCompletionRequest`,
/// exposing OpenAI's sampling parameters for chat completion.
108
impl OpenAISamplingOptionsProvider for NvCreateChatCompletionRequest {
109
    /// Retrieves the temperature parameter for sampling, if set.
110
    fn get_temperature(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
111
        self.inner.temperature
112
113
    }

114
    /// Retrieves the top-p (nucleus sampling) parameter, if set.
115
    fn get_top_p(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
116
        self.inner.top_p
117
118
    }

119
    /// Retrieves the frequency penalty parameter, if set.
120
    fn get_frequency_penalty(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
121
        self.inner.frequency_penalty
122
123
    }

124
    /// Retrieves the presence penalty parameter, if set.
125
    fn get_presence_penalty(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
126
        self.inner.presence_penalty
127
128
    }

129
    /// Returns a reference to the optional `NvExt` extension, if available.
130
131
132
    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    /// Retrieves the seed value for random number generation, if set.
    fn get_seed(&self) -> Option<i64> {
        self.inner.seed
    }

    /// Retrieves the number of completions to generate for each prompt, if set.
    fn get_n(&self) -> Option<u8> {
        self.inner.n
    }

    /// Retrieves the best_of parameter, if set.
    fn get_best_of(&self) -> Option<u8> {
        None // Not supported in chat completions
    }
147
148
}

149
150
151
152
153
154
155
156
157
158
/// Implements `CommonExtProvider` for `NvCreateChatCompletionRequest`,
/// providing access to common extension fields.
impl CommonExtProvider for NvCreateChatCompletionRequest {
    /// Returns a reference to the CommonExt struct.
    fn common_ext(&self) -> Option<&CommonExt> {
        Some(&self.common)
    }

    /// Guided Decoding Options
    fn get_guided_json(&self) -> Option<&serde_json::Value> {
159
        self.common.guided_json.as_ref()
160
161
162
    }

    fn get_guided_regex(&self) -> Option<String> {
163
        self.common.guided_regex.clone()
164
165
166
    }

    fn get_guided_grammar(&self) -> Option<String> {
167
        self.common.guided_grammar.clone()
168
169
170
    }

    fn get_guided_choice(&self) -> Option<Vec<String>> {
171
        self.common.guided_choice.clone()
172
173
174
    }

    fn get_guided_decoding_backend(&self) -> Option<String> {
175
        self.common.guided_decoding_backend.clone()
176
    }
177

178
    fn get_guided_whitespace_pattern(&self) -> Option<String> {
179
        self.common.guided_whitespace_pattern.clone()
180
181
    }

182
    fn get_top_k(&self) -> Option<i32> {
183
        self.common.top_k
184
185
    }

186
    fn get_min_p(&self) -> Option<f32> {
187
        self.common.min_p
188
189
    }

190
    fn get_repetition_penalty(&self) -> Option<f32> {
191
        self.common.repetition_penalty
192
    }
193
194
195
196

    fn get_include_stop_str_in_output(&self) -> Option<bool> {
        self.common.include_stop_str_in_output
    }
197
198
}

199
200
/// Implements `OpenAIStopConditionsProvider` for `NvCreateChatCompletionRequest`,
/// providing access to stop conditions that control chat completion behavior.
201
impl OpenAIStopConditionsProvider for NvCreateChatCompletionRequest {
202
    /// Retrieves the maximum number of tokens allowed in the response.
203
    #[allow(deprecated)]
Paul Hendricks's avatar
Paul Hendricks committed
204
    fn get_max_tokens(&self) -> Option<u32> {
205
        self.inner.max_completion_tokens.or(self.inner.max_tokens)
206
207
    }

208
    /// Retrieves the minimum number of tokens required in the response.
209
210
    /// Returns `min_tokens` Value
    /// `min_tokens` is not an OpenAI-supported parameter.
Paul Hendricks's avatar
Paul Hendricks committed
211
    fn get_min_tokens(&self) -> Option<u32> {
212
        self.common.min_tokens
213
214
    }

215
216
217
218
219
220
221
    /// Retrieves the stop conditions that terminate the chat completion response.
    ///
    /// Converts OpenAI's `Stop` enum to a `Vec<String>`, normalizing the representation.
    ///
    /// # Returns
    /// * `Some(Vec<String>)` if stop conditions are set.
    /// * `None` if no stop conditions are defined.
222
    fn get_stop(&self) -> Option<Vec<String>> {
223
        self.inner.stop.as_ref().map(|stop| match stop {
224
225
            dynamo_async_openai::types::Stop::String(s) => vec![s.clone()],
            dynamo_async_openai::types::Stop::StringArray(arr) => arr.clone(),
226
        })
227
228
    }

229
    /// Returns a reference to the optional `NvExt` extension, if available.
230
231
232
    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }
233
234
235
236
237

    /// Get ignore_eos from CommonExt.
    fn get_common_ignore_eos(&self) -> Option<bool> {
        self.common.ignore_eos
    }
238

239
    /// Get the effective ignore_eos value from CommonExt.
240
    fn get_ignore_eos(&self) -> Option<bool> {
241
        self.common.ignore_eos
242
    }
243
}
244

Greg Clark's avatar
Greg Clark committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
impl OpenAIOutputOptionsProvider for NvCreateChatCompletionRequest {
    fn get_logprobs(&self) -> Option<u32> {
        match self.inner.logprobs {
            Some(true) => match self.inner.top_logprobs {
                Some(top_logprobs) => Some(top_logprobs as u32),
                None => Some(1_u32),
            },
            Some(false) => None,
            None => None,
        }
    }

    fn get_prompt_logprobs(&self) -> Option<u32> {
        None
    }

    fn get_skip_special_tokens(&self) -> Option<bool> {
        None
    }

    fn get_formatted_prompt(&self) -> Option<bool> {
        None
    }
}

270
271
272
273
274
275
276
277
/// Implements `ValidateRequest` for `NvCreateChatCompletionRequest`,
/// allowing us to validate the data.
impl ValidateRequest for NvCreateChatCompletionRequest {
    fn validate(&self) -> Result<(), anyhow::Error> {
        validate::validate_messages(&self.inner.messages)?;
        validate::validate_model(&self.inner.model)?;
        // none for store
        validate::validate_reasoning_effort(&self.inner.reasoning_effort)?;
278
        // none for metadata
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
        validate::validate_frequency_penalty(self.inner.frequency_penalty)?;
        validate::validate_logit_bias(&self.inner.logit_bias)?;
        // none for logprobs
        validate::validate_top_logprobs(self.inner.top_logprobs)?;
        // validate::validate_max_tokens(self.inner.max_tokens)?; // warning depricated field
        validate::validate_max_completion_tokens(self.inner.max_completion_tokens)?;
        validate::validate_n(self.inner.n)?;
        // none for modalities
        // none for prediction
        // none for audio
        validate::validate_presence_penalty(self.inner.presence_penalty)?;
        // none for response_format
        // none for seed
        validate::validate_service_tier(&self.inner.service_tier)?;
        validate::validate_stop(&self.inner.stop)?;
        // none for stream
        // none for stream_options
        validate::validate_temperature(self.inner.temperature)?;
        validate::validate_top_p(self.inner.top_p)?;
        validate::validate_tools(&self.inner.tools.as_deref())?;
        // none for tool_choice
        // none for parallel_tool_calls
        validate::validate_user(self.inner.user.as_deref())?;
        // none for function call
        // none for functions
304
305
        // Common Ext
        validate::validate_repetition_penalty(self.get_repetition_penalty())?;
306
307
        validate::validate_min_p(self.get_min_p())?;
        validate::validate_top_k(self.get_top_k())?;
308
309
310
311

        Ok(())
    }
}