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

7
8
9
#[cfg(feature = "kserve")]
mod kserve;

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

drbh's avatar
drbh committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#[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>,
}

34
35
/// Hub type
#[derive(Clone, Debug, Deserialize)]
36
pub struct HubModelInfo {
37
38
39
40
41
42
    #[serde(rename(deserialize = "id"))]
    pub model_id: String,
    pub sha: Option<String>,
    pub pipeline_tag: Option<String>,
}

43
44
45
46
47
48
49
50
51
52
53
54
55
56
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct ChatTemplate {
    name: String,
    template: String,
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ChatTemplateVersions {
    Single(String),
    Multiple(Vec<ChatTemplate>),
}

#[derive(Debug, Clone, Deserialize, Default)]
57
pub struct HubTokenizerConfig {
58
    pub chat_template: Option<ChatTemplateVersions>,
59
    pub completion_template: Option<String>,
60
    #[serde(deserialize_with = "token_serde::deserialize")]
61
    pub bos_token: Option<String>,
62
    #[serde(deserialize_with = "token_serde::deserialize")]
63
    pub eos_token: Option<String>,
64
65
66
    pub tokenizer_class: Option<String>,
    pub add_bos_token: Option<bool>,
    pub add_eos_token: Option<bool>,
67
68
69
}

impl HubTokenizerConfig {
70
71
72
    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()
73
74
75
    }
}

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#[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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#[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 {
    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()
    }
}

109
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
drbh's avatar
drbh committed
110
111
#[serde(tag = "type", content = "value")]
pub(crate) enum GrammarType {
112
113
114
115
116
    /// 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
117
    #[serde(alias = "json_object")]
118
119
    #[schema(example = json ! ({"properties": {"location":{"type": "string"}}}))]
    Json(serde_json::Value),
drbh's avatar
drbh committed
120
121
122
123
    #[serde(rename = "regex")]
    Regex(String),
}

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
mod token_serde {
    use super::*;
    use serde::de;
    use serde::Deserializer;
    use serde_json::Value;

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;

        match value {
            Value::String(s) => Ok(Some(s)),
            Value::Object(map) => {
                if let Some(content) = map.get("content").and_then(|v| v.as_str()) {
                    Ok(Some(content.to_string()))
                } else {
                    Err(de::Error::custom(
                        "content key not found in structured token",
                    ))
                }
            }
147
            Value::Null => Ok(None),
148
149
150
151
152
            _ => Err(de::Error::custom("invalid token format")),
        }
    }
}

153
154
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct Info {
155
    /// Model info
156
157
158
159
    #[schema(example = "bigscience/blomm-560m")]
    pub model_id: String,
    #[schema(nullable = true, example = "e985a63cdc139290c5f700ff1929f0b5942cced2")]
    pub model_sha: Option<String>,
160
161
162
163
    #[schema(example = "torch.float16")]
    pub model_dtype: String,
    #[schema(example = "cuda")]
    pub model_device_type: String,
164
165
    #[schema(nullable = true, example = "text-generation")]
    pub model_pipeline_tag: Option<String>,
166
167
168
169
170
171
172
173
    /// 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
174
    pub max_input_tokens: usize,
175
176
177
178
179
180
181
182
    #[schema(example = "2048")]
    pub max_total_tokens: usize,
    #[schema(example = "1.2")]
    pub waiting_served_ratio: f32,
    #[schema(example = "32000")]
    pub max_batch_total_tokens: u32,
    #[schema(example = "20")]
    pub max_waiting_tokens: usize,
183
184
    #[schema(nullable = true, example = "null")]
    pub max_batch_size: Option<usize>,
185
186
    #[schema(example = "2")]
    pub validation_workers: usize,
187
188
    #[schema(example = "32")]
    pub max_client_batch_size: usize,
189
    /// Router Info
190
191
    #[schema(example = "text-generation-router")]
    pub router: &'static str,
192
193
194
195
    #[schema(example = "0.5.0")]
    pub version: &'static str,
    #[schema(nullable = true, example = "null")]
    pub sha: Option<&'static str>,
196
197
    #[schema(nullable = true, example = "null")]
    pub docker_label: Option<&'static str>,
198
199
}

drbh's avatar
drbh committed
200
#[derive(Clone, Debug, Deserialize, ToSchema, Default)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
201
pub(crate) struct GenerateParameters {
202
    /// Generate best_of sequences and return the one if the highest token logprobs.
203
204
205
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 1)]
    pub best_of: Option<usize>,
206
207

    /// The value used to module the logits distribution.
208
209
210
211
212
213
214
215
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 0.5
    )]
    pub temperature: Option<f32>,
216
217
218

    /// The parameter for repetition penalty. 1.0 means no penalty.
    /// See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
219
220
221
222
223
224
225
226
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 1.03
    )]
    pub repetition_penalty: Option<f32>,
227
228
229
230

    /// 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.
231
    #[serde(default)]
232
233
234
235
236
237
238
    #[schema(
        exclusive_minimum = -2.0,
        nullable = true,
        default = "null",
        example = 0.1
    )]
    pub frequency_penalty: Option<f32>,
239
240

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

    /// Top-p value for nucleus sampling.
246
247
248
249
250
251
252
253
254
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub top_p: Option<f32>,
255
256
257

    /// Typical Decoding mass
    /// See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information.
258
    #[serde(default)]
259
260
261
262
263
264
265
266
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub typical_p: Option<f32>,
267
268

    /// Activate logits sampling.
269
    #[serde(default)]
270
    #[schema(default = "false", example = true)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
271
    pub do_sample: bool,
272
273

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

    /// Whether to prepend the prompt to the generated text
OlivierDehaene's avatar
OlivierDehaene committed
279
    #[serde(default)]
280
    #[schema(nullable = true, default = "null", example = false)]
281
    pub return_full_text: Option<bool>,
282
283

    /// Stop generating tokens if a member of `stop` is generated.
284
    #[serde(default)]
285
    #[schema(inline, max_items = 4, example = json ! (["photographer"]))]
286
    pub stop: Vec<String>,
287
288

    /// Truncate inputs tokens to the given size.
OlivierDehaene's avatar
OlivierDehaene committed
289
    #[serde(default)]
290
    #[schema(nullable = true, default = "null", example = "null")]
291
    pub truncate: Option<usize>,
292
293

    /// Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226).
294
    #[serde(default)]
295
296
    #[schema(default = "false", example = true)]
    pub watermark: bool,
297
298

    /// Whether to return generation details.
299
    #[serde(default)]
300
    #[schema(default = "true")]
OlivierDehaene's avatar
OlivierDehaene committed
301
    pub details: bool,
302
303

    /// Whether to return decoder input token logprobs and ids.
304
    #[serde(default)]
305
    #[schema(default = "false")]
306
    pub decoder_input_details: bool,
307
308

    /// Random sampling seed.
309
    #[serde(default)]
310
311
312
313
314
315
    #[schema(
        exclusive_minimum = 0,
        nullable = true,
        default = "null",
        example = "null"
    )]
316
    pub seed: Option<u64>,
317
318

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

    /// Grammar constraints for the generation.
drbh's avatar
drbh committed
324
    #[serde(default)]
325
    #[schema(nullable = true, default = "null", example = "null")]
drbh's avatar
drbh committed
326
    pub grammar: Option<GrammarType>,
drbh's avatar
drbh committed
327
328
329
330
331

    /// 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
332
333
}

334
fn default_max_new_tokens() -> Option<u32> {
335
    Some(100)
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
336
337
338
339
}

fn default_parameters() -> GenerateParameters {
    GenerateParameters {
340
        best_of: None,
341
342
        temperature: None,
        repetition_penalty: None,
343
        frequency_penalty: None,
344
345
        top_k: None,
        top_p: None,
346
        typical_p: None,
347
        do_sample: true,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
348
        max_new_tokens: default_max_new_tokens(),
349
        return_full_text: None,
350
        stop: Vec::new(),
351
        truncate: None,
352
        watermark: false,
OlivierDehaene's avatar
OlivierDehaene committed
353
        details: false,
354
        decoder_input_details: false,
355
        seed: None,
Nicolas Patry's avatar
Nicolas Patry committed
356
        top_n_tokens: None,
drbh's avatar
drbh committed
357
        grammar: None,
drbh's avatar
drbh committed
358
        adapter_id: None,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
359
360
361
    }
}

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
mod prompt_serde {
    use serde::{self, Deserialize, Deserializer};
    use serde_json::Value;

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        match value {
            Value::String(s) => Ok(vec![s]),
            Value::Array(arr) if arr.is_empty() => Err(serde::de::Error::custom(
                "Empty array detected. Do not use an empty array for the prompt.",
            )),
            Value::Array(arr) => arr
                .iter()
                .map(|v| match v {
                    Value::String(s) => Ok(s.to_owned()),
                    _ => Err(serde::de::Error::custom("Expected a string")),
                })
                .collect(),
            _ => Err(serde::de::Error::custom(
                "Expected a string or an array of strings",
            )),
        }
    }
}

390
391
392
393
394
395
396
397
398
#[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.
    pub model: String,

    /// The prompt to generate completions for.
    #[schema(example = "What is Deep Learning?")]
399
400
    #[serde(deserialize_with = "prompt_serde::deserialize")]
    pub prompt: Vec<String>,
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437

    /// 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>,
438
439
440
441
442

    /// Up to 4 sequences where the API will stop generating further tokens.
    #[serde(default)]
    #[schema(nullable = true, example = "null")]
    pub stop: Option<Vec<String>>,
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
}

#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
pub(crate) struct Completion {
    pub id: String,
    pub object: 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,
}

466
#[derive(Clone, Deserialize, Serialize, ToSchema)]
467
468
469
pub(crate) struct ChatCompletion {
    pub id: String,
    pub object: String,
470
    #[schema(example = "1706270835")]
471
    pub created: u64,
472
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
473
474
475
476
477
478
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionComplete>,
    pub usage: Usage,
}

479
#[derive(Clone, Deserialize, Serialize, ToSchema)]
480
481
pub(crate) struct ChatCompletionComplete {
    pub index: u32,
Nicolas Patry's avatar
Nicolas Patry committed
482
    pub message: OutputMessage,
483
    pub logprobs: Option<ChatCompletionLogprobs>,
484
485
486
    pub finish_reason: String,
}

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#[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;
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529

        // 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
530
531
532
533
534
535
                        .into_iter()
                        .map(|t| ChatCompletionTopLogprob {
                            token: t.text,
                            logprob: t.logprob,
                        })
                        .collect(),
536
537
538
539
540
541
                    None => vec![], // Handle the case where there are no top tokens
                },
            })
            .collect();

        Self { content }
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
    }
}

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

558
#[derive(Clone, Deserialize, Serialize, ToSchema, Default)]
559
560
561
562
563
564
565
566
567
568
pub(crate) struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

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
        Self {
            id: String::new(),
601
            object: "chat.completion".into(),
602
603
604
605
606
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionComplete {
                index: 0,
Nicolas Patry's avatar
Nicolas Patry committed
607
                message,
608
                logprobs: return_logprobs
609
                    .then(|| ChatCompletionLogprobs::from((details.tokens, details.top_tokens))),
610
611
612
613
614
615
616
617
618
619
                finish_reason: details.finish_reason.to_string(),
            }],
            usage: Usage {
                prompt_tokens: details.prefill.len() as u32,
                completion_tokens: details.generated_tokens,
                total_tokens: details.prefill.len() as u32 + details.generated_tokens,
            },
        }
    }
}
620
621
622
623
624
625
626
627
628
#[derive(Clone, Deserialize, Serialize, ToSchema)]
pub(crate) struct CompletionCompleteChunk {
    pub id: String,
    pub object: String,
    pub created: u64,
    pub choices: Vec<CompletionComplete>,
    pub model: String,
    pub system_fingerprint: String,
}
Nicolas Patry's avatar
Nicolas Patry committed
629

630
#[derive(Clone, Serialize, ToSchema)]
631
632
633
pub(crate) struct ChatCompletionChunk {
    pub id: String,
    pub object: String,
634
    #[schema(example = "1706270978")]
635
    pub created: u64,
636
    #[schema(example = "mistralai/Mistral-7B-Instruct-v0.2")]
637
638
639
640
641
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionChoice>,
}

642
#[derive(Clone, Serialize, ToSchema)]
643
644
645
pub(crate) struct ChatCompletionChoice {
    pub index: u32,
    pub delta: ChatCompletionDelta,
646
    pub logprobs: Option<ChatCompletionLogprobs>,
647
648
649
    pub finish_reason: Option<String>,
}

Nicolas Patry's avatar
Nicolas Patry committed
650
651
652
653
654
655
656
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct ToolCallDelta {
    #[schema(example = "assistant")]
    role: String,
    tool_calls: DeltaToolCall,
}

657
658
#[derive(Clone, Debug, Serialize, ToSchema)]
#[serde(untagged)]
Nicolas Patry's avatar
Nicolas Patry committed
659
660
661
enum ChatCompletionDelta {
    Chat(TextMessage),
    Tool(ToolCallDelta),
drbh's avatar
drbh committed
662
663
}

Nicolas Patry's avatar
Nicolas Patry committed
664
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
665
666
667
668
669
670
671
pub(crate) struct DeltaToolCall {
    pub index: u32,
    pub id: String,
    pub r#type: String,
    pub function: Function,
}

Nicolas Patry's avatar
Nicolas Patry committed
672
#[derive(Clone, Deserialize, Serialize, ToSchema, Debug, PartialEq)]
drbh's avatar
drbh committed
673
674
675
pub(crate) struct Function {
    pub name: Option<String>,
    pub arguments: String,
676
677
}

drbh's avatar
drbh committed
678
#[allow(clippy::too_many_arguments)]
679
680
681
682
impl ChatCompletionChunk {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
drbh's avatar
drbh committed
683
684
        delta: Option<String>,
        tool_calls: Option<Vec<String>>,
685
        created: u64,
686
        logprobs: Option<ChatCompletionLogprobs>,
687
688
        finish_reason: Option<String>,
    ) -> Self {
689
        let delta = match (delta, tool_calls) {
Nicolas Patry's avatar
Nicolas Patry committed
690
691
692
693
694
695
696
            (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 {
697
698
699
700
701
702
703
                    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
704
705
706
707
708
709
                },
            }),
            (None, None) => ChatCompletionDelta::Chat(TextMessage {
                role: "assistant".to_string(),
                content: "".to_string(),
            }),
710
        };
711
712
        Self {
            id: String::new(),
713
            object: "chat.completion.chunk".to_string(),
714
715
716
717
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionChoice {
718
                index: 0,
719
                delta,
720
721
722
723
724
725
726
727
728
                logprobs,
                finish_reason,
            }],
        }
    }
}

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

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

    /// The maximum number of tokens that can be generated in the chat completion.
    #[serde(default)]
766
    #[schema(example = "32")]
767
768
769
770
771
772
    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)]
773
    #[schema(nullable = true, example = "2")]
774
775
776
777
778
    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)]
779
    #[schema(nullable = true, example = 0.1)]
780
781
    pub presence_penalty: Option<f32>,

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

787
788
789
790
791
    #[serde(default = "bool::default")]
    pub stream: bool,

    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,
792
793
794
795
796
797

    /// 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)]
798
    #[schema(nullable = true, example = 1.0)]
799
800
801
802
803
    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)]
804
    #[schema(nullable = true, example = 0.95)]
805
    pub top_p: Option<f32>,
drbh's avatar
drbh committed
806
807
808
809
810
811
812
813
814
815
816

    /// 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
    #[serde(default = "default_tool_prompt")]
    #[schema(
        nullable = true,
817
        example = "\"You will be presented with a JSON schema representing a set of tools.\nIf the user request lacks of sufficient information to make a precise tool selection: Do not invent any tool's properties, instead notify with an error message.\n\nJSON Schema:\n\""
drbh's avatar
drbh committed
818
819
820
821
822
823
824
825
    )]
    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")]
    #[serde(deserialize_with = "deserialize_tool_choice::deserialize")]
    pub tool_choice: Option<ToolType>,
drbh's avatar
drbh committed
826
827
828
829
830
831
832

    /// 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>,
drbh's avatar
drbh committed
833
834
835
836
}

fn default_tool_prompt() -> Option<String> {
    Some(
837
        "\nYou will be presented with a JSON schema representing a set of tools.\nIf the user request lacks of sufficient information to make a precise tool selection: Do not invent any tool's properties, instead notify with an error message.\n\nJSON Schema:\n".to_string(),
drbh's avatar
drbh committed
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
    )
}
#[derive(Clone, Deserialize, ToSchema, Serialize)]
enum ToolType {
    FunctionName(String),
    OneOf,
}

/// Deserialize the tool choice from the JSON input or from the function name ("none" is allowed but mapped to None)
mod deserialize_tool_choice {
    use super::*;
    use serde::de;
    use serde::Deserializer;
    use serde_json::Value;

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<ToolType>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;

        match value {
            Value::String(s) => match s.as_str() {
                "none" => Ok(None),
                "auto" => Ok(Some(ToolType::OneOf)),
                _ => Ok(Some(ToolType::FunctionName(s))),
            },
            Value::Object(map) => {
                if let Some(content) = map
                    .get("function")
                    .and_then(|v| v.get("name"))
                    .and_then(|v| v.as_str())
                {
                    Ok(Some(ToolType::FunctionName(content.to_string())))
                } else {
                    Err(de::Error::custom("function key not found in tool choice"))
                }
            }
            Value::Null => Ok(Some(ToolType::OneOf)),
            _ => Err(de::Error::custom("invalid token format")),
        }
    }
}

882
#[derive(Debug, Deserialize, Serialize, ToSchema, PartialEq)]
drbh's avatar
drbh committed
883
884
885
886
887
888
pub struct Tools {
    #[serde(flatten)]
    functions_map: FunctionsMap,
    properties: Properties,
}

889
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
890
891
892
893
894
struct FunctionsMap {
    #[serde(rename = "$functions")]
    functions: std::collections::HashMap<String, serde_json::Value>,
}

895
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
896
897
898
899
900
struct FunctionRef {
    #[serde(rename = "$ref")]
    ref_path: String,
}

901
#[derive(Debug, Serialize, Deserialize, PartialEq)]
drbh's avatar
drbh committed
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
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
917
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema, Default, PartialEq)]
drbh's avatar
drbh committed
918
919
920
921
pub(crate) struct FunctionDefinition {
    #[serde(default)]
    pub description: Option<String>,
    pub name: String,
922
923
    #[serde(alias = "parameters")]
    pub arguments: serde_json::Value,
drbh's avatar
drbh committed
924
925
926
927
928
929
930
931
932
}

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

935
#[derive(Clone, Serialize, Deserialize, Default)]
936
pub(crate) struct ChatTemplateInputs<'a> {
Nicolas Patry's avatar
Nicolas Patry committed
937
    messages: Vec<TextMessage>,
938
939
    bos_token: Option<&'a str>,
    eos_token: Option<&'a str>,
940
    add_generation_prompt: bool,
941
942
    tools: Option<&'a str>,
    tools_prompt: Option<&'a str>,
943
944
}

Nicolas Patry's avatar
Nicolas Patry committed
945
#[derive(Clone, Deserialize, Serialize, ToSchema, Default, Debug, PartialEq)]
drbh's avatar
drbh committed
946
pub(crate) struct ToolCall {
947
    pub id: String,
drbh's avatar
drbh committed
948
949
950
951
    pub r#type: String,
    pub function: FunctionDefinition,
}

Nicolas Patry's avatar
Nicolas Patry committed
952
953
954
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
struct Url {
    url: String,
drbh's avatar
drbh committed
955
956
}

Nicolas Patry's avatar
Nicolas Patry committed
957
958
959
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
struct ImageUrl {
    image_url: Url,
drbh's avatar
drbh committed
960
961
}

Nicolas Patry's avatar
Nicolas Patry committed
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
struct Text {
    text: String,
}

#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
enum MessageChunk {
    Text(Text),
    ImageUrl(ImageUrl),
}

#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct Message {
    #[schema(example = "user")]
    role: String,
    #[schema(example = "My name is David and I")]
    #[serde(deserialize_with = "message_content_serde::deserialize")]
    content: Vec<MessageChunk>,
drbh's avatar
drbh committed
982
    #[serde(default, skip_serializing_if = "Option::is_none")]
Nicolas Patry's avatar
Nicolas Patry committed
983
984
    #[schema(example = "\"David\"")]
    name: Option<String>,
drbh's avatar
drbh committed
985
986
987
988
}

mod message_content_serde {
    use super::*;
Nicolas Patry's avatar
Nicolas Patry committed
989
    use serde::{Deserialize, Deserializer};
drbh's avatar
drbh committed
990

Nicolas Patry's avatar
Nicolas Patry committed
991
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<MessageChunk>, D::Error>
drbh's avatar
drbh committed
992
993
994
    where
        D: Deserializer<'de>,
    {
Nicolas Patry's avatar
Nicolas Patry committed
995
996
997
998
999
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Message {
            Text(String),
            Chunks(Vec<MessageChunk>),
drbh's avatar
drbh committed
1000
        }
Nicolas Patry's avatar
Nicolas Patry committed
1001
1002
1003
1004
1005
1006
1007
1008
        let message: Message = Deserialize::deserialize(deserializer)?;
        let chunks = match message {
            Message::Text(text) => {
                vec![MessageChunk::Text(Text { text })]
            }
            Message::Chunks(s) => s,
        };
        Ok(chunks)
drbh's avatar
drbh committed
1009
1010
1011
    }
}

Nicolas Patry's avatar
Nicolas Patry committed
1012
1013
#[derive(Clone, Deserialize, ToSchema, Serialize, Debug, PartialEq)]
pub struct TextMessage {
1014
1015
1016
    #[schema(example = "user")]
    pub role: String,
    #[schema(example = "My name is David and I")]
Nicolas Patry's avatar
Nicolas Patry committed
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
    pub content: String,
}

impl From<Message> for TextMessage {
    fn from(value: Message) -> Self {
        TextMessage {
            role: value.role,
            content: value
                .content
                .into_iter()
                .map(|c| match c {
                    MessageChunk::Text(Text { text }) => text,
                    MessageChunk::ImageUrl(image) => {
                        let url = image.image_url.url;
                        format!("![]({url})")
                    }
                })
                .collect::<Vec<_>>()
                .join(""),
        }
    }
}

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

1054
#[derive(Clone, Debug, Deserialize, ToSchema)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1055
pub(crate) struct GenerateRequest {
1056
    #[schema(example = "My name is Olivier and I")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1057
1058
1059
1060
1061
    pub inputs: String,
    #[serde(default = "default_parameters")]
    pub parameters: GenerateParameters,
}

1062
1063
1064
1065
1066
1067
1068
#[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
1069
    #[schema(default = "false")]
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
    pub stream: bool,
}

impl From<CompatGenerateRequest> for GenerateRequest {
    fn from(req: CompatGenerateRequest) -> Self {
        Self {
            inputs: req.inputs,
            parameters: req.parameters,
        }
    }
}

1082
1083
1084
1085
1086
1087
#[derive(Debug, Serialize, ToSchema)]
pub struct PrefillToken {
    #[schema(example = 0)]
    id: u32,
    #[schema(example = "test")]
    text: String,
1088
    #[schema(nullable = true, example = - 0.34)]
1089
1090
1091
    logprob: f32,
}

1092
#[derive(Debug, Serialize, ToSchema, Clone)]
1093
1094
1095
1096
1097
pub struct Token {
    #[schema(example = 0)]
    id: u32,
    #[schema(example = "test")]
    text: String,
1098
    #[schema(nullable = true, example = - 0.34)]
1099
    logprob: f32,
1100
1101
    #[schema(example = "false")]
    special: bool,
1102
1103
}

1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
#[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
1116
#[derive(Debug, Serialize, ToSchema)]
1117
#[serde(rename_all(serialize = "snake_case"))]
1118
#[schema(example = "Length")]
1119
1120
1121
1122
1123
1124
1125
1126
1127
pub(crate) enum FinishReason {
    #[schema(rename = "length")]
    Length,
    #[serde(rename = "eos_token")]
    #[schema(rename = "eos_token")]
    EndOfSequenceToken,
    #[schema(rename = "stop_sequence")]
    StopSequence,
}
1128

1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
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"),
        }
    }
}

1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
#[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
1151
1152
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
1153
1154
}

1155
#[derive(Serialize, ToSchema)]
OlivierDehaene's avatar
OlivierDehaene committed
1156
pub(crate) struct Details {
1157
1158
1159
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
OlivierDehaene's avatar
OlivierDehaene committed
1160
    pub generated_tokens: u32,
1161
    #[schema(nullable = true, example = 42)]
1162
    pub seed: Option<u64>,
1163
1164
    pub prefill: Vec<PrefillToken>,
    pub tokens: Vec<Token>,
1165
1166
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_of_sequences: Option<Vec<BestOfSequence>>,
Nicolas Patry's avatar
Nicolas Patry committed
1167
1168
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
OlivierDehaene's avatar
OlivierDehaene committed
1169
1170
}

1171
#[derive(Serialize, ToSchema)]
1172
pub(crate) struct GenerateResponse {
1173
    #[schema(example = "test")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1174
    pub generated_text: String,
OlivierDehaene's avatar
OlivierDehaene committed
1175
1176
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Details>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1177
}
1178

1179
1180
1181
1182
#[derive(Serialize, ToSchema)]
#[serde(transparent)]
pub(crate) struct TokenizeResponse(Vec<SimpleToken>);

1183
1184
1185
1186
1187
1188
#[derive(Serialize, ToSchema)]
pub(crate) struct StreamDetails {
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
    pub generated_tokens: u32,
1189
    #[schema(nullable = true, example = 42)]
1190
1191
1192
1193
    pub seed: Option<u64>,
}

#[derive(Serialize, ToSchema)]
1194
pub(crate) struct StreamResponse {
1195
    pub index: u32,
1196
    pub token: Token,
Nicolas Patry's avatar
Nicolas Patry committed
1197
1198
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Token>,
1199
    #[schema(nullable = true, default = "null", example = "test")]
1200
    pub generated_text: Option<String>,
1201
1202
    #[schema(nullable = true, default = "null")]
    pub details: Option<StreamDetails>,
1203
1204
}

1205
#[derive(Serialize, ToSchema)]
1206
1207
pub(crate) struct ErrorResponse {
    pub error: String,
1208
    pub error_type: String,
1209
}
1210
1211

#[cfg(test)]
1212
mod tests {
1213
    use super::*;
Nicolas Patry's avatar
Nicolas Patry committed
1214
    use serde_json::json;
1215
1216
    use tokenizers::Tokenizer;

1217
    pub(crate) async fn get_tokenizer() -> Tokenizer {
1218
1219
1220
1221
        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()
1222
    }
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236

    #[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
1237
1238
1239
1240
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
        assert_eq!(
            config.bos_token,
            Some("<|begin▁of▁sentence|>".to_string())
        );
        assert_eq!(config.eos_token, Some("<|end▁of▁sentence|>".to_string()));

        // 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
1272
1273
1274
1275
        assert_eq!(
            config.chat_template,
            Some(ChatTemplateVersions::Single("test".to_string()))
        );
1276
1277
1278
1279
1280
1281
        assert_eq!(
            config.bos_token,
            Some("<|begin▁of▁sentence|>".to_string())
        );
        assert_eq!(config.eos_token, Some("<|end▁of▁sentence|>".to_string()));
    }
Nicolas Patry's avatar
Nicolas Patry committed
1282
1283
1284

    #[test]
    fn test_chat_simple_string() {
Nicolas Patry's avatar
Nicolas Patry committed
1285
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1286
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1287
1288
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1289
                "content": "What is Deep Learning?"
Nicolas Patry's avatar
Nicolas Patry committed
1290
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message {
                role: "user".to_string(),
                content: vec![MessageChunk::Text(Text {
                    text: "What is Deep Learning?".to_string()
                }),],
                name: None
            }
        );
    }

    #[test]
    fn test_chat_request() {
Nicolas Patry's avatar
Nicolas Patry committed
1308
        let json = json!({
Nicolas Patry's avatar
Nicolas Patry committed
1309
            "model": "",
Nicolas Patry's avatar
Nicolas Patry committed
1310
1311
            "messages": [{
                "role": "user",
Nicolas Patry's avatar
Nicolas Patry committed
1312
1313
                "content": [
                    {"type": "text", "text": "Whats in this image?"},
Nicolas Patry's avatar
Nicolas Patry committed
1314
                    {"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
1315
                ]
Nicolas Patry's avatar
Nicolas Patry committed
1316
            }]
Nicolas Patry's avatar
Nicolas Patry committed
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
        });
        let request: ChatRequest = serde_json::from_str(json.to_string().as_str()).unwrap();

        assert_eq!(
            request.messages[0],
            Message{
                role: "user".to_string(),
                content: vec![
                    MessageChunk::Text(Text { text: "Whats in this image?".to_string() }),
                    MessageChunk::ImageUrl(ImageUrl { image_url: Url { url: "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png".to_string() } })
                ],
                name: None
            }
        );
    }
Nicolas Patry's avatar
Nicolas Patry committed
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377

    #[test]
    fn text_message_convert() {
        let message = Message{
                role: "user".to_string(),
                content: vec![
                    MessageChunk::Text(Text { text: "Whats in this image?".to_string() }),
                    MessageChunk::ImageUrl(ImageUrl { image_url: Url { url: "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png".to_string() } })
                ],
                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"}}}]}"#
        );
    }
1378
}