lib.rs 49.3 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

Nicolas Patry's avatar
Nicolas Patry committed
15
16
use crate::infer::{Infer, InferError};
use crate::server::prepare_chat_input;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
17
use serde::{Deserialize, Serialize};
Nicolas Patry's avatar
Nicolas Patry committed
18
use tracing::warn;
19
use utoipa::ToSchema;
Olivier Dehaene's avatar
Olivier Dehaene committed
20
use validation::Validation;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
21

22
23
/// Hub type
#[derive(Clone, Debug, Deserialize)]
24
pub struct HubModelInfo {
25
26
27
28
29
30
    #[serde(rename(deserialize = "id"))]
    pub model_id: String,
    pub sha: Option<String>,
    pub pipeline_tag: Option<String>,
}

31
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
32
33
34
35
36
pub struct ChatTemplate {
    name: String,
    template: String,
}

37
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
38
39
40
41
42
43
#[serde(untagged)]
pub enum ChatTemplateVersions {
    Single(String),
    Multiple(Vec<ChatTemplate>),
}

44
45
use std::path::Path;

46
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
47
pub struct HubTokenizerConfig {
48
    pub chat_template: Option<ChatTemplateVersions>,
49
    pub completion_template: Option<String>,
50
51
    pub bos_token: Option<TokenizerConfigToken>,
    pub eos_token: Option<TokenizerConfigToken>,
52
53
54
    pub tokenizer_class: Option<String>,
    pub add_bos_token: Option<bool>,
    pub add_eos_token: Option<bool>,
55
56
57
}

impl HubTokenizerConfig {
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    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,
        }
78
79
80
    }
}

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#[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
100
101
102
103
104
105
106
107
#[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 {
108
109
110
111
    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
112
113
114
    }
}

115
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
Nicolas Patry's avatar
Nicolas Patry committed
116
#[cfg_attr(test, derive(PartialEq))]
drbh's avatar
drbh committed
117
118
#[serde(tag = "type", content = "value")]
pub(crate) enum GrammarType {
119
120
121
122
123
    /// 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
124
    #[serde(alias = "json_object")]
125
126
    #[schema(example = json ! ({"properties": {"location":{"type": "string"}}}))]
    Json(serde_json::Value),
drbh's avatar
drbh committed
127
128
129
130
    #[serde(rename = "regex")]
    Regex(String),
}

131
132
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct Info {
133
    /// Model info
134
135
136
137
    #[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
138
139
140
141
    // #[schema(example = "torch.float16")]
    // pub model_dtype: String,
    // #[schema(example = "cuda")]
    // pub model_device_type: String,
142
143
    #[schema(nullable = true, example = "text-generation")]
    pub model_pipeline_tag: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
144

145
146
147
148
149
150
151
152
    /// 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
153
    pub max_input_tokens: usize,
154
155
156
157
    #[schema(example = "2048")]
    pub max_total_tokens: usize,
    #[schema(example = "2")]
    pub validation_workers: usize,
158
159
    #[schema(example = "32")]
    pub max_client_batch_size: usize,
Nicolas Patry's avatar
Nicolas Patry committed
160

161
    /// Router Info
162
163
    #[schema(example = "text-generation-router")]
    pub router: &'static str,
164
165
166
167
    #[schema(example = "0.5.0")]
    pub version: &'static str,
    #[schema(nullable = true, example = "null")]
    pub sha: Option<&'static str>,
168
169
    #[schema(nullable = true, example = "null")]
    pub docker_label: Option<&'static str>,
170
171
}

drbh's avatar
drbh committed
172
#[derive(Clone, Debug, Deserialize, ToSchema, Default)]
Nicolas Patry's avatar
Nicolas Patry committed
173
#[cfg_attr(test, derive(PartialEq))]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
174
pub(crate) struct GenerateParameters {
175
    /// Generate best_of sequences and return the one if the highest token logprobs.
176
177
178
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 1)]
    pub best_of: Option<usize>,
179
180

    /// The value used to module the logits distribution.
181
182
183
184
185
186
187
188
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 0.5
    )]
    pub temperature: Option<f32>,
189
190
191

    /// The parameter for repetition penalty. 1.0 means no penalty.
    /// See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
192
193
194
195
196
197
198
199
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 1.03
    )]
    pub repetition_penalty: Option<f32>,
200
201
202
203

    /// 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.
204
    #[serde(default)]
205
206
207
208
209
210
211
    #[schema(
        exclusive_minimum = -2.0,
        nullable = true,
        default = "null",
        example = 0.1
    )]
    pub frequency_penalty: Option<f32>,
212
213

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

    /// Top-p value for nucleus sampling.
219
220
221
222
223
224
225
226
227
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub top_p: Option<f32>,
228
229
230

    /// Typical Decoding mass
    /// See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information.
231
    #[serde(default)]
232
233
234
235
236
237
238
239
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub typical_p: Option<f32>,
240
241

    /// Activate logits sampling.
242
    #[serde(default)]
243
    #[schema(default = "false", example = true)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
244
    pub do_sample: bool,
245
246

    /// Maximum number of tokens to generate.
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
247
    #[serde(default = "default_max_new_tokens")]
248
    #[schema(nullable = true, default = "100", example = "20")]
249
    pub max_new_tokens: Option<u32>,
250
251

    /// Whether to prepend the prompt to the generated text
OlivierDehaene's avatar
OlivierDehaene committed
252
    #[serde(default)]
253
    #[schema(nullable = true, default = "null", example = false)]
254
    pub return_full_text: Option<bool>,
255
256

    /// Stop generating tokens if a member of `stop` is generated.
257
    #[serde(default)]
258
    #[schema(inline, max_items = 4, example = json ! (["photographer"]))]
259
    pub stop: Vec<String>,
260
261

    /// Truncate inputs tokens to the given size.
OlivierDehaene's avatar
OlivierDehaene committed
262
    #[serde(default)]
263
    #[schema(nullable = true, default = "null", example = "null")]
264
    pub truncate: Option<usize>,
265
266

    /// Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226).
267
    #[serde(default)]
268
269
    #[schema(default = "false", example = true)]
    pub watermark: bool,
270
271

    /// Whether to return generation details.
272
    #[serde(default)]
273
    #[schema(default = "true")]
OlivierDehaene's avatar
OlivierDehaene committed
274
    pub details: bool,
275
276

    /// Whether to return decoder input token logprobs and ids.
277
    #[serde(default)]
278
    #[schema(default = "false")]
279
    pub decoder_input_details: bool,
280
281

    /// Random sampling seed.
282
    #[serde(default)]
283
284
285
286
287
288
    #[schema(
        exclusive_minimum = 0,
        nullable = true,
        default = "null",
        example = "null"
    )]
289
    pub seed: Option<u64>,
290
291

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

    /// Grammar constraints for the generation.
drbh's avatar
drbh committed
297
    #[serde(default)]
298
    #[schema(nullable = true, default = "null", example = "null")]
drbh's avatar
drbh committed
299
    pub grammar: Option<GrammarType>,
drbh's avatar
drbh committed
300
301
302
303
304

    /// 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
305
306
}

307
fn default_max_new_tokens() -> Option<u32> {
308
    Some(100)
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
309
310
311
312
}

fn default_parameters() -> GenerateParameters {
    GenerateParameters {
313
        best_of: None,
314
315
        temperature: None,
        repetition_penalty: None,
316
        frequency_penalty: None,
317
318
        top_k: None,
        top_p: None,
319
        typical_p: None,
320
        do_sample: true,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
321
        max_new_tokens: default_max_new_tokens(),
322
        return_full_text: None,
323
        stop: Vec::new(),
324
        truncate: None,
325
        watermark: false,
OlivierDehaene's avatar
OlivierDehaene committed
326
        details: false,
327
        decoder_input_details: false,
328
        seed: None,
Nicolas Patry's avatar
Nicolas Patry committed
329
        top_n_tokens: None,
drbh's avatar
drbh committed
330
        grammar: None,
drbh's avatar
drbh committed
331
        adapter_id: None,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
332
333
334
    }
}

335
336
337
338
339
340
341
342
343
344
345
346
347
#[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;
348

349
    fn try_from(value: PromptDeserializer) -> Result<Self, Self::Error> {
350
        match value {
351
352
353
354
355
356
357
358
359
360
361
            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))
                }
            }
362
363
364
365
        }
    }
}

366
367
368
369
370
#[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.
371
    pub model: Option<String>,
372
373
374

    /// The prompt to generate completions for.
    #[schema(example = "What is Deep Learning?")]
375
    pub prompt: Prompt,
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

    /// The maximum number of tokens that can be generated in the chat completion.
    #[serde(default)]
    #[schema(default = "32")]
    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>,
413
414
415
416
417

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

420
421
422
423
424
425
426
427
428
#[derive(Clone, Serialize, ToSchema)]
#[serde(tag = "object")]
enum Completion {
    #[serde(rename = "text_completion")]
    Chunk(Chunk),
    #[serde(rename = "text_completion")]
    Final(CompletionFinal),
}

429
#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
430
pub(crate) struct CompletionFinal {
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    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,
}

449
450
451
452
453
454
455
456
457
#[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,
}

458
#[derive(Clone, Deserialize, Serialize, ToSchema)]
459
460
pub(crate) struct ChatCompletion {
    pub id: String,
461
    #[schema(example = "1706270835")]
462
    pub created: u64,
463
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
464
465
466
467
468
469
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionComplete>,
    pub usage: Usage,
}

470
#[derive(Clone, Deserialize, Serialize, ToSchema)]
471
472
pub(crate) struct ChatCompletionComplete {
    pub index: u32,
Nicolas Patry's avatar
Nicolas Patry committed
473
    pub message: OutputMessage,
474
    pub logprobs: Option<ChatCompletionLogprobs>,
475
476
477
    pub finish_reason: String,
}

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
#[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;
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520

        // 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
521
522
523
524
525
526
                        .into_iter()
                        .map(|t| ChatCompletionTopLogprob {
                            token: t.text,
                            logprob: t.logprob,
                        })
                        .collect(),
527
528
529
530
531
532
                    None => vec![], // Handle the case where there are no top tokens
                },
            })
            .collect();

        Self { content }
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
    }
}

#[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,
}

549
#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
550
551
552
553
554
555
pub(crate) struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

556
557
558
559
560
561
562
563
564
#[derive(Clone, Serialize, ToSchema)]
#[serde(tag = "object")]
enum CompletionType {
    #[serde(rename = "chat.completion.chunk")]
    ChatCompletionChunk(ChatCompletionChunk),
    #[serde(rename = "chat.completion")]
    ChatCompletion(ChatCompletion),
}

565
566
567
568
impl ChatCompletion {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
drbh's avatar
drbh committed
569
        output: Option<String>,
570
571
572
        created: u64,
        details: Details,
        return_logprobs: bool,
573
        tool_calls: Option<Vec<ToolCall>>,
574
    ) -> Self {
Nicolas Patry's avatar
Nicolas Patry committed
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
        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(),
                })
            }
        };
599
600
601
602
603
604
605
        Self {
            id: String::new(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionComplete {
                index: 0,
Nicolas Patry's avatar
Nicolas Patry committed
606
                message,
607
                logprobs: return_logprobs
608
                    .then(|| ChatCompletionLogprobs::from((details.tokens, details.top_tokens))),
609
                finish_reason: details.finish_reason.format(true),
610
611
612
613
614
615
616
617
618
            }],
            usage: Usage {
                prompt_tokens: details.prefill.len() as u32,
                completion_tokens: details.generated_tokens,
                total_tokens: details.prefill.len() as u32 + details.generated_tokens,
            },
        }
    }
}
619
#[derive(Clone, Serialize, ToSchema)]
620
621
pub(crate) struct ChatCompletionChunk {
    pub id: String,
622
    #[schema(example = "1706270978")]
623
    pub created: u64,
624
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
625
626
627
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionChoice>,
Nicolas Patry's avatar
Nicolas Patry committed
628
    pub usage: Option<Usage>,
629
630
}

631
#[derive(Clone, Serialize, ToSchema)]
632
633
634
pub(crate) struct ChatCompletionChoice {
    pub index: u32,
    pub delta: ChatCompletionDelta,
635
    pub logprobs: Option<ChatCompletionLogprobs>,
636
637
638
    pub finish_reason: Option<String>,
}

Nicolas Patry's avatar
Nicolas Patry committed
639
640
641
642
643
644
645
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct ToolCallDelta {
    #[schema(example = "assistant")]
    role: String,
    tool_calls: DeltaToolCall,
}

646
647
#[derive(Clone, Debug, Serialize, ToSchema)]
#[serde(untagged)]
Nicolas Patry's avatar
Nicolas Patry committed
648
649
650
enum ChatCompletionDelta {
    Chat(TextMessage),
    Tool(ToolCallDelta),
drbh's avatar
drbh committed
651
652
}

Nicolas Patry's avatar
Nicolas Patry committed
653
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
654
655
656
657
658
659
660
pub(crate) struct DeltaToolCall {
    pub index: u32,
    pub id: String,
    pub r#type: String,
    pub function: Function,
}

Nicolas Patry's avatar
Nicolas Patry committed
661
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
662
663
664
pub(crate) struct Function {
    pub name: Option<String>,
    pub arguments: String,
665
666
}

drbh's avatar
drbh committed
667
#[allow(clippy::too_many_arguments)]
668
669
670
671
impl ChatCompletionChunk {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
drbh's avatar
drbh committed
672
673
        delta: Option<String>,
        tool_calls: Option<Vec<String>>,
674
        created: u64,
675
        logprobs: Option<ChatCompletionLogprobs>,
676
        finish_reason: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
677
        usage: Option<Usage>,
678
    ) -> Self {
679
        let delta = match (delta, tool_calls) {
Nicolas Patry's avatar
Nicolas Patry committed
680
681
682
683
684
685
686
            (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 {
687
688
689
690
691
692
693
                    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
694
695
696
697
698
699
                },
            }),
            (None, None) => ChatCompletionDelta::Chat(TextMessage {
                role: "assistant".to_string(),
                content: "".to_string(),
            }),
700
        };
701
702
703
704
705
706
        Self {
            id: String::new(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionChoice {
707
                index: 0,
708
                delta,
709
710
711
                logprobs,
                finish_reason,
            }],
Nicolas Patry's avatar
Nicolas Patry committed
712
            usage,
713
714
715
716
717
        }
    }
}

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

724
    /// A list of messages comprising the conversation so far.
drbh's avatar
drbh committed
725
    #[schema(example = "[{\"role\": \"user\", \"content\": \"What is Deep Learning?\"}]")]
726
727
728
729
730
    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)]
731
    #[schema(example = "1.0")]
732
733
734
735
736
737
738
739
740
741
742
743
744
745
    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)]
746
    #[schema(example = "false")]
747
748
749
750
751
    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)]
752
    #[schema(example = "5")]
753
754
755
756
    pub top_logprobs: Option<u32>,

    /// The maximum number of tokens that can be generated in the chat completion.
    #[serde(default)]
757
    #[schema(example = "32")]
758
759
760
761
762
763
    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)]
764
    #[schema(nullable = true, example = "2")]
765
766
767
768
769
    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)]
770
    #[schema(nullable = true, example = 0.1)]
771
772
    pub presence_penalty: Option<f32>,

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

778
779
780
781
782
    #[serde(default = "bool::default")]
    pub stream: bool,

    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,
783
784
785
786
787
788

    /// 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)]
789
    #[schema(nullable = true, example = 1.0)]
790
791
792
793
794
    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)]
795
    #[schema(nullable = true, example = 0.95)]
796
    pub top_p: Option<f32>,
drbh's avatar
drbh committed
797
798
799
800
801
802
803
804

    /// 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
805
    #[serde(default)]
drbh's avatar
drbh committed
806
807
    #[schema(
        nullable = true,
drbh's avatar
drbh committed
808
        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
809
810
811
812
813
814
    )]
    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)]
    #[schema(nullable = true, example = "null")]
drbh's avatar
drbh committed
815
    pub tool_choice: ToolChoice,
drbh's avatar
drbh committed
816
817
818
819
820
821
822

    /// 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>,
823
824
825
826
827

    /// A guideline to be used in the chat_template
    #[serde(default)]
    #[schema(nullable = true, default = "null", example = "null")]
    pub guideline: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
828
829
830
831
832
833
834

    /// 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
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
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,
            guideline,
            presence_penalty,
            frequency_penalty,
            top_p,
            top_logprobs,
            ..
        } = self;

        let repetition_penalty = presence_penalty.map(|x| x + 2.0);
        let max_new_tokens = max_tokens.or(Some(100));
        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),
        };
        let (inputs, grammar, using_tools) = prepare_chat_input(
            infer,
            response_format,
            tools,
            tool_choice,
            &tool_prompt,
            guideline,
            messages,
        )?;

        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
909
#[derive(Clone, Deserialize, ToSchema, Serialize)]
Nicolas Patry's avatar
Nicolas Patry committed
910
#[cfg_attr(test, derive(Debug, PartialEq))]
Nicolas Patry's avatar
Nicolas Patry committed
911
912
913
914
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
915
916
}

drbh's avatar
drbh committed
917
918
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
919
}
920
921

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
922
923
#[schema(example = "auto")]
/// Controls which (if any) tool is called by the model.
924
pub enum ToolType {
925
926
    /// Means the model can pick between generating a message or calling one or more tools.
    #[schema(rename = "auto")]
drbh's avatar
drbh committed
927
    OneOf,
928
929
    /// Means the model will not call any tool and instead generates a message.
    #[schema(rename = "none")]
drbh's avatar
drbh committed
930
    NoTool,
931
932
933
    /// Forces the model to call a specific tool.
    #[schema(rename = "function")]
    Function(FunctionName),
drbh's avatar
drbh committed
934
935
}

936
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
937
938
939
940
pub struct FunctionName {
    pub name: String,
}

drbh's avatar
drbh committed
941
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, ToSchema)]
942
943
#[serde(from = "ToolTypeDeserializer")]
pub struct ToolChoice(pub Option<ToolType>);
drbh's avatar
drbh committed
944

945
946
947
#[derive(Deserialize)]
#[serde(untagged)]
enum ToolTypeDeserializer {
948
    Null,
drbh's avatar
drbh committed
949
950
    String(String),
    ToolType(ToolType),
951
}
drbh's avatar
drbh committed
952

953
954
impl From<ToolTypeDeserializer> for ToolChoice {
    fn from(value: ToolTypeDeserializer) -> Self {
drbh's avatar
drbh committed
955
        match value {
956
            ToolTypeDeserializer::Null => ToolChoice(None),
drbh's avatar
drbh committed
957
958
959
            ToolTypeDeserializer::String(s) => match s.as_str() {
                "none" => ToolChoice(Some(ToolType::NoTool)),
                "auto" => ToolChoice(Some(ToolType::OneOf)),
960
                _ => ToolChoice(Some(ToolType::Function(FunctionName { name: s }))),
drbh's avatar
drbh committed
961
            },
drbh's avatar
drbh committed
962
            ToolTypeDeserializer::ToolType(tool_type) => ToolChoice(Some(tool_type)),
drbh's avatar
drbh committed
963
964
965
966
        }
    }
}

967
#[derive(Debug, Deserialize, Serialize, ToSchema, PartialEq)]
drbh's avatar
drbh committed
968
pub struct JsonSchemaTool {
drbh's avatar
drbh committed
969
970
971
972
973
    #[serde(flatten)]
    functions_map: FunctionsMap,
    properties: Properties,
}

974
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
975
976
977
978
979
struct FunctionsMap {
    #[serde(rename = "$functions")]
    functions: std::collections::HashMap<String, serde_json::Value>,
}

980
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
981
982
983
984
985
struct FunctionRef {
    #[serde(rename = "$ref")]
    ref_path: String,
}

986
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
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
1002
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema, Default, PartialEq)]
drbh's avatar
drbh committed
1003
1004
1005
1006
pub(crate) struct FunctionDefinition {
    #[serde(default)]
    pub description: Option<String>,
    pub name: String,
1007
1008
    #[serde(alias = "parameters")]
    pub arguments: serde_json::Value,
drbh's avatar
drbh committed
1009
1010
1011
}

#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
Nicolas Patry's avatar
Nicolas Patry committed
1012
#[cfg_attr(test, derive(PartialEq))]
drbh's avatar
drbh committed
1013
1014
1015
1016
1017
1018
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,
1019
1020
}

1021
#[derive(Clone, Serialize, Deserialize, Default)]
1022
pub(crate) struct ChatTemplateInputs<'a> {
Nicolas Patry's avatar
Nicolas Patry committed
1023
    messages: Vec<TextMessage>,
1024
1025
    bos_token: Option<&'a str>,
    eos_token: Option<&'a str>,
1026
    add_generation_prompt: bool,
drbh's avatar
drbh committed
1027
    tools: Option<Vec<Tool>>,
1028
    guideline: Option<&'a str>,
1029
1030
}

Nicolas Patry's avatar
Nicolas Patry committed
1031
#[derive(Clone, Deserialize, Serialize, ToSchema, Default, Debug, PartialEq)]
drbh's avatar
drbh committed
1032
pub(crate) struct ToolCall {
1033
    pub id: String,
drbh's avatar
drbh committed
1034
1035
1036
1037
    pub r#type: String,
    pub function: FunctionDefinition,
}

Nicolas Patry's avatar
Nicolas Patry committed
1038
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
1039
pub struct Url {
Nicolas Patry's avatar
Nicolas Patry committed
1040
    url: String,
drbh's avatar
drbh committed
1041
1042
}

Nicolas Patry's avatar
Nicolas Patry committed
1043
1044
1045
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
1046
1047
1048
pub enum MessageChunk {
    Text { text: String },
    ImageUrl { image_url: Url },
Nicolas Patry's avatar
Nicolas Patry committed
1049
1050
1051
1052
1053
1054
1055
}

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

1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
#[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
1074
1075
1076
1077
                *self = MessageContent::MultipleChunks(vec![
                    MessageChunk::Text { text: text.clone() },
                    chunk,
                ]);
Nicolas Patry's avatar
Nicolas Patry committed
1078
            }
1079
1080
1081
1082
            MessageContent::MultipleChunks(chunks) => {
                chunks.push(chunk);
            }
        }
drbh's avatar
drbh committed
1083
1084
1085
    }
}

Nicolas Patry's avatar
Nicolas Patry committed
1086
1087
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct TextMessage {
1088
1089
1090
    #[schema(example = "user")]
    pub role: String,
    #[schema(example = "My name is David and I")]
Nicolas Patry's avatar
Nicolas Patry committed
1091
1092
1093
1094
1095
1096
1097
    pub content: String,
}

impl From<Message> for TextMessage {
    fn from(value: Message) -> Self {
        TextMessage {
            role: value.role,
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
            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
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
        }
    }
}

#[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),
1125
1126
}

1127
#[derive(Clone, Debug, Deserialize, ToSchema)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1128
pub(crate) struct GenerateRequest {
1129
    #[schema(example = "My name is Olivier and I")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1130
1131
1132
    pub inputs: String,
    #[serde(default = "default_parameters")]
    pub parameters: GenerateParameters,
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142

    /// 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
1143
1144
}

1145
1146
1147
1148
1149
1150
1151
#[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
1152
    #[schema(default = "false")]
1153
1154
1155
1156
1157
1158
1159
    pub stream: bool,
}

impl From<CompatGenerateRequest> for GenerateRequest {
    fn from(req: CompatGenerateRequest) -> Self {
        Self {
            inputs: req.inputs,
1160
            add_special_tokens: true,
1161
1162
1163
1164
1165
            parameters: req.parameters,
        }
    }
}

1166
1167
1168
#[derive(Debug, Serialize, ToSchema)]
pub struct PrefillToken {
    #[schema(example = 0)]
Nicolas Patry's avatar
Nicolas Patry committed
1169
    pub id: u32,
1170
    #[schema(example = "test")]
Nicolas Patry's avatar
Nicolas Patry committed
1171
    pub text: String,
1172
    #[schema(nullable = true, example = - 0.34)]
Nicolas Patry's avatar
Nicolas Patry committed
1173
    pub logprob: f32,
1174
1175
}

1176
#[derive(Debug, Serialize, ToSchema, Clone)]
1177
1178
pub struct Token {
    #[schema(example = 0)]
Nicolas Patry's avatar
Nicolas Patry committed
1179
    pub id: u32,
1180
    #[schema(example = "test")]
Nicolas Patry's avatar
Nicolas Patry committed
1181
    pub text: String,
1182
    #[schema(nullable = true, example = - 0.34)]
Nicolas Patry's avatar
Nicolas Patry committed
1183
    pub logprob: f32,
1184
    #[schema(example = "false")]
Nicolas Patry's avatar
Nicolas Patry committed
1185
    pub special: bool,
1186
1187
}

1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
#[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,
}

OlivierDehaene's avatar
OlivierDehaene committed
1200
#[derive(Debug, Serialize, ToSchema)]
1201
#[serde(rename_all(serialize = "snake_case"))]
1202
#[schema(example = "Length")]
Nicolas Patry's avatar
Nicolas Patry committed
1203
pub enum FinishReason {
1204
1205
1206
1207
1208
1209
1210
1211
    #[schema(rename = "length")]
    Length,
    #[serde(rename = "eos_token")]
    #[schema(rename = "eos_token")]
    EndOfSequenceToken,
    #[schema(rename = "stop_sequence")]
    StopSequence,
}
1212

1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
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"),
        }
    }
}

1223
1224
1225
1226
1227
1228
1229
1230
1231
impl FinishReason {
    pub fn format(&self, use_stop: bool) -> String {
        match self {
            FinishReason::EndOfSequenceToken if use_stop => "stop".to_string(),
            _ => self.to_string(),
        }
    }
}

1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
#[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
1244
1245
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
1246
1247
}

1248
#[derive(Serialize, ToSchema)]
OlivierDehaene's avatar
OlivierDehaene committed
1249
pub(crate) struct Details {
1250
1251
1252
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
OlivierDehaene's avatar
OlivierDehaene committed
1253
    pub generated_tokens: u32,
1254
    #[schema(nullable = true, example = 42)]
1255
    pub seed: Option<u64>,
1256
1257
    pub prefill: Vec<PrefillToken>,
    pub tokens: Vec<Token>,
1258
1259
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_of_sequences: Option<Vec<BestOfSequence>>,
Nicolas Patry's avatar
Nicolas Patry committed
1260
1261
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
OlivierDehaene's avatar
OlivierDehaene committed
1262
1263
}

1264
#[derive(Serialize, ToSchema)]
1265
pub(crate) struct GenerateResponse {
1266
    #[schema(example = "test")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1267
    pub generated_text: String,
OlivierDehaene's avatar
OlivierDehaene committed
1268
1269
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Details>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1270
}
1271

1272
1273
1274
1275
1276
1277
#[derive(Serialize, ToSchema)]
pub(crate) struct ChatTokenizeResponse {
    pub(crate) tokenize_response: TokenizeResponse,
    pub(crate) templated_text: String,
}

1278
1279
1280
1281
#[derive(Serialize, ToSchema)]
#[serde(transparent)]
pub(crate) struct TokenizeResponse(Vec<SimpleToken>);

1282
1283
1284
1285
1286
1287
#[derive(Serialize, ToSchema)]
pub(crate) struct StreamDetails {
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
    pub generated_tokens: u32,
1288
    #[schema(nullable = true, example = 42)]
1289
    pub seed: Option<u64>,
1290
1291
    #[schema(example = 1)]
    pub input_length: u32,
1292
1293
1294
}

#[derive(Serialize, ToSchema)]
1295
pub(crate) struct StreamResponse {
1296
    pub index: u32,
1297
    pub token: Token,
Nicolas Patry's avatar
Nicolas Patry committed
1298
1299
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Token>,
1300
    #[schema(nullable = true, default = "null", example = "test")]
1301
    pub generated_text: Option<String>,
1302
1303
    #[schema(nullable = true, default = "null")]
    pub details: Option<StreamDetails>,
1304
1305
}

1306
#[derive(Serialize, ToSchema)]
1307
1308
pub(crate) struct ErrorResponse {
    pub error: String,
1309
    pub error_type: String,
1310
}
1311

drbh's avatar
drbh committed
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
#[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(),
        }
    }
}

1340
#[cfg(test)]
1341
mod tests {
1342
    use super::*;
Nicolas Patry's avatar
Nicolas Patry committed
1343
    use serde_json::json;
1344
1345
    use tokenizers::Tokenizer;

1346
    pub(crate) async fn get_tokenizer() -> Tokenizer {
1347
1348
1349
1350
        let api = hf_hub::api::sync::Api::new().unwrap();
        let repo = api.model("gpt2".to_string());
        let filename = repo.get("tokenizer.json").unwrap();
        Tokenizer::from_file(filename).unwrap()
1351
    }
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365

    #[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
1366
1367
1368
1369
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1370
1371
        assert_eq!(
            config.bos_token,
1372
1373
1374
1375
1376
1377
1378
1379
1380
            Some(TokenizerConfigToken::String(
                "<|begin▁of▁sentence|>".to_string()
            ))
        );
        assert_eq!(
            config.eos_token,
            Some(TokenizerConfigToken::String(
                "<|end▁of▁sentence|>".to_string()
            ))
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
        );

        // 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
1408
1409
1410
1411
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1412
1413
        assert_eq!(
            config.bos_token,
1414
1415
1416
1417
1418
1419
1420
1421
1422
            Some(TokenizerConfigToken::Object {
                content: "<|begin▁of▁sentence|>".to_string()
            })
        );
        assert_eq!(
            config.eos_token,
            Some(TokenizerConfigToken::Object {
                content: "<|end▁of▁sentence|>".to_string()
            })
1423
1424
        );
    }
Nicolas Patry's avatar
Nicolas Patry committed
1425
1426
1427

    #[test]
    fn test_chat_simple_string() {
Nicolas Patry's avatar
Nicolas Patry committed
1428
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1429
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1430
1431
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1432
                "content": "What is Deep Learning?"
Nicolas Patry's avatar
Nicolas Patry committed
1433
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1434
1435
1436
1437
1438
1439
1440
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message {
                role: "user".to_string(),
1441
                content: MessageContent::SingleText("What is Deep Learning?".to_string()),
Nicolas Patry's avatar
Nicolas Patry committed
1442
1443
1444
1445
1446
                name: None
            }
        );
    }

drbh's avatar
drbh committed
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
    #[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
1476
1477
    #[test]
    fn test_chat_request() {
Nicolas Patry's avatar
Nicolas Patry committed
1478
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1479
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1480
1481
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1482
1483
                "content": [
                    {"type": "text", "text": "Whats in this image?"},
Nicolas Patry's avatar
Nicolas Patry committed
1484
                    {"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
1485
                ]
Nicolas Patry's avatar
Nicolas Patry committed
1486
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1487
1488
1489
1490
1491
1492
1493
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message{
                role: "user".to_string(),
1494
1495
1496
1497
                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
1498
1499
1500
1501
                name: None
            }
        );
    }
Nicolas Patry's avatar
Nicolas Patry committed
1502
1503
1504
1505
1506

    #[test]
    fn text_message_convert() {
        let message = Message{
                role: "user".to_string(),
1507
1508
1509
1510
                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
1511
1512
1513
1514
1515
                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
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536

    #[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
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
    #[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"}}}]}"#
        );
    }
1569
}