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

20
21
22
use crate::engines::ValidateRequest;

use super::{
23
24
25
26
    common_ext::{CommonExt, CommonExtProvider},
    nvext::NvExt,
    nvext::NvExtProvider,
    validate, OpenAISamplingOptionsProvider, OpenAIStopConditionsProvider,
27
};
28
29
30
31

mod aggregator;
mod delta;

Paul Hendricks's avatar
Paul Hendricks committed
32
pub use aggregator::DeltaAggregator;
33
34
pub use delta::DeltaGenerator;

35
/// A request structure for creating a chat completion, extending OpenAI's
36
/// `CreateChatCompletionRequest` with [`NvExt`] extensions and common fields.
37
38
39
///
/// # Fields
/// - `inner`: The base OpenAI chat completion request, embedded using `serde(flatten)`.
40
41
42
/// - `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
43
#[derive(Serialize, Deserialize, Validate, Debug, Clone)]
44
pub struct NvCreateChatCompletionRequest {
Paul Hendricks's avatar
Paul Hendricks committed
45
46
    #[serde(flatten)]
    pub inner: async_openai::types::CreateChatCompletionRequest,
47

48
49
50
    #[serde(flatten, default)]
    pub common: CommonExt,

51
    #[serde(skip_serializing_if = "Option::is_none")]
52
53
54
    pub nvext: Option<NvExt>,
}

55
56
57
58
59
60
/// 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)`.
Paul Hendricks's avatar
Paul Hendricks committed
61
#[derive(Serialize, Deserialize, Validate, Debug, Clone)]
62
pub struct NvCreateChatCompletionResponse {
Paul Hendricks's avatar
Paul Hendricks committed
63
64
    #[serde(flatten)]
    pub inner: async_openai::types::CreateChatCompletionResponse,
65
66
}

67
68
69
70
71
72
/// A response structure for streamed chat completions, embedding OpenAI's
/// `CreateChatCompletionStreamResponse`.
///
/// # Fields
/// - `inner`: The base OpenAI streaming chat completion response, embedded
///   using `serde(flatten)`.
Paul Hendricks's avatar
Paul Hendricks committed
73
#[derive(Serialize, Deserialize, Validate, Debug, Clone)]
74
pub struct NvCreateChatCompletionStreamResponse {
Paul Hendricks's avatar
Paul Hendricks committed
75
76
    #[serde(flatten)]
    pub inner: async_openai::types::CreateChatCompletionStreamResponse,
77
78
}

79
80
/// Implements `NvExtProvider` for `NvCreateChatCompletionRequest`,
/// providing access to NVIDIA-specific extensions.
81
impl NvExtProvider for NvCreateChatCompletionRequest {
82
    /// Returns a reference to the optional `NvExt` extension, if available.
83
84
85
86
    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }

87
    /// Returns `None`, as raw prompt extraction is not implemented.
88
89
90
91
92
    fn raw_prompt(&self) -> Option<String> {
        None
    }
}

93
94
/// Implements `AnnotationsProvider` for `NvCreateChatCompletionRequest`,
/// enabling retrieval and management of request annotations.
95
impl AnnotationsProvider for NvCreateChatCompletionRequest {
96
    /// Retrieves the list of annotations from `NvExt`, if present.
Biswa Panda's avatar
Biswa Panda committed
97
98
99
100
101
102
    fn annotations(&self) -> Option<Vec<String>> {
        self.nvext
            .as_ref()
            .and_then(|nvext| nvext.annotations.clone())
    }

103
104
105
106
107
108
109
    /// 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
110
111
112
113
114
115
116
117
    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)
    }
}
118

119
120
/// Implements `OpenAISamplingOptionsProvider` for `NvCreateChatCompletionRequest`,
/// exposing OpenAI's sampling parameters for chat completion.
121
impl OpenAISamplingOptionsProvider for NvCreateChatCompletionRequest {
122
    /// Retrieves the temperature parameter for sampling, if set.
123
    fn get_temperature(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
124
        self.inner.temperature
125
126
    }

127
    /// Retrieves the top-p (nucleus sampling) parameter, if set.
128
    fn get_top_p(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
129
        self.inner.top_p
130
131
    }

132
    /// Retrieves the frequency penalty parameter, if set.
133
    fn get_frequency_penalty(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
134
        self.inner.frequency_penalty
135
136
    }

137
    /// Retrieves the presence penalty parameter, if set.
138
    fn get_presence_penalty(&self) -> Option<f32> {
Paul Hendricks's avatar
Paul Hendricks committed
139
        self.inner.presence_penalty
140
141
    }

142
    /// Returns a reference to the optional `NvExt` extension, if available.
143
144
145
146
147
    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }
}

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/// 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> {
        self.common
            .guided_json
            .as_ref()
            .or_else(|| self.nvext.as_ref().and_then(|nv| nv.guided_json.as_ref()))
    }

    fn get_guided_regex(&self) -> Option<String> {
        self.common
            .guided_regex
            .clone()
            .or_else(|| self.nvext.as_ref().and_then(|nv| nv.guided_regex.clone()))
    }

    fn get_guided_grammar(&self) -> Option<String> {
        self.common
            .guided_grammar
            .clone()
            .or_else(|| self.nvext.as_ref().and_then(|nv| nv.guided_grammar.clone()))
    }

    fn get_guided_choice(&self) -> Option<Vec<String>> {
        self.common
            .guided_choice
            .clone()
            .or_else(|| self.nvext.as_ref().and_then(|nv| nv.guided_choice.clone()))
    }

    fn get_guided_decoding_backend(&self) -> Option<String> {
        self.common.guided_decoding_backend.clone().or_else(|| {
            self.nvext
                .as_ref()
                .and_then(|nv| nv.guided_decoding_backend.clone())
        })
    }
}

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

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

210
211
212
213
214
215
216
    /// 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.
217
    fn get_stop(&self) -> Option<Vec<String>> {
218
219
220
221
        self.inner.stop.as_ref().map(|stop| match stop {
            async_openai::types::Stop::String(s) => vec![s.clone()],
            async_openai::types::Stop::StringArray(arr) => arr.clone(),
        })
222
223
    }

224
    /// Returns a reference to the optional `NvExt` extension, if available.
225
226
227
    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }
228
229
230
231
232

    /// Get ignore_eos from CommonExt.
    fn get_common_ignore_eos(&self) -> Option<bool> {
        self.common.ignore_eos
    }
233
}
234
235
236
237
238
239
240
241
242
243
244
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
270
271
272

/// 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)?;
        validate::validate_metadata(&self.inner.metadata)?;
        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

        Ok(())
    }
}