lib.rs 55.8 KB
Newer Older
1
/// Text Generation Inference Webserver
OlivierDehaene's avatar
OlivierDehaene committed
2
pub mod config;
Nicolas Patry's avatar
Nicolas Patry committed
3
pub mod infer;
Olivier Dehaene's avatar
Olivier Dehaene committed
4
pub mod server;
Nicolas Patry's avatar
Nicolas Patry committed
5
pub mod validation;
Olivier Dehaene's avatar
Olivier Dehaene committed
6

7
8
#[cfg(feature = "kserve")]
mod kserve;
Nicolas Patry's avatar
Nicolas Patry committed
9
pub mod logging;
10

11
mod sagemaker;
12
pub mod usage_stats;
Nicolas Patry's avatar
Nicolas Patry committed
13
mod vertex;
14

15
use crate::infer::tool_grammar::ToolGrammar;
Nicolas Patry's avatar
Nicolas Patry committed
16
use crate::infer::{Infer, InferError};
17
18
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
19
use serde::{Deserialize, Serialize};
20
use tokenizers::Encoding;
Nicolas Patry's avatar
Nicolas Patry committed
21
use tracing::warn;
22
use utoipa::ToSchema;
Olivier Dehaene's avatar
Olivier Dehaene committed
23
use validation::Validation;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
24

25
#[allow(clippy::large_enum_variant)]
26
27
28
29
30
#[derive(Clone)]
pub enum Tokenizer {
    Python {
        tokenizer_name: String,
        revision: Option<String>,
31
        trust_remote_code: bool,
32
33
34
35
36
37
38
39
40
41
42
    },
    Rust(tokenizers::Tokenizer),
}

pub struct PyTokenizer<'a>(pyo3::Bound<'a, pyo3::PyAny>);

impl<'a> PyTokenizer<'a> {
    fn from_py(
        py: Python<'a>,
        tokenizer_name: String,
        revision: Option<String>,
43
        trust_remote_code: bool,
44
45
46
47
48
49
    ) -> PyResult<PyTokenizer<'a>> {
        let transformers = py.import_bound("transformers")?;
        let auto = transformers.getattr("AutoTokenizer")?;
        let from_pretrained = auto.getattr("from_pretrained")?;
        let args = (tokenizer_name,);
        let kwargs = if let Some(rev) = &revision {
50
51
52
53
54
            [
                ("revision", rev.to_string().into_py(py)),
                ("trust_remote_code", trust_remote_code.into_py(py)),
            ]
            .into_py_dict_bound(py)
55
        } else {
56
            [("trust_remote_code", trust_remote_code.into_py(py))].into_py_dict_bound(py)
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
        };
        let tokenizer = from_pretrained.call(args, Some(&kwargs))?;
        tracing::info!("Loaded a python tokenizer");
        Ok(PyTokenizer(tokenizer))
    }
}

trait TokenizerTrait {
    fn encode_trait(
        &self,
        query: String,
        add_special_tokens: bool,
    ) -> Result<tokenizers::Encoding, Box<dyn std::error::Error + Send + Sync>>;
}

impl TokenizerTrait for tokenizers::Tokenizer {
    fn encode_trait(
        &self,
        query: String,
        add_special_tokens: bool,
    ) -> Result<tokenizers::Encoding, Box<dyn std::error::Error + Send + Sync>> {
        self.encode(query, add_special_tokens)
    }
}

impl<'a> TokenizerTrait for PyTokenizer<'a> {
    fn encode_trait(
        &self,
        query: String,
        add_special_tokens: bool,
    ) -> Result<tokenizers::Encoding, Box<dyn std::error::Error + Send + Sync>> {
        let py = self.0.py();
        let kwargs = [
            ("text", query.into_py(py)),
            ("add_special_tokens", add_special_tokens.into_py(py)),
        ]
        .into_py_dict_bound(py);
        let encode = self.0.getattr("encode")?;
        let input_ids: Vec<u32> = encode.call((), Some(&kwargs))?.extract()?;
        Ok(Encoding::new(
            input_ids,
            vec![],                           // type ids
            vec![],                           // tokens (strings)
            vec![],                           // words
            vec![],                           // offsets
            vec![],                           // special_tokens_mask
            vec![],                           // attention_mask
            vec![],                           // overflowing
            std::collections::HashMap::new(), //sequence_ranges
        ))
    }
}

110
111
/// Hub type
#[derive(Clone, Debug, Deserialize)]
112
pub struct HubModelInfo {
113
114
115
116
117
118
    #[serde(rename(deserialize = "id"))]
    pub model_id: String,
    pub sha: Option<String>,
    pub pipeline_tag: Option<String>,
}

119
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
120
121
122
123
124
pub struct ChatTemplate {
    name: String,
    template: String,
}

125
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
126
127
128
129
130
131
#[serde(untagged)]
pub enum ChatTemplateVersions {
    Single(String),
    Multiple(Vec<ChatTemplate>),
}

132
133
use std::path::Path;

134
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
135
pub struct HubTokenizerConfig {
136
    pub chat_template: Option<ChatTemplateVersions>,
137
    pub completion_template: Option<String>,
138
139
    pub bos_token: Option<TokenizerConfigToken>,
    pub eos_token: Option<TokenizerConfigToken>,
140
141
142
    pub tokenizer_class: Option<String>,
    pub add_bos_token: Option<bool>,
    pub add_eos_token: Option<bool>,
143
144
145
}

impl HubTokenizerConfig {
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    pub fn from_file<P: AsRef<Path>>(filename: P) -> Option<Self> {
        std::fs::read_to_string(filename)
            .ok()
            .and_then(|content| serde_json::from_str(&content).ok())
    }
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(untagged)]
pub enum TokenizerConfigToken {
    String(String),
    Object { content: String },
}

impl TokenizerConfigToken {
    pub fn as_str(&self) -> &str {
        match self {
            TokenizerConfigToken::String(s) => s,
            TokenizerConfigToken::Object { content } => content,
        }
166
167
168
    }
}

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "processor_class")]
pub enum HubPreprocessorConfig {
    Idefics2Processor(Idefics2Preprocessor),
}

impl HubPreprocessorConfig {
    pub fn from_file<P: AsRef<std::path::Path>>(filename: P) -> Option<Self> {
        let content = std::fs::read_to_string(filename).ok()?;
        serde_json::from_str(&content).ok()
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Idefics2Preprocessor {
    #[serde(default)]
    do_image_splitting: bool,
}

drbh's avatar
drbh committed
188
189
190
191
192
193
194
195
#[derive(Debug, Clone, Deserialize, Default)]
pub struct HubProcessorConfig {
    pub chat_template: Option<ChatTemplateVersions>,
    pub image_seq_len: usize,
    pub processor_class: Option<String>,
}

impl HubProcessorConfig {
196
197
198
199
    pub fn from_file<P: AsRef<Path>>(filename: P) -> Option<Self> {
        std::fs::read_to_string(filename)
            .ok()
            .and_then(|content| serde_json::from_str(&content).ok())
drbh's avatar
drbh committed
200
201
202
    }
}

203
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
Nicolas Patry's avatar
Nicolas Patry committed
204
#[cfg_attr(test, derive(PartialEq))]
drbh's avatar
drbh committed
205
206
#[serde(tag = "type", content = "value")]
pub(crate) enum GrammarType {
207
208
209
210
211
    /// A string that represents a [JSON Schema](https://json-schema.org/).
    ///
    /// JSON Schema is a declarative language that allows to annotate JSON documents
    /// with types and descriptions.
    #[serde(rename = "json")]
drbh's avatar
drbh committed
212
    #[serde(alias = "json_object")]
213
214
    #[schema(example = json ! ({"properties": {"location":{"type": "string"}}}))]
    Json(serde_json::Value),
drbh's avatar
drbh committed
215
216
217
218
    #[serde(rename = "regex")]
    Regex(String),
}

219
220
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct Info {
221
    /// Model info
222
223
224
225
    #[schema(example = "bigscience/blomm-560m")]
    pub model_id: String,
    #[schema(nullable = true, example = "e985a63cdc139290c5f700ff1929f0b5942cced2")]
    pub model_sha: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
226
227
228
229
    // #[schema(example = "torch.float16")]
    // pub model_dtype: String,
    // #[schema(example = "cuda")]
    // pub model_device_type: String,
230
231
    #[schema(nullable = true, example = "text-generation")]
    pub model_pipeline_tag: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
232

233
234
235
236
237
238
239
240
    /// Router Parameters
    #[schema(example = "128")]
    pub max_concurrent_requests: usize,
    #[schema(example = "2")]
    pub max_best_of: usize,
    #[schema(example = "4")]
    pub max_stop_sequences: usize,
    #[schema(example = "1024")]
OlivierDehaene's avatar
OlivierDehaene committed
241
    pub max_input_tokens: usize,
242
243
244
245
    #[schema(example = "2048")]
    pub max_total_tokens: usize,
    #[schema(example = "2")]
    pub validation_workers: usize,
246
247
    #[schema(example = "32")]
    pub max_client_batch_size: usize,
Nicolas Patry's avatar
Nicolas Patry committed
248

249
    /// Router Info
250
251
    #[schema(example = "text-generation-router")]
    pub router: &'static str,
252
253
254
255
    #[schema(example = "0.5.0")]
    pub version: &'static str,
    #[schema(nullable = true, example = "null")]
    pub sha: Option<&'static str>,
256
257
    #[schema(nullable = true, example = "null")]
    pub docker_label: Option<&'static str>,
258
259
}

drbh's avatar
drbh committed
260
#[derive(Clone, Debug, Deserialize, ToSchema, Default)]
Nicolas Patry's avatar
Nicolas Patry committed
261
#[cfg_attr(test, derive(PartialEq))]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
262
pub(crate) struct GenerateParameters {
263
    /// Generate best_of sequences and return the one if the highest token logprobs.
264
265
266
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 1)]
    pub best_of: Option<usize>,
267
268

    /// The value used to module the logits distribution.
269
270
271
272
273
274
275
276
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 0.5
    )]
    pub temperature: Option<f32>,
277
278
279

    /// The parameter for repetition penalty. 1.0 means no penalty.
    /// See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
280
281
282
283
284
285
286
287
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 1.03
    )]
    pub repetition_penalty: Option<f32>,
288
289
290
291

    /// The parameter for frequency penalty. 1.0 means no penalty
    /// Penalize new tokens based on their existing frequency in the text so far,
    /// decreasing the model's likelihood to repeat the same line verbatim.
292
    #[serde(default)]
293
294
295
296
297
298
299
    #[schema(
        exclusive_minimum = -2.0,
        nullable = true,
        default = "null",
        example = 0.1
    )]
    pub frequency_penalty: Option<f32>,
300
301

    /// The number of highest probability vocabulary tokens to keep for top-k-filtering.
302
    #[serde(default)]
303
304
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 10)]
    pub top_k: Option<i32>,
305
306

    /// Top-p value for nucleus sampling.
307
308
309
310
311
312
313
314
315
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub top_p: Option<f32>,
316
317
318

    /// Typical Decoding mass
    /// See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information.
319
    #[serde(default)]
320
321
322
323
324
325
326
327
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub typical_p: Option<f32>,
328
329

    /// Activate logits sampling.
330
    #[serde(default)]
331
    #[schema(default = "false", example = true)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
332
    pub do_sample: bool,
333
334

    /// Maximum number of tokens to generate.
335
336
    #[serde(default)]
    #[schema(nullable = true, default = "1024", example = "20")]
337
    pub max_new_tokens: Option<u32>,
338
339

    /// Whether to prepend the prompt to the generated text
OlivierDehaene's avatar
OlivierDehaene committed
340
    #[serde(default)]
341
    #[schema(nullable = true, default = "null", example = false)]
342
    pub return_full_text: Option<bool>,
343
344

    /// Stop generating tokens if a member of `stop` is generated.
345
    #[serde(default)]
346
    #[schema(inline, max_items = 4, example = json ! (["photographer"]))]
347
    pub stop: Vec<String>,
348
349

    /// Truncate inputs tokens to the given size.
OlivierDehaene's avatar
OlivierDehaene committed
350
    #[serde(default)]
351
    #[schema(nullable = true, default = "null", example = "null")]
352
    pub truncate: Option<usize>,
353
354

    /// Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226).
355
    #[serde(default)]
356
357
    #[schema(default = "false", example = true)]
    pub watermark: bool,
358
359

    /// Whether to return generation details.
360
    #[serde(default)]
361
    #[schema(default = "true")]
OlivierDehaene's avatar
OlivierDehaene committed
362
    pub details: bool,
363
364

    /// Whether to return decoder input token logprobs and ids.
365
    #[serde(default)]
366
    #[schema(default = "false")]
367
    pub decoder_input_details: bool,
368
369

    /// Random sampling seed.
370
    #[serde(default)]
371
372
373
374
375
376
    #[schema(
        exclusive_minimum = 0,
        nullable = true,
        default = "null",
        example = "null"
    )]
377
    pub seed: Option<u64>,
378
379

    /// The number of highest probability vocabulary tokens to keep for top-n-filtering.
Nicolas Patry's avatar
Nicolas Patry committed
380
381
382
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 5)]
    pub top_n_tokens: Option<u32>,
383
384

    /// Grammar constraints for the generation.
drbh's avatar
drbh committed
385
    #[serde(default)]
386
    #[schema(nullable = true, default = "null", example = "null")]
drbh's avatar
drbh committed
387
    pub grammar: Option<GrammarType>,
drbh's avatar
drbh committed
388
389
390
391
392

    /// Lora adapter id
    #[serde(default)]
    #[schema(nullable = true, default = "null", example = "null")]
    pub adapter_id: Option<String>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
393
394
395
396
}

fn default_parameters() -> GenerateParameters {
    GenerateParameters {
397
        best_of: None,
398
399
        temperature: None,
        repetition_penalty: None,
400
        frequency_penalty: None,
401
402
        top_k: None,
        top_p: None,
403
        typical_p: None,
404
        do_sample: true,
405
        max_new_tokens: None,
406
        return_full_text: None,
407
        stop: Vec::new(),
408
        truncate: None,
409
        watermark: false,
OlivierDehaene's avatar
OlivierDehaene committed
410
        details: false,
411
        decoder_input_details: false,
412
        seed: None,
Nicolas Patry's avatar
Nicolas Patry committed
413
        top_n_tokens: None,
drbh's avatar
drbh committed
414
        grammar: None,
drbh's avatar
drbh committed
415
        adapter_id: None,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
416
417
418
    }
}

419
420
421
422
423
424
425
426
427
428
429
430
431
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug)]
#[serde(try_from = "PromptDeserializer")]
pub struct Prompt(pub Vec<String>);

#[derive(Deserialize)]
#[serde(untagged)]
enum PromptDeserializer {
    Single(String),
    Multiple(Vec<String>),
}

impl TryFrom<PromptDeserializer> for Prompt {
    type Error = String;
432

433
    fn try_from(value: PromptDeserializer) -> Result<Self, Self::Error> {
434
        match value {
435
436
437
438
439
440
441
442
443
444
445
            PromptDeserializer::Single(s) => Ok(Prompt(vec![s])),
            PromptDeserializer::Multiple(v) => {
                if v.is_empty() {
                    Err(
                        "Empty array detected. Do not use an empty array for the prompt."
                            .to_string(),
                    )
                } else {
                    Ok(Prompt(v))
                }
            }
446
447
448
449
        }
    }
}

450
451
452
453
454
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug)]
pub struct CompletionRequest {
    /// UNUSED
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
    /// ID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API.
455
    pub model: Option<String>,
456
457
458

    /// The prompt to generate completions for.
    #[schema(example = "What is Deep Learning?")]
459
    pub prompt: Prompt,
460
461
462

    /// The maximum number of tokens that can be generated in the chat completion.
    #[serde(default)]
463
    #[schema(default = "1024", example = "32")]
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
    pub max_tokens: Option<u32>,

    /// 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. We generally recommend altering this or `top_p` but not both.
    #[serde(default)]
    #[schema(nullable = true, example = 1.0)]
    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.
    #[serde(default)]
    #[schema(nullable = true, example = 0.95)]
    pub top_p: Option<f32>,

    #[serde(default = "bool::default")]
    pub stream: bool,

    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,

    /// The text to append to the prompt. This is useful for completing sentences or generating a paragraph of text.
    /// please see the completion_template field in the model's tokenizer_config.json file for completion template.
    #[serde(default)]
    pub suffix: Option<String>,

    #[serde(default)]
    pub repetition_penalty: 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(default)]
    #[schema(example = "1.0")]
    pub frequency_penalty: Option<f32>,
497
498
499
500
501

    /// Up to 4 sequences where the API will stop generating further tokens.
    #[serde(default)]
    #[schema(nullable = true, example = "null")]
    pub stop: Option<Vec<String>>,
502
503
}

504
505
506
507
508
509
510
511
512
#[derive(Clone, Serialize, ToSchema)]
#[serde(tag = "object")]
enum Completion {
    #[serde(rename = "text_completion")]
    Chunk(Chunk),
    #[serde(rename = "text_completion")]
    Final(CompletionFinal),
}

513
#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
514
pub(crate) struct CompletionFinal {
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
    pub id: String,
    #[schema(example = "1706270835")]
    pub created: u64,
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<CompletionComplete>,
    pub usage: Usage,
}

#[derive(Clone, Deserialize, Serialize, ToSchema)]
pub(crate) struct CompletionComplete {
    pub index: u32,
    pub text: String,
    pub logprobs: Option<Vec<f32>>,
    pub finish_reason: String,
}

533
534
535
536
537
538
539
540
541
#[derive(Clone, Deserialize, Serialize, ToSchema)]
pub(crate) struct Chunk {
    pub id: String,
    pub created: u64,
    pub choices: Vec<CompletionComplete>,
    pub model: String,
    pub system_fingerprint: String,
}

542
#[derive(Clone, Deserialize, Serialize, ToSchema)]
543
544
pub(crate) struct ChatCompletion {
    pub id: String,
545
    #[schema(example = "1706270835")]
546
    pub created: u64,
547
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
548
549
550
551
552
553
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionComplete>,
    pub usage: Usage,
}

554
#[derive(Clone, Deserialize, Serialize, ToSchema)]
555
556
pub(crate) struct ChatCompletionComplete {
    pub index: u32,
Nicolas Patry's avatar
Nicolas Patry committed
557
    pub message: OutputMessage,
558
    pub logprobs: Option<ChatCompletionLogprobs>,
559
560
561
    pub finish_reason: String,
}

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
#[derive(Clone, Deserialize, Serialize, ToSchema)]
pub(crate) struct ChatCompletionLogprobs {
    content: Vec<ChatCompletionLogprob>,
}

impl From<(Token, Vec<Token>)> for ChatCompletionLogprobs {
    fn from(value: (Token, Vec<Token>)) -> Self {
        let (token, top_tokens) = value;

        Self {
            content: vec![ChatCompletionLogprob {
                token: token.text,
                logprob: token.logprob,
                top_logprobs: top_tokens
                    .into_iter()
                    .map(|t| ChatCompletionTopLogprob {
                        token: t.text,
                        logprob: t.logprob,
                    })
                    .collect(),
            }],
        }
    }
}

impl From<(Vec<Token>, Vec<Vec<Token>>)> for ChatCompletionLogprobs {
    fn from(value: (Vec<Token>, Vec<Vec<Token>>)) -> Self {
        let (tokens, top_tokens) = value;
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604

        // Create an iterator that produces None for top_tokens once it's exhausted
        let top_tokens_iter = top_tokens
            .into_iter()
            .map(Some)
            .chain(std::iter::repeat(None));

        let content = tokens
            .into_iter()
            .zip(top_tokens_iter)
            .map(|(t, top_t_option)| ChatCompletionLogprob {
                token: t.text,
                logprob: t.logprob,
                top_logprobs: match top_t_option {
                    Some(top_t) => top_t
605
606
607
608
609
610
                        .into_iter()
                        .map(|t| ChatCompletionTopLogprob {
                            token: t.text,
                            logprob: t.logprob,
                        })
                        .collect(),
611
612
613
614
615
616
                    None => vec![], // Handle the case where there are no top tokens
                },
            })
            .collect();

        Self { content }
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
    }
}

#[derive(Clone, Deserialize, Serialize, ToSchema)]
pub(crate) struct ChatCompletionLogprob {
    token: String,
    logprob: f32,
    top_logprobs: Vec<ChatCompletionTopLogprob>,
}

#[derive(Clone, Deserialize, Serialize, ToSchema)]
pub(crate) struct ChatCompletionTopLogprob {
    token: String,
    logprob: f32,
}

633
#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
634
635
636
637
638
639
pub(crate) struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

640
641
642
643
644
645
646
647
648
#[derive(Clone, Serialize, ToSchema)]
#[serde(tag = "object")]
enum CompletionType {
    #[serde(rename = "chat.completion.chunk")]
    ChatCompletionChunk(ChatCompletionChunk),
    #[serde(rename = "chat.completion")]
    ChatCompletion(ChatCompletion),
}

649
650
651
652
impl ChatCompletion {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
drbh's avatar
drbh committed
653
        output: Option<String>,
654
655
656
        created: u64,
        details: Details,
        return_logprobs: bool,
657
        tool_calls: Option<Vec<ToolCall>>,
658
    ) -> Self {
Nicolas Patry's avatar
Nicolas Patry committed
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
        let message = match (output, tool_calls) {
            (Some(content), None) => OutputMessage::ChatMessage(TextMessage {
                role: "assistant".into(),
                content,
            }),
            (None, Some(tool_calls)) => OutputMessage::ToolCall(ToolCallMessage {
                role: "assistant".to_string(),
                tool_calls,
            }),
            (Some(output), Some(_)) => {
                warn!("Received both chat and tool call");
                OutputMessage::ChatMessage(TextMessage {
                    role: "assistant".into(),
                    content: output,
                })
            }
            (None, None) => {
                warn!("Didn't receive an answer");
                OutputMessage::ChatMessage(TextMessage {
                    role: "assistant".into(),
                    content: "".to_string(),
                })
            }
        };
683
684
685
686
687
688
689
        Self {
            id: String::new(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionComplete {
                index: 0,
Nicolas Patry's avatar
Nicolas Patry committed
690
                message,
691
                logprobs: return_logprobs
692
                    .then(|| ChatCompletionLogprobs::from((details.tokens, details.top_tokens))),
693
                finish_reason: details.finish_reason.format(true),
694
695
696
697
698
699
700
701
702
            }],
            usage: Usage {
                prompt_tokens: details.prefill.len() as u32,
                completion_tokens: details.generated_tokens,
                total_tokens: details.prefill.len() as u32 + details.generated_tokens,
            },
        }
    }
}
703
#[derive(Clone, Serialize, ToSchema)]
704
705
pub(crate) struct ChatCompletionChunk {
    pub id: String,
706
    #[schema(example = "1706270978")]
707
    pub created: u64,
708
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
709
710
711
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionChoice>,
Nicolas Patry's avatar
Nicolas Patry committed
712
    pub usage: Option<Usage>,
713
714
}

715
#[derive(Clone, Serialize, ToSchema)]
716
717
718
pub(crate) struct ChatCompletionChoice {
    pub index: u32,
    pub delta: ChatCompletionDelta,
719
    pub logprobs: Option<ChatCompletionLogprobs>,
720
721
722
    pub finish_reason: Option<String>,
}

Nicolas Patry's avatar
Nicolas Patry committed
723
724
725
726
727
728
729
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct ToolCallDelta {
    #[schema(example = "assistant")]
    role: String,
    tool_calls: DeltaToolCall,
}

730
731
#[derive(Clone, Debug, Serialize, ToSchema)]
#[serde(untagged)]
Nicolas Patry's avatar
Nicolas Patry committed
732
733
734
enum ChatCompletionDelta {
    Chat(TextMessage),
    Tool(ToolCallDelta),
drbh's avatar
drbh committed
735
736
}

Nicolas Patry's avatar
Nicolas Patry committed
737
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
738
739
740
741
742
743
744
pub(crate) struct DeltaToolCall {
    pub index: u32,
    pub id: String,
    pub r#type: String,
    pub function: Function,
}

Nicolas Patry's avatar
Nicolas Patry committed
745
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
746
747
748
pub(crate) struct Function {
    pub name: Option<String>,
    pub arguments: String,
749
750
}

drbh's avatar
drbh committed
751
#[allow(clippy::too_many_arguments)]
752
753
754
755
impl ChatCompletionChunk {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
drbh's avatar
drbh committed
756
757
        delta: Option<String>,
        tool_calls: Option<Vec<String>>,
758
        created: u64,
759
        logprobs: Option<ChatCompletionLogprobs>,
760
        finish_reason: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
761
        usage: Option<Usage>,
762
    ) -> Self {
763
        let delta = match (delta, tool_calls) {
Nicolas Patry's avatar
Nicolas Patry committed
764
765
766
767
768
769
770
            (Some(delta), _) => ChatCompletionDelta::Chat(TextMessage {
                role: "assistant".to_string(),
                content: delta,
            }),
            (None, Some(tool_calls)) => ChatCompletionDelta::Tool(ToolCallDelta {
                role: "assistant".to_string(),
                tool_calls: DeltaToolCall {
771
772
773
774
775
776
777
                    index: 0,
                    id: String::new(),
                    r#type: "function".to_string(),
                    function: Function {
                        name: None,
                        arguments: tool_calls[0].to_string(),
                    },
Nicolas Patry's avatar
Nicolas Patry committed
778
779
780
781
782
783
                },
            }),
            (None, None) => ChatCompletionDelta::Chat(TextMessage {
                role: "assistant".to_string(),
                content: "".to_string(),
            }),
784
        };
785
786
787
788
789
790
        Self {
            id: String::new(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionChoice {
791
                index: 0,
792
                delta,
793
794
795
                logprobs,
                finish_reason,
            }],
Nicolas Patry's avatar
Nicolas Patry committed
796
            usage,
797
798
799
800
801
        }
    }
}

#[derive(Clone, Deserialize, ToSchema, Serialize)]
Nicolas Patry's avatar
Nicolas Patry committed
802
#[cfg_attr(test, derive(Debug, PartialEq, Default))]
803
pub(crate) struct ChatRequest {
804
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
drbh's avatar
drbh committed
805
    /// [UNUSED] ID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API.
806
    pub model: Option<String>,
drbh's avatar
drbh committed
807

808
    /// A list of messages comprising the conversation so far.
drbh's avatar
drbh committed
809
    #[schema(example = "[{\"role\": \"user\", \"content\": \"What is Deep Learning?\"}]")]
810
811
812
813
814
    pub messages: Vec<Message>,

    /// 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(default)]
815
    #[schema(example = "1.0")]
816
817
818
819
820
821
822
823
824
825
826
827
828
829
    pub frequency_penalty: Option<f32>,

    /// UNUSED
    /// Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens
    /// (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. 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.
    #[serde(default)]
    pub logit_bias: Option<Vec<f32>>,

    /// 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.
    #[serde(default)]
830
    #[schema(example = "false")]
831
832
833
834
835
    pub logprobs: Option<bool>,

    /// An integer between 0 and 5 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(default)]
836
    #[schema(example = "5")]
837
838
839
840
    pub top_logprobs: Option<u32>,

    /// The maximum number of tokens that can be generated in the chat completion.
    #[serde(default)]
841
    #[schema(default = "1024", example = "32")]
842
843
844
845
846
847
    pub max_tokens: Option<u32>,

    /// UNUSED
    /// How many chat completion choices to generate for each input message. Note that you will be charged based on the
    /// number of generated tokens across all of the choices. Keep n as 1 to minimize costs.
    #[serde(default)]
848
    #[schema(nullable = true, example = "2")]
849
850
851
852
853
    pub n: Option<u32>,

    /// 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(default)]
854
    #[schema(nullable = true, example = 0.1)]
855
856
    pub presence_penalty: Option<f32>,

857
858
859
860
861
    /// Up to 4 sequences where the API will stop generating further tokens.
    #[serde(default)]
    #[schema(nullable = true, example = "null")]
    pub stop: Option<Vec<String>>,

862
863
864
865
866
    #[serde(default = "bool::default")]
    pub stream: bool,

    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,
867
868
869
870
871
872

    /// 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.
    ///
    /// We generally recommend altering this or `top_p` but not both.
    #[serde(default)]
873
    #[schema(nullable = true, example = 1.0)]
874
875
876
877
878
    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.
    #[serde(default)]
879
    #[schema(nullable = true, example = 0.95)]
880
    pub top_p: Option<f32>,
drbh's avatar
drbh committed
881
882
883
884
885
886
887
888

    /// 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.
    #[serde(default)]
    #[schema(nullable = true, example = "null")]
    pub tools: Option<Vec<Tool>>,

    /// A prompt to be appended before the tools
drbh's avatar
drbh committed
889
    #[serde(default)]
drbh's avatar
drbh committed
890
891
    #[schema(
        nullable = true,
drbh's avatar
drbh committed
892
        example = "Given the functions available, please respond with a JSON for a function call with its proper arguments that best answers the given prompt. Respond in the format {name: function name, parameters: dictionary of argument name and its value}.Do not use variables."
drbh's avatar
drbh committed
893
894
895
896
897
    )]
    pub tool_prompt: Option<String>,

    /// A specific tool to use. If not provided, the model will default to use any of the tools provided in the tools parameter.
    #[serde(default)]
898
    #[schema(nullable = true, default = "auto", example = "auto")]
drbh's avatar
drbh committed
899
    pub tool_choice: ToolChoice,
drbh's avatar
drbh committed
900
901
902
903
904
905
906

    /// Response format constraints for the generation.
    ///
    /// NOTE: A request can use `response_format` OR `tools` but not both.
    #[serde(default)]
    #[schema(nullable = true, default = "null", example = "null")]
    pub response_format: Option<GrammarType>,
907

Nicolas Patry's avatar
Nicolas Patry committed
908
909
910
911
912
913
    /// Options for streaming response. Only set this when you set stream: true.
    #[serde(default)]
    #[schema(nullable = true, example = "null")]
    pub stream_options: Option<StreamOptions>,
}

Nicolas Patry's avatar
Nicolas Patry committed
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
impl ChatRequest {
    fn try_into_generate(self, infer: &Infer) -> Result<(GenerateRequest, bool), InferError> {
        let ChatRequest {
            model,
            max_tokens,
            messages,
            seed,
            stop,
            stream,
            tools,
            tool_choice,
            tool_prompt,
            temperature,
            response_format,
            presence_penalty,
            frequency_penalty,
            top_p,
            top_logprobs,
            ..
        } = self;

        let repetition_penalty = presence_penalty.map(|x| x + 2.0);
936
        let max_new_tokens = max_tokens;
Nicolas Patry's avatar
Nicolas Patry committed
937
938
939
940
941
942
943
944
945
        let tool_prompt = tool_prompt
            .filter(|s| !s.is_empty())
            .unwrap_or_else(default_tool_prompt);
        let stop = stop.unwrap_or_default();
        // enable greedy only when temperature is 0
        let (do_sample, temperature) = match temperature {
            Some(temperature) if temperature == 0.0 => (false, None),
            other => (true, other),
        };
946
947
948
949
950
951
952
953
954

        if response_format.is_some() && tools.is_some() {
            return Err(InferError::ToolError(
                "Grammar and tools are mutually exclusive".into(),
            ));
        }

        let (inputs, grammar, using_tools) = match response_format {
            Some(format) => {
Lucain's avatar
Lucain committed
955
                let inputs = infer.apply_chat_template(messages, None)?;
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
                (inputs, Some(format), false)
            }
            None => {
                if let Some(tools) = tools {
                    match ToolGrammar::apply(tools, tool_choice)? {
                        Some((updated_tools, tool_schema)) => {
                            let grammar = GrammarType::Json(serde_json::json!(tool_schema));
                            let inputs: String = infer.apply_chat_template(
                                messages,
                                Some((updated_tools, tool_prompt)),
                            )?;
                            (inputs, Some(grammar), true)
                        }
                        None => {
                            // same as if no response_format or tools are set
Lucain's avatar
Lucain committed
971
                            let inputs = infer.apply_chat_template(messages, None)?;
972
973
974
975
976
                            (inputs, None, false)
                        }
                    }
                } else {
                    // if no response_format or tools are set simply apply the chat template to generate inputs
Lucain's avatar
Lucain committed
977
                    let inputs = infer.apply_chat_template(messages, None)?;
978
979
980
981
                    (inputs, None, false)
                }
            }
        };
Nicolas Patry's avatar
Nicolas Patry committed
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

        Ok((
            GenerateRequest {
                inputs: inputs.to_string(),
                add_special_tokens: false,
                parameters: GenerateParameters {
                    best_of: None,
                    temperature,
                    repetition_penalty,
                    frequency_penalty,
                    top_k: None,
                    top_p,
                    typical_p: None,
                    do_sample,
                    max_new_tokens,
                    return_full_text: None,
                    stop,
                    truncate: None,
                    watermark: false,
                    details: true,
                    decoder_input_details: !stream,
                    seed,
                    top_n_tokens: top_logprobs,
                    grammar,
                    adapter_id: model.filter(|m| *m != "tgi").map(String::from),
                },
            },
            using_tools,
        ))
    }
}

Nicolas Patry's avatar
Nicolas Patry committed
1014
#[derive(Clone, Deserialize, ToSchema, Serialize)]
Nicolas Patry's avatar
Nicolas Patry committed
1015
#[cfg_attr(test, derive(Debug, PartialEq))]
Nicolas Patry's avatar
Nicolas Patry committed
1016
1017
1018
1019
struct StreamOptions {
    /// If set, an additional chunk will be streamed before the data: [DONE] message. The usage field on this chunk shows the token usage statistics for the entire request, and the choices field will always be an empty array. All other chunks will also include a usage field, but with a null value.
    #[schema(example = "true")]
    include_usage: bool,
drbh's avatar
drbh committed
1020
1021
}

drbh's avatar
drbh committed
1022
1023
pub fn default_tool_prompt() -> String {
    "\nGiven the functions available, please respond with a JSON for a function call with its proper arguments that best answers the given prompt. Respond in the format {name: function name, parameters: dictionary of argument name and its value}.Do not use variables.\n".to_string()
drbh's avatar
drbh committed
1024
}
1025

1026
1027
1028
1029
1030
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum TypedChoice {
    #[serde(rename = "function")]
    Function { function: FunctionName },
drbh's avatar
drbh committed
1031
1032
}

1033
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1034
1035
1036
1037
pub struct FunctionName {
    pub name: String,
}

1038
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema, Default)]
1039
#[serde(from = "ToolTypeDeserializer")]
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
#[serde(rename_all = "snake_case")]
/// <https://platform.openai.com/docs/guides/function-calling/configuring-function-calling-behavior-using-the-tool_choice-parameter>
pub enum ToolChoice {
    /// Means the model can pick between generating a message or calling one or more tools.
    #[default]
    Auto,
    /// Means the model will not call any tool and instead generates a message.
    #[serde(rename = "none")]
    NoTool,
    /// Means the model must call one or more tools.
    Required,
    /// Forces the model to call a specific tool. This structure aligns with the `OpenAI` API schema to force a specific tool.
    Function(FunctionName),
}
drbh's avatar
drbh committed
1054

1055
#[derive(Deserialize, ToSchema)]
1056
#[serde(untagged)]
1057
1058
1059
1060
1061
1062
1063
/// Controls which (if any) tool is called by the model.
/// - `none` means the model will not call any tool and instead generates a message.
/// - `auto` means the model can pick between generating a message or calling one or more tools.
/// - `required` means the model must call one or more tools.
/// - Specifying a particular tool via `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.
///
/// `none` is the default when no tools are present. `auto` is the default if tools are present."
1064
enum ToolTypeDeserializer {
1065
    /// None means `null` was passed in the JSON, and the default choice is applied based on the presence of tools.
1066
    Null,
1067
1068
1069

    /// `auto` means the model can pick between generating a message or calling one or more tools.
    #[schema(example = "auto")]
drbh's avatar
drbh committed
1070
    String(String),
1071
1072
1073
1074

    /// Specifying a particular tool forces the model to call that tool, with structured function details.
    #[schema(example = r#"{"type": "function", "function": {"name": "my_function"}}"#)]
    TypedChoice(TypedChoice),
1075
}
drbh's avatar
drbh committed
1076

1077
1078
impl From<ToolTypeDeserializer> for ToolChoice {
    fn from(value: ToolTypeDeserializer) -> Self {
drbh's avatar
drbh committed
1079
        match value {
1080
            ToolTypeDeserializer::Null => ToolChoice::Auto,
drbh's avatar
drbh committed
1081
            ToolTypeDeserializer::String(s) => match s.as_str() {
1082
1083
1084
1085
                "none" => ToolChoice::NoTool,
                "auto" => ToolChoice::Auto,
                "required" => ToolChoice::Required,
                _ => ToolChoice::Function(FunctionName { name: s }),
drbh's avatar
drbh committed
1086
            },
1087
1088
1089
            ToolTypeDeserializer::TypedChoice(TypedChoice::Function { function }) => {
                ToolChoice::Function(function)
            }
drbh's avatar
drbh committed
1090
1091
1092
1093
        }
    }
}

1094
#[derive(Debug, Deserialize, Serialize, ToSchema, PartialEq)]
drbh's avatar
drbh committed
1095
pub struct JsonSchemaTool {
drbh's avatar
drbh committed
1096
1097
1098
1099
1100
    #[serde(flatten)]
    functions_map: FunctionsMap,
    properties: Properties,
}

1101
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
1102
1103
1104
1105
1106
struct FunctionsMap {
    #[serde(rename = "$functions")]
    functions: std::collections::HashMap<String, serde_json::Value>,
}

1107
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
1108
1109
1110
1111
1112
struct FunctionRef {
    #[serde(rename = "$ref")]
    ref_path: String,
}

1113
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
struct Properties {
    #[serde(serialize_with = "serialize_function")]
    function: Vec<FunctionRef>,
}

fn serialize_function<S>(functions: &Vec<FunctionRef>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    use serde::ser::SerializeStruct;
    let mut state = serializer.serialize_struct("Function", 1)?;
    state.serialize_field("anyOf", functions)?;
    state.end()
}

Nicolas Patry's avatar
Nicolas Patry committed
1129
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema, Default, PartialEq)]
drbh's avatar
drbh committed
1130
1131
1132
1133
pub(crate) struct FunctionDefinition {
    #[serde(default)]
    pub description: Option<String>,
    pub name: String,
1134
1135
    #[serde(alias = "parameters")]
    pub arguments: serde_json::Value,
drbh's avatar
drbh committed
1136
1137
1138
}

#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
Nicolas Patry's avatar
Nicolas Patry committed
1139
#[cfg_attr(test, derive(PartialEq))]
drbh's avatar
drbh committed
1140
1141
1142
1143
1144
1145
pub(crate) struct Tool {
    // The type of the tool. Currently, only 'function' is supported.
    #[schema(example = "function")]
    pub r#type: String,
    // Grab the tool as generic JSON for debugging purposes.
    pub function: FunctionDefinition,
1146
1147
}

1148
#[derive(Clone, Serialize, Deserialize, Default)]
1149
pub(crate) struct ChatTemplateInputs<'a> {
Nicolas Patry's avatar
Nicolas Patry committed
1150
    messages: Vec<TextMessage>,
1151
1152
    bos_token: Option<&'a str>,
    eos_token: Option<&'a str>,
1153
    add_generation_prompt: bool,
drbh's avatar
drbh committed
1154
    tools: Option<Vec<Tool>>,
1155
1156
}

Nicolas Patry's avatar
Nicolas Patry committed
1157
#[derive(Clone, Deserialize, Serialize, ToSchema, Default, Debug, PartialEq)]
drbh's avatar
drbh committed
1158
pub(crate) struct ToolCall {
1159
    pub id: String,
drbh's avatar
drbh committed
1160
1161
1162
1163
    pub r#type: String,
    pub function: FunctionDefinition,
}

Nicolas Patry's avatar
Nicolas Patry committed
1164
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
1165
pub struct Url {
Nicolas Patry's avatar
Nicolas Patry committed
1166
    url: String,
drbh's avatar
drbh committed
1167
1168
}

Nicolas Patry's avatar
Nicolas Patry committed
1169
1170
1171
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
1172
1173
1174
pub enum MessageChunk {
    Text { text: String },
    ImageUrl { image_url: Url },
Nicolas Patry's avatar
Nicolas Patry committed
1175
1176
1177
1178
1179
1180
1181
}

#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct Message {
    #[schema(example = "user")]
    role: String,
    #[schema(example = "My name is David and I")]
1182
    pub content: MessageContent,
drbh's avatar
drbh committed
1183
    #[serde(default, skip_serializing_if = "Option::is_none")]
Nicolas Patry's avatar
Nicolas Patry committed
1184
1185
    #[schema(example = "\"David\"")]
    name: Option<String>,
drbh's avatar
drbh committed
1186
1187
}

1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
#[serde(untagged)]
pub enum MessageContent {
    SingleText(String),
    MultipleChunks(Vec<MessageChunk>),
}

// Pushing a chunk to a single text message will convert it to a multiple chunks message
impl MessageContent {
    pub fn push(&mut self, chunk: MessageChunk) {
        match self {
            MessageContent::SingleText(text) => {
drbh's avatar
drbh committed
1200
1201
1202
1203
                *self = MessageContent::MultipleChunks(vec![
                    MessageChunk::Text { text: text.clone() },
                    chunk,
                ]);
Nicolas Patry's avatar
Nicolas Patry committed
1204
            }
1205
1206
1207
1208
            MessageContent::MultipleChunks(chunks) => {
                chunks.push(chunk);
            }
        }
drbh's avatar
drbh committed
1209
1210
1211
    }
}

Nicolas Patry's avatar
Nicolas Patry committed
1212
1213
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct TextMessage {
1214
1215
1216
    #[schema(example = "user")]
    pub role: String,
    #[schema(example = "My name is David and I")]
Nicolas Patry's avatar
Nicolas Patry committed
1217
1218
1219
1220
1221
1222
1223
    pub content: String,
}

impl From<Message> for TextMessage {
    fn from(value: Message) -> Self {
        TextMessage {
            role: value.role,
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
            content: match value.content {
                MessageContent::SingleText(text) => text,
                MessageContent::MultipleChunks(chunks) => chunks
                    .into_iter()
                    .map(|chunk| match chunk {
                        MessageChunk::Text { text } => text,
                        MessageChunk::ImageUrl { image_url } => format!("![]({})", image_url.url),
                    })
                    .collect::<Vec<_>>()
                    .join(""),
            },
Nicolas Patry's avatar
Nicolas Patry committed
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
        }
    }
}

#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct ToolCallMessage {
    #[schema(example = "assistant")]
    role: String,
    tool_calls: Vec<ToolCall>,
}

#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
#[serde(untagged)]
pub(crate) enum OutputMessage {
    ChatMessage(TextMessage),
    ToolCall(ToolCallMessage),
1251
1252
}

1253
#[derive(Clone, Debug, Deserialize, ToSchema)]
1254
#[cfg_attr(test, derive(PartialEq))]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1255
pub(crate) struct GenerateRequest {
1256
    #[schema(example = "My name is Olivier and I")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1257
1258
1259
    pub inputs: String,
    #[serde(default = "default_parameters")]
    pub parameters: GenerateParameters,
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269

    /// This is used internally because some requests
    /// already contain the templated input therefore
    /// we shouldn't add the special tokens.
    #[serde(default = "default_true", skip)]
    pub add_special_tokens: bool,
}

fn default_true() -> bool {
    true
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1270
1271
}

1272
1273
1274
1275
1276
1277
1278
#[derive(Clone, Debug, Deserialize, ToSchema)]
pub(crate) struct CompatGenerateRequest {
    #[schema(example = "My name is Olivier and I")]
    pub inputs: String,
    #[serde(default = "default_parameters")]
    pub parameters: GenerateParameters,
    #[serde(default)]
OlivierDehaene's avatar
OlivierDehaene committed
1279
    #[schema(default = "false")]
1280
1281
1282
1283
1284
1285
1286
    pub stream: bool,
}

impl From<CompatGenerateRequest> for GenerateRequest {
    fn from(req: CompatGenerateRequest) -> Self {
        Self {
            inputs: req.inputs,
1287
            add_special_tokens: true,
1288
1289
1290
1291
1292
            parameters: req.parameters,
        }
    }
}

1293
1294
1295
#[derive(Debug, Serialize, ToSchema)]
pub struct PrefillToken {
    #[schema(example = 0)]
Nicolas Patry's avatar
Nicolas Patry committed
1296
    pub id: u32,
1297
    #[schema(example = "test")]
Nicolas Patry's avatar
Nicolas Patry committed
1298
    pub text: String,
1299
    #[schema(nullable = true, example = - 0.34)]
Nicolas Patry's avatar
Nicolas Patry committed
1300
    pub logprob: f32,
1301
1302
}

1303
#[derive(Debug, Serialize, ToSchema, Clone)]
1304
1305
pub struct Token {
    #[schema(example = 0)]
Nicolas Patry's avatar
Nicolas Patry committed
1306
    pub id: u32,
1307
    #[schema(example = "test")]
Nicolas Patry's avatar
Nicolas Patry committed
1308
    pub text: String,
1309
    #[schema(nullable = true, example = - 0.34)]
Nicolas Patry's avatar
Nicolas Patry committed
1310
    pub logprob: f32,
1311
    #[schema(example = "false")]
Nicolas Patry's avatar
Nicolas Patry committed
1312
    pub special: bool,
1313
1314
}

1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
#[derive(Debug, Serialize, ToSchema)]
pub struct SimpleToken {
    #[schema(example = 0)]
    id: u32,
    #[schema(example = "test")]
    text: String,
    #[schema(example = 0)]
    start: usize,
    #[schema(example = 2)]
    stop: usize,
}

1327
#[derive(Debug, Serialize, ToSchema, Clone)]
1328
#[serde(rename_all(serialize = "snake_case"))]
1329
#[schema(example = "Length")]
Nicolas Patry's avatar
Nicolas Patry committed
1330
pub enum FinishReason {
1331
1332
1333
1334
1335
1336
1337
1338
    #[schema(rename = "length")]
    Length,
    #[serde(rename = "eos_token")]
    #[schema(rename = "eos_token")]
    EndOfSequenceToken,
    #[schema(rename = "stop_sequence")]
    StopSequence,
}
1339

1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
impl std::fmt::Display for FinishReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FinishReason::Length => write!(f, "length"),
            FinishReason::EndOfSequenceToken => write!(f, "eos_token"),
            FinishReason::StopSequence => write!(f, "stop_sequence"),
        }
    }
}

1350
1351
1352
1353
1354
1355
1356
1357
1358
impl FinishReason {
    pub fn format(&self, use_stop: bool) -> String {
        match self {
            FinishReason::EndOfSequenceToken if use_stop => "stop".to_string(),
            _ => self.to_string(),
        }
    }
}

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
#[derive(Serialize, ToSchema)]
pub(crate) struct BestOfSequence {
    #[schema(example = "test")]
    pub generated_text: String,
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
    pub generated_tokens: u32,
    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,
    pub prefill: Vec<PrefillToken>,
    pub tokens: Vec<Token>,
Nicolas Patry's avatar
Nicolas Patry committed
1371
1372
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
1373
1374
}

1375
#[derive(Serialize, ToSchema)]
OlivierDehaene's avatar
OlivierDehaene committed
1376
pub(crate) struct Details {
1377
1378
1379
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
OlivierDehaene's avatar
OlivierDehaene committed
1380
    pub generated_tokens: u32,
1381
    #[schema(nullable = true, example = 42)]
1382
    pub seed: Option<u64>,
1383
1384
    pub prefill: Vec<PrefillToken>,
    pub tokens: Vec<Token>,
1385
1386
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_of_sequences: Option<Vec<BestOfSequence>>,
Nicolas Patry's avatar
Nicolas Patry committed
1387
1388
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
OlivierDehaene's avatar
OlivierDehaene committed
1389
1390
}

1391
#[derive(Serialize, ToSchema)]
1392
pub(crate) struct GenerateResponse {
1393
    #[schema(example = "test")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1394
    pub generated_text: String,
OlivierDehaene's avatar
OlivierDehaene committed
1395
1396
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Details>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1397
}
1398

1399
1400
1401
1402
1403
1404
#[derive(Serialize, ToSchema)]
pub(crate) struct ChatTokenizeResponse {
    pub(crate) tokenize_response: TokenizeResponse,
    pub(crate) templated_text: String,
}

1405
1406
1407
1408
#[derive(Serialize, ToSchema)]
#[serde(transparent)]
pub(crate) struct TokenizeResponse(Vec<SimpleToken>);

1409
1410
1411
1412
1413
1414
#[derive(Serialize, ToSchema)]
pub(crate) struct StreamDetails {
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
    pub generated_tokens: u32,
1415
    #[schema(nullable = true, example = 42)]
1416
    pub seed: Option<u64>,
1417
1418
    #[schema(example = 1)]
    pub input_length: u32,
1419
1420
1421
}

#[derive(Serialize, ToSchema)]
1422
pub(crate) struct StreamResponse {
1423
    pub index: u32,
1424
    pub token: Token,
Nicolas Patry's avatar
Nicolas Patry committed
1425
1426
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Token>,
1427
    #[schema(nullable = true, default = "null", example = "test")]
1428
    pub generated_text: Option<String>,
1429
1430
    #[schema(nullable = true, default = "null")]
    pub details: Option<StreamDetails>,
1431
1432
}

1433
#[derive(Serialize, ToSchema)]
1434
1435
pub(crate) struct ErrorResponse {
    pub error: String,
1436
    pub error_type: String,
1437
}
1438

drbh's avatar
drbh committed
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
#[derive(Serialize, Deserialize, ToSchema)]
pub(crate) struct ModelInfo {
    #[schema(example = "gpt2")]
    pub id: String,
    #[schema(example = "model")]
    pub object: String,
    #[schema(example = 1686935002)]
    pub created: u64,
    #[schema(example = "openai")]
    pub owned_by: String,
}

#[derive(Serialize, Deserialize, ToSchema)]
pub(crate) struct ModelsInfo {
    #[schema(example = "list")]
    pub object: String,
    pub data: Vec<ModelInfo>,
}

impl Default for ModelsInfo {
    fn default() -> Self {
        ModelsInfo {
            object: "list".to_string(),
            data: Vec::new(),
        }
    }
}

1467
#[cfg(test)]
1468
mod tests {
1469
    use super::*;
Nicolas Patry's avatar
Nicolas Patry committed
1470
    use serde_json::json;
1471

1472
    pub(crate) fn get_tokenizer() -> Tokenizer {
1473
1474
1475
        let api = hf_hub::api::sync::Api::new().unwrap();
        let repo = api.model("gpt2".to_string());
        let filename = repo.get("tokenizer.json").unwrap();
1476
        Tokenizer::Rust(tokenizers::Tokenizer::from_file(filename).unwrap())
1477
    }
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491

    #[test]
    fn test_hub_nested_tokens_tokenizer_config() {
        // this is a subset of the tokenizer.json file
        // in this case we expect the tokens to be encoded as simple strings
        let json_content = r#"{
            "chat_template": "test",
            "bos_token": "<|begin▁of▁sentence|>",
            "eos_token": "<|end▁of▁sentence|>"
        }"#;

        let config: HubTokenizerConfig = serde_json::from_str(json_content).unwrap();

        // check that we successfully parsed the tokens
1492
1493
1494
1495
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1496
1497
        assert_eq!(
            config.bos_token,
1498
1499
1500
1501
1502
1503
1504
1505
1506
            Some(TokenizerConfigToken::String(
                "<|begin▁of▁sentence|>".to_string()
            ))
        );
        assert_eq!(
            config.eos_token,
            Some(TokenizerConfigToken::String(
                "<|end▁of▁sentence|>".to_string()
            ))
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
        );

        // in this case we expect the tokens to be encoded as structured tokens
        // we want the content of the structured token
        let json_content = r#"{
            "chat_template": "test",
            "bos_token": {
              "__type": "AddedToken",
              "content": "<|begin▁of▁sentence|>",
              "lstrip": false,
              "normalized": true,
              "rstrip": false,
              "single_word": false
            },
            "eos_token": {
              "__type": "AddedToken",
              "content": "<|end▁of▁sentence|>",
              "lstrip": false,
              "normalized": true,
              "rstrip": false,
              "single_word": false
            }
        }"#;

        let config: HubTokenizerConfig = serde_json::from_str(json_content).unwrap();

        // check that we successfully parsed the tokens
1534
1535
1536
1537
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1538
1539
        assert_eq!(
            config.bos_token,
1540
1541
1542
1543
1544
1545
1546
1547
1548
            Some(TokenizerConfigToken::Object {
                content: "<|begin▁of▁sentence|>".to_string()
            })
        );
        assert_eq!(
            config.eos_token,
            Some(TokenizerConfigToken::Object {
                content: "<|end▁of▁sentence|>".to_string()
            })
1549
1550
        );
    }
Nicolas Patry's avatar
Nicolas Patry committed
1551
1552
1553

    #[test]
    fn test_chat_simple_string() {
Nicolas Patry's avatar
Nicolas Patry committed
1554
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1555
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1556
1557
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1558
                "content": "What is Deep Learning?"
Nicolas Patry's avatar
Nicolas Patry committed
1559
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1560
1561
1562
1563
1564
1565
1566
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message {
                role: "user".to_string(),
1567
                content: MessageContent::SingleText("What is Deep Learning?".to_string()),
Nicolas Patry's avatar
Nicolas Patry committed
1568
1569
1570
1571
1572
                name: None
            }
        );
    }

drbh's avatar
drbh committed
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
    #[test]
    fn test_message_content_append() {
        let mut content = MessageContent::SingleText("Initial text".to_string());
        let chunk = MessageChunk::Text {
            text: "Additional text".to_string(),
        };

        content.push(chunk);

        match content {
            MessageContent::MultipleChunks(chunks) => {
                assert_eq!(chunks.len(), 2);
                assert_eq!(
                    chunks[0],
                    MessageChunk::Text {
                        text: "Initial text".to_string()
                    }
                );
                assert_eq!(
                    chunks[1],
                    MessageChunk::Text {
                        text: "Additional text".to_string()
                    }
                );
            }
            _ => panic!("Expected MultipleChunks, but got a different variant"),
        }
    }

Nicolas Patry's avatar
Nicolas Patry committed
1602
1603
    #[test]
    fn test_chat_request() {
Nicolas Patry's avatar
Nicolas Patry committed
1604
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1605
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1606
1607
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1608
1609
                "content": [
                    {"type": "text", "text": "Whats in this image?"},
Nicolas Patry's avatar
Nicolas Patry committed
1610
                    {"type": "image_url", "image_url": {"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png"}},
Nicolas Patry's avatar
Nicolas Patry committed
1611
                ]
Nicolas Patry's avatar
Nicolas Patry committed
1612
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1613
1614
1615
1616
1617
1618
1619
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message{
                role: "user".to_string(),
1620
1621
1622
1623
                content: MessageContent::MultipleChunks(vec![
                    MessageChunk::Text { text: "Whats in this image?".to_string() },
                    MessageChunk::ImageUrl { image_url: Url { url: "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png".to_string() }},
                ]),
Nicolas Patry's avatar
Nicolas Patry committed
1624
1625
1626
1627
                name: None
            }
        );
    }
Nicolas Patry's avatar
Nicolas Patry committed
1628
1629
1630
1631
1632

    #[test]
    fn text_message_convert() {
        let message = Message{
                role: "user".to_string(),
1633
1634
1635
1636
                content: MessageContent::MultipleChunks(vec![
                    MessageChunk::Text { text: "Whats in this image?".to_string() },
                    MessageChunk::ImageUrl { image_url: Url { url: "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png".to_string() } }
                ]),
Nicolas Patry's avatar
Nicolas Patry committed
1637
1638
1639
1640
1641
                name: None
            };
        let textmsg: TextMessage = message.into();
        assert_eq!(textmsg.content, "Whats in this image?![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png)");
    }
Nicolas Patry's avatar
Nicolas Patry committed
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662

    #[test]
    fn test_chat_stream_options() {
        let json = json!({
            "model": "",
            "stream_options": {"include_usage": true},
            "messages": [{
                "role": "user",
                "content": "Hello"
            }]
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert!(matches!(
            request.stream_options,
            Some(StreamOptions {
                include_usage: true
            })
        ));
    }

Nicolas Patry's avatar
Nicolas Patry committed
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
    #[test]
    fn openai_output() {
        let message = OutputMessage::ChatMessage(TextMessage {
            role: "assistant".to_string(),
            content: "This is the answer".to_string(),
        });
        let serialized = serde_json::to_string(&message).unwrap();
        assert_eq!(
            serialized,
            r#"{"role":"assistant","content":"This is the answer"}"#
        );

        let message = OutputMessage::ToolCall(ToolCallMessage {
            role: "assistant".to_string(),
            tool_calls: vec![ToolCall {
                id: "0".to_string(),
                r#type: "function".to_string(),
                function: FunctionDefinition {
                    description: None,
                    name: "myfn".to_string(),
                    arguments: json!({
                        "format": "csv"
                    }),
                },
            }],
        });
        let serialized = serde_json::to_string(&message).unwrap();
        assert_eq!(
            serialized,
            r#"{"role":"assistant","tool_calls":[{"id":"0","type":"function","function":{"description":null,"name":"myfn","arguments":{"format":"csv"}}}]}"#
        );
    }
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731

    #[test]
    fn tool_choice_formats() {
        #[derive(Deserialize)]
        struct TestRequest {
            tool_choice: ToolChoice,
        }

        let de_none: TestRequest = serde_json::from_str(r#"{"tool_choice":"none"}"#).unwrap();
        assert_eq!(de_none.tool_choice, ToolChoice::NoTool);

        let de_auto: TestRequest = serde_json::from_str(r#"{"tool_choice":"auto"}"#).unwrap();
        assert_eq!(de_auto.tool_choice, ToolChoice::Auto);

        let de_required: TestRequest =
            serde_json::from_str(r#"{"tool_choice":"required"}"#).unwrap();
        assert_eq!(de_required.tool_choice, ToolChoice::Required);

        let de_named: TestRequest = serde_json::from_str(r#"{"tool_choice":"myfn"}"#).unwrap();
        assert_eq!(
            de_named.tool_choice,
            ToolChoice::Function(FunctionName {
                name: "myfn".to_string(),
            })
        );

        let de_openai_named: TestRequest = serde_json::from_str(
            r#"{"tool_choice":{"type":"function","function":{"name":"myfn"}}}"#,
        )
        .unwrap();
        assert_eq!(
            de_openai_named.tool_choice,
            ToolChoice::Function(FunctionName {
                name: "myfn".to_string(),
            })
        );
    }
1732
}