openai.rs 6.68 KB
Newer Older
1
2
3
4
5
6
7
8
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use serde::{Deserialize, Serialize};

use super::{
    ContentProvider,
9
    common::{self, OutputOptionsProvider, SamplingOptionsProvider, StopConditionsProvider},
10
};
11
use crate::protocols::openai::common_ext::{CommonExtProvider, choose_with_deprecation};
12

13
pub mod chat_completions;
14
pub mod common_ext;
15
16
17
18
pub mod completions;
pub mod embeddings;
pub mod models;
pub mod nvext;
19
pub mod responses;
20
pub mod validate;
21

22
use validate::{
23
    FREQUENCY_PENALTY_RANGE, PRESENCE_PENALTY_RANGE, TEMPERATURE_RANGE, TOP_P_RANGE, validate_range,
24
};
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

#[derive(Serialize, Deserialize, Debug)]
pub struct AnnotatedDelta<R> {
    pub delta: R,
    pub id: Option<String>,
    pub event: Option<String>,
    pub comment: Option<String>,
}

trait OpenAISamplingOptionsProvider {
    fn get_temperature(&self) -> Option<f32>;

    fn get_top_p(&self) -> Option<f32>;

    fn get_frequency_penalty(&self) -> Option<f32>;

    fn get_presence_penalty(&self) -> Option<f32>;

    fn nvext(&self) -> Option<&nvext::NvExt>;
}

trait OpenAIStopConditionsProvider {
Paul Hendricks's avatar
Paul Hendricks committed
47
    fn get_max_tokens(&self) -> Option<u32>;
48

Paul Hendricks's avatar
Paul Hendricks committed
49
    fn get_min_tokens(&self) -> Option<u32>;
50
51
52
53

    fn get_stop(&self) -> Option<Vec<String>>;

    fn nvext(&self) -> Option<&nvext::NvExt>;
54
55
56
57
58
59
60
61
62
63

    /// Get ignore_eos from CommonExt if the type supports it.
    /// Default returns None for types without CommonExt support.
    fn get_common_ignore_eos(&self) -> Option<bool> {
        None
    }

    /// Get the effective ignore_eos value, considering both CommonExt and NvExt.
    /// CommonExt (root-level) takes precedence over NvExt.
    fn get_ignore_eos(&self) -> Option<bool> {
64
65
66
67
68
        choose_with_deprecation(
            "ignore_eos",
            self.get_common_ignore_eos().as_ref(),
            self.nvext().and_then(|nv| nv.ignore_eos.as_ref()),
        )
69
    }
70
71
}

Greg Clark's avatar
Greg Clark committed
72
73
74
75
76
77
78
79
80
81
trait OpenAIOutputOptionsProvider {
    fn get_logprobs(&self) -> Option<u32>;

    fn get_prompt_logprobs(&self) -> Option<u32>;

    fn get_skip_special_tokens(&self) -> Option<bool>;

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

82
impl<T: OpenAISamplingOptionsProvider + CommonExtProvider> SamplingOptionsProvider for T {
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
    fn extract_sampling_options(&self) -> Result<common::SamplingOptions> {
        // let result = self.validate();
        // if let Err(e) = result {
        //     return Err(format!("Error validating sampling options: {}", e));
        // }

        let mut temperature = validate_range(self.get_temperature(), &TEMPERATURE_RANGE)
            .map_err(|e| anyhow::anyhow!("Error validating temperature: {}", e))?;
        let mut top_p = validate_range(self.get_top_p(), &TOP_P_RANGE)
            .map_err(|e| anyhow::anyhow!("Error validating top_p: {}", e))?;
        let frequency_penalty =
            validate_range(self.get_frequency_penalty(), &FREQUENCY_PENALTY_RANGE)
                .map_err(|e| anyhow::anyhow!("Error validating frequency_penalty: {}", e))?;
        let presence_penalty = validate_range(self.get_presence_penalty(), &PRESENCE_PENALTY_RANGE)
            .map_err(|e| anyhow::anyhow!("Error validating presence_penalty: {}", e))?;
98
99
        let top_k = CommonExtProvider::get_top_k(self);
        let repetition_penalty = CommonExtProvider::get_repetition_penalty(self);
100
101
102
103
104
105
106
107
108

        if let Some(nvext) = self.nvext() {
            let greedy = nvext.greed_sampling.unwrap_or(false);
            if greedy {
                top_p = None;
                temperature = None;
            }
        }

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
        let guided_decoding_backend = self.get_guided_decoding_backend();
        let guided_json = self.get_guided_json();
        let guided_regex = self.get_guided_regex();
        let guided_grammar = self.get_guided_grammar();
        let guided_choice = self.get_guided_choice();

        let guided_decoding = match common::GuidedDecodingOptions::from_optional(
            guided_json.cloned(),
            guided_regex,
            guided_choice,
            guided_grammar,
            guided_decoding_backend,
        ) {
            Ok(options) => options,
            Err(e) => {
                // Handle the validation error (log, return error, etc.)
                tracing::error!("Invalid guided decoding options: {:?}", e);
                return Err(e);
127
            }
128
        };
129

130
131
132
133
134
        Ok(common::SamplingOptions {
            n: None,
            best_of: None,
            frequency_penalty,
            presence_penalty,
135
            repetition_penalty,
136
137
            temperature,
            top_p,
138
            top_k,
139
140
141
142
            min_p: None,
            seed: None,
            use_beam_search: None,
            length_penalty: None,
143
            guided_decoding,
144
145
146
147
148
149
        })
    }
}

impl<T: OpenAIStopConditionsProvider> StopConditionsProvider for T {
    fn extract_stop_conditions(&self) -> Result<common::StopConditions> {
Paul Hendricks's avatar
Paul Hendricks committed
150
        let max_tokens = self.get_max_tokens();
151
152
153
        let min_tokens = self.get_min_tokens();
        let stop = self.get_stop();

154
155
156
157
        if let Some(stop) = &stop
            && stop.len() > 4
        {
            anyhow::bail!("stop conditions must be less than 4")
158
159
        }

160
161
        // Use the trait method to get ignore_eos, which handles precedence
        let ignore_eos = self.get_ignore_eos();
162
163
164

        Ok(common::StopConditions {
            max_tokens,
Paul Hendricks's avatar
Paul Hendricks committed
165
            min_tokens,
166
167
168
169
170
171
172
            stop,
            stop_token_ids_hidden: None,
            ignore_eos,
        })
    }
}

Greg Clark's avatar
Greg Clark committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
impl<T: OpenAIOutputOptionsProvider> OutputOptionsProvider for T {
    fn extract_output_options(&self) -> Result<common::OutputOptions> {
        let logprobs = self.get_logprobs();
        let prompt_logprobs = self.get_prompt_logprobs();
        let skip_special_tokens = self.get_skip_special_tokens();
        let formatted_prompt = self.get_formatted_prompt();

        Ok(common::OutputOptions {
            logprobs,
            prompt_logprobs,
            skip_special_tokens,
            formatted_prompt,
        })
    }
}

189
190
pub trait DeltaGeneratorExt<ResponseType: Send + 'static + std::fmt::Debug>:
    Send + 'static
191
192
193
194
195
{
    fn choice_from_postprocessor(
        &mut self,
        response: common::llm_backend::BackendOutput,
    ) -> Result<ResponseType>;
196
197
198

    /// Gets the current prompt token count (Input Sequence Length).
    fn get_isl(&self) -> Option<u32>;
199
}
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct ParsingOptions {
    pub tool_call_parser: Option<String>,

    pub reasoning_parser: Option<String>,
}

impl ParsingOptions {
    pub fn new(tool_call_parser: Option<String>, reasoning_parser: Option<String>) -> Self {
        Self {
            tool_call_parser,
            reasoning_parser,
        }
    }
}