server.rs 101 KB
Newer Older
1
/// HTTP Server logic
OlivierDehaene's avatar
OlivierDehaene committed
2
use crate::config::Config;
Nicolas Patry's avatar
Nicolas Patry committed
3
4
use crate::infer::tool_grammar::ToolGrammar;
use crate::infer::{Backend, Infer, InferError, InferResponse, InferStreamResponse};
5
6
7
8
9
#[cfg(feature = "kserve")]
use crate::kserve::{
    kerve_server_metadata, kserve_health_live, kserve_health_ready, kserve_model_infer,
    kserve_model_metadata, kserve_model_metadata_ready,
};
10
11
12
13
use crate::sagemaker::{
    sagemaker_compatibility, SagemakerRequest, SagemakerResponse, SagemakerStreamResponse,
    __path_sagemaker_compatibility,
};
14
use crate::validation::ValidationError;
Nicolas Patry's avatar
Nicolas Patry committed
15
16
use crate::vertex::vertex_compatibility;
use crate::ChatTokenizeResponse;
17
use crate::{
18
19
20
    usage_stats, BestOfSequence, Details, ErrorResponse, FinishReason, FunctionName,
    GenerateParameters, GenerateRequest, GenerateResponse, GrammarType, HubModelInfo,
    HubProcessorConfig, HubTokenizerConfig, Info, Message, MessageChunk, MessageContent,
Nicolas Patry's avatar
Nicolas Patry committed
21
    OutputMessage, PrefillToken, SimpleToken, StreamDetails, StreamOptions, StreamResponse,
22
23
    TextMessage, Token, TokenizeResponse, Tokenizer, ToolCallDelta, ToolCallMessage, Url, Usage,
    Validation,
24
25
26
27
};
use crate::{
    ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionComplete,
    ChatCompletionDelta, ChatCompletionLogprob, ChatCompletionLogprobs, ChatCompletionTopLogprob,
28
    ChatRequest, Chunk, CompatGenerateRequest, Completion, CompletionComplete, CompletionFinal,
Nicolas Patry's avatar
Nicolas Patry committed
29
    CompletionRequest, CompletionType, DeltaToolCall, Function, Prompt, Tool,
30
};
drbh's avatar
drbh committed
31
use crate::{FunctionDefinition, HubPreprocessorConfig, ToolCall, ToolChoice, ToolType};
drbh's avatar
drbh committed
32
use crate::{ModelInfo, ModelsInfo};
33
use async_stream::__private::AsyncStream;
Olivier Dehaene's avatar
Olivier Dehaene committed
34
use axum::extract::Extension;
Nicolas Patry's avatar
Nicolas Patry committed
35
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode};
36
use axum::response::sse::{Event, KeepAlive, Sse};
37
use axum::response::{IntoResponse, Response};
Olivier Dehaene's avatar
Olivier Dehaene committed
38
use axum::routing::{get, post};
39
use axum::{http, Json, Router};
Nicolas Patry's avatar
Nicolas Patry committed
40
use axum_tracing_opentelemetry::middleware::OtelAxumLayer;
41
use futures::stream::StreamExt;
42
use futures::stream::{FuturesOrdered, FuturesUnordered};
43
use futures::Stream;
drbh's avatar
drbh committed
44
use futures::TryStreamExt;
Nicolas Patry's avatar
Nicolas Patry committed
45
46
use hf_hub::api::tokio::{Api, ApiBuilder, ApiRepo};
use hf_hub::{Cache, Repo, RepoType};
Erik Kaunismäki's avatar
Erik Kaunismäki committed
47
use http::header::AUTHORIZATION;
48
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};
49
use pyo3::prelude::*;
Nicolas Patry's avatar
Nicolas Patry committed
50
use pyo3::types::IntoPyDict;
51
use regex::Regex;
drbh's avatar
drbh committed
52
use serde_json::Value;
53
use std::convert::Infallible;
Nicolas Patry's avatar
Nicolas Patry committed
54
55
56
57
use std::fs::File;
use std::io::BufReader;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
OlivierDehaene's avatar
OlivierDehaene committed
58
use thiserror::Error;
59
use tokio::select;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
60
use tokio::signal;
61
use tokio::sync::oneshot;
Olivier Dehaene's avatar
Olivier Dehaene committed
62
use tokio::time::Instant;
63
use tower_http::cors::{AllowOrigin, CorsLayer};
64
use tracing::{info_span, instrument, Instrument};
65
66
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
Olivier Dehaene's avatar
Olivier Dehaene committed
67

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
fn encoding_to_tokens(encoding: &tokenizers::Encoding, input: &str) -> Vec<SimpleToken> {
    let offsets = encoding.get_offsets();
    let input_ids = encoding.get_ids();
    if offsets.len() == input_ids.len() {
        input_ids
            .iter()
            .zip(offsets)
            .map(|(&id, &(start, stop))| {
                let text = input
                    .chars()
                    .skip(start)
                    .take(stop - start)
                    .collect::<String>();
                SimpleToken {
                    id,
                    text,
                    start,
                    stop,
                }
            })
            .collect()
    } else {
        encoding
            .get_ids()
            .iter()
            .map(|&id| SimpleToken {
                id,
                text: "".to_string(),
                start: 0,
                stop: 0,
            })
            .collect()
    }
}

103
104
/// Generate tokens if `stream == false` or a stream of token if `stream == true`
#[utoipa::path(
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
post,
tag = "Text Generation Inference",
path = "/",
request_body = CompatGenerateRequest,
responses(
(status = 200, description = "Generated Text",
content(
("application/json" = GenerateResponse),
("text/event-stream" = StreamResponse),
)),
(status = 424, description = "Generation Error", body = ErrorResponse,
example = json ! ({"error": "Request failed during generation"})),
(status = 429, description = "Model is overloaded", body = ErrorResponse,
example = json ! ({"error": "Model is overloaded"})),
(status = 422, description = "Input validation error", body = ErrorResponse,
example = json ! ({"error": "Input validation error"})),
(status = 500, description = "Incomplete generation", body = ErrorResponse,
example = json ! ({"error": "Incomplete generation"})),
)
124
)]
125
#[instrument(skip(infer, req))]
126
pub(crate) async fn compat_generate(
127
    Extension(default_return_full_text): Extension<bool>,
128
    infer: Extension<Infer>,
129
    compute_type: Extension<ComputeType>,
130
    Json(mut req): Json<CompatGenerateRequest>,
131
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
132
133
    // default return_full_text given the pipeline_tag
    if req.parameters.return_full_text.is_none() {
134
        req.parameters.return_full_text = Some(default_return_full_text)
135
136
    }

137
138
    // switch on stream
    if req.stream {
139
        Ok(generate_stream(infer, compute_type, Json(req.into()))
140
141
142
            .await
            .into_response())
    } else {
143
        let (headers, Json(generation)) = generate(infer, compute_type, Json(req.into())).await?;
144
        // wrap generation inside a Vec to match api-inference
145
        Ok((headers, Json(vec![generation])).into_response())
146
147
148
    }
}

149
150
/// Text Generation Inference endpoint info
#[utoipa::path(
151
152
153
154
get,
tag = "Text Generation Inference",
path = "/info",
responses((status = 200, description = "Served model info", body = Info))
155
156
)]
#[instrument]
157
158
async fn get_model_info(info: Extension<Info>) -> Json<Info> {
    Json(info.0)
159
160
}

drbh's avatar
drbh committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#[utoipa::path(
get,
tag = "Text Generation Inference",
path = "/v1/models",
responses(
(status = 200, description = "Served model info", body = ModelInfo),
(status = 404, description = "Model not found", body = ErrorResponse),
)
)]
#[instrument(skip(info))]
/// Get model info
async fn openai_get_model_info(info: Extension<Info>) -> Json<ModelsInfo> {
    Json(ModelsInfo {
        data: vec![ModelInfo {
            id: info.0.model_id.clone(),
            object: "model".to_string(),
            created: 0, // TODO: determine how to get this
            owned_by: info.0.model_id.clone(),
        }],
        ..Default::default()
    })
}

184
185
186
187
188
189
190
191
192
#[utoipa::path(
    post,
    tag = "Text Generation Inference",
    path = "/chat_tokenize",
    request_body = ChatRequest,
    responses((status = 200, description = "Templated and tokenized ChatRequest", body = ChatTokenizeResponse))
)]
async fn get_chat_tokenize(
    Extension(infer): Extension<Infer>,
Nicolas Patry's avatar
Nicolas Patry committed
193
    Json(chat): Json<ChatRequest>,
194
195
196
) -> Result<(HeaderMap, Json<ChatTokenizeResponse>), (StatusCode, Json<ErrorResponse>)> {
    metrics::counter!("tgi_request_count").increment(1);

Nicolas Patry's avatar
Nicolas Patry committed
197
    let generate_request: GenerateRequest = chat.try_into_generate(&infer)?.0;
198
199
200
    let input = generate_request.inputs.clone();
    let encoding = infer.tokenize(generate_request).await?;

201
202
203
204
205
206
207
    let tokens = encoding_to_tokens(&encoding, &input);

    let resp = ChatTokenizeResponse {
        tokenize_response: TokenizeResponse(tokens),
        templated_text: input,
    };
    Ok((HeaderMap::new(), Json(resp)))
208
209
}

210
#[utoipa::path(
211
212
213
214
215
216
217
218
get,
tag = "Text Generation Inference",
path = "/health",
responses(
(status = 200, description = "Everything is working fine"),
(status = 503, description = "Text generation inference is down", body = ErrorResponse,
example = json ! ({"error": "unhealthy", "error_type": "healthcheck"})),
)
219
)]
Nicolas Patry's avatar
Nicolas Patry committed
220
#[instrument(skip(infer))]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
221
/// Health check method
Nicolas Patry's avatar
Nicolas Patry committed
222
223
async fn health(infer: Extension<Infer>) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
    match infer.health().await {
224
225
226
227
228
229
230
231
232
        true => Ok(()),
        false => Err((
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ErrorResponse {
                error: "unhealthy".to_string(),
                error_type: "healthcheck".to_string(),
            }),
        )),
    }
Olivier Dehaene's avatar
Olivier Dehaene committed
233
234
}

235
236
/// Generate tokens
#[utoipa::path(
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
post,
tag = "Text Generation Inference",
path = "/generate",
request_body = GenerateRequest,
responses(
(status = 200, description = "Generated Text", body = GenerateResponse),
(status = 424, description = "Generation Error", body = ErrorResponse,
example = json ! ({"error": "Request failed during generation"})),
(status = 429, description = "Model is overloaded", body = ErrorResponse,
example = json ! ({"error": "Model is overloaded"})),
(status = 422, description = "Input validation error", body = ErrorResponse,
example = json ! ({"error": "Input validation error"})),
(status = 500, description = "Incomplete generation", body = ErrorResponse,
example = json ! ({"error": "Incomplete generation"})),
)
252
)]
253
#[instrument(
254
255
skip_all,
fields(
256
parameters = ? req.parameters,
257
258
259
260
261
262
263
total_time,
validation_time,
queue_time,
inference_time,
time_per_token,
seed,
)
264
)]
Olivier Dehaene's avatar
Olivier Dehaene committed
265
async fn generate(
266
    infer: Extension<Infer>,
267
    Extension(ComputeType(compute_type)): Extension<ComputeType>,
268
    Json(req): Json<GenerateRequest>,
269
) -> Result<(HeaderMap, Json<GenerateResponse>), (StatusCode, Json<ErrorResponse>)> {
270
    let span = tracing::Span::current();
271
272
273
    generate_internal(infer, ComputeType(compute_type), Json(req), span).await
}

274
pub(crate) async fn generate_internal(
275
276
277
278
279
    infer: Extension<Infer>,
    ComputeType(compute_type): ComputeType,
    Json(req): Json<GenerateRequest>,
    span: tracing::Span,
) -> Result<(HeaderMap, Json<GenerateResponse>), (StatusCode, Json<ErrorResponse>)> {
280
    let start_time = Instant::now();
281
    metrics::counter!("tgi_request_count").increment(1);
282

283
    // Do not long ultra long inputs, like image payloads.
284
285
286
287
    tracing::debug!(
        "Input: {}",
        &req.inputs.chars().take(1000).collect::<String>()
    );
288

289
    let compute_characters = req.inputs.chars().count();
290
    let mut add_prompt = None;
291
292
    if req.parameters.return_full_text.unwrap_or(false) {
        add_prompt = Some(req.inputs.clone());
293
294
    }

Nicolas Patry's avatar
Nicolas Patry committed
295
    let details: bool = req.parameters.details || req.parameters.decoder_input_details;
296
297

    // Inference
298
    let (response, best_of_responses) = match req.parameters.best_of {
299
        Some(best_of) if best_of > 1 => {
300
            let (response, best_of_responses) = infer.generate_best_of(req, best_of).await?;
301
302
            (response, Some(best_of_responses))
        }
303
        _ => (infer.generate(req).await?, None),
304
    };
Olivier Dehaene's avatar
Olivier Dehaene committed
305

OlivierDehaene's avatar
OlivierDehaene committed
306
    // Token details
307
    let input_length = response._input_length;
OlivierDehaene's avatar
OlivierDehaene committed
308
    let details = match details {
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        true => {
            // convert best_of_responses
            let best_of_sequences = best_of_responses.map(|responses: Vec<InferResponse>| {
                responses
                    .into_iter()
                    .map(|response: InferResponse| {
                        // Add prompt if return_full_text
                        let mut output_text = response.generated_text.text;
                        if let Some(prompt) = &add_prompt {
                            output_text = prompt.clone() + &output_text;
                        }

                        BestOfSequence {
                            generated_text: output_text,
OlivierDehaene's avatar
OlivierDehaene committed
323
                            finish_reason: response.generated_text.finish_reason,
324
325
326
                            generated_tokens: response.generated_text.generated_tokens,
                            prefill: response.prefill,
                            tokens: response.tokens,
Nicolas Patry's avatar
Nicolas Patry committed
327
                            top_tokens: response.top_tokens,
328
329
330
331
332
333
334
                            seed: response.generated_text.seed,
                        }
                    })
                    .collect()
            });

            Some(Details {
OlivierDehaene's avatar
OlivierDehaene committed
335
                finish_reason: response.generated_text.finish_reason,
336
337
338
339
340
                generated_tokens: response.generated_text.generated_tokens,
                prefill: response.prefill,
                tokens: response.tokens,
                seed: response.generated_text.seed,
                best_of_sequences,
Nicolas Patry's avatar
Nicolas Patry committed
341
                top_tokens: response.top_tokens,
342
343
            })
        }
OlivierDehaene's avatar
OlivierDehaene committed
344
345
346
        false => None,
    };

347
348
349
350
    // Timings
    let total_time = start_time.elapsed();
    let validation_time = response.queued - start_time;
    let queue_time = response.start - response.queued;
351
352
    let inference_time = Instant::now() - response.start;
    let time_per_token = inference_time / response.generated_text.generated_tokens;
353

354
355
356
357
358
359
360
361
    // Tracing metadata
    span.record("total_time", format!("{total_time:?}"));
    span.record("validation_time", format!("{validation_time:?}"));
    span.record("queue_time", format!("{queue_time:?}"));
    span.record("inference_time", format!("{inference_time:?}"));
    span.record("time_per_token", format!("{time_per_token:?}"));
    span.record("seed", format!("{:?}", response.generated_text.seed));

362
363
    // Headers
    let mut headers = HeaderMap::new();
364
    headers.insert("x-compute-type", compute_type.parse().unwrap());
365
366
    headers.insert(
        "x-compute-time",
Nicolas Patry's avatar
Nicolas Patry committed
367
        total_time.as_secs_f64().to_string().parse().unwrap(),
368
369
370
371
372
    );
    headers.insert(
        "x-compute-characters",
        compute_characters.to_string().parse().unwrap(),
    );
373
374
375
376
377
378
379
380
381
382
383
    headers.insert(
        "x-total-time",
        total_time.as_millis().to_string().parse().unwrap(),
    );
    headers.insert(
        "x-validation-time",
        validation_time.as_millis().to_string().parse().unwrap(),
    );
    headers.insert(
        "x-queue-time",
        queue_time.as_millis().to_string().parse().unwrap(),
Olivier Dehaene's avatar
Olivier Dehaene committed
384
    );
385
386
387
388
389
390
391
392
    headers.insert(
        "x-inference-time",
        inference_time.as_millis().to_string().parse().unwrap(),
    );
    headers.insert(
        "x-time-per-token",
        time_per_token.as_millis().to_string().parse().unwrap(),
    );
393
394
395
396
397
    headers.insert("x-prompt-tokens", input_length.into());
    headers.insert(
        "x-generated-tokens",
        response.generated_text.generated_tokens.into(),
    );
398

399
    // Metrics
400
401
402
403
404
405
406
407
408
    metrics::counter!("tgi_request_success").increment(1);
    metrics::histogram!("tgi_request_duration").record(total_time.as_secs_f64());
    metrics::histogram!("tgi_request_validation_duration").record(validation_time.as_secs_f64());
    metrics::histogram!("tgi_request_queue_duration").record(queue_time.as_secs_f64());
    metrics::histogram!("tgi_request_inference_duration").record(inference_time.as_secs_f64());
    metrics::histogram!("tgi_request_mean_time_per_token_duration")
        .record(time_per_token.as_secs_f64());
    metrics::histogram!("tgi_request_generated_tokens")
        .record(response.generated_text.generated_tokens as f64);
409

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
410
    // Send response
411
412
413
414
415
    let mut output_text = response.generated_text.text;
    if let Some(prompt) = add_prompt {
        output_text = prompt + &output_text;
    }

416
417
    tracing::debug!("Output: {}", output_text);
    tracing::info!("Success");
418

419
    let response = GenerateResponse {
420
        generated_text: output_text,
OlivierDehaene's avatar
OlivierDehaene committed
421
        details,
422
    };
423
    Ok((headers, Json(response)))
Olivier Dehaene's avatar
Olivier Dehaene committed
424
425
}

Yannic Kilcher's avatar
Yannic Kilcher committed
426
/// Generate a stream of token using Server-Sent Events
427
#[utoipa::path(
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
post,
tag = "Text Generation Inference",
path = "/generate_stream",
request_body = GenerateRequest,
responses(
(status = 200, description = "Generated Text", body = StreamResponse,
content_type = "text/event-stream"),
(status = 424, description = "Generation Error", body = ErrorResponse,
example = json ! ({"error": "Request failed during generation"}),
content_type = "text/event-stream"),
(status = 429, description = "Model is overloaded", body = ErrorResponse,
example = json ! ({"error": "Model is overloaded"}),
content_type = "text/event-stream"),
(status = 422, description = "Input validation error", body = ErrorResponse,
example = json ! ({"error": "Input validation error"}),
content_type = "text/event-stream"),
(status = 500, description = "Incomplete generation", body = ErrorResponse,
example = json ! ({"error": "Incomplete generation"}),
content_type = "text/event-stream"),
)
448
)]
449
#[instrument(
450
451
skip_all,
fields(
452
parameters = ? req.parameters,
453
454
455
456
457
458
459
total_time,
validation_time,
queue_time,
inference_time,
time_per_token,
seed,
)
460
461
)]
async fn generate_stream(
462
    Extension(infer): Extension<Infer>,
463
    Extension(compute_type): Extension<ComputeType>,
464
    Json(req): Json<GenerateRequest>,
465
466
467
468
) -> (
    HeaderMap,
    Sse<impl Stream<Item = Result<Event, Infallible>>>,
) {
469
    let span = tracing::Span::current();
470
    let (headers, response_stream) =
471
472
473
474
475
476
477
478
479
480
481
482
483
        generate_stream_internal(infer, compute_type, Json(req), span).await;

    let response_stream = async_stream::stream! {
        let mut response_stream = Box::pin(response_stream);
        while let Some(raw_event) = response_stream.next().await {
            yield Ok(raw_event.map_or_else(Event::from, |token| {
                Event::default()
                    .json_data(token)
                    .unwrap_or_else(|e| InferError::StreamSerializationError(e.to_string()).into())
            }));
        }
    };

484
485
486
487
488
489
    let sse = Sse::new(response_stream).keep_alive(KeepAlive::default());
    (headers, sse)
}

async fn generate_stream_internal(
    infer: Infer,
490
    ComputeType(compute_type): ComputeType,
491
    Json(req): Json<GenerateRequest>,
492
    span: tracing::Span,
493
494
495
496
) -> (
    HeaderMap,
    impl Stream<Item = Result<StreamResponse, InferError>>,
) {
497
    let start_time = Instant::now();
498
    metrics::counter!("tgi_request_count").increment(1);
499

500
    tracing::debug!("Input: {}", req.inputs);
501

502
    let compute_characters = req.inputs.chars().count();
503
504

    let mut headers = HeaderMap::new();
505
    headers.insert("x-compute-type", compute_type.parse().unwrap());
506
507
508
509
    headers.insert(
        "x-compute-characters",
        compute_characters.to_string().parse().unwrap(),
    );
510
    headers.insert("X-Accel-Buffering", "no".parse().unwrap());
511

512
513
514
515
    let stream = async_stream::stream! {
        // Inference
        let mut end_reached = false;
        let mut error = false;
516
517

        let mut add_prompt = None;
518
519
        if req.parameters.return_full_text.unwrap_or(false) {
            add_prompt = Some(req.inputs.clone());
520
        }
521
        let details = req.parameters.details;
522

523
        let best_of = req.parameters.best_of.unwrap_or(1);
524
525
        if best_of != 1 {
            let err = InferError::from(ValidationError::BestOfStream);
526
            metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
527
            tracing::error!("{err}");
528
            yield Err(err);
529
        } else if req.parameters.decoder_input_details {
530
            let err = InferError::from(ValidationError::PrefillDetailsStream);
531
            metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
532
            tracing::error!("{err}");
533
            yield Err(err);
534
        } else {
535
            match infer.generate_stream(req).instrument(info_span!(parent: &span, "async_stream")).await {
536
                // Keep permit as long as generate_stream lives
537
                Ok((_permit, input_length, response_stream)) => {
538
                    let mut index = 0;
Nicolas Patry's avatar
Nicolas Patry committed
539
                    let mut response_stream = Box::pin(response_stream);
540
541
                    // Server-Sent Event stream
                    while let Some(response) = response_stream.next().await {
542
                        index += 1;
543
544
545
546
547
548
                        match response {
                            Ok(response) => {
                                match response {
                                    // Prefill is ignored
                                    InferStreamResponse::Prefill(_) => {}
                                    // Yield event for every new token
Nicolas Patry's avatar
Nicolas Patry committed
549
550
551
552
                                    InferStreamResponse::Intermediate{
                                        token,
                                        top_tokens,
                                    } => {
553
554
                                        tracing::debug!(parent: &span, "Token: {:?}", token);

555
556
                                        // StreamResponse
                                        let stream_token = StreamResponse {
557
                                            index,
558
                                            token,
Nicolas Patry's avatar
Nicolas Patry committed
559
                                            top_tokens,
560
561
562
                                            generated_text: None,
                                            details: None,
                                        };
563
                                        yield Ok(stream_token);
564
                                    }
565
566
                                    // Yield event for last token and compute timings
                                    InferStreamResponse::End {
567
                                        token,
568
569
570
                                        generated_text,
                                        start,
                                        queued,
Nicolas Patry's avatar
Nicolas Patry committed
571
                                        top_tokens,
572
573
574
575
                                    } => {
                                        // Token details
                                        let details = match details {
                                            true => Some(StreamDetails {
OlivierDehaene's avatar
OlivierDehaene committed
576
                                                finish_reason: generated_text.finish_reason,
577
578
                                                generated_tokens: generated_text.generated_tokens,
                                                seed: generated_text.seed,
579
                                                input_length,
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
                                            }),
                                            false => None,
                                        };

                                        // Timings
                                        let total_time = start_time.elapsed();
                                        let validation_time = queued - start_time;
                                        let queue_time = start - queued;
                                        let inference_time = Instant::now() - start;
                                        let time_per_token = inference_time / generated_text.generated_tokens;

                                        // Tracing metadata
                                        span.record("total_time", format!("{total_time:?}"));
                                        span.record("validation_time", format!("{validation_time:?}"));
                                        span.record("queue_time", format!("{queue_time:?}"));
                                        span.record("inference_time", format!("{inference_time:?}"));
                                        span.record("time_per_token", format!("{time_per_token:?}"));
                                        span.record("seed", format!("{:?}", generated_text.seed));

                                        // Metrics
600
601
602
603
604
605
606
                                        metrics::counter!("tgi_request_success").increment(1);
                                        metrics::histogram!("tgi_request_duration").record(total_time.as_secs_f64());
                                        metrics::histogram!("tgi_request_validation_duration").record(validation_time.as_secs_f64());
                                        metrics::histogram!("tgi_request_queue_duration").record(queue_time.as_secs_f64());
                                        metrics::histogram!("tgi_request_inference_duration").record(inference_time.as_secs_f64());
                                        metrics::histogram!("tgi_request_mean_time_per_token_duration").record(time_per_token.as_secs_f64());
                                        metrics::histogram!("tgi_request_generated_tokens").record(generated_text.generated_tokens as f64);
607
608
609
610
611
612
613
614
615

                                        // StreamResponse
                                        end_reached = true;

                                        let mut output_text = generated_text.text;
                                        if let Some(prompt) = add_prompt {
                                            output_text = prompt + &output_text;
                                        }

616
617
                                        tracing::debug!(parent: &span, "Output: {}", output_text);
                                        tracing::info!(parent: &span, "Success");
618

619
                                        let stream_token = StreamResponse {
620
                                            index,
621
                                            token,
Nicolas Patry's avatar
Nicolas Patry committed
622
                                            top_tokens,
623
624
625
626
                                            generated_text: Some(output_text),
                                            details
                                        };

627
                                        yield Ok(stream_token);
628
629
                                        break;
                                    }
630
631
                                }
                            }
632
633
634
                            // yield error
                            Err(err) => {
                                error = true;
635
                                yield Err(err);
636
637
                                break;
                            }
638
639
                        }
                    }
640
641
642
643
                },
                // yield error
                Err(err) => {
                    error = true;
644
                    yield Err(err);
645
                }
646
647
648
649
            }
            // Check if generation reached the end
            // Skip if we already sent an error
            if !end_reached && !error {
650
                let err = InferError::IncompleteGenerationStream;
651
                metrics::counter!("tgi_request_failure", "err" => "incomplete").increment(1);
652
                tracing::error!("{err}");
653
                yield Err(err);
654
655
656
657
            }
        }
    };

658
659
660
    (headers, stream)
}

661
662
/// Generate tokens
#[utoipa::path(
OlivierDehaene's avatar
OlivierDehaene committed
663
664
665
666
667
668
669
post,
tag = "Text Generation Inference",
path = "/v1/completions",
request_body = CompletionRequest,
responses(
(status = 200, description = "Generated Chat Completion",
content(
670
671
("application/json" = CompletionFinal),
("text/event-stream" = Chunk),
OlivierDehaene's avatar
OlivierDehaene committed
672
673
674
675
676
677
678
679
680
681
682
)),
(status = 424, description = "Generation Error", body = ErrorResponse,
example = json ! ({"error": "Request failed during generation"})),
(status = 429, description = "Model is overloaded", body = ErrorResponse,
example = json ! ({"error": "Model is overloaded"})),
(status = 422, description = "Input validation error", body = ErrorResponse,
example = json ! ({"error": "Input validation error"})),
(status = 500, description = "Incomplete generation", body = ErrorResponse,
example = json ! ({"error": "Incomplete generation"})),
)
)]
683
#[instrument(
OlivierDehaene's avatar
OlivierDehaene committed
684
685
686
687
688
689
690
691
692
693
694
skip_all,
fields(
// parameters = ? req.parameters,
total_time,
validation_time,
queue_time,
inference_time,
time_per_token,
seed,
)
)]
695
pub(crate) async fn completions(
696
697
698
699
700
    Extension(infer): Extension<Infer>,
    Extension(compute_type): Extension<ComputeType>,
    Extension(info): Extension<Info>,
    Json(req): Json<CompletionRequest>,
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
701
    let span = tracing::Span::current();
702
    metrics::counter!("tgi_request_count").increment(1);
703

704
    let CompletionRequest {
705
        model,
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
        max_tokens,
        seed,
        stop,
        stream,
        temperature,
        ..
    } = req;

    let max_new_tokens = max_tokens.or(Some(100));
    let stop = stop.unwrap_or_default();
    // enable greedy only when temperature is 0
    let (do_sample, temperature) = match temperature {
        Some(temperature) if temperature == 0.0 => (false, None),
        other => (true, other),
    };
721
722
723

    // if suffix is present throw an error
    if req.suffix.is_some() {
724
        metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
725
726
727
728
729
730
731
732
733
734
        return Err((
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(ErrorResponse {
                error: "Suffix is not supported and can be achieved by preprocessing the prompt."
                    .to_string(),
                error_type: "suffix not supported".to_string(),
            }),
        ));
    }

735
    if req.prompt.0.len() > info.max_client_batch_size {
736
        metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
737
738
739
740
741
742
743
744
745
746
747
748
749
750
        return Err((
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(ErrorResponse {
                error: format!(
                    "Number of prompts exceeds the maximum allowed batch size of {}",
                    info.max_client_batch_size
                ),
                error_type: "batch size exceeded".to_string(),
            }),
        ));
    }

    let generate_requests: Vec<GenerateRequest> = req
        .prompt
751
        .0
752
753
754
        .iter()
        .map(|prompt| GenerateRequest {
            inputs: prompt.to_string(),
755
            add_special_tokens: true,
756
757
            parameters: GenerateParameters {
                best_of: None,
758
                temperature,
759
760
761
762
763
                repetition_penalty: req.repetition_penalty,
                frequency_penalty: req.frequency_penalty,
                top_k: None,
                top_p: req.top_p,
                typical_p: None,
764
                do_sample,
765
766
                max_new_tokens,
                return_full_text: None,
767
                stop: stop.clone(),
768
769
770
771
772
773
774
                truncate: None,
                watermark: false,
                details: true,
                decoder_input_details: !stream,
                seed,
                top_n_tokens: None,
                grammar: None,
775
                adapter_id: model.as_ref().filter(|m| *m != "tgi").map(String::from),
776
777
778
779
780
781
782
            },
        })
        .collect();

    let mut x_compute_type = None;
    let mut x_compute_characters = 0u32;
    let mut x_accel_buffering = None;
783
784

    if stream {
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
        let mut response_streams = FuturesOrdered::new();
        for (index, generate_request) in generate_requests.into_iter().enumerate() {
            let model_id = info.model_id.clone();
            let system_fingerprint =
                format!("{}-{}", info.version, info.docker_label.unwrap_or("native"));
            let infer_clone = infer.clone();
            let compute_type_clone = compute_type.clone();
            let span_clone = span.clone();

            // Create a future for each generate_stream_internal call.
            let generate_future = async move {
                let (header_tx, header_rx) = oneshot::channel();
                let (sse_tx, sse_rx) = tokio::sync::mpsc::unbounded_channel();

                tokio::spawn(async move {
800
                    let (headers, response_stream) = generate_stream_internal(
801
802
803
804
805
806
                        infer_clone.clone(),
                        compute_type_clone.clone(),
                        Json(generate_request),
                        span_clone.clone(),
                    )
                    .await;
807

808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
                    let response_stream = async_stream::stream! {
                        let mut response_stream = Box::pin(response_stream);

                        while let Some(stream_token) = response_stream.next().await {
                            match stream_token {
                                Ok(stream_token) => {
                                    let event = Event::default();

                                    let current_time = std::time::SystemTime::now()
                                        .duration_since(std::time::UNIX_EPOCH)
                                        .unwrap_or_else(|_| std::time::Duration::from_secs(0))
                                        .as_secs();

                                    let message = match stream_token.details {
                                        Some(details) => {
                                            let completion_tokens = details.generated_tokens;
                                            let prompt_tokens = details.input_length;
                                            let total_tokens = prompt_tokens + completion_tokens;

                                            Completion::Final(CompletionFinal {
                                                id: String::new(),
                                                created: current_time,
                                                model: model_id.clone(),
                                                system_fingerprint: system_fingerprint.clone(),
                                                choices: vec![CompletionComplete {
                                                    finish_reason: details.finish_reason.to_string(),
                                                    index: index as u32,
                                                    logprobs: None,
                                                    text: stream_token.token.text,
                                                }],
                                                usage: Usage {
                                                    prompt_tokens,
                                                    completion_tokens,
                                                    total_tokens,
                                                },
                                            })
                                        }
                                        None => Completion::Chunk(Chunk {
                                            id: String::new(),
                                            created: current_time,
                                            choices: vec![CompletionComplete {
                                                finish_reason: String::new(),
                                                index: index as u32,
                                                logprobs: None,
                                                text: stream_token.token.text,
                                            }],
                                            model: model_id.clone(),
                                            system_fingerprint: system_fingerprint.clone(),
                                        }),
                                    };

                                    let event = event
                                        .json_data(message)
                                        .unwrap_or_else(|_e| Event::default());

                                    yield Ok(event);
                                }
                                Err(err) => yield Ok(Event::from(err)),
                            }
                        }
                    };

870
                    // send and dont wait for response
871
                    let _ = header_tx.send(headers);
872

873
                    // pin an emit messages to the sse_tx
874
                    let mut sse = Box::pin(response_stream);
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
                    while let Some(event) = sse.next().await {
                        if sse_tx.send(event).is_err() {
                            tracing::error!("Failed to send event. Receiver dropped.");
                            break;
                        }
                    }
                });

                (header_rx, sse_rx)
            };
            response_streams.push_back(generate_future);
        }

        let mut all_rxs = vec![];

        while let Some((header_rx, sse_rx)) = response_streams.next().await {
            all_rxs.push(sse_rx);

            // get the headers from the first response of each stream
            let headers = header_rx.await.map_err(|e| {
                tracing::error!("Failed to get headers: {:?}", e);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ErrorResponse {
                        error: "Failed to get headers".to_string(),
                        error_type: "headers".to_string(),
                    }),
902
                )
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
            })?;
            if x_compute_type.is_none() {
                x_compute_type = headers
                    .get("x-compute-type")
                    .and_then(|v| v.to_str().ok())
                    .map(|v| v.to_string());

                x_accel_buffering = headers
                    .get("x-accel-buffering")
                    .and_then(|v| v.to_str().ok())
                    .map(|v| v.to_string());
            }
            x_compute_characters += headers
                .get("x-compute-characters")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse().ok())
                .unwrap_or(0);
        }
921

922
923
924
925
926
927
928
929
        let mut headers = HeaderMap::new();
        if let Some(x_compute_type) = x_compute_type {
            headers.insert("x-compute-type", x_compute_type.parse().unwrap());
        }
        headers.insert("x-compute-characters", x_compute_characters.into());
        if let Some(x_accel_buffering) = x_accel_buffering {
            headers.insert("x-accel-buffering", x_accel_buffering.parse().unwrap());
        }
930

931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
        // now sink the sse streams into a single stream and remove the ones that are done
        let stream: AsyncStream<Result<Event, Infallible>, _> = async_stream::stream! {
            loop {
                let mut i = 0;
                while i < all_rxs.len() {
                    let rx = &mut all_rxs[i];
                    select! {
                        Some(event) = rx.recv() => {
                            yield event;
                        }
                        else => {
                            all_rxs.remove(i);
                            continue; // skip the increment to handle the next element at the same index
                        }
                    }
                    i += 1; // only increment when no element was removed
                }

                if all_rxs.is_empty() {
                    break;
                }
            }
        };

955
956
957
958
        let stream = stream.chain(futures::stream::once(async {
            Ok(Event::default().data("[DONE]"))
        }));

959
        let sse = Sse::new(stream).keep_alive(KeepAlive::default());
960
961
962
963
964
965
966
        Ok((headers, sse).into_response())
    } else {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_else(|_| std::time::Duration::from_secs(0))
            .as_secs();

967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
        let responses = FuturesUnordered::new();
        for (index, generate_request) in generate_requests.into_iter().enumerate() {
            let infer_clone = infer.clone();
            let compute_type_clone = compute_type.clone();
            let span_clone = span.clone();
            let response_future = async move {
                let result = generate_internal(
                    Extension(infer_clone),
                    compute_type_clone,
                    Json(generate_request),
                    span_clone,
                )
                .await;
                result.map(|(headers, generation)| (index, headers, generation))
            };
            responses.push(response_future);
        }
        let generate_responses = responses.try_collect::<Vec<_>>().await?;

        let mut prompt_tokens = 0u32;
        let mut completion_tokens = 0u32;
        let mut total_tokens = 0u32;

        let mut x_compute_time = 0u32;
        let mut x_total_time = 0u32;
        let mut x_validation_time = 0u32;
        let mut x_queue_time = 0u32;
        let mut x_inference_time = 0u32;
        let mut x_time_per_token = 0u32;
        let mut x_prompt_tokens = 0u32;
        let mut x_generated_tokens = 0u32;

        let choices = generate_responses
            .into_iter()
            .map(|(index, headers, Json(generation))| {
                let details = generation.details.ok_or((
                    // this should never happen but handle if details are missing unexpectedly
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ErrorResponse {
                        error: "No details in generation".to_string(),
                        error_type: "no details".to_string(),
                    }),
                ))?;

                if x_compute_type.is_none() {
                    x_compute_type = headers
                        .get("x-compute-type")
                        .and_then(|v| v.to_str().ok())
                        .map(|v| v.to_string());
                }

                // accumulate headers and usage from each response
                x_compute_time += headers
                    .get("x-compute-time")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_compute_characters += headers
                    .get("x-compute-characters")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_total_time += headers
                    .get("x-total-time")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_validation_time += headers
                    .get("x-validation-time")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_queue_time += headers
                    .get("x-queue-time")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_inference_time += headers
                    .get("x-inference-time")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_time_per_token += headers
                    .get("x-time-per-token")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_prompt_tokens += headers
                    .get("x-prompt-tokens")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);
                x_generated_tokens += headers
                    .get("x-generated-tokens")
                    .and_then(|v| v.to_str().ok()?.parse().ok())
                    .unwrap_or(0);

                prompt_tokens += details.prefill.len() as u32;
                completion_tokens += details.generated_tokens;
                total_tokens += details.prefill.len() as u32 + details.generated_tokens;

                Ok(CompletionComplete {
1061
                    finish_reason: details.finish_reason.format(true),
1062
1063
1064
1065
1066
1067
1068
                    index: index as u32,
                    logprobs: None,
                    text: generation.generated_text,
                })
            })
            .collect::<Result<Vec<_>, _>>()
            .map_err(|(status, Json(err))| (status, Json(err)))?;
1069

1070
        let response = Completion::Final(CompletionFinal {
1071
1072
1073
1074
1075
1076
1077
1078
            id: "".to_string(),
            created: current_time,
            model: info.model_id.clone(),
            system_fingerprint: format!(
                "{}-{}",
                info.version,
                info.docker_label.unwrap_or("native")
            ),
1079
            choices,
1080
            usage: Usage {
1081
1082
1083
                prompt_tokens,
                completion_tokens,
                total_tokens,
1084
            },
1085
        });
1086

1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
        // headers similar to `generate` but aggregated
        let mut headers = HeaderMap::new();
        if let Some(x_compute_type) = x_compute_type {
            headers.insert("x-compute-type", x_compute_type.parse().unwrap());
        }
        headers.insert("x-compute-characters", x_compute_characters.into());
        headers.insert("x-total-time", x_total_time.into());
        headers.insert("x-validation-time", x_validation_time.into());
        headers.insert("x-queue-time", x_queue_time.into());
        headers.insert("x-inference-time", x_inference_time.into());
        headers.insert("x-time-per-token", x_time_per_token.into());
        headers.insert("x-prompt-tokens", x_prompt_tokens.into());
        headers.insert("x-generated-tokens", x_generated_tokens.into());
        if let Some(x_accel_buffering) = x_accel_buffering {
            headers.insert("x-accel-buffering", x_accel_buffering.parse().unwrap());
        }
1103
1104
1105
1106
        Ok((headers, Json(response)).into_response())
    }
}

1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
enum StreamState {
    Buffering,
    BufferTrailing,
    Content { skip_close_quote: bool },
}

/// Convert a StreamResponse into an Event to be sent over SSE
fn create_event_from_stream_token(
    stream_token: &StreamResponse,
    logprobs: bool,
    stream_options: Option<StreamOptions>,
    inner_using_tools: bool,
    system_fingerprint: String,
    model_id: String,
) -> Event {
    let event = Event::default();
    let current_time = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_else(|_| std::time::Duration::from_secs(0))
        .as_secs();

    let logprobs = logprobs.then(|| {
        ChatCompletionLogprobs::from((stream_token.token.clone(), stream_token.top_tokens.clone()))
    });

    // replace the content with the tool calls if grammar is present
    let (content, tool_calls) = if inner_using_tools {
        (None, Some(vec![stream_token.token.text.clone()]))
    } else {
        let content = if !stream_token.token.special {
            Some(stream_token.token.text.clone())
        } else {
            None
        };

        (content, None)
    };

    let (usage, finish_reason) = match &stream_token.details {
        Some(details) => {
            let usage = if stream_options
                .as_ref()
                .map(|s| s.include_usage)
                .unwrap_or(false)
            {
                let completion_tokens = details.generated_tokens;
                let prompt_tokens = details.input_length;
                let total_tokens = prompt_tokens + completion_tokens;
                Some(Usage {
                    completion_tokens,
                    prompt_tokens,
                    total_tokens,
                })
            } else {
                None
            };
            (usage, Some(details.finish_reason.format(true)))
        }
        None => (None, None),
    };

    let chat_complete = CompletionType::ChatCompletionChunk(ChatCompletionChunk::new(
        model_id.clone(),
        system_fingerprint.clone(),
        content,
        tool_calls,
        current_time,
        logprobs,
        finish_reason,
        usage,
    ));

    event.json_data(chat_complete).unwrap_or_else(|e| {
        println!("Failed to serialize ChatCompletionChunk: {:?}", e);
        Event::default()
    })
}

1185
1186
/// Generate tokens
#[utoipa::path(
OlivierDehaene's avatar
OlivierDehaene committed
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
post,
tag = "Text Generation Inference",
path = "/v1/chat/completions",
request_body = ChatRequest,
responses(
(status = 200, description = "Generated Chat Completion",
content(
("application/json" = ChatCompletion),
("text/event-stream" = ChatCompletionChunk),
)),
(status = 424, description = "Generation Error", body = ErrorResponse,
example = json ! ({"error": "Request failed during generation"})),
(status = 429, description = "Model is overloaded", body = ErrorResponse,
example = json ! ({"error": "Model is overloaded"})),
(status = 422, description = "Input validation error", body = ErrorResponse,
example = json ! ({"error": "Input validation error"})),
(status = 500, description = "Incomplete generation", body = ErrorResponse,
example = json ! ({"error": "Incomplete generation"})),
)
)]
1207
#[instrument(
OlivierDehaene's avatar
OlivierDehaene committed
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
skip_all,
fields(
// parameters = ? req.parameters,
total_time,
validation_time,
queue_time,
inference_time,
time_per_token,
seed,
)
)]
1219
pub(crate) async fn chat_completions(
1220
    Extension(infer): Extension<Infer>,
1221
    Extension(compute_type): Extension<ComputeType>,
1222
    Extension(info): Extension<Info>,
Nicolas Patry's avatar
Nicolas Patry committed
1223
    Json(chat): Json<ChatRequest>,
1224
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
1225
    let span = tracing::Span::current();
1226
    metrics::counter!("tgi_request_count").increment(1);
1227
1228
    let ChatRequest {
        stream,
Nicolas Patry's avatar
Nicolas Patry committed
1229
        stream_options,
Nicolas Patry's avatar
Nicolas Patry committed
1230
        logprobs,
1231
        ..
Nicolas Patry's avatar
Nicolas Patry committed
1232
1233
1234
    } = chat.clone();
    let (generate_request, using_tools): (GenerateRequest, bool) =
        chat.try_into_generate(&infer)?;
1235

Nicolas Patry's avatar
Nicolas Patry committed
1236
    let logprobs = logprobs.unwrap_or_default();
1237
1238
1239
1240
1241
1242

    // static values that will be returned in all cases
    let model_id = info.model_id.clone();
    let system_fingerprint = format!("{}-{}", info.version, info.docker_label.unwrap_or("native"));
    // switch on stream
    if stream {
1243
1244
        let (headers, response_stream) =
            generate_stream_internal(infer, compute_type, Json(generate_request), span).await;
1245

1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
        // regex to match any function name
        let function_regex = match Regex::new(r#"\{"function":\{"_name":"([^"]+)""#) {
            Ok(regex) => regex,
            Err(e) => {
                return Err((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ErrorResponse {
                        error: format!("Failed to compile regex: {}", e),
                        error_type: "regex".to_string(),
                    }),
                ))
            }
        };
1259

1260
1261
1262
1263
1264
1265
        let response_stream = async_stream::stream! {
            let mut response_stream = Box::pin(response_stream);
            let mut buffer = Vec::new();
            let mut json_buffer = String::new();
            let mut state = if using_tools {
                StreamState::Buffering
drbh's avatar
drbh committed
1266
            } else {
1267
1268
1269
                StreamState::Content {
                    skip_close_quote: false,
                }
drbh's avatar
drbh committed
1270
            };
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
            let mut response_as_tool = using_tools;
            while let Some(result) = response_stream.next().await {
                if let Ok(stream_token) = result {
                    let token_text = &stream_token.token.text.clone();
                    match state {
                        StreamState::Buffering => {
                            json_buffer.push_str(&token_text.replace(" ", ""));
                            buffer.push(stream_token);
                            if let Some(captures) = function_regex.captures(&json_buffer) {
                                let function_name = captures[1].to_string();
                                if function_name == "no_tool" {
                                    state = StreamState::BufferTrailing;
                                    response_as_tool = false;
                                    buffer.clear();
                                    json_buffer.clear();
                                } else {
                                    state = StreamState::Content {
                                        skip_close_quote: false,
                                    };
                                    // send all the buffered messages
                                    for stream_token in &buffer {
                                        let event = create_event_from_stream_token(
                                            stream_token,
                                            logprobs,
                                            stream_options.clone(),
                                            response_as_tool,
                                            system_fingerprint.clone(),
                                            model_id.clone(),
                                        );
                                        yield Ok::<Event, Infallible>(event);
                                    }
                                }
                            }
                        }
                        // if we skipped sending the buffer we need to avoid sending the following json key and quotes
                        StreamState::BufferTrailing => {
                            let infix_text = "\"content\":\"";
                            json_buffer.push_str(&token_text.replace(" ", ""));
                            // keep capturing until we find the infix text
                            match json_buffer.find(infix_text) {
                                Some(content_key_index) => {
                                    json_buffer =
                                        json_buffer[content_key_index + infix_text.len()..].to_string();
                                }
                                None => {
                                    continue;
                                }
                            }
                            // if there is leftover text after removing the infix text, we need to send it
                            if !json_buffer.is_empty() {
                                let event = Event::default();
                                let current_time = std::time::SystemTime::now()
                                    .duration_since(std::time::UNIX_EPOCH)
                                    .unwrap_or_else(|_| std::time::Duration::from_secs(0))
                                    .as_secs();
                                let chat_complete =
                                    CompletionType::ChatCompletionChunk(ChatCompletionChunk::new(
                                        model_id.clone(),
                                        system_fingerprint.clone(),
                                        Some(json_buffer.clone()),
                                        None,
                                        current_time,
                                        None,
                                        None,
                                        None,
                                    ));
                                yield Ok(event.json_data(chat_complete).unwrap_or_else(|e| {
                                    InferError::StreamSerializationError(e.to_string()).into()
                                }));
                            }
                            // cleanup the buffers
                            buffer.clear();
                            json_buffer.clear();
                            state = StreamState::Content {
                                skip_close_quote: true,
                            };
                        }
                        StreamState::Content { skip_close_quote } => {
                            if skip_close_quote && token_text.contains('"') {
                                break;
                            }
drbh's avatar
drbh committed
1352

1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
                            // send the content
                            let event = create_event_from_stream_token(
                                &stream_token,
                                logprobs,
                                stream_options.clone(),
                                response_as_tool,
                                system_fingerprint.clone(),
                                model_id.clone(),
                            );

                            yield Ok::<Event, Infallible>(event);
                        }
                    }
Nicolas Patry's avatar
Nicolas Patry committed
1366
                }
1367
1368
            }
            yield Ok::<Event, Infallible>(Event::default().data("[DONE]"));
1369
1370
1371
1372
1373
        };

        let sse = Sse::new(response_stream).keep_alive(KeepAlive::default());
        Ok((headers, sse).into_response())
    } else {
1374
1375
        let (headers, Json(generation)) =
            generate_internal(Extension(infer), compute_type, Json(generate_request), span).await?;
1376
1377
1378
1379
1380
1381

        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_else(|_| std::time::Duration::from_secs(0))
            .as_secs();

drbh's avatar
drbh committed
1382
        let (tool_calls, output) = if using_tools {
1383
1384
1385
1386
1387
1388
1389
            let gen_text_value: Value =
                serde_json::from_str(&generation.generated_text).map_err(|e| {
                    InferError::ToolError(format!(
                        "Failed to parse generated text: {} {:?}",
                        e, generation.generated_text
                    ))
                })?;
drbh's avatar
drbh committed
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
            let function = gen_text_value.get("function").ok_or(InferError::ToolError(
                "No function found in generated text".to_string(),
            ))?;

            let name = function
                .get("_name")
                .and_then(Value::as_str)
                .ok_or(InferError::ToolError(
                    "No _name found in generated text".to_string(),
                ))?
                .to_string();

            let mut arguments = function.clone();
            if let Value::Object(ref mut props) = arguments {
                props.remove("_name");
            }
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
            match name.as_str() {
                "no_tool" => {
                    // parse the content message
                    let content_message = arguments
                        .get("content")
                        .and_then(Value::as_str)
                        .ok_or_else(|| {
                            InferError::ToolError(
                                "No `content` found in generated text".to_string(),
                            )
                        })?
                        .to_string();
                    (None, Some(content_message))
                }
                _ => {
                    let tool_calls = vec![ToolCall {
                        id: "0".to_string(),
                        r#type: "function".to_string(),
                        function: FunctionDefinition {
                            description: None,
                            name,
                            arguments,
                        },
                    }];
                    (Some(tool_calls), None)
                }
            }
drbh's avatar
drbh committed
1433
1434
1435
        } else {
            (None, Some(generation.generated_text))
        };
1436
        // build the complete response object with the full text
1437
        let response = CompletionType::ChatCompletion(ChatCompletion::new(
1438
1439
            model_id,
            system_fingerprint,
drbh's avatar
drbh committed
1440
            output,
1441
1442
1443
            current_time,
            generation.details.unwrap(),
            logprobs,
drbh's avatar
drbh committed
1444
            tool_calls,
1445
        ));
1446
1447
1448
1449

        // wrap generation inside a Vec to match api-inference
        Ok((headers, Json(response)).into_response())
    }
1450
1451
}

1452
1453
/// Tokenize inputs
#[utoipa::path(
OlivierDehaene's avatar
OlivierDehaene committed
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
post,
tag = "Text Generation Inference",
path = "/tokenize",
request_body = GenerateRequest,
responses(
(status = 200, description = "Tokenized ids", body = TokenizeResponse),
(status = 404, description = "No tokenizer found", body = ErrorResponse,
example = json ! ({"error": "No fast tokenizer available"})),
)
)]
1464
1465
1466
1467
#[instrument(skip_all)]
async fn tokenize(
    Extension(infer): Extension<Infer>,
    Json(req): Json<GenerateRequest>,
1468
) -> Result<Json<TokenizeResponse>, (StatusCode, Json<ErrorResponse>)> {
1469
1470
    let input = req.inputs.clone();
    let encoding = infer.tokenize(req).await?;
1471
1472
    let tokens = encoding_to_tokens(&encoding, &input);
    Ok(Json(TokenizeResponse(tokens)))
1473
1474
}

1475
1476
/// Prometheus metrics scrape endpoint
#[utoipa::path(
1477
1478
1479
1480
    get,
    tag = "Text Generation Inference",
    path = "/metrics",
    responses((status = 200, description = "Prometheus Metrics", body = String))
1481
1482
1483
1484
1485
)]
async fn metrics(prom_handle: Extension<PrometheusHandle>) -> String {
    prom_handle.render()
}

1486
1487
1488
#[derive(Clone, Debug)]
pub(crate) struct ComputeType(String);

Nicolas Patry's avatar
Nicolas Patry committed
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
// OpenAPI documentation
#[derive(OpenApi)]
#[openapi(
paths(
health,
get_model_info,
compat_generate,
generate,
generate_stream,
chat_completions,
completions,
tokenize,
metrics,
drbh's avatar
drbh committed
1502
openai_get_model_info,
1503
sagemaker_compatibility,
Nicolas Patry's avatar
Nicolas Patry committed
1504
1505
1506
1507
1508
),
components(
schemas(
Info,
CompatGenerateRequest,
1509
SagemakerRequest,
Nicolas Patry's avatar
Nicolas Patry committed
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
GenerateRequest,
GrammarType,
ChatRequest,
Message,
MessageContent,
MessageChunk,
Url,
FunctionName,
OutputMessage,
TextMessage,
ToolCallMessage,
ToolCallDelta,
ChatCompletionComplete,
ChatCompletionChoice,
ChatCompletionDelta,
ChatCompletionChunk,
ChatCompletionLogprob,
ChatCompletionLogprobs,
ChatCompletionTopLogprob,
ChatCompletion,
CompletionRequest,
CompletionComplete,
1532
1533
SagemakerResponse,
SagemakerStreamResponse,
Nicolas Patry's avatar
Nicolas Patry committed
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
Chunk,
Completion,
CompletionFinal,
Prompt,
GenerateParameters,
PrefillToken,
Token,
GenerateResponse,
TokenizeResponse,
SimpleToken,
BestOfSequence,
Details,
FinishReason,
StreamResponse,
StreamDetails,
ErrorResponse,
GrammarType,
Usage,
Nicolas Patry's avatar
Nicolas Patry committed
1552
StreamOptions,
Nicolas Patry's avatar
Nicolas Patry committed
1553
1554
1555
1556
1557
1558
1559
DeltaToolCall,
ToolType,
Tool,
ToolCall,
Function,
FunctionDefinition,
ToolChoice,
drbh's avatar
drbh committed
1560
ModelInfo,
Nicolas Patry's avatar
Nicolas Patry committed
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
)
),
tags(
(name = "Text Generation Inference", description = "Hugging Face Text Generation Inference API")
),
info(
title = "Text Generation Inference",
license(
name = "Apache 2.0",
url = "https://www.apache.org/licenses/LICENSE-2.0"
)
)
)]
pub struct ApiDoc;

pub fn schema() -> ApiDoc {
    ApiDoc
}

1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
fn py_resolve_tokenizer(
    py: pyo3::Python,
    tokenizer_name: &str,
    revision: Option<&str>,
    trust_remote_code: bool,
) -> pyo3::PyResult<()> {
    let transformers = py.import_bound("transformers")?;
    let auto = transformers.getattr("AutoTokenizer")?;
    let from_pretrained = auto.getattr("from_pretrained")?;
    let args = (tokenizer_name,);
    let kwargs = if let Some(rev) = &revision {
        [
            ("revision", rev.to_string().into_py(py)),
            ("trust_remote_code", trust_remote_code.into_py(py)),
        ]
        .into_py_dict_bound(py)
    } else {
        [("trust_remote_code", trust_remote_code.into_py(py))].into_py_dict_bound(py)
    };
    let tokenizer = from_pretrained.call(args, Some(&kwargs))?;
    let save = tokenizer.getattr("save_pretrained")?;
    let args = ("out".to_string(),);
    save.call1(args)?;
    Ok(())
}

fn legacy_tokenizer_handle(config_filename: Option<&PathBuf>) -> Option<()> {
    // XXX Legacy case for FasterDecoding/medusa-vicuna-7b-v1.3
    // and state-spaces/mamba-130m
    tracing::warn!("Odd tokenizer detected, falling back on legacy tokenization");

    #[derive(serde::Deserialize)]
    struct FallbackConfig {
        base_model_name_or_path: Option<String>,
        model_type: Option<String>,
        ssm_config: Option<serde_json::Value>,
    }
    config_filename.and_then(|filename| {
        std::fs::read_to_string(filename)
            .ok()
            .as_ref()
            .and_then(|c| {
                let config: Result<FallbackConfig, _> = serde_json::from_str(c);
                if let Ok(config) = config {
                    if config.model_type.is_none() {
                        if let Some(base) = config.base_model_name_or_path {
                            pyo3::Python::with_gil(|py| -> PyResult<()> {
                                py_resolve_tokenizer(py, &base, Some("main"), false)
                            })
                            .ok()?;
                        }
                    }
                    if config.ssm_config.is_some() {
                        // XXX Legacy mamba
                        pyo3::Python::with_gil(|py| -> PyResult<()> {
                            py_resolve_tokenizer(py, "EleutherAI/gpt-neox-20b", Some("main"), false)
                        })
                        .ok()?;
                    }
                }
                Some(())
            })
    })
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1645
1646
1647
/// Serving method
#[allow(clippy::too_many_arguments)]
pub async fn run(
Nicolas Patry's avatar
Nicolas Patry committed
1648
    backend: impl Backend + Send + Sync + 'static,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1649
    max_concurrent_requests: usize,
1650
    max_best_of: usize,
1651
    max_stop_sequences: usize,
Nicolas Patry's avatar
Nicolas Patry committed
1652
    max_top_n_tokens: u32,
OlivierDehaene's avatar
OlivierDehaene committed
1653
    max_input_tokens: usize,
1654
    max_total_tokens: usize,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1655
    validation_workers: usize,
Erik Kaunismäki's avatar
Erik Kaunismäki committed
1656
    api_key: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
1657
1658
1659
    tokenizer_name: String,
    tokenizer_config_path: Option<String>,
    revision: Option<String>,
1660
    trust_remote_code: bool,
Nicolas Patry's avatar
Nicolas Patry committed
1661
1662
1663
    hostname: String,
    port: u16,
    cors_allow_origin: Option<Vec<String>>,
1664
    ngrok: bool,
1665
1666
    _ngrok_authtoken: Option<String>,
    _ngrok_edge: Option<String>,
Nicolas Patry's avatar
Nicolas Patry committed
1667
    disable_grammar_support: bool,
1668
    max_client_batch_size: usize,
1669
    usage_stats_level: usage_stats::UsageStatsLevel,
OlivierDehaene's avatar
OlivierDehaene committed
1670
) -> Result<(), WebServerError> {
Nicolas Patry's avatar
Nicolas Patry committed
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
    // CORS allowed origins
    // map to go inside the option and then map to parse from String to HeaderValue
    // Finally, convert to AllowOrigin
    let allow_origin: Option<AllowOrigin> = cors_allow_origin.map(|cors_allow_origin| {
        AllowOrigin::list(
            cors_allow_origin
                .iter()
                .map(|origin| origin.parse::<HeaderValue>().unwrap()),
        )
    });
1681

Nicolas Patry's avatar
Nicolas Patry committed
1682
1683
1684
1685
    // Parse Huggingface hub token
    let authorization_token = std::env::var("HF_TOKEN")
        .or_else(|_| std::env::var("HUGGING_FACE_HUB_TOKEN"))
        .ok();
OlivierDehaene's avatar
OlivierDehaene committed
1686

Nicolas Patry's avatar
Nicolas Patry committed
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
    // Tokenizer instance
    // This will only be used to validate payloads
    let local_path = Path::new(&tokenizer_name);

    // Shared API builder initialization
    let api_builder = || {
        let mut builder = ApiBuilder::new()
            .with_progress(false)
            .with_token(authorization_token);

        if let Ok(cache_dir) = std::env::var("HUGGINGFACE_HUB_CACHE") {
            builder = builder.with_cache_dir(cache_dir.into());
        }

        builder
    };

    // Decide if we need to use the API based on the revision and local path
    let use_api = revision.is_some() || !local_path.exists() || !local_path.is_dir();

    // Initialize API if needed
    #[derive(Clone)]
    enum Type {
        Api(Api),
        Cache(Cache),
        None,
    }
    let api = if use_api {
        if std::env::var("HF_HUB_OFFLINE") == Ok("1".to_string()) {
            let cache = std::env::var("HUGGINGFACE_HUB_CACHE")
                .map_err(|_| ())
                .map(|cache_dir| Cache::new(cache_dir.into()))
                .unwrap_or_else(|_| Cache::default());
            tracing::warn!("Offline mode active using cache defaults");
            Type::Cache(cache)
        } else {
            tracing::info!("Using the Hugging Face API");
            match api_builder().build() {
                Ok(api) => Type::Api(api),
                Err(_) => {
                    tracing::warn!("Unable to build the Hugging Face API");
                    Type::None
OlivierDehaene's avatar
OlivierDehaene committed
1729
                }
Nicolas Patry's avatar
Nicolas Patry committed
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
            }
        }
    } else {
        Type::None
    };

    // Load tokenizer and model info
    let (
        config_filename,
        tokenizer_config_filename,
        preprocessor_config_filename,
        processor_config_filename,
        model_info,
    ) = match api {
        Type::None => (
            Some(local_path.join("config.json")),
            Some(local_path.join("tokenizer_config.json")),
            Some(local_path.join("preprocessor_config.json")),
            Some(local_path.join("processor_config.json")),
            None,
        ),
        Type::Api(api) => {
            let api_repo = api.repo(Repo::with_revision(
                tokenizer_name.to_string(),
                RepoType::Model,
                revision.clone().unwrap_or_else(|| "main".to_string()),
            ));

            let config_filename = api_repo.get("config.json").await.ok();
            let tokenizer_config_filename = api_repo.get("tokenizer_config.json").await.ok();
            let preprocessor_config_filename = api_repo.get("preprocessor_config.json").await.ok();
            let processor_config_filename = api_repo.get("processor_config.json").await.ok();
OlivierDehaene's avatar
OlivierDehaene committed
1762

Nicolas Patry's avatar
Nicolas Patry committed
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
            let model_info = if let Some(model_info) = get_hub_model_info(&api_repo).await {
                Some(model_info)
            } else {
                tracing::warn!("Could not retrieve model info from the Hugging Face hub.");
                None
            };
            (
                config_filename,
                tokenizer_config_filename,
                preprocessor_config_filename,
                processor_config_filename,
                model_info,
            )
        }
        Type::Cache(cache) => {
            let repo = cache.repo(Repo::with_revision(
                tokenizer_name.to_string(),
                RepoType::Model,
                revision.clone().unwrap_or_else(|| "main".to_string()),
            ));
            (
                repo.get("config.json"),
                repo.get("tokenizer_config.json"),
                repo.get("preprocessor_config.json"),
                repo.get("processor_config.json"),
                None,
            )
        }
    };

    // Read the JSON contents of the file as an instance of 'HubTokenizerConfig'.
    let tokenizer_config: Option<HubTokenizerConfig> = if let Some(filename) = tokenizer_config_path
    {
        HubTokenizerConfig::from_file(filename)
    } else {
        tokenizer_config_filename.and_then(HubTokenizerConfig::from_file)
    };
    let tokenizer_config = tokenizer_config.unwrap_or_else(|| {
        tracing::warn!("Could not find tokenizer config locally and no API specified");
        HubTokenizerConfig::default()
    });

1805
    let tokenizer: Tokenizer = {
Nicolas Patry's avatar
Nicolas Patry committed
1806
        use pyo3::prelude::*;
1807
1808
        pyo3::Python::with_gil(|py| -> PyResult<()> {
            py_resolve_tokenizer(py, &tokenizer_name, revision.as_deref(), trust_remote_code)?;
Nicolas Patry's avatar
Nicolas Patry committed
1809
1810
1811
1812
            Ok(())
        })
        .inspect_err(|err| {
            tracing::error!("Failed to import python tokenizer {err}");
1813
1814
1815
1816
1817
1818
1819
1820
1821
        })
        .or_else(|err| {
            let out = legacy_tokenizer_handle(config_filename.as_ref());
            out.ok_or(err)
        })
        .expect("We cannot load a tokenizer");
        let filename = "out/tokenizer.json";
        if let Ok(tok) = tokenizers::Tokenizer::from_file(filename) {
            Tokenizer::Rust(tok)
Nicolas Patry's avatar
Nicolas Patry committed
1822
        } else {
1823
1824
1825
1826
1827
1828
            Tokenizer::Python {
                tokenizer_name: tokenizer_name.clone(),
                revision: revision.clone(),
            }
        }
    };
Nicolas Patry's avatar
Nicolas Patry committed
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855

    let config: Option<Config> = config_filename.and_then(|filename| {
        std::fs::read_to_string(filename)
            .ok()
            .as_ref()
            .and_then(|c| {
                let config: Result<Config, _> = serde_json::from_str(c);
                if let Err(err) = &config {
                    tracing::warn!("Could not parse config {err:?}");
                }
                config.ok()
            })
    });
    let model_info = model_info.unwrap_or_else(|| HubModelInfo {
        model_id: tokenizer_name.to_string(),
        sha: None,
        pipeline_tag: None,
    });

    let processor_config = processor_config_filename
        .and_then(HubProcessorConfig::from_file)
        .unwrap_or_default();

    let preprocessor_config: Option<HubPreprocessorConfig> =
        preprocessor_config_filename.and_then(HubPreprocessorConfig::from_file);

    tracing::info!("Using config {config:?}");
OlivierDehaene's avatar
OlivierDehaene committed
1856

Nicolas Patry's avatar
Nicolas Patry committed
1857
1858
    // Only send usage stats when TGI is run in container and the function returns Some
    let is_container = matches!(usage_stats::is_container(), Ok(true));
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
    let user_agent = match (usage_stats_level, is_container) {
        (usage_stats::UsageStatsLevel::On | usage_stats::UsageStatsLevel::NoStack, true) => {
            let reduced_args = usage_stats::Args::new(
                config.clone(),
                tokenizer_config.tokenizer_class.clone(),
                max_concurrent_requests,
                max_best_of,
                max_stop_sequences,
                max_top_n_tokens,
                max_input_tokens,
                max_total_tokens,
                // waiting_served_ratio,
                // max_batch_prefill_tokens,
                // max_batch_total_tokens,
                // max_waiting_tokens,
                // max_batch_size,
                revision.clone(),
                validation_workers,
                disable_grammar_support,
                max_client_batch_size,
                usage_stats_level,
            );
            Some(usage_stats::UserAgent::new(reduced_args))
        }
        _ => None,
Nicolas Patry's avatar
Nicolas Patry committed
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
    };

    if let Some(ref ua) = user_agent {
        let start_event =
            usage_stats::UsageStatsEvent::new(ua.clone(), usage_stats::EventType::Start, None);
        tokio::spawn(async move {
            start_event.send().await;
        });
    };
    let compat_return_full_text = match &model_info.pipeline_tag {
        None => {
            tracing::warn!("no pipeline tag found for model {tokenizer_name}");
            true
        }
        Some(pipeline_tag) => pipeline_tag.as_str() == "text-generation",
    };
    let result = start(
        backend,
        max_concurrent_requests,
        max_best_of,
        max_stop_sequences,
        max_top_n_tokens,
        max_input_tokens,
        max_total_tokens,
        validation_workers,
        api_key,
        config,
        (tokenizer, tokenizer_config),
        (preprocessor_config, processor_config),
        hostname,
        port,
        ngrok,
        _ngrok_authtoken,
        _ngrok_edge,
        disable_grammar_support,
        max_client_batch_size,
        model_info,
        compat_return_full_text,
        allow_origin,
    )
    .await;

    if let Some(ua) = user_agent {
        match result {
            Ok(_) => {
                let stop_event = usage_stats::UsageStatsEvent::new(
                    ua.clone(),
                    usage_stats::EventType::Stop,
                    None,
                );
                stop_event.send().await;
                Ok(())
OlivierDehaene's avatar
OlivierDehaene committed
1936
            }
Nicolas Patry's avatar
Nicolas Patry committed
1937
            Err(e) => {
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
                let description = match usage_stats_level {
                    usage_stats::UsageStatsLevel::On => Some(e.to_string()),
                    usage_stats::UsageStatsLevel::NoStack => Some("unknow_error".to_string()),
                    _ => None,
                };
                let event = usage_stats::UsageStatsEvent::new(
                    ua.clone(),
                    usage_stats::EventType::Error,
                    description,
                );
                event.send().await;

Nicolas Patry's avatar
Nicolas Patry committed
1950
                Err(e)
OlivierDehaene's avatar
OlivierDehaene committed
1951
1952
            }
        }
Nicolas Patry's avatar
Nicolas Patry committed
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
    } else {
        result
    }
}

#[allow(clippy::too_many_arguments)]
async fn start(
    backend: impl Backend + Send + Sync + 'static,
    max_concurrent_requests: usize,
    max_best_of: usize,
    max_stop_sequences: usize,
    max_top_n_tokens: u32,
    max_input_tokens: usize,
    max_total_tokens: usize,
    validation_workers: usize,
    api_key: Option<String>,
    config: Option<Config>,
1970
    (tokenizer, tokenizer_config): (Tokenizer, HubTokenizerConfig),
Nicolas Patry's avatar
Nicolas Patry committed
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
    (preprocessor_config, processor_config): (Option<HubPreprocessorConfig>, HubProcessorConfig),
    hostname: String,
    port: u16,
    ngrok: bool,
    _ngrok_authtoken: Option<String>,
    _ngrok_edge: Option<String>,
    disable_grammar_support: bool,
    max_client_batch_size: usize,
    model_info: HubModelInfo,
    compat_return_full_text: bool,
    allow_origin: Option<AllowOrigin>,
) -> Result<(), WebServerError> {
    // Determine the server port based on the feature and environment variable.
    let port = if cfg!(feature = "google") {
        std::env::var("AIP_HTTP_PORT")
            .map(|aip_http_port| aip_http_port.parse::<u16>().unwrap_or(port))
            .unwrap_or(port)
    } else {
        port
    };

    let addr = match hostname.parse() {
        Ok(ip) => SocketAddr::new(ip, port),
        Err(_) => {
            tracing::warn!("Invalid hostname, defaulting to 0.0.0.0");
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port)
        }
OlivierDehaene's avatar
OlivierDehaene committed
1998
1999
    };

Nicolas Patry's avatar
Nicolas Patry committed
2000
    // Create state
2001
2002
2003
    let validation = Validation::new(
        validation_workers,
        tokenizer,
2004
        config,
2005
        preprocessor_config,
2006
        max_best_of,
2007
        max_stop_sequences,
Nicolas Patry's avatar
Nicolas Patry committed
2008
        max_top_n_tokens,
OlivierDehaene's avatar
OlivierDehaene committed
2009
        max_input_tokens,
2010
        max_total_tokens,
Nicolas Patry's avatar
Nicolas Patry committed
2011
        disable_grammar_support,
2012
    );
OlivierDehaene's avatar
OlivierDehaene committed
2013

2014
    let infer = Infer::new(
Nicolas Patry's avatar
Nicolas Patry committed
2015
        backend,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
2016
        validation,
2017
        max_concurrent_requests,
2018
        tokenizer_config,
drbh's avatar
drbh committed
2019
        processor_config,
2020
    );
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
2021

2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
    // Duration buckets
    let duration_matcher = Matcher::Suffix(String::from("duration"));
    let n_duration_buckets = 35;
    let mut duration_buckets = Vec::with_capacity(n_duration_buckets);
    // Minimum duration in seconds
    let mut value = 0.0001;
    for _ in 0..n_duration_buckets {
        // geometric sequence
        value *= 1.5;
        duration_buckets.push(value);
    }
    // Input Length buckets
    let input_length_matcher = Matcher::Full(String::from("tgi_request_input_length"));
    let input_length_buckets: Vec<f64> = (0..100)
OlivierDehaene's avatar
OlivierDehaene committed
2036
        .map(|x| (max_input_tokens as f64 / 100.0) * (x + 1) as f64)
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
        .collect();
    // Generated tokens buckets
    let generated_tokens_matcher = Matcher::Full(String::from("tgi_request_generated_tokens"));
    let generated_tokens_buckets: Vec<f64> = (0..100)
        .map(|x| (max_total_tokens as f64 / 100.0) * (x + 1) as f64)
        .collect();
    // Input Length buckets
    let max_new_tokens_matcher = Matcher::Full(String::from("tgi_request_max_new_tokens"));
    let max_new_tokens_buckets: Vec<f64> = (0..100)
        .map(|x| (max_total_tokens as f64 / 100.0) * (x + 1) as f64)
        .collect();
    // Batch size buckets
    let batch_size_matcher = Matcher::Full(String::from("tgi_batch_next_size"));
2050
    let batch_size_buckets: Vec<f64> = (0..1024).map(|x| (x + 1) as f64).collect();
OlivierDehaene's avatar
OlivierDehaene committed
2051
    // Speculated tokens buckets
Nicolas Patry's avatar
Nicolas Patry committed
2052
2053
    // let skipped_matcher = Matcher::Full(String::from("tgi_request_skipped_tokens"));
    // let skipped_buckets: Vec<f64> = (0..shard_info.speculate + 1).map(|x| x as f64).collect();
2054

2055
    // Prometheus handler
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
    let builder = PrometheusBuilder::new()
        .set_buckets_for_metric(duration_matcher, &duration_buckets)
        .unwrap()
        .set_buckets_for_metric(input_length_matcher, &input_length_buckets)
        .unwrap()
        .set_buckets_for_metric(generated_tokens_matcher, &generated_tokens_buckets)
        .unwrap()
        .set_buckets_for_metric(max_new_tokens_matcher, &max_new_tokens_buckets)
        .unwrap()
        .set_buckets_for_metric(batch_size_matcher, &batch_size_buckets)
        .unwrap();
Nicolas Patry's avatar
Nicolas Patry committed
2067
2068
    // .set_buckets_for_metric(skipped_matcher, &skipped_buckets)
    // .unwrap();
2069
2070
2071
2072
2073
2074
    // See: https://github.com/metrics-rs/metrics/issues/467#issuecomment-2022755151
    let (recorder, _) = builder
        .build()
        .expect("failed to build prometheus recorder");
    let prom_handle = recorder.handle();
    metrics::set_global_recorder(recorder).expect("Failed to set global recorder");
2075

2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
    // Metrics descriptions
    metrics::describe_counter!("tgi_request_success", "Number of successful requests");
    metrics::describe_histogram!(
        "tgi_request_duration",
        metrics::Unit::Seconds,
        "Request duration"
    );
    metrics::describe_histogram!(
        "tgi_request_validation_duration",
        metrics::Unit::Seconds,
        "Request validation duration"
    );
    metrics::describe_histogram!(
        "tgi_request_queue_duration",
        metrics::Unit::Seconds,
        "Request queue duration"
    );
    metrics::describe_histogram!(
        "tgi_request_inference_duration",
        metrics::Unit::Seconds,
        "Request inference duration"
    );
    metrics::describe_histogram!(
        "tgi_request_mean_time_per_token_duration",
        metrics::Unit::Seconds,
        "Mean time per token per request"
    );
    metrics::describe_histogram!(
        "tgi_request_generated_tokens",
        metrics::Unit::Count,
        "Generated tokens per request"
    );
    metrics::describe_counter!(
        "tgi_batch_inference_count",
        metrics::Unit::Count,
        "Inference calls per method (prefill or decode)"
    );
    metrics::describe_counter!(
        "tgi_request_count",
        metrics::Unit::Count,
        "Total number of requests"
    );
    metrics::describe_counter!(
        "tgi_batch_inference_success",
        metrics::Unit::Count,
        "Number of successful inference calls per method (prefill or decode)"
    );
    metrics::describe_gauge!(
        "tgi_batch_current_size",
        metrics::Unit::Count,
        "Current batch size"
    );
    metrics::describe_gauge!("tgi_queue_size", metrics::Unit::Count, "Current queue size");
    metrics::describe_gauge!(
        "tgi_batch_current_max_tokens",
        metrics::Unit::Count,
        "Maximum tokens for the current batch"
    );
2134
2135
2136
2137
2138
    metrics::describe_gauge!(
        "tgi_batch_total_tokens",
        metrics::Unit::Count,
        "Maximum amount of tokens in total."
    );
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
    metrics::describe_histogram!(
        "tgi_request_max_new_tokens",
        metrics::Unit::Count,
        "Maximum new tokens per request"
    );
    metrics::describe_histogram!(
        "tgi_batch_inference_duration",
        metrics::Unit::Seconds,
        "Batch inference duration"
    );
    metrics::describe_histogram!(
        "tgi_batch_forward_duration",
        metrics::Unit::Seconds,
        "Batch forward duration per method (prefill or decode)"
    );
    metrics::describe_histogram!(
        "tgi_request_skipped_tokens",
        metrics::Unit::Count,
        "Speculated tokens per request"
    );
    metrics::describe_histogram!(
        "tgi_batch_filter_duration",
        metrics::Unit::Seconds,
        "Time spent filtering batches and sending generated tokens per method (prefill or decode)"
    );
    metrics::describe_histogram!(
        "tgi_request_queue_duration",
        metrics::Unit::Seconds,
        "Time spent in the queue per request"
    );
    metrics::describe_histogram!(
        "tgi_request_validation_duration",
        metrics::Unit::Seconds,
        "Time spent validating the request"
    );
    metrics::describe_histogram!(
        "tgi_request_duration",
        metrics::Unit::Seconds,
        "Total time spent processing the request"
    );
    metrics::describe_histogram!(
        "tgi_batch_decode_duration",
        metrics::Unit::Seconds,
        "Time spent decoding a batch per method (prefill or decode)"
    );
    metrics::describe_histogram!(
        "tgi_request_input_length",
        metrics::Unit::Count,
        "Input token length per request"
    );
    metrics::describe_histogram!(
        "tgi_batch_next_size",
        metrics::Unit::Count,
        "Batch size of the next batch"
    );

2195
2196
2197
2198
2199
2200
2201
    // CORS layer
    let allow_origin = allow_origin.unwrap_or(AllowOrigin::any());
    let cors_layer = CorsLayer::new()
        .allow_methods([Method::GET, Method::POST])
        .allow_headers([http::header::CONTENT_TYPE])
        .allow_origin(allow_origin);

2202
2203
2204
2205
    // Endpoint info
    let info = Info {
        model_id: model_info.model_id,
        model_sha: model_info.sha,
Nicolas Patry's avatar
Nicolas Patry committed
2206
2207
        // model_dtype: shard_info.dtype,
        // model_device_type: shard_info.device_type,
2208
2209
2210
2211
        model_pipeline_tag: model_info.pipeline_tag,
        max_concurrent_requests,
        max_best_of,
        max_stop_sequences,
OlivierDehaene's avatar
OlivierDehaene committed
2212
        max_input_tokens,
2213
        max_total_tokens,
Nicolas Patry's avatar
Nicolas Patry committed
2214
2215
2216
2217
        // waiting_served_ratio,
        // max_batch_total_tokens,
        // max_waiting_tokens,
        // max_batch_size,
2218
        validation_workers,
2219
        max_client_batch_size,
2220
        router: env!("CARGO_PKG_NAME"),
2221
2222
        version: env!("CARGO_PKG_VERSION"),
        sha: option_env!("VERGEN_GIT_SHA"),
2223
        docker_label: option_env!("DOCKER_LABEL"),
2224
2225
    };

2226
2227
2228
2229
2230
    #[allow(unused_mut)] // mut is needed for conditional compilation
    let mut doc = ApiDoc::openapi();

    #[cfg(feature = "google")]
    {
2231
2232
        use crate::vertex::__path_vertex_compatibility;
        use crate::vertex::{VertexInstance, VertexRequest, VertexResponse};
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263

        #[derive(OpenApi)]
        #[openapi(
            paths(vertex_compatibility),
            components(schemas(VertexInstance, VertexRequest, VertexResponse))
        )]
        struct VertexApiDoc;

        doc.merge(VertexApiDoc::openapi());
    }

    #[cfg(feature = "kserve")]
    {
        use crate::kserve::{
            InferenceOutput, InferenceRequest, LiveResponse, MetadataServerResponse, OutputChunk,
            ReadyResponse,
        };
        use crate::kserve::{
            __path_kerve_server_metadata, __path_kserve_health_live, __path_kserve_health_ready,
            __path_kserve_model_infer, __path_kserve_model_metadata,
            __path_kserve_model_metadata_ready,
        };

        #[derive(OpenApi)]
        #[openapi(
            paths(
                kserve_health_live,
                kserve_health_ready,
                kerve_server_metadata,
                kserve_model_metadata,
                kserve_model_metadata_ready,
2264
                kserve_model_infer,
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
            ),
            components(schemas(
                InferenceOutput,
                InferenceRequest,
                LiveResponse,
                MetadataServerResponse,
                OutputChunk,
                ReadyResponse,
            ))
        )]
        struct KServeApiDoc;

        doc.merge(KServeApiDoc::openapi());
    }
drbh's avatar
drbh committed
2279

2280
    // Configure Swagger UI
drbh's avatar
drbh committed
2281
    let swagger_ui = SwaggerUi::new("/docs").url("/api-doc/openapi.json", doc);
2282
2283

    // Define base and health routes
Erik Kaunismäki's avatar
Erik Kaunismäki committed
2284
    let mut base_routes = Router::new()
2285
        .route("/", post(compat_generate))
Olivier Dehaene's avatar
Olivier Dehaene committed
2286
        .route("/generate", post(generate))
2287
        .route("/generate_stream", post(generate_stream))
2288
        .route("/v1/chat/completions", post(chat_completions))
2289
        .route("/v1/completions", post(completions))
drbh's avatar
drbh committed
2290
        .route("/vertex", post(vertex_compatibility))
2291
        .route("/invocations", post(sagemaker_compatibility))
Erik Kaunismäki's avatar
Erik Kaunismäki committed
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
        .route("/tokenize", post(tokenize));

    if let Some(api_key) = api_key {
        let mut prefix = "Bearer ".to_string();
        prefix.push_str(&api_key);

        // Leak to allow FnMut
        let api_key: &'static str = prefix.leak();

        let auth = move |headers: HeaderMap,
                         request: axum::extract::Request,
                         next: axum::middleware::Next| async move {
            match headers.get(AUTHORIZATION) {
                Some(token) => match token.to_str() {
                    Ok(token_str) if token_str.to_lowercase() == api_key.to_lowercase() => {
                        let response = next.run(request).await;
                        Ok(response)
                    }
                    _ => Err(StatusCode::UNAUTHORIZED),
                },
                None => Err(StatusCode::UNAUTHORIZED),
            }
        };

        base_routes = base_routes.layer(axum::middleware::from_fn(auth))
    }
    let info_routes = Router::new()
        .route("/", get(health))
2320
        .route("/chat_tokenize", post(get_chat_tokenize))
Erik Kaunismäki's avatar
Erik Kaunismäki committed
2321
        .route("/info", get(get_model_info))
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
2322
        .route("/health", get(health))
2323
        .route("/ping", get(health))
drbh's avatar
drbh committed
2324
2325
        .route("/metrics", get(metrics))
        .route("/v1/models", get(openai_get_model_info));
2326

2327
2328
    let compute_type =
        ComputeType(std::env::var("COMPUTE_TYPE").unwrap_or("gpu+optimized".to_string()));
2329

2330
    // Combine routes and layers
drbh's avatar
drbh committed
2331
    let mut app = Router::new()
2332
2333
        .merge(swagger_ui)
        .merge(base_routes)
2334
        .merge(info_routes);
drbh's avatar
drbh committed
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349

    #[cfg(feature = "google")]
    {
        tracing::info!("Built with `google` feature");
        tracing::info!(
            "Environment variables `AIP_PREDICT_ROUTE` and `AIP_HEALTH_ROUTE` will be respected."
        );
        if let Ok(env_predict_route) = std::env::var("AIP_PREDICT_ROUTE") {
            app = app.route(&env_predict_route, post(vertex_compatibility));
        }
        if let Ok(env_health_route) = std::env::var("AIP_HEALTH_ROUTE") {
            app = app.route(&env_health_route, get(health));
        }
    }

2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
    #[cfg(feature = "kserve")]
    {
        tracing::info!("Built with `kserve` feature");
        app = app
            .route(
                "/v2/models/:model_name/versions/:model_version/infer",
                post(kserve_model_infer),
            )
            .route(
                "/v2/models/:model_name/versions/:model_version",
                get(kserve_model_metadata),
            )
            .route("/v2/health/ready", get(kserve_health_ready))
            .route("/v2/health/live", get(kserve_health_live))
            .route("/v2", get(kerve_server_metadata))
            .route(
                "/v2/models/:model_name/versions/:model_version/ready",
                get(kserve_model_metadata_ready),
            );
    }

drbh's avatar
drbh committed
2371
2372
    // add layers after routes
    app = app
2373
        .layer(Extension(info))
2374
2375
        .layer(Extension(compat_return_full_text))
        .layer(Extension(infer))
2376
        .layer(Extension(compute_type))
2377
        .layer(Extension(prom_handle.clone()))
Nicolas Patry's avatar
Nicolas Patry committed
2378
        .layer(OtelAxumLayer::default())
2379
        .layer(cors_layer);
Olivier Dehaene's avatar
Olivier Dehaene committed
2380

OlivierDehaene's avatar
OlivierDehaene committed
2381
2382
    tracing::info!("Connected");

2383
2384
2385
    if ngrok {
        #[cfg(feature = "ngrok")]
        {
2386
            panic!("ngrok feature is not functional with axum=0.7 and hyper=1, waiting on https://github.com/ngrok/ngrok-rust/pull/137/files to re-enable.");
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400

            // Run server
        }
        #[cfg(not(feature = "ngrok"))]
        {
            let _ngrok_authtoken = ngrok_authtoken;
            let _ngrok_domain = ngrok_domain;
            let _ngrok_username = ngrok_username;
            let _ngrok_password = ngrok_password;

            panic!("`text-generation-router` was compiled without the `ngrok` feature");
        }
    } else {
        // Run server
2401
2402
2403

        let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
        axum::serve(listener, app)
2404
            .with_graceful_shutdown(shutdown_signal())
OlivierDehaene's avatar
OlivierDehaene committed
2405
2406
            .await
            .map_err(|err| WebServerError::Axum(Box::new(err)))?;
2407
    }
2408
    Ok(())
Olivier Dehaene's avatar
Olivier Dehaene committed
2409
}
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
2410

Nicolas Patry's avatar
Nicolas Patry committed
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
/// get model info from the Huggingface Hub
pub async fn get_hub_model_info(api: &ApiRepo) -> Option<HubModelInfo> {
    let response = api.info_request().send().await.ok()?;

    if response.status().is_success() {
        let hub_model_info: HubModelInfo =
            serde_json::from_str(&response.text().await.ok()?).ok()?;
        if let Some(sha) = &hub_model_info.sha {
            tracing::info!(
                "Serving revision {sha} of model {}",
                hub_model_info.model_id
            );
        }
        Some(hub_model_info)
    } else {
        None
    }
}

/// get tokenizer_config from the Huggingface Hub
pub async fn get_tokenizer_config(api_repo: &ApiRepo) -> Option<HubTokenizerConfig> {
    let tokenizer_config_filename = api_repo.get("tokenizer_config.json").await.ok()?;

    // Open the file in read-only mode with buffer.
    let file = File::open(tokenizer_config_filename).ok()?;
    let reader = BufReader::new(file);

    // Read the JSON contents of the file as an instance of 'HubTokenizerConfig'.
    let tokenizer_config: HubTokenizerConfig = serde_json::from_reader(reader)
        .map_err(|e| {
            tracing::warn!("Unable to parse tokenizer config: {}", e);
            e
        })
        .ok()?;

    Some(tokenizer_config)
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
/// Shutdown signal handler
async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }

    tracing::info!("signal received, starting graceful shutdown");
2474
    opentelemetry::global::shutdown_tracer_provider();
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
2475
}
2476
2477
2478
2479
2480
2481
2482
2483
2484

/// Convert to Axum supported formats
impl From<InferError> for (StatusCode, Json<ErrorResponse>) {
    fn from(err: InferError) -> Self {
        let status_code = match err {
            InferError::GenerationError(_) => StatusCode::FAILED_DEPENDENCY,
            InferError::Overloaded(_) => StatusCode::TOO_MANY_REQUESTS,
            InferError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
            InferError::IncompleteGeneration => StatusCode::INTERNAL_SERVER_ERROR,
2485
            InferError::IncompleteGenerationStream => StatusCode::INTERNAL_SERVER_ERROR,
2486
            InferError::TemplateError(_) => StatusCode::UNPROCESSABLE_ENTITY,
2487
            InferError::MissingTemplateVariable(_) => StatusCode::UNPROCESSABLE_ENTITY,
2488
            InferError::ToolError(_) => StatusCode::UNPROCESSABLE_ENTITY,
2489
            InferError::StreamSerializationError(_) => StatusCode::INTERNAL_SERVER_ERROR,
2490
2491
2492
2493
2494
2495
        };

        (
            status_code,
            Json(ErrorResponse {
                error: err.to_string(),
2496
                error_type: err.error_type().to_string(),
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
            }),
        )
    }
}

impl From<InferError> for Event {
    fn from(err: InferError) -> Self {
        Event::default()
            .json_data(ErrorResponse {
                error: err.to_string(),
2507
                error_type: err.error_type().to_string(),
2508
2509
2510
2511
            })
            .unwrap()
    }
}
OlivierDehaene's avatar
OlivierDehaene committed
2512
2513
2514
2515
2516
2517

#[derive(Debug, Error)]
pub enum WebServerError {
    #[error("Axum error: {0}")]
    Axum(#[from] axum::BoxError),
}
Nicolas Patry's avatar
Nicolas Patry committed
2518

drbh's avatar
drbh committed
2519
type PreparedInput = (String, Option<GrammarType>, bool);
2520

Nicolas Patry's avatar
Nicolas Patry committed
2521
pub(crate) fn prepare_chat_input(
2522
2523
2524
2525
2526
    infer: &Infer,
    response_format: Option<GrammarType>,
    tools: Option<Vec<Tool>>,
    tool_choice: ToolChoice,
    tool_prompt: &str,
2527
    guideline: Option<String>,
2528
2529
2530
2531
2532
2533
2534
2535
    messages: Vec<Message>,
) -> Result<PreparedInput, InferError> {
    if response_format.is_some() && tools.is_some() {
        return Err(InferError::ToolError(
            "Grammar and tools are mutually exclusive".into(),
        ));
    }

drbh's avatar
drbh committed
2536
    // when response_format is set, tools are not included when applying the chat template to generate inputs
2537
    if let Some(format) = response_format {
2538
        let inputs = infer.apply_chat_template(guideline, messages, None)?;
drbh's avatar
drbh committed
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
        return Ok((inputs, Some(format), false));
    }

    // when no response_format is set and tools are included, apply the chat template with the tools
    // to generate inputs
    if let Some(tools) = tools {
        let (updated_tools, tool_schema) = ToolGrammar::apply(tools, tool_choice)?;

        let grammar = tool_schema
            .as_ref()
            .map(|t| GrammarType::Json(serde_json::json!(t)));

        let inputs: String = infer.apply_chat_template(
            guideline,
            messages,
            Some((updated_tools, tool_prompt.into())),
        )?;
        return Ok((inputs, grammar, tool_schema.is_some()));
2557
2558
    }

drbh's avatar
drbh committed
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
    // if no response_format or tools are set simply apply the chat template to generate inputs
    let inputs = infer.apply_chat_template(guideline, messages, None)?;
    Ok((inputs, None, false))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ChatTemplateVersions;
    use crate::HubTokenizerConfig;
    use crate::TokenizerConfigToken;
    use crate::Tool;

2572
    use crate::tests::get_tokenizer;
drbh's avatar
drbh committed
2573
2574
    use serde_json::json;

2575
2576
    #[tokio::test]
    async fn test_prepare_chat_input() {
drbh's avatar
drbh committed
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
        // Mock Backend to avoid network requests
        struct MockBackend;

        impl Backend for MockBackend {
            fn schedule(
                &self,
                _request: crate::validation::ValidGenerateRequest,
            ) -> Result<
                tokio_stream::wrappers::UnboundedReceiverStream<
                    Result<InferStreamResponse, InferError>,
                >,
                InferError,
            > {
                unimplemented!("Never called in this test");
            }
            fn health<'a, 'async_trait>(
                &'a self,
                _current_health: bool,
            ) -> core::pin::Pin<
                Box<dyn core::future::Future<Output = bool> + core::marker::Send + 'async_trait>,
            >
            where
                'a: 'async_trait,
                Self: 'async_trait,
            {
                unimplemented!("Never called in this test");
            }
        }

        let backend = MockBackend {};

        let mut tokenizer_config = HubTokenizerConfig::default();

        // mock tokenizer config values
        tokenizer_config.bos_token = Some(TokenizerConfigToken::String("<s>".to_string()));
        tokenizer_config.eos_token = Some(TokenizerConfigToken::String("</s>".to_string()));
        tokenizer_config.chat_template = Some(
            ChatTemplateVersions::Single("{%- if messages[0][\"role\"] == \"system\" %}\n    {%- set system_message = messages[0][\"content\"] %}\n    {%- set loop_messages = messages[1:] %}\n{%- else %}\n    {%- set loop_messages = messages %}\n{%- endif %}\n{%- if not tools is defined %}\n    {%- set tools = none %}\n{%- endif %}\n{%- set user_messages = loop_messages | selectattr(\"role\", \"equalto\", \"user\") | list %}\n\n{#- This block checks for alternating user/assistant messages, skipping tool calling messages #}\n{%- set ns = namespace() %}\n{%- set ns.index = 0 %}\n{%- for message in loop_messages %}\n    {%- if not (message.role == \"tool\" or message.role == \"tool_results\" or (message.tool_calls is defined and message.tool_calls is not none)) %}\n        {%- if (message[\"role\"] == \"user\") != (ns.index % 2 == 0) %}\n            {{- raise_exception(\"After the optional system message, conversation roles must alternate user/assistant/user/assistant/...\") }}\n        {%- endif %}\n        {%- set ns.index = ns.index + 1 %}\n    {%- endif %}\n{%- endfor %}\n\n{{- bos_token }}\n{%- for message in loop_messages %}\n    {%- if message[\"role\"] == \"user\" %}\n        {%- if tools is not none and (message == user_messages[-1]) %}\n            {{- \"[AVAILABLE_TOOLS] [\" }}\n            {%- for tool in tools %}\n                {%- set tool = tool.function %}\n                {{- '{\"type\": \"function\", \"function\": {' }}\n                {%- for key, val in tool.items() if key != \"return\" %}\n                    {%- if val is string %}\n                        {{- '\"' + key + '\": \"' + val + '\"' }}\n                    {%- else %}\n                        {{- '\"' + key + '\": ' + val|tojson }}\n                    {%- endif %}\n                    {%- if not loop.last %}\n                        {{- \", \" }}\n                    {%- endif %}\n                {%- endfor %}\n                {{- \"}}\" }}\n                {%- if not loop.last %}\n                    {{- \", \" }}\n                {%- else %}\n                    {{- \"]\" }}\n                {%- endif %}\n            {%- endfor %}\n            {{- \"[/AVAILABLE_TOOLS]\" }}\n            {%- endif %}\n        {%- if loop.last and system_message is defined %}\n            {{- \"[INST] \" + system_message + \"\\n\\n\" + message[\"content\"] + \"[/INST]\" }}\n        {%- else %}\n            {{- \"[INST] \" + message[\"content\"] + \"[/INST]\" }}\n        {%- endif %}\n    {%- elif message.tool_calls is defined and message.tool_calls is not none %}\n        {{- \"[TOOL_CALLS] [\" }}\n        {%- for tool_call in message.tool_calls %}\n            {%- set out = tool_call.function|tojson %}\n            {{- out[:-1] }}\n            {%- if not tool_call.id is defined or tool_call.id|length != 9 %}\n                {{- raise_exception(\"Tool call IDs should be alphanumeric strings with length 9!\") }}\n            {%- endif %}\n            {{- ', \"id\": \"' + tool_call.id + '\"}' }}\n            {%- if not loop.last %}\n                {{- \", \" }}\n            {%- else %}\n                {{- \"]\" + eos_token }}\n            {%- endif %}\n        {%- endfor %}\n    {%- elif message[\"role\"] == \"assistant\" %}\n        {{- \" \" + message[\"content\"]|trim + eos_token}}\n    {%- elif message[\"role\"] == \"tool_results\" or message[\"role\"] == \"tool\" %}\n        {%- if message.content is defined and message.content.content is defined %}\n            {%- set content = message.content.content %}\n        {%- else %}\n            {%- set content = message.content %}\n        {%- endif %}\n        {{- '[TOOL_RESULTS] {\"content\": ' + content|string + \", \" }}\n        {%- if not message.tool_call_id is defined or message.tool_call_id|length != 9 %}\n            {{- raise_exception(\"Tool call IDs should be alphanumeric strings with length 9!\") }}\n        {%- endif %}\n        {{- '\"call_id\": \"' + message.tool_call_id + '\"}[/TOOL_RESULTS]' }}\n    {%- else %}\n        {{- raise_exception(\"Only user and assistant roles are supported, with the exception of an initial optional system message!\") }}\n    {%- endif %}\n{%- endfor %}\n".to_string())
        );

2617
2618
        let tokenizer = get_tokenizer();

drbh's avatar
drbh committed
2619
2620
        let infer = Infer::new(
            backend,
2621
            Validation::new(1, tokenizer, None, None, 1, 1, 1, 1, 1, false),
drbh's avatar
drbh committed
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
            1,
            tokenizer_config,
            HubProcessorConfig::default(),
        );
        let response_format = None;
        let tools = Some(vec![Tool {
            r#type: "function".to_string(),
            function: FunctionDefinition {
                name: "get_current_weather".to_string(),
                description: Some("Get the current weather".to_string()),
                arguments: json!({
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA"
                        },
                        "format": {
                            "type": "string",
                            "enum": ["celsius", "fahrenheit"],
                            "description": "The temperature unit to use. Infer this from the users location."
                        }
                    },
                    "required": ["location", "format"]
                }),
            },
        }]);
        let tool_prompt = "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.";
        let guideline = None;
        let messages = vec![Message {
            name: None,
            role: "user".to_string(),
            content: MessageContent::SingleText(
                "What is the weather like in New York?".to_string(),
            ),
        }];

        let result = prepare_chat_input(
            &infer,
            response_format,
            tools,
            ToolChoice(None),
            tool_prompt,
            guideline,
            messages,
        );

        assert!(result.is_ok());
2670
        let (inputs, _grammar, using_tools) = result.expect("Failed to prepare chat input");
drbh's avatar
drbh committed
2671
        assert_eq!(using_tools, true);
2672
        assert_eq!(inputs, "<s>[AVAILABLE_TOOLS] [{\"type\": \"function\", \"function\": {\"arguments\": {\"properties\":{\"format\":{\"description\":\"The temperature unit to use. Infer this from the users location.\",\"enum\":[\"celsius\",\"fahrenheit\"],\"type\":\"string\"},\"location\":{\"description\":\"The city and state, e.g. San Francisco, CA\",\"type\":\"string\"}},\"required\":[\"location\",\"format\"],\"type\":\"object\"}, \"description\": \"Get the current weather\", \"name\": \"get_current_weather\"}}, {\"type\": \"function\", \"function\": {\"arguments\": {\"properties\":{\"content\":{\"description\":\"The response content\",\"type\":\"string\"}},\"required\":[\"content\"],\"type\":\"object\"}, \"description\": \"Open ened response with no specific tool selected\", \"name\": \"no_tool\"}}][/AVAILABLE_TOOLS][INST] What is the weather like in New York?\n---\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.[/INST]".to_string());
drbh's avatar
drbh committed
2673
    }
2674
}