chat_completions.rs 56.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 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.

use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt;
use std::fmt::Display;

use derive_builder::Builder;
use serde::de::{self, SeqAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize};
use serde::{Deserializer, Serializer};
use serde_json::Value;
use validator::Validate;

mod aggregator;
mod delta;

use super::nvext::NvExtProvider;
pub use super::{CompletionTokensDetails, CompletionUsage, PromptTokensDetails};
// pub use aggregator::DeltaAggregator;
pub use delta::DeltaGenerator;

use super::{
    common::{self, ChatCompletionLogprobs, SamplingOptionsProvider, StopConditionsProvider},
    nvext::NvExt,
    validate_logit_bias, ContentProvider, OpenAISamplingOptionsProvider,
    OpenAIStopConditionsProvider,
};
Neelay Shah's avatar
Neelay Shah committed
43
44

use triton_distributed_runtime::protocols::annotated::AnnotationsProvider;
45
46
47
48
49
50
51
52
53
54
55
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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

/// Request object which is used to generate chat completions.
#[derive(Serialize, Deserialize, Builder, Validate, Debug, Clone)]
#[builder(build_fn(private, name = "build_internal", validate = "Self::validate"))]
pub struct ChatCompletionRequest {
    /// Multi-turn chat messages.
    ///
    /// NIM Compatibility:
    /// Multi-turn chat models vary, some of which work with the OpenAI ChatGPT format, while others
    /// will require `NvExt`.
    pub messages: Vec<ChatCompletionMessage>,

    /// Name of the model
    #[builder(setter(into))]
    pub model: String,

    /// The maximum number of tokens that can be generated in the completion.
    /// The token count of your prompt plus max_tokens cannot exceed the model's context length.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    #[validate(range(min = 1))]
    pub max_tokens: Option<i32>,

    /// The minimum number of tokens to generate. We ignore stop tokens until we see this many
    /// tokens. Leave this None unless you are working on the pre-processor.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub min_tokens: Option<i32>,

    /// If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only
    /// server-sent events as they become available, with the stream terminated by a data: \[DONE\]
    ///
    /// NIM Compatibility:
    /// The NIM SDK can send extra meta data in the SSE stream using the `:` comment, `event:`,
    /// or `id:` fields. See the `enable_sse_metadata` field in the NvExt object.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub stream: Option<bool>,

    /// How many chat completion choices to generate for each input message.
    ///
    /// NIM Compatibility:
    /// Values greater than 1 are not currently supported by NIM.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub n: Option<i32>,

    /// What sampling `temperature` to use, between 0 and 2. Higher values like 0.8 will make the
    /// output more random, while lower values like 0.2 will make it more focused and deterministic.
    /// OpenAI defaults to 1.0; however, in this crate, the default is None, and model-specific defaults
    /// can be applied later as part of associating the request with a given model.
    ///
    /// OpenAI generally recommend altering this or `top_p` but not both.
    ///
    /// TODO(): Add a model specific validation which could enforce only a single type of sampling can be used.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[validate(range(min = "super::MIN_TEMPERATURE", max = "super::MAX_TEMPERATURE"))]
    #[builder(default, setter(into, strip_option))]
    pub temperature: Option<f32>,

    /// An alternative to sampling with `temperature`, called nucleus sampling, where the model
    /// considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens
    /// comprising the top 10% probability mass are considered.
    ///
    /// We generally recommend altering this or `temperature` but not both.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[validate(range(min = "super::MIN_TOP_P", max = "super::MAX_TOP_P"))]
    #[builder(default, setter(into, strip_option))]
    pub top_p: Option<f32>,

    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency
    /// in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[validate(range(
        min = "super::MIN_FREQUENCY_PENALTY",
        max = "super::MAX_FREQUENCY_PENALTY"
    ))]
    #[builder(default, setter(into, strip_option))]
    pub frequency_penalty: Option<f32>,

    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in
    /// the text so far, increasing the model's likelihood to talk about new topics.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[validate(range(
        min = "super::MIN_PRESENCE_PENALTY",
        max = "super::MAX_PRESENCE_PENALTY"
    ))]
    #[builder(default, setter(into, strip_option))]
    pub presence_penalty: Option<f32>,

    /// OpenAI specific API fields:
    /// See: <https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format>
    ///
    /// NIM Compatibility:
    /// This option is not currently supported by NIM LLM. An error will be returned if this field is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default)]
    pub response_format: Option<Value>,

    /// Up to 4 sequences where the API will stop generating further tokens.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[validate(length(max = 4))]
    #[builder(default, setter(into, strip_option))]
    pub stop: Option<Vec<String>>,

    /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities
    /// of each output token returned in the content of message.
    ///
    /// Not all models support logprobs. If logprobs is set to true for a model that does not support it,
    /// the request will be processed as if logprobs is set to false.
    ///
    /// NIM Compatibility:
    /// TODO - Add a NvExt `strict` object which will disable relaxing of model specific limitations; meaning,
    /// if the user requests `logprobs` and the model does not support them, the request will fail wth an error.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub logprobs: Option<bool>,

    /// An integer between 0 and 20 specifying the number of most likely tokens to return at each token position,
    /// each with an associated log probability. logprobs must be set to true if this parameter is used.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[validate(range(min = 0, max = 20))]
    #[builder(default, setter(into, strip_option))]
    pub top_logprobs: Option<i32>,

    /// Modify the likelihood of specified tokens appearing in the completion.
    ///
    /// Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an
    /// associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs.
    /// Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact
    /// effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of
    /// selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
    ///
    /// As specified in the OpenAI examples, this is a map of tokens_ids as strings to a bias value that
    /// is an integer.
    ///
    /// However, the OpenAI blog using the SDK shows that it can also be specified more accurately as a
    /// map of token_ids as ints to a bias value that is also an int.
    ///
    /// NIM Compatibility:
    /// In the conversion of the OpenAI request to the internal NIM format, the keys of this map will be
    /// validated to ensure they are integers. Since different models may have different tokenizers, the
    /// range and values will again be validated on the compute backend to ensure they map to valid tokens
    /// in the vocabulary of the model.
    ///
    /// ```
Neelay Shah's avatar
Neelay Shah committed
191
    /// use triton_distributed_llm::protocols::openai::completions::CompletionRequest;
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
273
274
    ///
    /// let request = CompletionRequest::builder()
    ///     .prompt("What is the meaning of life?")
    ///     .model("meta/llama-3.1-8b-instruct")
    ///     .add_logit_bias(1337, -100) // using an int as a key is ok
    ///     .add_logit_bias("42", 100)  // using a string as a key is also ok
    ///     .build()
    ///     .expect("Should not fail");
    ///
    /// assert!(CompletionRequest::builder()
    ///     .prompt("What is the meaning of life?")
    ///     .model("meta/llama-3.1-8b-instruct")
    ///     .add_logit_bias("some non int", -100)
    ///     .build()
    ///     .is_err());
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    #[validate(custom(function = "validate_logit_bias"))]
    #[builder(default, setter(into, strip_option))]
    pub logit_bias: Option<HashMap<String, i32>>,

    /// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
    ///
    /// NIM Compatibility:
    /// If provided, then the value of this field will be included in the trace metadata and the accounting
    /// data (if enabled).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub user: Option<String>,

    /// If specified, our system will make a best effort to sample deterministically, such that repeated
    /// requests with the same seed and parameters should return the same result. Determinism is not guaranteed,
    /// and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(into, strip_option))]
    pub seed: Option<i64>,

    /// A list of tools the model may call. Currently, only functions are supported as a tool. Use this to
    /// provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.
    ///
    /// NIM Compatibility:
    /// This field is not currently supported by NIM LLM. An error will be returned if this field is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default)]
    pub tools: Option<Vec<Tool>>,

    /// Controls which (if any) function is called by the model. none means the model will not call a function
    /// and instead generates a message. auto means the model can pick between generating a message or calling
    /// a function. Specifying a particular function via {"type": "function", "function": {"name": "my_function"}}
    /// forces the model to call that function.
    ///
    /// `none` is the default when no functions are present. `auto` is the default if functions are present.
    ///
    /// NIM Compatibility:
    /// This field is not currently supported by NIM LLM. An error will be returned if this field is set.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(serialize_with = "serialize_tool_choice")]
    #[builder(default)]
    pub tool_choice: Option<ToolChoiceType>,

    /// Additional parameters supported by NIM backends
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(default, setter(strip_option))]
    pub nvext: Option<NvExt>,
}

impl ChatCompletionRequest {
    pub fn builder() -> ChatCompletionRequestBuilder {
        ChatCompletionRequestBuilder::default()
    }
}

impl ChatCompletionRequestBuilder {
    // This is a pre-build validate function
    // This is called before the generated build method, in this case build_internal, is called
    // This has access to the internal state of the builder
    fn validate(&self) -> Result<(), String> {
        Ok(())
    }

    /// Builds and validates the ChatCompletionRequest
    ///
    /// ```rust
Neelay Shah's avatar
Neelay Shah committed
275
    /// use triton_distributed_llm::protocols::openai::chat_completions::ChatCompletionRequest;
276
277
278
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
    ///
    /// let request = ChatCompletionRequest::builder()
    ///     .model("mixtral-8x7b-instruct-v0.1")
    ///     .add_user_message("Hello")
    ///     .max_tokens(16)
    ///     .build()
    ///     .expect("Failed to build ChatCompletionRequest");
    /// ```
    pub fn build(&self) -> anyhow::Result<ChatCompletionRequest> {
        // Calls the build_private, validates the result, then performs addition
        // post build validation where we are looking a mutually exclusive fields
        // and ensuring that there are not mutually exclusive collisions.
        let request = self
            .build_internal()
            .map_err(|e| anyhow::anyhow!("Failed to build ChatCompletionRequest: {}", e))?;

        request
            .validate()
            .map_err(|e| anyhow::anyhow!("Failed to validate ChatCompletionRequest: {}", e))?;

        // check mutually exclusive fields
        if request.top_logprobs.is_some() {
            if request.logprobs.is_none() {
                anyhow::bail!("top_logprobs requires logprobs to be set to true");
            }
            if let Some(logprobs) = request.logprobs {
                if !logprobs {
                    anyhow::bail!("top_logprobs requires logprobs to be set to true");
                }
            }
        }

        Ok(request)
    }

    /// Add a message to the `Vec<ChatCompletionMessage>` in the ChatCompletionRequest
    /// This will either create or append to the `Vec<ChatCompletionMessage>`
    pub fn add_message(&mut self, message: ChatCompletionMessage) -> &mut Self {
        // If messages exist we get them or we create new messages with Vec::new
        self.messages.get_or_insert_with(Vec::new).push(message);
        self
    }

    /// Add a user message to the `Vec<ChatCompletionMessage>` in the ChatCompletionRequest
    pub fn add_user_message(&mut self, content: impl Into<String>) -> &mut Self {
        self.add_message(ChatCompletionMessage {
            role: MessageRole::user,
            content: Content::Text(content.into()),
            name: None,
        })
    }

    /// Add an assistant message to the `Vec<ChatCompletionMessage>` in the ChatCompletionRequest
    pub fn add_assistant_message(&mut self, content: impl Into<String>) -> &mut Self {
        self.add_message(ChatCompletionMessage {
            role: MessageRole::assistant,
            content: Content::Text(content.into()),
            name: None,
        })
    }

    /// Add a system message to the `Vec<ChatCompletionMessage>` in the ChatCompletionRequest
    pub fn add_system_message(&mut self, content: impl Into<String>) -> &mut Self {
        self.add_message(ChatCompletionMessage {
            role: MessageRole::system,
            content: Content::Text(content.into()),
            name: None,
        })
    }

    /// Add a stop condition to the `Vec<String>` in the ChatCompletionRequest
    /// This will either create or append to the `Vec<String>`
    pub fn add_stop(&mut self, stop: impl Into<String>) -> &mut Self {
        self.stop
            .get_or_insert_with(|| Some(vec![]))
            .as_mut()
            .expect("stop should always be Some(Vec)")
            .push(stop.into());
        self
    }

    /// Add a token and bias to the `HashMap<String, i32>` in the ChatCompletionRequest
    /// This will either create or update the `HashMap<String, i32>`
    /// See: [`ChatCompletionRequest::logit_bias`] for more details
    pub fn add_logit_bias<T>(&mut self, token_id: T, bias: i32) -> &mut Self
    where
        T: std::fmt::Display,
    {
        self.logit_bias
            .get_or_insert_with(|| Some(HashMap::new()))
            .as_mut()
            .expect("logit_bias should always be Some(HashMap)")
            .insert(token_id.to_string(), bias);

        self
    }
}

/// Each turn in a conversation is represented by a ChatCompletionMessage.
#[derive(Builder, Debug, Deserialize, Serialize, Clone)]
pub struct ChatCompletionMessage {
    pub role: MessageRole,

    #[serde(deserialize_with = "deserialize_content")]
    pub content: Content,

    #[serde(skip_serializing_if = "Option::is_none", default)]
    #[builder(default)]
    pub name: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum MessageRole {
    user,
    system,
    assistant,
    function,
}

impl Display for MessageRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        use MessageRole::*;
        let s = match self {
            user => "user",
            system => "system",
            assistant => "assistant",
            function => "function",
        };
        write!(f, "{s}")
    }
}

#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
pub enum Content {
    Text(String),
    ImageUrl(Vec<ImageUrl>),
}

impl serde::Serialize for Content {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match *self {
            Content::Text(ref text) => serializer.serialize_str(text),
            Content::ImageUrl(ref image_url) => image_url.serialize(serializer),
        }
    }
}

fn deserialize_content<'de, D>(deserializer: D) -> Result<Content, D::Error>
where
    D: Deserializer<'de>,
{
    struct ContentVisitor;

    impl<'de> Visitor<'de> for ContentVisitor {
        type Value = Content;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a string or an array of content parts")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Content::Text(value.to_owned()))
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut parts = Vec::new();
            while let Some(value) = seq.next_element::<String>()? {
                if value.starts_with("http://") || value.starts_with("https://") {
                    parts.push(ImageUrl {
                        r#type: ContentType::image_url,
                        text: None,
                        image_url: Some(ImageUrlType { url: value }),
                    });
                } else {
                    parts.push(ImageUrl {
                        r#type: ContentType::text,
                        text: Some(value),
                        image_url: None,
                    });
                }
            }
            Ok(Content::ImageUrl(parts))
        }
    }

    deserializer.deserialize_any(ContentVisitor)
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum ContentType {
    text,
    image_url,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub struct ImageUrlType {
    pub url: String,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub struct ImageUrl {
    pub r#type: ContentType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_url: Option<ImageUrlType>,
}

/// Represents a chat completion response returned by model, based on the provided input.
pub type ChatCompletionResponse = ChatCompletionGeneric<ChatCompletionChoice>;

/// Represents a streamed chunk of a chat completion response returned by model, based on the provided input.
pub type ChatCompletionResponseDelta = ChatCompletionGeneric<ChatCompletionChoiceDelta>;

/// Common structure for chat completion responses; the only delta is the type of choices which differs
/// between streaming and non-streaming requests.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ChatCompletionGeneric<C>
where
    C: Serialize + Clone + ContentProvider,
{
    /// A unique identifier for the chat completion.
    pub id: String,

    /// A list of chat completion choices. Can be more than one if n is greater than 1.
    pub choices: Vec<C>,

    /// The Unix timestamp (in seconds) of when the chat completion was created.
    pub created: u64,

    /// The model used for the chat completion.
    pub model: String,

    /// The object type, which is `chat.completion` if the type of `Choice` is `ChatCompletionChoice`,
    /// or is `chat.completion.chunk` if the type of `Choice` is `ChatCompletionChoiceDelta`.
    pub object: String,

    /// Usage information for the completion request.
    pub usage: Option<CompletionUsage>,

    /// The service tier used for processing the request, optional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_tier: Option<ServiceTier>,

    /// This fingerprint represents the backend configuration that the model runs with.
    ///
    /// Can be used in conjunction with the seed request parameter to understand when backend changes
    /// have been made that might impact determinism.
    ///
    /// NIM Compatibility:
    /// This field is not supported by the NIM; however it will be added in the future.
    /// The optional nature of this field will be relaxed when it is supported.
    pub system_fingerprint: Option<String>,
    // TODO() - add NvResponseExtention
}

// Enum for service tier, either "scale" or "default"
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ServiceTier {
    Auto,
    Scale,
    Default,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ChatCompletionChoice {
    /// A chat completion message generated by the model.
    pub message: ChatCompletionContent,

    /// The index of the choice in the list of choices.
    pub index: u64,

    /// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural
    /// stop point or a provided stop sequence, `length` if the maximum number of tokens specified
    /// in the request was reached, `content_filter` if content was omitted due to a flag from our content
    /// filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called
    /// a function.
    ///
    /// NIM Compatibility:
    /// Only `stop` and `length` are currently supported by NIM.
    /// NIM may also provide additional reasons in the future, such as `error`, `timeout` or `cancelation`.
    pub finish_reason: FinishReason,

    /// Log probability information for the choice, optional field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<ChatCompletionLogprobs>,
}

impl ContentProvider for ChatCompletionChoice {
    fn content(&self) -> String {
        self.message.content()
    }
}

/// Same as ChatCompletionMessage, but received during a response stream.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ChatCompletionChoiceDelta {
    /// The index of the choice in the list of choices.
    pub index: u64,

    /// The reason the model stopped generating tokens. This will be `stop` if the model hit a natural
    /// stop point or a provided stop sequence, `length` if the maximum number of tokens specified
    /// in the request was reached, `content_filter` if content was omitted due to a flag from our content
    /// filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called
    /// a function.
    ///
    /// NIM Compatibility:
    /// Only `stop` and `length` are currently supported by NIM.
    /// NIM may also provide additional reasons in the future, such as `error`, `timeout` or `cancelation`.
    pub finish_reason: Option<FinishReason>,

    /// A chat completion delta generated by streamed model responses.
    pub delta: ChatCompletionContent,

    /// Log probability information for the choice, optional field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<ChatCompletionLogprobs>,
}

impl ContentProvider for ChatCompletionChoiceDelta {
    fn content(&self) -> String {
        self.delta.content()
    }
}

/// A chat completion message generated by the model.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ChatCompletionContent {
    /// The role of the author of this message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<MessageRole>,

    /// The contents of the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,

    /// Tool calls made by the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ToolCall>>,
}

impl ContentProvider for ChatCompletionContent {
    fn content(&self) -> String {
        self.content.clone().unwrap_or("".to_string())
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum ToolChoiceType {
    None,
    Auto,
    ToolChoice { tool: Tool },
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct Function {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub parameters: FunctionParameters,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum JSONSchemaType {
    Object,
    Number,
    String,
    Array,
    Null,
    Boolean,
}

#[derive(Debug, Deserialize, Serialize, Clone, Default, PartialEq, Eq)]
pub struct JSONSchemaDefine {
    #[serde(rename = "type")]
    pub schema_type: Option<JSONSchemaType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, Box<JSONSchemaDefine>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<Box<JSONSchemaDefine>>,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct FunctionParameters {
    #[serde(rename = "type")]
    pub schema_type: JSONSchemaType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, Box<JSONSchemaDefine>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum FinishReason {
    stop,
    length,
    content_filter,
    tool_calls,
    cancelled,
    null,
}

/// from_str trait
impl std::str::FromStr for FinishReason {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "stop" => Ok(FinishReason::stop),
            "length" => Ok(FinishReason::length),
            "content_filter" => Ok(FinishReason::content_filter),
            "tool_calls" => Ok(FinishReason::tool_calls),
            "null" => Ok(FinishReason::null),
            _ => Err(format!("Unknown FinishReason: {}", s)),
        }
    }
}

impl std::fmt::Display for FinishReason {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            FinishReason::stop => write!(f, "stop"),
            FinishReason::length => write!(f, "length"),
            FinishReason::content_filter => write!(f, "content_filter"),
            FinishReason::tool_calls => write!(f, "tool_calls"),
            FinishReason::cancelled => write!(f, "cancelled"),
            FinishReason::null => write!(f, "null"),
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
#[allow(non_camel_case_types)]
pub struct FinishDetails {
    pub r#type: FinishReason,
    pub stop: String,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ToolCall {
    pub id: String,
    pub r#type: String,
    pub function: ToolCallFunction,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ToolCallFunction {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

fn serialize_tool_choice<S>(
    value: &Option<ToolChoiceType>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match value {
        Some(ToolChoiceType::None) => serializer.serialize_str("none"),
        Some(ToolChoiceType::Auto) => serializer.serialize_str("auto"),
        Some(ToolChoiceType::ToolChoice { tool }) => {
            let mut map = serializer.serialize_map(Some(2))?;
            map.serialize_entry("type", &tool.r#type)?;
            map.serialize_entry("function", &tool.function)?;
            map.end()
        }
        None => serializer.serialize_none(),
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct Tool {
    pub r#type: ToolType,
    pub function: Function,
}

#[derive(Debug, Deserialize, Serialize, Copy, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ToolType {
    Function,
}

impl ChatCompletionRequest {}

impl NvExtProvider for ChatCompletionRequest {
    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }

    fn raw_prompt(&self) -> Option<String> {
        None
    }
}

Biswa Panda's avatar
Biswa Panda committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
impl AnnotationsProvider for ChatCompletionRequest {
    fn annotations(&self) -> Option<Vec<String>> {
        self.nvext
            .as_ref()
            .and_then(|nvext| nvext.annotations.clone())
    }

    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)
    }
}
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644

impl OpenAISamplingOptionsProvider for ChatCompletionRequest {
    fn get_temperature(&self) -> Option<f32> {
        self.temperature
    }

    fn get_top_p(&self) -> Option<f32> {
        self.top_p
    }

    fn get_frequency_penalty(&self) -> Option<f32> {
        self.frequency_penalty
    }

    fn get_presence_penalty(&self) -> Option<f32> {
        self.presence_penalty
    }

    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }
}

impl OpenAIStopConditionsProvider for ChatCompletionRequest {
    fn get_max_tokens(&self) -> Option<i32> {
        self.max_tokens
    }

    fn get_min_tokens(&self) -> Option<i32> {
        self.min_tokens
    }

    fn get_stop(&self) -> Option<Vec<String>> {
        self.stop.clone()
    }

    fn nvext(&self) -> Option<&NvExt> {
        self.nvext.as_ref()
    }
}

/// Implements TryFrom for converting an OpenAI's ChatCompletionRequest to an Engine's CompletionRequest
impl TryFrom<ChatCompletionRequest> for common::CompletionRequest {
    type Error = anyhow::Error;

    fn try_from(request: ChatCompletionRequest) -> Result<Self, Self::Error> {
        // openai_api_rs::v1::chat_completion
        // pub struct ChatCompletionRequest {
        //  NA pub model: String,
        //  L  pub messages: Vec<ChatCompletionMessage, Global>,
        //  SO pub temperature: Option<f32>,
        //  SO pub top_p: Option<f32>,
        //  SO pub n: Option<i32>,
        //  ** pub response_format: Option<Value>,
        //  NA pub stream: Option<bool>,  // See Issue #8
        //  SC pub stop: Option<Vec<String, Global>>,
        //  SC pub max_tokens: Option<i32>,
        //  SO pub presence_penalty: Option<f32>,
        //  SO pub frequency_penalty: Option<f32>,
        //  ** pub logit_bias: Option<HashMap<String, i32, RandomState>>,
        //  ** pub user: Option<String>,
        //  SO pub seed: Option<i64>,
        //  ** pub tools: Option<Vec<Tool, Global>>,
        //  ** pub tool_choice: Option<ToolChoiceType>,
        // }
        //
        // ** not supported
        // NA not applicable
        // L  local in this method
        // SO extract_sampling_options
        // SC extract_stop_conditions

        // first we validate the OpenAI request
        // we can not validate everything as some fields require backend awareness
        // however, we can validate against the public OpenAI limit
        request
            .validate()
            .map_err(|e| anyhow::anyhow!("Failed to validate ChatCompletionRequest: {}", e))?;

        // todo(ryan) - open a ticket to support this
        if request.logit_bias.is_some() {
            anyhow::bail!("logit_bias is not supported");
        }

        // todo(ryan) - add support for user
        if request.user.is_some() {
            anyhow::bail!("user is not supported");
        }

        if request.response_format.is_some() {
            anyhow::bail!("response_format is not supported");
        }

        if request.tools.is_some() {
            anyhow::bail!("tools is not supported");
        }

        if request.tool_choice.is_some() {
            anyhow::bail!("tool_choice is not supported");
        }

        // sampling options
        let sampling_options = request
            .extract_sampling_options()
            .map_err(|e| anyhow::anyhow!("Failed to extract SamplingOptions: {}", e))?;

        // stop conditions
        let stop_conditions = request
            .extract_stop_conditions()
            .map_err(|e| anyhow::anyhow!("Failed to extract StopConditions: {}", e))?;

        // first we need to process the messages
        let prompt = common::PromptType::ChatCompletion(
            validate_and_collect_chat_messages(request.messages)
                .map_err(|e| anyhow::anyhow!("Failed to validate chat messages: {}", e))?,
        );

        // return the completion request
        Ok(common::CompletionRequest {
            prompt,
            stop_conditions,
            sampling_options,
            mdc_sum: None,
            annotations: None,
        })
    }
}

impl TryFrom<common::StreamingCompletionResponse> for ChatCompletionChoice {
    type Error = anyhow::Error;

    fn try_from(response: common::StreamingCompletionResponse) -> Result<Self, Self::Error> {
        let choice = ChatCompletionChoice {
            index: response.delta.index.unwrap_or(0) as u64,
            message: ChatCompletionContent {
                role: Some(MessageRole::assistant),
                content: response.delta.text,
                tool_calls: None,
            },

            finish_reason: match &response.delta.finish_reason {
                Some(common::FinishReason::EoS) => FinishReason::stop,
                Some(common::FinishReason::Stop) => FinishReason::stop,
                Some(common::FinishReason::Length) => FinishReason::length,
                Some(common::FinishReason::Error(err_msg)) => {
                    return Err(anyhow::anyhow!("finish_reason::error = {}", err_msg));
                }
                Some(common::FinishReason::Cancelled) => FinishReason::null,
                None => FinishReason::null,
            },

            logprobs: response.logprobs,
        };

        Ok(choice)
    }
}

impl TryFrom<common::StreamingCompletionResponse> for ChatCompletionChoiceDelta {
    type Error = anyhow::Error;

    fn try_from(response: common::StreamingCompletionResponse) -> Result<Self, Self::Error> {
        let choice = ChatCompletionChoiceDelta {
            index: response.delta.index.unwrap_or(0) as u64,
            delta: ChatCompletionContent {
                role: Some(MessageRole::assistant),
                content: response.delta.text,
                tool_calls: None,
            },

            finish_reason: match &response.delta.finish_reason {
                Some(common::FinishReason::EoS) => Some(FinishReason::stop),
                Some(common::FinishReason::Stop) => Some(FinishReason::stop),
                Some(common::FinishReason::Length) => Some(FinishReason::length),
                Some(common::FinishReason::Error(err_msg)) => {
                    return Err(anyhow::anyhow!("finish_reason::error = {}", err_msg));
                }
                Some(common::FinishReason::Cancelled) => Some(FinishReason::null),
                None => None,
            },
            logprobs: response.logprobs,
        };

        Ok(choice)
    }
}

fn validate_and_collect_chat_messages(
    messages: Vec<ChatCompletionMessage>,
) -> Result<common::ChatContext, anyhow::Error> {
    let mut system_prompt = None;
    let mut turns = VecDeque::new();
    let mut last_role = MessageRole::assistant;

    for message in messages {
        match message.role {
            MessageRole::system => {
                if system_prompt.is_some() {
                    return Err(anyhow::anyhow!("More than one system message found"));
                }
                system_prompt = Some(message.content);
            }
            MessageRole::user | MessageRole::assistant => {
                if last_role == message.role {
                    if turns.is_empty() {
                        return Err(anyhow::anyhow!("First message must be a user message"));
                    }
                    return Err(anyhow::anyhow!(
                        "User and assistant messages must alternate"
                    ));
                }
                last_role = message.role.clone();
                turns.push_back(message);
            }
            MessageRole::function => {} // Ignoring function messages as per assumption.
        }
    }

    if let Some(first) = turns.front() {
        if let MessageRole::assistant = first.role {
            return Err(anyhow::anyhow!("Sequence must start with a user message"));
        }
    }

    if turns.len() % 2 == 0 {
        return Err(anyhow::anyhow!("Sequence must end with a user message"));
    }

    let mut context = Vec::new();
    while turns.len() >= 2 {
        let user = turns.pop_front().unwrap();
        let asst = turns.pop_front().unwrap();

        let user = match user.content {
            Content::Text(text) => text,
            _ => return Err(anyhow::anyhow!("User message must be text")),
        };
        let asst = match asst.content {
            Content::Text(text) => text,
            _ => return Err(anyhow::anyhow!("Assistant message must be text")),
        };
        context.push(common::ChatTurn {
            user,
            assistant: asst,
        });
    }

    let prompt = turns.pop_back().unwrap();
    let prompt = match prompt.content {
        Content::Text(text) => text,
        _ => return Err(anyhow::anyhow!("Prompt message must be text")),
    };

    let system_prompt = match system_prompt {
        Some(Content::Text(text)) => Some(text),
        Some(_) => return Err(anyhow::anyhow!("System prompt must be text")),
        None => None,
    };

    Ok(common::ChatContext {
        completion: common::CompletionContext {
            prompt,
            system_prompt,
        },
        context,
    })
}

#[cfg(test)]
mod tests {
    use anyhow::Result;
    use serde_json::json;
    use std::error::Error;

    use super::*;

    #[test]
    fn test_chat_completions_valid_request_minimal() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello!")
            .build();

        assert!(
            request.is_ok(),
            "Request should succeed with minimal fields"
        );
        Ok(())
    }

    #[test]
    fn test_chat_completions_valid_request_full() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello!")
            .max_tokens(50)
            .stream(true)
            .n(1)
            .temperature(1.0)
            .top_p(0.9)
            .frequency_penalty(0.5)
            .presence_penalty(0.5)
            .stop(vec!["The end.".to_string()])
            .logprobs(true)
            .top_logprobs(5)
            .logit_bias(HashMap::new())
            .user("test_user")
            .seed(1234)
            .build();

        println!("{:?}", request);

        assert!(
            request.is_ok(),
            "Request should succeed with all fields set"
        );
        Ok(())
    }

    #[test]
    fn test_chat_completions_top_logprobs_requires_logprobs() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello!")
            .top_logprobs(5) // logprobs is not set to true
            .build();

        assert!(
            request.is_err(),
            "Request should fail when top_logprobs is set without logprobs being true"
        );
        Ok(())
    }

    #[ignore]
    #[test]
    fn test_chat_completions_max_tokens_out_of_range() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello!")
            .max_tokens(4097) // assuming the model has a max context length of 4096
            .build();

        assert!(
            request.is_err(),
            "Request should fail when max_tokens exceeds model's context length"
        );
        Ok(())
    }

    #[test]
    fn test_chat_completions_invalid_top_p() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello!")
            .top_p(1.5) // Invalid, should be between 0 and 1
            .build();

        assert!(
            request.is_err(),
            "Request should fail with invalid top_p value"
        );
        Ok(())
    }

    #[test]
    fn test_chat_completions_missing_messages() -> Result<(), Box<dyn Error>> {
        // Missing messages field in the request
        let request_result = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct") // Valid model
            .build(); // This should fail because no messages are provided.

        assert!(
            request_result.is_err(),
            "Expected request to fail without messages."
        );

        if let Err(e) = request_result {
            println!("Expected error: {}", e); // Optionally print the error for debugging
        }

        Ok(())
    }

    #[test]
    fn test_chat_completions_negative_max_tokens() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello, world!")
            .max_tokens(-10)
            .build();

        assert!(
            request.is_err(),
            "Request should fail with negative max_tokens"
        );

        Ok(())
    }

    #[ignore]
    #[test]
    fn test_chat_completions_unsupported_logit_bias() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello, world!")
            .add_logit_bias("50256", -100)
            .build();

        assert!(request.is_err(), "Request should fail with logit_bias");

        Ok(())
    }

    #[test]
    fn test_chat_completions_invalid_temperature() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hello!")
            .temperature(2.5) // Invalid, should be between 0 and 2
            .build();

        assert!(
            request.is_err(),
            "Request should fail with invalid temperature"
        );

        Ok(())
    }

    #[test]
    fn test_chat_completions_max_stop_sequences() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Tell me a story.")
            .stop(vec![
                "The end.".to_string(),
                "Once upon a time,".to_string(),
                "And then,".to_string(),
                "They lived happily ever after.".to_string(),
            ]) // 4 stop sequences, valid
            .build();

        assert!(
            request.is_ok(),
            "Request should succeed with 4 stop sequences"
        );
        Ok(())
    }

    #[test]
    fn test_chat_completions_large_stop_sequences() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Tell me a story.")
            .stop(vec![
                "The end.".to_string(),
                "And so,".to_string(),
                "Once upon a time,".to_string(),
                "They lived happily ever after.".to_string(),
                "Unexpected stop.".to_string(),
            ])
            .build();

        assert!(
            request.is_err(),
            "Request should fail with too many stop sequences"
        );

        Ok(())
    }

    #[ignore]
    #[test]
    fn test_chat_completions_invalid_stop_sequences() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Tell me a joke.")
            .stop(vec!["".to_string()])
            .build();

        assert!(
            request.is_err(),
            "Request should fail with invalid stop sequences"
        );

        Ok(())
    }

    #[ignore]
    #[test]
    fn test_chat_completions_presence_penalty_out_of_range() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("What's up?")
            .presence_penalty(3.0) // Out of valid range (-2.0 to 2.0)
            .build();

        assert!(
            request.is_err(),
            "Request should fail with invalid presence_penalty"
        );

        Ok(())
    }

    #[test]
    fn test_chat_completions_invalid_presence_penalty() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("What's up?")
            .presence_penalty(-2.5) // Invalid, should be between -2.0 and 2.0
            .build();

        assert!(
            request.is_err(),
            "Request should fail with invalid presence_penalty"
        );
        Ok(())
    }

    #[ignore]
    #[tokio::test]
    async fn test_chat_completions_with_user_field() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Hi there!")
            .user("test_user")
            .build()
            .unwrap();

        // assert!(request.is_err(), "Request should fail with 'user' field");

        let result: Result<common::CompletionRequest> = request.try_into();

        assert!(
            result.is_err(),
            "Conversion should fail with 'user' field set",
        );

        Ok(())
    }

    #[test]
    fn test_chat_completions_valid_with_seed() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("meta/llama-3.1-8b-instruct")
            .add_user_message("Repeatable result")
            .seed(12345)
            .build();

        assert!(
            request.is_ok(),
            "Request should succeed with seed value for determinism"
        );
        Ok(())
    }

    #[test]
    fn test_validate_chat_messages_multiple_system_messages() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("test-model")
            .add_system_message("System message 1")
            .add_system_message("System message 2")
            .add_user_message("Hello!")
            .build()?;

        let result = validate_and_collect_chat_messages(request.messages.clone());
        assert!(result.is_err());
        if let Err(e) = result {
            assert_eq!(e.to_string(), "More than one system message found");
        }

        Ok(())
    }

    #[test]
    fn test_validate_chat_messages_user_messages_do_not_alternate() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("test-model")
            .add_user_message("Hello!")
            .add_user_message("How are you?")
            .build()?;

        let result = validate_and_collect_chat_messages(request.messages.clone());
        assert!(result.is_err());

        if let Err(e) = result {
            assert_eq!(e.to_string(), "User and assistant messages must alternate");
        }

        Ok(())
    }

    #[ignore]
    #[test]
    fn test_validate_chat_messages_user_message_not_text() -> Result<(), Box<dyn Error>> {
        let message = ChatCompletionMessage {
            role: MessageRole::user,
            content: Content::ImageUrl(vec![ImageUrl {
                r#type: ContentType::image_url,
                text: None,
                image_url: Some(ImageUrlType {
                    url: "http://example.com/image.png".to_string(),
                }),
            }]),
            name: None,
        };

        let request = ChatCompletionRequest::builder()
            .model("test-model")
            .add_message(message)
            .build()?;

        let result = validate_and_collect_chat_messages(request.messages.clone());
        assert!(result.is_err());

        if let Err(e) = result {
            assert_eq!(e.to_string(), "Generic error: User message must be text");
        }

        Ok(())
    }

    #[test]
    fn test_try_from_chat_completion_request_with_unsupported_fields() -> Result<(), Box<dyn Error>>
    {
        let request = ChatCompletionRequest::builder()
            .model("test-model")
            .add_user_message("Hello!")
            .response_format(Some(json!({"format": "unsupported"})))
            .tools(Some(vec![Tool {
                r#type: ToolType::Function,
                function: Function {
                    name: "test_function".to_string(),
                    description: None,
                    parameters: FunctionParameters {
                        schema_type: JSONSchemaType::Object,
                        properties: None,
                        required: None,
                    },
                },
            }]))
            .tool_choice(Some(ToolChoiceType::Auto))
            .build()?;

        let result: Result<common::CompletionRequest> = request.try_into();
        assert!(
            result.is_err(),
            "Conversion should fail with unsupported fields"
        );

        Ok(())
    }

    #[test]
    fn test_deserialize_content_with_image_urls() {
        let json_data = r#"
    {
        "role": "assistant",
        "content": [
            "This is a text message.",
            "https://example.com/image1.png",
            "Another text message.",
            "https://example.com/image2.png"
        ]
    }
    "#;

        let message: ChatCompletionMessage =
            serde_json::from_str(json_data).expect("Deserialization failed");

        if let Content::ImageUrl(parts) = message.content {
            assert_eq!(parts.len(), 4);
            assert_eq!(parts[0].r#type, ContentType::text);
            assert_eq!(parts[0].text.as_ref().unwrap(), "This is a text message.");
            assert_eq!(parts[1].r#type, ContentType::image_url);
            assert_eq!(
                parts[1].image_url.as_ref().unwrap().url,
                "https://example.com/image1.png"
            );
        } else {
            panic!("Expected Content::ImageUrl");
        }
    }

    #[test]
    fn test_try_from_chat_completion_request_success() -> Result<(), Box<dyn Error>> {
        let request = ChatCompletionRequest::builder()
            .model("test-model")
            .add_user_message("Hello!")
            .add_assistant_message("Hi there!")
            .add_user_message("How are you?")
            .build()?;

        let completion_request: common::CompletionRequest = request.try_into()?;

        assert!(matches!(
            completion_request.prompt,
            common::PromptType::ChatCompletion(_)
        ));

        Ok(())
    }

    #[test]
    fn test_chat_completion_sampling_params_with_valid_nvext() {
        let nvext = NvExt {
            ignore_eos: Some(true),
            repetition_penalty: Some(0.6),
            top_k: Some(3),
            use_raw_prompt: None,
            greed_sampling: None,
            annotations: None,
        };
        let request = ChatCompletionRequest::builder()
            .nvext(nvext)
            .model("foo")
            .add_system_message("Hello!")
            .build()
            .expect("Failed to build request with valid nvext");

        assert_eq!(request.nvext.as_ref().unwrap().ignore_eos, Some(true));
        assert_eq!(
            request.nvext.as_ref().unwrap().repetition_penalty,
            Some(0.6)
        );
        assert_eq!(request.nvext.as_ref().unwrap().top_k, Some(3));
    }

    #[test]
    fn test_completion_sampling_params_without_nvext() {
        let request = ChatCompletionRequest::builder()
            .model("foo")
            .add_user_message("Test")
            .build()
            .unwrap();

        assert_eq!(request.frequency_penalty, None);
        assert_eq!(request.logprobs, None);
    }

    #[test]
    fn test_completion_sampling_params_with_valid_nvext() {
        let nvext = NvExt {
            ignore_eos: Some(true),
            repetition_penalty: Some(0.6),
            top_k: Some(3),
            ..Default::default()
        };
        let request = ChatCompletionRequest::builder()
            .nvext(nvext)
            .model("foo")
            .add_user_message("Test")
            .build()
            .expect("Failed to build request with valid nvext");

        assert_eq!(request.nvext.as_ref().unwrap().ignore_eos, Some(true));
        assert_eq!(
            request.nvext.as_ref().unwrap().repetition_penalty,
            Some(0.6)
        );
        assert_eq!(request.nvext.as_ref().unwrap().top_k, Some(3));
    }

    // #[test]
    // fn test_normalize_unicode_characters() {
    //     let str = "Hello there how are you\u{E0020}?".to_string();
    //     let normalized = str.sanitize_text();

    //     assert_eq!(normalized, "Hello there how are you?");
    // }

    // #[tokio::test]
    // async fn test_chat_completion_request_filtered() {
    //     // Define input messages with Unicode character to filter
    //     let messages = vec![
    //         ChatCompletionMessage {
    //             role: MessageRole::user,
    //             content: Content::Text(
    //                 "Hello there how are you\u{E0020}?"
    //                     .to_string()
    //                     .normalize_unicode_characters(),
    //             ),
    //             name: None,
    //         },
    //         ChatCompletionMessage {
    //             role: MessageRole::assistant,
    //             content: Content::Text("How may I help you?".to_string()),
    //             name: None,
    //         },
    //         ChatCompletionMessage {
    //             role: MessageRole::user,
    //             content: Content::Text("Do something for me?".to_string()),
    //             name: None,
    //         },
    //     ];

    //     // Define expected filtered messages
    //     let expected = vec![
    //         ChatCompletionMessage {
    //             role: MessageRole::user,
    //             content: Content::Text("Hello there how are you?".to_string()),
    //             name: None,
    //         },
    //         ChatCompletionMessage {
    //             role: MessageRole::assistant,
    //             content: Content::Text("How may I help you?".to_string()),
    //             name: None,
    //         },
    //         ChatCompletionMessage {
    //             role: MessageRole::user,
    //             content: Content::Text("Do something for me?".to_string()),
    //             name: None,
    //         },
    //     ];

    //     // Build ChatCompletionRequest with filtering applied
    //     let request = ChatCompletionRequest::builder()
    //         .model("foo")
    //         .messages(messages)
    //         .build()
    //         .expect("Failed to build ChatCompletionRequest");

    //     // Validate each message matches the expected filtered content
    //     for (i, message) in request.messages.iter().enumerate() {
    //         assert_eq!(message.role, expected[i].role);
    //         if let Content::Text(ref content) = message.content {
    //             if let Content::Text(ref expected_content) = expected[i].content {
    //                 assert_eq!(content, expected_content);
    //             }
    //         }
    //     }
    // }
}