lib.rs 45.9 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
12
pub mod usage_stats;

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
13
use serde::{Deserialize, Serialize};
Nicolas Patry's avatar
Nicolas Patry committed
14
use tracing::warn;
15
use utoipa::ToSchema;
Olivier Dehaene's avatar
Olivier Dehaene committed
16
use validation::Validation;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
17

18
19
20
21
22
23
24
#[derive(PartialEq)]
pub enum Attention {
    Paged,
    FlashDecoding,
    FlashInfer,
}

25
26
27
28
29
30
31
32
33
34
impl Attention {
    pub fn block_size(&self) -> u32 {
        match self {
            Attention::FlashDecoding => 256,
            Attention::FlashInfer => 1,
            Attention::Paged => 16,
        }
    }
}

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#[derive(Debug)]
pub struct ParseError;

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Cannot parse attention value")
    }
}
impl std::error::Error for ParseError {}

impl std::str::FromStr for Attention {
    type Err = ParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "paged" => Ok(Attention::Paged),
            "flashdecoding" => Ok(Attention::FlashDecoding),
            "flashinfer" => Ok(Attention::FlashInfer),
            _ => Err(ParseError),
        }
    }
}

drbh's avatar
drbh committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#[derive(Clone, Deserialize, ToSchema)]
pub(crate) struct VertexInstance {
    #[schema(example = "What is Deep Learning?")]
    pub inputs: String,
    #[schema(nullable = true, default = "null", example = "null")]
    pub parameters: Option<GenerateParameters>,
}

#[derive(Deserialize, ToSchema)]
pub(crate) struct VertexRequest {
    #[serde(rename = "instances")]
    pub instances: Vec<VertexInstance>,
}

#[derive(Clone, Deserialize, ToSchema, Serialize)]
pub(crate) struct VertexResponse {
    pub predictions: Vec<String>,
}

76
77
/// Hub type
#[derive(Clone, Debug, Deserialize)]
78
pub struct HubModelInfo {
79
80
81
82
83
84
    #[serde(rename(deserialize = "id"))]
    pub model_id: String,
    pub sha: Option<String>,
    pub pipeline_tag: Option<String>,
}

85
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
86
87
88
89
90
pub struct ChatTemplate {
    name: String,
    template: String,
}

91
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
92
93
94
95
96
97
#[serde(untagged)]
pub enum ChatTemplateVersions {
    Single(String),
    Multiple(Vec<ChatTemplate>),
}

98
99
use std::path::Path;

100
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
101
pub struct HubTokenizerConfig {
102
    pub chat_template: Option<ChatTemplateVersions>,
103
    pub completion_template: Option<String>,
104
105
    pub bos_token: Option<TokenizerConfigToken>,
    pub eos_token: Option<TokenizerConfigToken>,
106
107
108
    pub tokenizer_class: Option<String>,
    pub add_bos_token: Option<bool>,
    pub add_eos_token: Option<bool>,
109
110
111
}

impl HubTokenizerConfig {
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    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,
        }
132
133
134
    }
}

135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#[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
154
155
156
157
158
159
160
161
#[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 {
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())
drbh's avatar
drbh committed
166
167
168
    }
}

169
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
drbh's avatar
drbh committed
170
171
#[serde(tag = "type", content = "value")]
pub(crate) enum GrammarType {
172
173
174
175
176
    /// 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
177
    #[serde(alias = "json_object")]
178
179
    #[schema(example = json ! ({"properties": {"location":{"type": "string"}}}))]
    Json(serde_json::Value),
drbh's avatar
drbh committed
180
181
182
183
    #[serde(rename = "regex")]
    Regex(String),
}

184
185
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct Info {
186
    /// Model info
187
188
189
190
    #[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
191
192
193
194
    // #[schema(example = "torch.float16")]
    // pub model_dtype: String,
    // #[schema(example = "cuda")]
    // pub model_device_type: String,
195
196
    #[schema(nullable = true, example = "text-generation")]
    pub model_pipeline_tag: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
197

198
199
200
201
202
203
204
205
    /// 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
206
    pub max_input_tokens: usize,
207
208
209
210
    #[schema(example = "2048")]
    pub max_total_tokens: usize,
    #[schema(example = "2")]
    pub validation_workers: usize,
211
212
    #[schema(example = "32")]
    pub max_client_batch_size: usize,
Nicolas Patry's avatar
Nicolas Patry committed
213

214
    /// Router Info
215
216
    #[schema(example = "text-generation-router")]
    pub router: &'static str,
217
218
219
220
    #[schema(example = "0.5.0")]
    pub version: &'static str,
    #[schema(nullable = true, example = "null")]
    pub sha: Option<&'static str>,
221
222
    #[schema(nullable = true, example = "null")]
    pub docker_label: Option<&'static str>,
223
224
}

drbh's avatar
drbh committed
225
#[derive(Clone, Debug, Deserialize, ToSchema, Default)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
226
pub(crate) struct GenerateParameters {
227
    /// Generate best_of sequences and return the one if the highest token logprobs.
228
229
230
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 1)]
    pub best_of: Option<usize>,
231
232

    /// The value used to module the logits distribution.
233
234
235
236
237
238
239
240
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 0.5
    )]
    pub temperature: Option<f32>,
241
242
243

    /// The parameter for repetition penalty. 1.0 means no penalty.
    /// See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
244
245
246
247
248
249
250
251
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 1.03
    )]
    pub repetition_penalty: Option<f32>,
252
253
254
255

    /// 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.
256
    #[serde(default)]
257
258
259
260
261
262
263
    #[schema(
        exclusive_minimum = -2.0,
        nullable = true,
        default = "null",
        example = 0.1
    )]
    pub frequency_penalty: Option<f32>,
264
265

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

    /// Top-p value for nucleus sampling.
271
272
273
274
275
276
277
278
279
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub top_p: Option<f32>,
280
281
282

    /// Typical Decoding mass
    /// See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information.
283
    #[serde(default)]
284
285
286
287
288
289
290
291
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub typical_p: Option<f32>,
292
293

    /// Activate logits sampling.
294
    #[serde(default)]
295
    #[schema(default = "false", example = true)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
296
    pub do_sample: bool,
297
298

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

    /// Whether to prepend the prompt to the generated text
OlivierDehaene's avatar
OlivierDehaene committed
304
    #[serde(default)]
305
    #[schema(nullable = true, default = "null", example = false)]
306
    pub return_full_text: Option<bool>,
307
308

    /// Stop generating tokens if a member of `stop` is generated.
309
    #[serde(default)]
310
    #[schema(inline, max_items = 4, example = json ! (["photographer"]))]
311
    pub stop: Vec<String>,
312
313

    /// Truncate inputs tokens to the given size.
OlivierDehaene's avatar
OlivierDehaene committed
314
    #[serde(default)]
315
    #[schema(nullable = true, default = "null", example = "null")]
316
    pub truncate: Option<usize>,
317
318

    /// Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226).
319
    #[serde(default)]
320
321
    #[schema(default = "false", example = true)]
    pub watermark: bool,
322
323

    /// Whether to return generation details.
324
    #[serde(default)]
325
    #[schema(default = "true")]
OlivierDehaene's avatar
OlivierDehaene committed
326
    pub details: bool,
327
328

    /// Whether to return decoder input token logprobs and ids.
329
    #[serde(default)]
330
    #[schema(default = "false")]
331
    pub decoder_input_details: bool,
332
333

    /// Random sampling seed.
334
    #[serde(default)]
335
336
337
338
339
340
    #[schema(
        exclusive_minimum = 0,
        nullable = true,
        default = "null",
        example = "null"
    )]
341
    pub seed: Option<u64>,
342
343

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

    /// Grammar constraints for the generation.
drbh's avatar
drbh committed
349
    #[serde(default)]
350
    #[schema(nullable = true, default = "null", example = "null")]
drbh's avatar
drbh committed
351
    pub grammar: Option<GrammarType>,
drbh's avatar
drbh committed
352
353
354
355
356

    /// 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
357
358
}

359
fn default_max_new_tokens() -> Option<u32> {
360
    Some(100)
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
361
362
363
364
}

fn default_parameters() -> GenerateParameters {
    GenerateParameters {
365
        best_of: None,
366
367
        temperature: None,
        repetition_penalty: None,
368
        frequency_penalty: None,
369
370
        top_k: None,
        top_p: None,
371
        typical_p: None,
372
        do_sample: true,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
373
        max_new_tokens: default_max_new_tokens(),
374
        return_full_text: None,
375
        stop: Vec::new(),
376
        truncate: None,
377
        watermark: false,
OlivierDehaene's avatar
OlivierDehaene committed
378
        details: false,
379
        decoder_input_details: false,
380
        seed: None,
Nicolas Patry's avatar
Nicolas Patry committed
381
        top_n_tokens: None,
drbh's avatar
drbh committed
382
        grammar: None,
drbh's avatar
drbh committed
383
        adapter_id: None,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
384
385
386
    }
}

387
388
389
390
391
392
393
394
395
396
397
398
399
#[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;
400

401
    fn try_from(value: PromptDeserializer) -> Result<Self, Self::Error> {
402
        match value {
403
404
405
406
407
408
409
410
411
412
413
            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))
                }
            }
414
415
416
417
        }
    }
}

418
419
420
421
422
#[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.
423
    pub model: Option<String>,
424
425
426

    /// The prompt to generate completions for.
    #[schema(example = "What is Deep Learning?")]
427
    pub prompt: Prompt,
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464

    /// 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>,
465
466
467
468
469

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

472
473
474
475
476
477
478
479
480
#[derive(Clone, Serialize, ToSchema)]
#[serde(tag = "object")]
enum Completion {
    #[serde(rename = "text_completion")]
    Chunk(Chunk),
    #[serde(rename = "text_completion")]
    Final(CompletionFinal),
}

481
#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
482
pub(crate) struct CompletionFinal {
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
    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,
}

501
502
503
504
505
506
507
508
509
#[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,
}

510
#[derive(Clone, Deserialize, Serialize, ToSchema)]
511
512
pub(crate) struct ChatCompletion {
    pub id: String,
513
    #[schema(example = "1706270835")]
514
    pub created: u64,
515
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
516
517
518
519
520
521
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionComplete>,
    pub usage: Usage,
}

522
#[derive(Clone, Deserialize, Serialize, ToSchema)]
523
524
pub(crate) struct ChatCompletionComplete {
    pub index: u32,
Nicolas Patry's avatar
Nicolas Patry committed
525
    pub message: OutputMessage,
526
    pub logprobs: Option<ChatCompletionLogprobs>,
527
528
529
    pub finish_reason: String,
}

530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#[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;
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572

        // 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
573
574
575
576
577
578
                        .into_iter()
                        .map(|t| ChatCompletionTopLogprob {
                            token: t.text,
                            logprob: t.logprob,
                        })
                        .collect(),
579
580
581
582
583
584
                    None => vec![], // Handle the case where there are no top tokens
                },
            })
            .collect();

        Self { content }
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
    }
}

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

601
#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
602
603
604
605
606
607
pub(crate) struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

608
609
610
611
612
613
614
615
616
#[derive(Clone, Serialize, ToSchema)]
#[serde(tag = "object")]
enum CompletionType {
    #[serde(rename = "chat.completion.chunk")]
    ChatCompletionChunk(ChatCompletionChunk),
    #[serde(rename = "chat.completion")]
    ChatCompletion(ChatCompletion),
}

617
618
619
620
impl ChatCompletion {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
drbh's avatar
drbh committed
621
        output: Option<String>,
622
623
624
        created: u64,
        details: Details,
        return_logprobs: bool,
625
        tool_calls: Option<Vec<ToolCall>>,
626
    ) -> Self {
Nicolas Patry's avatar
Nicolas Patry committed
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
        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(),
                })
            }
        };
651
652
653
654
655
656
657
        Self {
            id: String::new(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionComplete {
                index: 0,
Nicolas Patry's avatar
Nicolas Patry committed
658
                message,
659
                logprobs: return_logprobs
660
                    .then(|| ChatCompletionLogprobs::from((details.tokens, details.top_tokens))),
661
                finish_reason: details.finish_reason.format(true),
662
663
664
665
666
667
668
669
670
            }],
            usage: Usage {
                prompt_tokens: details.prefill.len() as u32,
                completion_tokens: details.generated_tokens,
                total_tokens: details.prefill.len() as u32 + details.generated_tokens,
            },
        }
    }
}
671
#[derive(Clone, Serialize, ToSchema)]
672
673
pub(crate) struct ChatCompletionChunk {
    pub id: String,
674
    #[schema(example = "1706270978")]
675
    pub created: u64,
676
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
677
678
679
680
681
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionChoice>,
}

682
#[derive(Clone, Serialize, ToSchema)]
683
684
685
pub(crate) struct ChatCompletionChoice {
    pub index: u32,
    pub delta: ChatCompletionDelta,
686
    pub logprobs: Option<ChatCompletionLogprobs>,
687
688
689
    pub finish_reason: Option<String>,
}

Nicolas Patry's avatar
Nicolas Patry committed
690
691
692
693
694
695
696
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct ToolCallDelta {
    #[schema(example = "assistant")]
    role: String,
    tool_calls: DeltaToolCall,
}

697
698
#[derive(Clone, Debug, Serialize, ToSchema)]
#[serde(untagged)]
Nicolas Patry's avatar
Nicolas Patry committed
699
700
701
enum ChatCompletionDelta {
    Chat(TextMessage),
    Tool(ToolCallDelta),
drbh's avatar
drbh committed
702
703
}

Nicolas Patry's avatar
Nicolas Patry committed
704
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
705
706
707
708
709
710
711
pub(crate) struct DeltaToolCall {
    pub index: u32,
    pub id: String,
    pub r#type: String,
    pub function: Function,
}

Nicolas Patry's avatar
Nicolas Patry committed
712
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
713
714
715
pub(crate) struct Function {
    pub name: Option<String>,
    pub arguments: String,
716
717
}

drbh's avatar
drbh committed
718
#[allow(clippy::too_many_arguments)]
719
720
721
722
impl ChatCompletionChunk {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
drbh's avatar
drbh committed
723
724
        delta: Option<String>,
        tool_calls: Option<Vec<String>>,
725
        created: u64,
726
        logprobs: Option<ChatCompletionLogprobs>,
727
728
        finish_reason: Option<String>,
    ) -> Self {
729
        let delta = match (delta, tool_calls) {
Nicolas Patry's avatar
Nicolas Patry committed
730
731
732
733
734
735
736
            (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 {
737
738
739
740
741
742
743
                    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
744
745
746
747
748
749
                },
            }),
            (None, None) => ChatCompletionDelta::Chat(TextMessage {
                role: "assistant".to_string(),
                content: "".to_string(),
            }),
750
        };
751
752
753
754
755
756
        Self {
            id: String::new(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionChoice {
757
                index: 0,
758
                delta,
759
760
761
762
763
764
765
766
767
                logprobs,
                finish_reason,
            }],
        }
    }
}

#[derive(Clone, Deserialize, ToSchema, Serialize)]
pub(crate) struct ChatRequest {
768
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
drbh's avatar
drbh committed
769
    /// [UNUSED] ID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API.
770
    pub model: Option<String>,
drbh's avatar
drbh committed
771

772
    /// A list of messages comprising the conversation so far.
drbh's avatar
drbh committed
773
    #[schema(example = "[{\"role\": \"user\", \"content\": \"What is Deep Learning?\"}]")]
774
775
776
777
778
    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)]
779
    #[schema(example = "1.0")]
780
781
782
783
784
785
786
787
788
789
790
791
792
793
    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)]
794
    #[schema(example = "false")]
795
796
797
798
799
    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)]
800
    #[schema(example = "5")]
801
802
803
804
    pub top_logprobs: Option<u32>,

    /// The maximum number of tokens that can be generated in the chat completion.
    #[serde(default)]
805
    #[schema(example = "32")]
806
807
808
809
810
811
    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)]
812
    #[schema(nullable = true, example = "2")]
813
814
815
816
817
    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)]
818
    #[schema(nullable = true, example = 0.1)]
819
820
    pub presence_penalty: Option<f32>,

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

826
827
828
829
830
    #[serde(default = "bool::default")]
    pub stream: bool,

    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,
831
832
833
834
835
836

    /// 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)]
837
    #[schema(nullable = true, example = 1.0)]
838
839
840
841
842
    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)]
843
    #[schema(nullable = true, example = 0.95)]
844
    pub top_p: Option<f32>,
drbh's avatar
drbh committed
845
846
847
848
849
850
851
852

    /// 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
853
    #[serde(default)]
drbh's avatar
drbh committed
854
855
    #[schema(
        nullable = true,
drbh's avatar
drbh committed
856
        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
857
858
859
860
861
862
    )]
    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
863
    pub tool_choice: ToolChoice,
drbh's avatar
drbh committed
864
865
866
867
868
869
870

    /// 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>,
871
872
873
874
875

    /// A guideline to be used in the chat_template
    #[serde(default)]
    #[schema(nullable = true, default = "null", example = "null")]
    pub guideline: Option<String>,
drbh's avatar
drbh committed
876
877
}

drbh's avatar
drbh committed
878
879
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
880
}
881
882
883
884

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, ToSchema)]
#[serde(untagged)]
pub enum ToolType {
drbh's avatar
drbh committed
885
    OneOf,
886
887
    FunctionName(String),
    Function { function: FunctionName },
drbh's avatar
drbh committed
888
    NoTool,
drbh's avatar
drbh committed
889
890
}

891
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
892
893
894
895
pub struct FunctionName {
    pub name: String,
}

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

900
901
902
#[derive(Deserialize)]
#[serde(untagged)]
enum ToolTypeDeserializer {
drbh's avatar
drbh committed
903
904
    String(String),
    ToolType(ToolType),
905
}
drbh's avatar
drbh committed
906

907
908
impl From<ToolTypeDeserializer> for ToolChoice {
    fn from(value: ToolTypeDeserializer) -> Self {
drbh's avatar
drbh committed
909
        match value {
drbh's avatar
drbh committed
910
911
912
913
            ToolTypeDeserializer::String(s) => match s.as_str() {
                "none" => ToolChoice(Some(ToolType::NoTool)),
                "auto" => ToolChoice(Some(ToolType::OneOf)),
                _ => ToolChoice(Some(ToolType::FunctionName(s))),
drbh's avatar
drbh committed
914
            },
drbh's avatar
drbh committed
915
            ToolTypeDeserializer::ToolType(tool_type) => ToolChoice(Some(tool_type)),
drbh's avatar
drbh committed
916
917
918
919
        }
    }
}

920
#[derive(Debug, Deserialize, Serialize, ToSchema, PartialEq)]
drbh's avatar
drbh committed
921
pub struct JsonSchemaTool {
drbh's avatar
drbh committed
922
923
924
925
926
    #[serde(flatten)]
    functions_map: FunctionsMap,
    properties: Properties,
}

927
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
928
929
930
931
932
struct FunctionsMap {
    #[serde(rename = "$functions")]
    functions: std::collections::HashMap<String, serde_json::Value>,
}

933
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
934
935
936
937
938
struct FunctionRef {
    #[serde(rename = "$ref")]
    ref_path: String,
}

939
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
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
955
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema, Default, PartialEq)]
drbh's avatar
drbh committed
956
957
958
959
pub(crate) struct FunctionDefinition {
    #[serde(default)]
    pub description: Option<String>,
    pub name: String,
960
961
    #[serde(alias = "parameters")]
    pub arguments: serde_json::Value,
drbh's avatar
drbh committed
962
963
964
965
966
967
968
969
970
}

#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
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,
971
972
}

973
#[derive(Clone, Serialize, Deserialize, Default)]
974
pub(crate) struct ChatTemplateInputs<'a> {
Nicolas Patry's avatar
Nicolas Patry committed
975
    messages: Vec<TextMessage>,
976
977
    bos_token: Option<&'a str>,
    eos_token: Option<&'a str>,
978
    add_generation_prompt: bool,
drbh's avatar
drbh committed
979
    tools: Option<Vec<Tool>>,
980
    guideline: Option<&'a str>,
981
982
}

Nicolas Patry's avatar
Nicolas Patry committed
983
#[derive(Clone, Deserialize, Serialize, ToSchema, Default, Debug, PartialEq)]
drbh's avatar
drbh committed
984
pub(crate) struct ToolCall {
985
    pub id: String,
drbh's avatar
drbh committed
986
987
988
989
    pub r#type: String,
    pub function: FunctionDefinition,
}

Nicolas Patry's avatar
Nicolas Patry committed
990
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
991
pub struct Url {
Nicolas Patry's avatar
Nicolas Patry committed
992
    url: String,
drbh's avatar
drbh committed
993
994
}

Nicolas Patry's avatar
Nicolas Patry committed
995
996
997
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
998
999
1000
pub enum MessageChunk {
    Text { text: String },
    ImageUrl { image_url: Url },
Nicolas Patry's avatar
Nicolas Patry committed
1001
1002
1003
1004
1005
1006
1007
}

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

1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
#[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
1026
1027
1028
1029
                *self = MessageContent::MultipleChunks(vec![
                    MessageChunk::Text { text: text.clone() },
                    chunk,
                ]);
Nicolas Patry's avatar
Nicolas Patry committed
1030
            }
1031
1032
1033
1034
            MessageContent::MultipleChunks(chunks) => {
                chunks.push(chunk);
            }
        }
drbh's avatar
drbh committed
1035
1036
1037
    }
}

Nicolas Patry's avatar
Nicolas Patry committed
1038
1039
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct TextMessage {
1040
1041
1042
    #[schema(example = "user")]
    pub role: String,
    #[schema(example = "My name is David and I")]
Nicolas Patry's avatar
Nicolas Patry committed
1043
1044
1045
1046
1047
1048
1049
    pub content: String,
}

impl From<Message> for TextMessage {
    fn from(value: Message) -> Self {
        TextMessage {
            role: value.role,
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
            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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
        }
    }
}

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

1079
#[derive(Clone, Debug, Deserialize, ToSchema)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1080
pub(crate) struct GenerateRequest {
1081
    #[schema(example = "My name is Olivier and I")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1082
1083
1084
    pub inputs: String,
    #[serde(default = "default_parameters")]
    pub parameters: GenerateParameters,
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094

    /// 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
1095
1096
}

1097
1098
1099
1100
1101
1102
1103
#[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
1104
    #[schema(default = "false")]
1105
1106
1107
1108
1109
1110
1111
    pub stream: bool,
}

impl From<CompatGenerateRequest> for GenerateRequest {
    fn from(req: CompatGenerateRequest) -> Self {
        Self {
            inputs: req.inputs,
1112
            add_special_tokens: true,
1113
1114
1115
1116
1117
            parameters: req.parameters,
        }
    }
}

1118
1119
1120
#[derive(Debug, Serialize, ToSchema)]
pub struct PrefillToken {
    #[schema(example = 0)]
Nicolas Patry's avatar
Nicolas Patry committed
1121
    pub id: u32,
1122
    #[schema(example = "test")]
Nicolas Patry's avatar
Nicolas Patry committed
1123
    pub text: String,
1124
    #[schema(nullable = true, example = - 0.34)]
Nicolas Patry's avatar
Nicolas Patry committed
1125
    pub logprob: f32,
1126
1127
}

1128
#[derive(Debug, Serialize, ToSchema, Clone)]
1129
1130
pub struct Token {
    #[schema(example = 0)]
Nicolas Patry's avatar
Nicolas Patry committed
1131
    pub id: u32,
1132
    #[schema(example = "test")]
Nicolas Patry's avatar
Nicolas Patry committed
1133
    pub text: String,
1134
    #[schema(nullable = true, example = - 0.34)]
Nicolas Patry's avatar
Nicolas Patry committed
1135
    pub logprob: f32,
1136
    #[schema(example = "false")]
Nicolas Patry's avatar
Nicolas Patry committed
1137
    pub special: bool,
1138
1139
}

1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
#[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
1152
#[derive(Debug, Serialize, ToSchema)]
1153
#[serde(rename_all(serialize = "snake_case"))]
1154
#[schema(example = "Length")]
Nicolas Patry's avatar
Nicolas Patry committed
1155
pub enum FinishReason {
1156
1157
1158
1159
1160
1161
1162
1163
    #[schema(rename = "length")]
    Length,
    #[serde(rename = "eos_token")]
    #[schema(rename = "eos_token")]
    EndOfSequenceToken,
    #[schema(rename = "stop_sequence")]
    StopSequence,
}
1164

1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
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"),
        }
    }
}

1175
1176
1177
1178
1179
1180
1181
1182
1183
impl FinishReason {
    pub fn format(&self, use_stop: bool) -> String {
        match self {
            FinishReason::EndOfSequenceToken if use_stop => "stop".to_string(),
            _ => self.to_string(),
        }
    }
}

1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
#[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
1196
1197
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
1198
1199
}

1200
#[derive(Serialize, ToSchema)]
OlivierDehaene's avatar
OlivierDehaene committed
1201
pub(crate) struct Details {
1202
1203
1204
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
OlivierDehaene's avatar
OlivierDehaene committed
1205
    pub generated_tokens: u32,
1206
    #[schema(nullable = true, example = 42)]
1207
    pub seed: Option<u64>,
1208
1209
    pub prefill: Vec<PrefillToken>,
    pub tokens: Vec<Token>,
1210
1211
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_of_sequences: Option<Vec<BestOfSequence>>,
Nicolas Patry's avatar
Nicolas Patry committed
1212
1213
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
OlivierDehaene's avatar
OlivierDehaene committed
1214
1215
}

1216
#[derive(Serialize, ToSchema)]
1217
pub(crate) struct GenerateResponse {
1218
    #[schema(example = "test")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1219
    pub generated_text: String,
OlivierDehaene's avatar
OlivierDehaene committed
1220
1221
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Details>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1222
}
1223

1224
1225
1226
1227
1228
1229
#[derive(Serialize, ToSchema)]
pub(crate) struct ChatTokenizeResponse {
    pub(crate) tokenize_response: TokenizeResponse,
    pub(crate) templated_text: String,
}

1230
1231
1232
1233
#[derive(Serialize, ToSchema)]
#[serde(transparent)]
pub(crate) struct TokenizeResponse(Vec<SimpleToken>);

1234
1235
1236
1237
1238
1239
#[derive(Serialize, ToSchema)]
pub(crate) struct StreamDetails {
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
    pub generated_tokens: u32,
1240
    #[schema(nullable = true, example = 42)]
1241
    pub seed: Option<u64>,
1242
1243
    #[schema(example = 1)]
    pub input_length: u32,
1244
1245
1246
}

#[derive(Serialize, ToSchema)]
1247
pub(crate) struct StreamResponse {
1248
    pub index: u32,
1249
    pub token: Token,
Nicolas Patry's avatar
Nicolas Patry committed
1250
1251
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Token>,
1252
    #[schema(nullable = true, default = "null", example = "test")]
1253
    pub generated_text: Option<String>,
1254
1255
    #[schema(nullable = true, default = "null")]
    pub details: Option<StreamDetails>,
1256
1257
}

1258
#[derive(Serialize, ToSchema)]
1259
1260
pub(crate) struct ErrorResponse {
    pub error: String,
1261
    pub error_type: String,
1262
}
1263
1264

#[cfg(test)]
1265
mod tests {
1266
    use super::*;
Nicolas Patry's avatar
Nicolas Patry committed
1267
    use serde_json::json;
1268
1269
    use tokenizers::Tokenizer;

1270
    pub(crate) async fn get_tokenizer() -> Tokenizer {
1271
1272
1273
1274
        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()
1275
    }
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289

    #[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
1290
1291
1292
1293
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1294
1295
        assert_eq!(
            config.bos_token,
1296
1297
1298
1299
1300
1301
1302
1303
1304
            Some(TokenizerConfigToken::String(
                "<|begin▁of▁sentence|>".to_string()
            ))
        );
        assert_eq!(
            config.eos_token,
            Some(TokenizerConfigToken::String(
                "<|end▁of▁sentence|>".to_string()
            ))
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
        );

        // 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
1332
1333
1334
1335
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1336
1337
        assert_eq!(
            config.bos_token,
1338
1339
1340
1341
1342
1343
1344
1345
1346
            Some(TokenizerConfigToken::Object {
                content: "<|begin▁of▁sentence|>".to_string()
            })
        );
        assert_eq!(
            config.eos_token,
            Some(TokenizerConfigToken::Object {
                content: "<|end▁of▁sentence|>".to_string()
            })
1347
1348
        );
    }
Nicolas Patry's avatar
Nicolas Patry committed
1349
1350
1351

    #[test]
    fn test_chat_simple_string() {
Nicolas Patry's avatar
Nicolas Patry committed
1352
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1353
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1354
1355
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1356
                "content": "What is Deep Learning?"
Nicolas Patry's avatar
Nicolas Patry committed
1357
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1358
1359
1360
1361
1362
1363
1364
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message {
                role: "user".to_string(),
1365
                content: MessageContent::SingleText("What is Deep Learning?".to_string()),
Nicolas Patry's avatar
Nicolas Patry committed
1366
1367
1368
1369
1370
                name: None
            }
        );
    }

drbh's avatar
drbh committed
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
    #[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
1400
1401
    #[test]
    fn test_chat_request() {
Nicolas Patry's avatar
Nicolas Patry committed
1402
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1403
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1404
1405
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1406
1407
                "content": [
                    {"type": "text", "text": "Whats in this image?"},
Nicolas Patry's avatar
Nicolas Patry committed
1408
                    {"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
1409
                ]
Nicolas Patry's avatar
Nicolas Patry committed
1410
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1411
1412
1413
1414
1415
1416
1417
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message{
                role: "user".to_string(),
1418
1419
1420
1421
                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
1422
1423
1424
1425
                name: None
            }
        );
    }
Nicolas Patry's avatar
Nicolas Patry committed
1426
1427
1428
1429
1430

    #[test]
    fn text_message_convert() {
        let message = Message{
                role: "user".to_string(),
1431
1432
1433
1434
                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
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
                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)");
    }
    #[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"}}}]}"#
        );
    }
1472
}