2025-03-12 08:28:47 +00:00
|
|
|
use crate::chat::{ChatChoice, ChatEvent, ChatState};
|
2023-01-31 16:04:00 +00:00
|
|
|
/// HTTP Server logic
|
2024-06-04 13:56:56 +00:00
|
|
|
use crate::config::Config;
|
2024-07-31 08:33:10 +00:00
|
|
|
use crate::infer::{Backend, Infer, InferError, InferResponse, InferStreamResponse};
|
2024-06-13 16:51:51 +00:00
|
|
|
#[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,
|
|
|
|
};
|
2024-10-23 11:26:01 +00:00
|
|
|
use crate::sagemaker::{
|
|
|
|
sagemaker_compatibility, SagemakerRequest, SagemakerResponse, SagemakerStreamResponse,
|
|
|
|
__path_sagemaker_compatibility,
|
|
|
|
};
|
2023-03-09 14:30:54 +00:00
|
|
|
use crate::validation::ValidationError;
|
2024-09-24 21:37:17 +00:00
|
|
|
use crate::vertex::vertex_compatibility;
|
|
|
|
use crate::ChatTokenizeResponse;
|
2022-10-27 12:25:29 +00:00
|
|
|
use crate::{
|
2024-07-31 14:29:07 +00:00
|
|
|
usage_stats, BestOfSequence, Details, ErrorResponse, FinishReason, FunctionName,
|
|
|
|
GenerateParameters, GenerateRequest, GenerateResponse, GrammarType, HubModelInfo,
|
|
|
|
HubProcessorConfig, HubTokenizerConfig, Info, Message, MessageChunk, MessageContent,
|
2024-09-19 18:50:37 +00:00
|
|
|
OutputMessage, PrefillToken, SimpleToken, StreamDetails, StreamOptions, StreamResponse,
|
2024-10-28 04:00:24 +00:00
|
|
|
TextMessage, Token, TokenizeResponse, Tokenizer, ToolCallDelta, ToolCallMessage, Url, Usage,
|
|
|
|
Validation,
|
2024-02-29 15:44:20 +00:00
|
|
|
};
|
|
|
|
use crate::{
|
|
|
|
ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionComplete,
|
|
|
|
ChatCompletionDelta, ChatCompletionLogprob, ChatCompletionLogprobs, ChatCompletionTopLogprob,
|
2024-07-03 10:56:27 +00:00
|
|
|
ChatRequest, Chunk, CompatGenerateRequest, Completion, CompletionComplete, CompletionFinal,
|
2024-09-24 21:37:17 +00:00
|
|
|
CompletionRequest, CompletionType, DeltaToolCall, Function, Prompt, Tool,
|
2022-10-27 12:25:29 +00:00
|
|
|
};
|
2024-11-19 18:31:59 +00:00
|
|
|
use crate::{FunctionDefinition, HubPreprocessorConfig, ToolCall, ToolChoice};
|
2025-02-21 09:30:29 +00:00
|
|
|
use crate::{MessageBody, ModelInfo, ModelsInfo};
|
2024-04-17 08:41:12 +00:00
|
|
|
use async_stream::__private::AsyncStream;
|
2024-11-21 18:20:15 +00:00
|
|
|
use axum::extract::{DefaultBodyLimit, Extension};
|
2024-07-31 08:33:10 +00:00
|
|
|
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode};
|
2023-01-31 16:04:00 +00:00
|
|
|
use axum::response::sse::{Event, KeepAlive, Sse};
|
2023-03-02 10:41:51 +00:00
|
|
|
use axum::response::{IntoResponse, Response};
|
2022-10-15 18:21:50 +00:00
|
|
|
use axum::routing::{get, post};
|
2023-02-17 17:22:00 +00:00
|
|
|
use axum::{http, Json, Router};
|
2023-09-27 08:40:18 +00:00
|
|
|
use axum_tracing_opentelemetry::middleware::OtelAxumLayer;
|
2023-04-09 18:22:27 +00:00
|
|
|
use futures::stream::StreamExt;
|
2024-04-17 08:41:12 +00:00
|
|
|
use futures::stream::{FuturesOrdered, FuturesUnordered};
|
2023-01-31 16:04:00 +00:00
|
|
|
use futures::Stream;
|
2024-02-20 13:04:51 +00:00
|
|
|
use futures::TryStreamExt;
|
2024-07-31 08:33:10 +00:00
|
|
|
use hf_hub::api::tokio::{Api, ApiBuilder, ApiRepo};
|
|
|
|
use hf_hub::{Cache, Repo, RepoType};
|
2024-07-29 09:14:17 +00:00
|
|
|
use http::header::AUTHORIZATION;
|
2023-04-09 18:13:28 +00:00
|
|
|
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};
|
2024-10-28 04:00:24 +00:00
|
|
|
use pyo3::prelude::*;
|
2024-09-11 20:41:56 +00:00
|
|
|
use pyo3::types::IntoPyDict;
|
2023-01-31 16:04:00 +00:00
|
|
|
use std::convert::Infallible;
|
2024-07-31 08:33:10 +00:00
|
|
|
use std::fs::File;
|
|
|
|
use std::io::BufReader;
|
|
|
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
|
|
|
use std::path::{Path, PathBuf};
|
2025-01-28 09:29:18 +00:00
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use std::sync::Arc;
|
|
|
|
use std::time::Duration;
|
2024-06-04 13:56:56 +00:00
|
|
|
use thiserror::Error;
|
2024-04-17 08:41:12 +00:00
|
|
|
use tokio::select;
|
2022-10-18 13:19:03 +00:00
|
|
|
use tokio::signal;
|
2024-04-17 08:41:12 +00:00
|
|
|
use tokio::sync::oneshot;
|
2022-10-11 08:36:51 +00:00
|
|
|
use tokio::time::Instant;
|
2023-02-17 17:22:00 +00:00
|
|
|
use tower_http::cors::{AllowOrigin, CorsLayer};
|
2023-02-13 12:02:45 +00:00
|
|
|
use tracing::{info_span, instrument, Instrument};
|
2023-02-03 11:43:37 +00:00
|
|
|
use utoipa::OpenApi;
|
|
|
|
use utoipa_swagger_ui::SwaggerUi;
|
2022-10-11 08:36:51 +00:00
|
|
|
|
2024-10-28 04:00:24 +00:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-18 14:16:06 +00:00
|
|
|
/// Generate tokens if `stream == false` or a stream of token if `stream == true`
|
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/",
|
|
|
|
request_body = CompatGenerateRequest,
|
|
|
|
responses(
|
|
|
|
(status = 200, description = "Generated Text",
|
|
|
|
content(
|
2024-11-15 12:21:50 +00:00
|
|
|
("application/json" = Vec<GenerateResponse>),
|
2023-07-21 14:56:30 +00:00
|
|
|
("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"})),
|
|
|
|
)
|
2023-04-18 14:16:06 +00:00
|
|
|
)]
|
2023-05-23 18:47:37 +00:00
|
|
|
#[instrument(skip(infer, req))]
|
2024-10-23 11:26:01 +00:00
|
|
|
pub(crate) async fn compat_generate(
|
2023-08-10 08:52:50 +00:00
|
|
|
Extension(default_return_full_text): Extension<bool>,
|
2023-02-27 13:56:58 +00:00
|
|
|
infer: Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
compute_type: Extension<ComputeType>,
|
2023-08-10 08:52:50 +00:00
|
|
|
Json(mut req): Json<CompatGenerateRequest>,
|
2023-03-02 10:41:51 +00:00
|
|
|
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
|
2023-02-28 09:19:32 +00:00
|
|
|
// default return_full_text given the pipeline_tag
|
|
|
|
if req.parameters.return_full_text.is_none() {
|
2023-08-10 08:52:50 +00:00
|
|
|
req.parameters.return_full_text = Some(default_return_full_text)
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
|
|
|
|
2023-02-27 13:56:58 +00:00
|
|
|
// switch on stream
|
|
|
|
if req.stream {
|
2024-01-29 11:30:50 +00:00
|
|
|
Ok(generate_stream(infer, compute_type, Json(req.into()))
|
2023-02-27 13:56:58 +00:00
|
|
|
.await
|
|
|
|
.into_response())
|
|
|
|
} else {
|
2024-01-29 10:20:08 +00:00
|
|
|
let (headers, Json(generation)) = generate(infer, compute_type, Json(req.into())).await?;
|
2023-02-27 13:56:58 +00:00
|
|
|
// wrap generation inside a Vec to match api-inference
|
2023-08-10 08:52:50 +00:00
|
|
|
Ok((headers, Json(vec![generation])).into_response())
|
2023-02-27 13:56:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-18 14:16:06 +00:00
|
|
|
/// Text Generation Inference endpoint info
|
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
get,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/info",
|
|
|
|
responses((status = 200, description = "Served model info", body = Info))
|
2023-04-18 14:16:06 +00:00
|
|
|
)]
|
|
|
|
#[instrument]
|
2023-04-25 11:11:18 +00:00
|
|
|
async fn get_model_info(info: Extension<Info>) -> Json<Info> {
|
|
|
|
Json(info.0)
|
2023-04-18 14:16:06 +00:00
|
|
|
}
|
|
|
|
|
2024-08-29 14:32:38 +00:00
|
|
|
#[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()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-11-04 05:44:59 +00:00
|
|
|
/// Template and tokenize ChatRequest
|
2024-08-06 11:51:32 +00:00
|
|
|
#[utoipa::path(
|
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/chat_tokenize",
|
|
|
|
request_body = ChatRequest,
|
2024-11-04 05:44:59 +00:00
|
|
|
responses(
|
|
|
|
(status = 200, description = "Templated and tokenized ChatRequest", body = ChatTokenizeResponse),
|
|
|
|
(status = 404, description = "Failed to tokenize ChatRequest", body = ErrorResponse),
|
|
|
|
)
|
2024-08-06 11:51:32 +00:00
|
|
|
)]
|
|
|
|
async fn get_chat_tokenize(
|
|
|
|
Extension(infer): Extension<Infer>,
|
2024-09-24 21:37:17 +00:00
|
|
|
Json(chat): Json<ChatRequest>,
|
2024-08-06 11:51:32 +00:00
|
|
|
) -> Result<(HeaderMap, Json<ChatTokenizeResponse>), (StatusCode, Json<ErrorResponse>)> {
|
|
|
|
metrics::counter!("tgi_request_count").increment(1);
|
|
|
|
|
2024-09-24 21:37:17 +00:00
|
|
|
let generate_request: GenerateRequest = chat.try_into_generate(&infer)?.0;
|
2024-08-06 11:51:32 +00:00
|
|
|
let input = generate_request.inputs.clone();
|
|
|
|
let encoding = infer.tokenize(generate_request).await?;
|
|
|
|
|
2024-10-28 04:00:24 +00:00
|
|
|
let tokens = encoding_to_tokens(&encoding, &input);
|
|
|
|
|
|
|
|
let resp = ChatTokenizeResponse {
|
|
|
|
tokenize_response: TokenizeResponse(tokens),
|
|
|
|
templated_text: input,
|
|
|
|
};
|
|
|
|
Ok((HeaderMap::new(), Json(resp)))
|
2024-08-06 11:51:32 +00:00
|
|
|
}
|
|
|
|
|
2023-04-26 18:23:54 +00:00
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
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"})),
|
|
|
|
)
|
2023-04-26 18:23:54 +00:00
|
|
|
)]
|
2024-07-31 08:33:10 +00:00
|
|
|
#[instrument(skip(infer))]
|
2022-10-18 13:19:03 +00:00
|
|
|
/// Health check method
|
2024-07-31 08:33:10 +00:00
|
|
|
async fn health(infer: Extension<Infer>) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
|
|
|
|
match infer.health().await {
|
2023-04-26 18:23:54 +00:00
|
|
|
true => Ok(()),
|
|
|
|
false => Err((
|
|
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: "unhealthy".to_string(),
|
|
|
|
error_type: "healthcheck".to_string(),
|
|
|
|
}),
|
|
|
|
)),
|
|
|
|
}
|
2022-10-14 13:56:21 +00:00
|
|
|
}
|
|
|
|
|
2023-02-03 11:43:37 +00:00
|
|
|
/// Generate tokens
|
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
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"})),
|
|
|
|
)
|
2023-02-03 11:43:37 +00:00
|
|
|
)]
|
2022-10-21 14:40:05 +00:00
|
|
|
#[instrument(
|
2023-07-21 14:56:30 +00:00
|
|
|
skip_all,
|
|
|
|
fields(
|
2023-08-10 08:52:50 +00:00
|
|
|
parameters = ? req.parameters,
|
2023-07-21 14:56:30 +00:00
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
2022-10-21 14:40:05 +00:00
|
|
|
)]
|
2022-10-11 08:36:51 +00:00
|
|
|
async fn generate(
|
2023-01-31 16:04:00 +00:00
|
|
|
infer: Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
Extension(ComputeType(compute_type)): Extension<ComputeType>,
|
2023-08-10 08:52:50 +00:00
|
|
|
Json(req): Json<GenerateRequest>,
|
2023-02-27 13:56:58 +00:00
|
|
|
) -> Result<(HeaderMap, Json<GenerateResponse>), (StatusCode, Json<ErrorResponse>)> {
|
2023-01-31 16:04:00 +00:00
|
|
|
let span = tracing::Span::current();
|
2024-12-06 04:52:00 +00:00
|
|
|
let (headers, _, response) =
|
|
|
|
generate_internal(infer, ComputeType(compute_type), Json(req), span).await?;
|
|
|
|
Ok((headers, response))
|
2024-04-17 08:41:12 +00:00
|
|
|
}
|
|
|
|
|
2024-06-13 16:51:51 +00:00
|
|
|
pub(crate) async fn generate_internal(
|
2024-04-17 08:41:12 +00:00
|
|
|
infer: Extension<Infer>,
|
|
|
|
ComputeType(compute_type): ComputeType,
|
|
|
|
Json(req): Json<GenerateRequest>,
|
|
|
|
span: tracing::Span,
|
2024-12-06 04:52:00 +00:00
|
|
|
) -> Result<(HeaderMap, u32, Json<GenerateResponse>), (StatusCode, Json<ErrorResponse>)> {
|
2022-10-21 14:40:05 +00:00
|
|
|
let start_time = Instant::now();
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_count").increment(1);
|
2023-01-31 13:21:51 +00:00
|
|
|
|
Adding Llava-Next (Llava 1.6) with full support. (#1709)
# What does this PR do?
- Changed all models to extract `embed_tokens` in order to enable llava
to separately call the embeddings and the core model layers.
- Added VlmCausalLM to inherit from FlashMistral in order to be
maximally supported. The only added logics sits on top and parses images
into pixel values, preallocates input_ids space for the image
embeddings, and passes them for the model.
- Added Clip for the vision tower.
- Didn't add flash for the vision tower since there's no padding anyway.
- Added heuristic (potentially incomplete) to calculate number of
features *before* calculating the clip patches (allows for easier logic
reuse of the LLM under the hood).
Still needs to be done:
- [x] Implement the image parsing in the controller side, to avoid
downloading n times per TP shard and also refusing requests too large
early and avoid issues where the truncation actually truncates the
image.
- [ ] Make sure it works with quantization properly.
- [x] Make sure it works with TP>1
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-04-09 19:32:00 +00:00
|
|
|
// Do not long ultra long inputs, like image payloads.
|
2024-09-11 16:10:40 +00:00
|
|
|
tracing::debug!(
|
|
|
|
"Input: {}",
|
|
|
|
&req.inputs.chars().take(1000).collect::<String>()
|
|
|
|
);
|
2023-05-23 18:47:37 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
let compute_characters = req.inputs.chars().count();
|
2023-02-28 09:19:32 +00:00
|
|
|
let mut add_prompt = None;
|
2023-08-10 08:52:50 +00:00
|
|
|
if req.parameters.return_full_text.unwrap_or(false) {
|
|
|
|
add_prompt = Some(req.inputs.clone());
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
|
|
|
|
2023-08-28 09:43:47 +00:00
|
|
|
let details: bool = req.parameters.details || req.parameters.decoder_input_details;
|
2023-02-28 09:19:32 +00:00
|
|
|
|
|
|
|
// Inference
|
2023-08-10 08:52:50 +00:00
|
|
|
let (response, best_of_responses) = match req.parameters.best_of {
|
2023-03-09 14:30:54 +00:00
|
|
|
Some(best_of) if best_of > 1 => {
|
2023-08-10 08:52:50 +00:00
|
|
|
let (response, best_of_responses) = infer.generate_best_of(req, best_of).await?;
|
2023-03-09 14:30:54 +00:00
|
|
|
(response, Some(best_of_responses))
|
|
|
|
}
|
2023-08-10 08:52:50 +00:00
|
|
|
_ => (infer.generate(req).await?, None),
|
2023-03-09 14:30:54 +00:00
|
|
|
};
|
2022-10-17 12:59:00 +00:00
|
|
|
|
2022-12-15 16:03:56 +00:00
|
|
|
// Token details
|
2024-01-11 18:01:43 +00:00
|
|
|
let input_length = response._input_length;
|
2022-12-15 16:03:56 +00:00
|
|
|
let details = match details {
|
2023-03-09 14:30:54 +00:00
|
|
|
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,
|
2024-06-04 13:56:56 +00:00
|
|
|
finish_reason: response.generated_text.finish_reason,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_tokens: response.generated_text.generated_tokens,
|
|
|
|
prefill: response.prefill,
|
|
|
|
tokens: response.tokens,
|
2023-08-28 09:43:47 +00:00
|
|
|
top_tokens: response.top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
seed: response.generated_text.seed,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect()
|
|
|
|
});
|
|
|
|
|
|
|
|
Some(Details {
|
2024-06-04 13:56:56 +00:00
|
|
|
finish_reason: response.generated_text.finish_reason,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_tokens: response.generated_text.generated_tokens,
|
|
|
|
prefill: response.prefill,
|
|
|
|
tokens: response.tokens,
|
|
|
|
seed: response.generated_text.seed,
|
|
|
|
best_of_sequences,
|
2023-08-28 09:43:47 +00:00
|
|
|
top_tokens: response.top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
})
|
|
|
|
}
|
2022-12-15 16:03:56 +00:00
|
|
|
false => None,
|
|
|
|
};
|
|
|
|
|
2022-10-21 14:40:05 +00:00
|
|
|
// Timings
|
|
|
|
let total_time = start_time.elapsed();
|
|
|
|
let validation_time = response.queued - start_time;
|
|
|
|
let queue_time = response.start - response.queued;
|
2023-01-31 16:04:00 +00:00
|
|
|
let inference_time = Instant::now() - response.start;
|
|
|
|
let time_per_token = inference_time / response.generated_text.generated_tokens;
|
2022-10-21 14:40:05 +00:00
|
|
|
|
2023-04-09 18:13:28 +00:00
|
|
|
// 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));
|
|
|
|
|
2022-10-21 14:40:05 +00:00
|
|
|
// Headers
|
|
|
|
let mut headers = HeaderMap::new();
|
2024-01-29 10:20:08 +00:00
|
|
|
headers.insert("x-compute-type", compute_type.parse().unwrap());
|
2023-03-02 10:41:51 +00:00
|
|
|
headers.insert(
|
|
|
|
"x-compute-time",
|
2024-02-28 10:30:37 +00:00
|
|
|
total_time.as_secs_f64().to_string().parse().unwrap(),
|
2023-03-02 10:41:51 +00:00
|
|
|
);
|
|
|
|
headers.insert(
|
|
|
|
"x-compute-characters",
|
|
|
|
compute_characters.to_string().parse().unwrap(),
|
|
|
|
);
|
2022-10-21 14:40:05 +00:00
|
|
|
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(),
|
2022-10-17 12:59:00 +00:00
|
|
|
);
|
2022-10-21 14:40:05 +00:00
|
|
|
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(),
|
|
|
|
);
|
2024-01-11 18:01:43 +00:00
|
|
|
headers.insert("x-prompt-tokens", input_length.into());
|
|
|
|
headers.insert(
|
|
|
|
"x-generated-tokens",
|
|
|
|
response.generated_text.generated_tokens.into(),
|
|
|
|
);
|
2022-10-21 14:40:05 +00:00
|
|
|
|
2023-02-16 16:18:53 +00:00
|
|
|
// Metrics
|
2024-07-08 14:03:59 +00:00
|
|
|
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);
|
2023-02-16 16:18:53 +00:00
|
|
|
|
2022-10-18 13:19:03 +00:00
|
|
|
// Send response
|
2023-02-28 09:19:32 +00:00
|
|
|
let mut output_text = response.generated_text.text;
|
|
|
|
if let Some(prompt) = add_prompt {
|
|
|
|
output_text = prompt + &output_text;
|
|
|
|
}
|
|
|
|
|
2023-05-23 18:47:37 +00:00
|
|
|
tracing::debug!("Output: {}", output_text);
|
|
|
|
tracing::info!("Success");
|
2023-04-09 18:13:28 +00:00
|
|
|
|
2023-02-02 14:02:04 +00:00
|
|
|
let response = GenerateResponse {
|
2023-02-28 09:19:32 +00:00
|
|
|
generated_text: output_text,
|
2022-12-15 16:03:56 +00:00
|
|
|
details,
|
2023-02-02 14:02:04 +00:00
|
|
|
};
|
2024-12-06 04:52:00 +00:00
|
|
|
Ok((headers, input_length, Json(response)))
|
2022-10-11 08:36:51 +00:00
|
|
|
}
|
|
|
|
|
2023-02-08 21:30:11 +00:00
|
|
|
/// Generate a stream of token using Server-Sent Events
|
2023-02-03 11:43:37 +00:00
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
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"),
|
|
|
|
)
|
2023-02-03 11:43:37 +00:00
|
|
|
)]
|
2023-01-31 16:04:00 +00:00
|
|
|
#[instrument(
|
2023-07-21 14:56:30 +00:00
|
|
|
skip_all,
|
|
|
|
fields(
|
2023-08-10 08:52:50 +00:00
|
|
|
parameters = ? req.parameters,
|
2023-07-21 14:56:30 +00:00
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
2023-01-31 16:04:00 +00:00
|
|
|
)]
|
|
|
|
async fn generate_stream(
|
2023-08-10 08:52:50 +00:00
|
|
|
Extension(infer): Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
Extension(compute_type): Extension<ComputeType>,
|
2023-08-10 08:52:50 +00:00
|
|
|
Json(req): Json<GenerateRequest>,
|
2023-03-02 10:41:51 +00:00
|
|
|
) -> (
|
|
|
|
HeaderMap,
|
|
|
|
Sse<impl Stream<Item = Result<Event, Infallible>>>,
|
|
|
|
) {
|
2024-04-17 08:41:12 +00:00
|
|
|
let span = tracing::Span::current();
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let (headers, response_stream) =
|
2024-10-10 13:28:25 +00:00
|
|
|
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())
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let sse = Sse::new(response_stream).keep_alive(KeepAlive::default());
|
|
|
|
(headers, sse)
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn generate_stream_internal(
|
|
|
|
infer: Infer,
|
2024-01-29 10:20:08 +00:00
|
|
|
ComputeType(compute_type): ComputeType,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
Json(req): Json<GenerateRequest>,
|
2024-04-17 08:41:12 +00:00
|
|
|
span: tracing::Span,
|
2024-10-10 13:28:25 +00:00
|
|
|
) -> (
|
|
|
|
HeaderMap,
|
|
|
|
impl Stream<Item = Result<StreamResponse, InferError>>,
|
|
|
|
) {
|
2023-01-31 16:04:00 +00:00
|
|
|
let start_time = Instant::now();
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_count").increment(1);
|
2023-01-31 16:04:00 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
tracing::debug!("Input: {}", req.inputs);
|
2023-05-23 18:47:37 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
let compute_characters = req.inputs.chars().count();
|
2023-03-02 10:41:51 +00:00
|
|
|
|
|
|
|
let mut headers = HeaderMap::new();
|
2024-01-29 11:30:50 +00:00
|
|
|
headers.insert("x-compute-type", compute_type.parse().unwrap());
|
2023-03-02 10:41:51 +00:00
|
|
|
headers.insert(
|
|
|
|
"x-compute-characters",
|
|
|
|
compute_characters.to_string().parse().unwrap(),
|
|
|
|
);
|
2023-06-28 09:50:12 +00:00
|
|
|
headers.insert("X-Accel-Buffering", "no".parse().unwrap());
|
2023-03-02 10:41:51 +00:00
|
|
|
|
2023-01-31 16:04:00 +00:00
|
|
|
let stream = async_stream::stream! {
|
|
|
|
// Inference
|
|
|
|
let mut end_reached = false;
|
|
|
|
let mut error = false;
|
2023-02-28 09:19:32 +00:00
|
|
|
|
|
|
|
let mut add_prompt = None;
|
2023-08-10 08:52:50 +00:00
|
|
|
if req.parameters.return_full_text.unwrap_or(false) {
|
|
|
|
add_prompt = Some(req.inputs.clone());
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
2023-08-10 08:52:50 +00:00
|
|
|
let details = req.parameters.details;
|
2023-01-31 16:04:00 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
let best_of = req.parameters.best_of.unwrap_or(1);
|
2023-06-02 15:12:30 +00:00
|
|
|
if best_of != 1 {
|
|
|
|
let err = InferError::from(ValidationError::BestOfStream);
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
|
2023-06-02 15:12:30 +00:00
|
|
|
tracing::error!("{err}");
|
2024-10-10 13:28:25 +00:00
|
|
|
yield Err(err);
|
2023-08-10 08:52:50 +00:00
|
|
|
} else if req.parameters.decoder_input_details {
|
2023-06-02 15:12:30 +00:00
|
|
|
let err = InferError::from(ValidationError::PrefillDetailsStream);
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
|
2023-06-02 15:12:30 +00:00
|
|
|
tracing::error!("{err}");
|
2024-10-10 13:28:25 +00:00
|
|
|
yield Err(err);
|
2023-06-02 15:12:30 +00:00
|
|
|
} else {
|
2023-08-10 08:52:50 +00:00
|
|
|
match infer.generate_stream(req).instrument(info_span!(parent: &span, "async_stream")).await {
|
2023-04-20 09:07:40 +00:00
|
|
|
// Keep permit as long as generate_stream lives
|
2024-08-12 15:26:11 +00:00
|
|
|
Ok((_permit, input_length, response_stream)) => {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let mut index = 0;
|
2024-07-31 08:33:10 +00:00
|
|
|
let mut response_stream = Box::pin(response_stream);
|
2023-03-09 14:30:54 +00:00
|
|
|
// Server-Sent Event stream
|
|
|
|
while let Some(response) = response_stream.next().await {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
index += 1;
|
2023-03-09 14:30:54 +00:00
|
|
|
match response {
|
|
|
|
Ok(response) => {
|
|
|
|
match response {
|
|
|
|
// Prefill is ignored
|
|
|
|
InferStreamResponse::Prefill(_) => {}
|
|
|
|
// Yield event for every new token
|
2023-08-28 09:43:47 +00:00
|
|
|
InferStreamResponse::Intermediate{
|
|
|
|
token,
|
|
|
|
top_tokens,
|
|
|
|
} => {
|
2023-05-23 18:47:37 +00:00
|
|
|
tracing::debug!(parent: &span, "Token: {:?}", token);
|
|
|
|
|
2023-03-09 14:30:54 +00:00
|
|
|
// StreamResponse
|
|
|
|
let stream_token = StreamResponse {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
index,
|
2023-03-09 14:30:54 +00:00
|
|
|
token,
|
2023-09-27 08:40:18 +00:00
|
|
|
top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_text: None,
|
|
|
|
details: None,
|
|
|
|
};
|
2024-10-10 13:28:25 +00:00
|
|
|
yield Ok(stream_token);
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
// Yield event for last token and compute timings
|
|
|
|
InferStreamResponse::End {
|
2023-01-31 16:04:00 +00:00
|
|
|
token,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_text,
|
|
|
|
start,
|
|
|
|
queued,
|
2023-08-28 09:43:47 +00:00
|
|
|
top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
} => {
|
|
|
|
// Token details
|
|
|
|
let details = match details {
|
|
|
|
true => Some(StreamDetails {
|
2024-06-04 13:56:56 +00:00
|
|
|
finish_reason: generated_text.finish_reason,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_tokens: generated_text.generated_tokens,
|
|
|
|
seed: generated_text.seed,
|
2024-08-12 15:26:11 +00:00
|
|
|
input_length,
|
2023-03-09 14:30:54 +00:00
|
|
|
}),
|
|
|
|
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
|
2024-07-08 14:03:59 +00:00
|
|
|
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);
|
2023-03-09 14:30:54 +00:00
|
|
|
|
|
|
|
// StreamResponse
|
|
|
|
end_reached = true;
|
|
|
|
|
|
|
|
let mut output_text = generated_text.text;
|
|
|
|
if let Some(prompt) = add_prompt {
|
|
|
|
output_text = prompt + &output_text;
|
|
|
|
}
|
|
|
|
|
2023-05-23 18:47:37 +00:00
|
|
|
tracing::debug!(parent: &span, "Output: {}", output_text);
|
|
|
|
tracing::info!(parent: &span, "Success");
|
2023-04-09 18:13:28 +00:00
|
|
|
|
2023-03-09 14:30:54 +00:00
|
|
|
let stream_token = StreamResponse {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
index,
|
2023-03-09 14:30:54 +00:00
|
|
|
token,
|
2023-09-27 08:40:18 +00:00
|
|
|
top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_text: Some(output_text),
|
|
|
|
details
|
|
|
|
};
|
|
|
|
|
2024-10-10 13:28:25 +00:00
|
|
|
yield Ok(stream_token);
|
2023-03-09 14:30:54 +00:00
|
|
|
break;
|
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
// yield error
|
|
|
|
Err(err) => {
|
|
|
|
error = true;
|
2024-10-10 13:28:25 +00:00
|
|
|
yield Err(err);
|
2023-03-09 14:30:54 +00:00
|
|
|
break;
|
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
},
|
|
|
|
// yield error
|
|
|
|
Err(err) => {
|
|
|
|
error = true;
|
2024-10-10 13:28:25 +00:00
|
|
|
yield Err(err);
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
}
|
|
|
|
// Check if generation reached the end
|
|
|
|
// Skip if we already sent an error
|
|
|
|
if !end_reached && !error {
|
2024-09-11 16:10:40 +00:00
|
|
|
let err = InferError::IncompleteGenerationStream;
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_failure", "err" => "incomplete").increment(1);
|
2023-03-09 14:30:54 +00:00
|
|
|
tracing::error!("{err}");
|
2024-10-10 13:28:25 +00:00
|
|
|
yield Err(err);
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
(headers, stream)
|
|
|
|
}
|
|
|
|
|
2024-02-29 15:44:20 +00:00
|
|
|
/// Generate tokens
|
|
|
|
#[utoipa::path(
|
2024-06-04 13:56:56 +00:00
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/v1/completions",
|
|
|
|
request_body = CompletionRequest,
|
|
|
|
responses(
|
|
|
|
(status = 200, description = "Generated Chat Completion",
|
|
|
|
content(
|
2024-07-09 15:23:48 +00:00
|
|
|
("application/json" = CompletionFinal),
|
|
|
|
("text/event-stream" = Chunk),
|
2024-06-04 13:56:56 +00:00
|
|
|
)),
|
|
|
|
(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"})),
|
|
|
|
)
|
|
|
|
)]
|
2024-02-29 15:44:20 +00:00
|
|
|
#[instrument(
|
2024-06-04 13:56:56 +00:00
|
|
|
skip_all,
|
|
|
|
fields(
|
|
|
|
// parameters = ? req.parameters,
|
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
|
|
|
)]
|
2024-10-23 11:26:01 +00:00
|
|
|
pub(crate) async fn completions(
|
2024-02-29 15:44:20 +00:00
|
|
|
Extension(infer): Extension<Infer>,
|
|
|
|
Extension(compute_type): Extension<ComputeType>,
|
|
|
|
Extension(info): Extension<Info>,
|
|
|
|
Json(req): Json<CompletionRequest>,
|
|
|
|
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
|
2024-04-17 08:41:12 +00:00
|
|
|
let span = tracing::Span::current();
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_count").increment(1);
|
2024-02-29 15:44:20 +00:00
|
|
|
|
2024-05-23 13:37:09 +00:00
|
|
|
let CompletionRequest {
|
2024-07-08 14:06:49 +00:00
|
|
|
model,
|
2024-05-23 13:37:09 +00:00
|
|
|
max_tokens,
|
|
|
|
seed,
|
|
|
|
stop,
|
|
|
|
stream,
|
|
|
|
temperature,
|
|
|
|
..
|
|
|
|
} = req;
|
|
|
|
|
2024-12-06 04:50:35 +00:00
|
|
|
let max_new_tokens = max_tokens;
|
2024-05-23 13:37:09 +00:00
|
|
|
let stop = stop.unwrap_or_default();
|
|
|
|
// enable greedy only when temperature is 0
|
|
|
|
let (do_sample, temperature) = match temperature {
|
2025-03-04 17:07:33 +00:00
|
|
|
Some(0.0) => (false, None),
|
2024-05-23 13:37:09 +00:00
|
|
|
other => (true, other),
|
|
|
|
};
|
2024-02-29 15:44:20 +00:00
|
|
|
|
|
|
|
// if suffix is present throw an error
|
|
|
|
if req.suffix.is_some() {
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
|
2024-02-29 15:44:20 +00:00
|
|
|
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(),
|
|
|
|
}),
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
2024-07-01 13:08:05 +00:00
|
|
|
if req.prompt.0.len() > info.max_client_batch_size {
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_failure", "err" => "validation").increment(1);
|
2024-04-17 08:41:12 +00:00
|
|
|
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
|
2024-07-01 13:08:05 +00:00
|
|
|
.0
|
2024-04-17 08:41:12 +00:00
|
|
|
.iter()
|
|
|
|
.map(|prompt| GenerateRequest {
|
|
|
|
inputs: prompt.to_string(),
|
2024-08-29 14:29:01 +00:00
|
|
|
add_special_tokens: true,
|
2024-04-17 08:41:12 +00:00
|
|
|
parameters: GenerateParameters {
|
|
|
|
best_of: None,
|
2024-05-23 13:37:09 +00:00
|
|
|
temperature,
|
2024-04-17 08:41:12 +00:00
|
|
|
repetition_penalty: req.repetition_penalty,
|
|
|
|
frequency_penalty: req.frequency_penalty,
|
|
|
|
top_k: None,
|
|
|
|
top_p: req.top_p,
|
|
|
|
typical_p: None,
|
2024-05-23 13:37:09 +00:00
|
|
|
do_sample,
|
2024-04-17 08:41:12 +00:00
|
|
|
max_new_tokens,
|
|
|
|
return_full_text: None,
|
2024-05-23 13:37:09 +00:00
|
|
|
stop: stop.clone(),
|
2024-04-17 08:41:12 +00:00
|
|
|
truncate: None,
|
|
|
|
watermark: false,
|
|
|
|
details: true,
|
|
|
|
decoder_input_details: !stream,
|
|
|
|
seed,
|
|
|
|
top_n_tokens: None,
|
|
|
|
grammar: None,
|
2024-07-08 14:06:49 +00:00
|
|
|
adapter_id: model.as_ref().filter(|m| *m != "tgi").map(String::from),
|
2024-04-17 08:41:12 +00:00
|
|
|
},
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
let mut x_compute_type = None;
|
|
|
|
let mut x_compute_characters = 0u32;
|
|
|
|
let mut x_accel_buffering = None;
|
2024-02-29 15:44:20 +00:00
|
|
|
|
|
|
|
if stream {
|
2024-04-17 08:41:12 +00:00
|
|
|
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 {
|
2024-10-10 13:28:25 +00:00
|
|
|
let (headers, response_stream) = generate_stream_internal(
|
2024-04-17 08:41:12 +00:00
|
|
|
infer_clone.clone(),
|
|
|
|
compute_type_clone.clone(),
|
|
|
|
Json(generate_request),
|
|
|
|
span_clone.clone(),
|
|
|
|
)
|
|
|
|
.await;
|
2024-02-29 15:44:20 +00:00
|
|
|
|
2024-10-10 13:28:25 +00:00
|
|
|
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);
|
|
|
|
}
|
2024-11-15 13:49:19 +00:00
|
|
|
Err(err) => yield Ok(err.into_openai_event()),
|
2024-10-10 13:28:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-04-17 08:41:12 +00:00
|
|
|
// send and dont wait for response
|
2024-10-10 13:28:25 +00:00
|
|
|
let _ = header_tx.send(headers);
|
2024-02-29 15:44:20 +00:00
|
|
|
|
2024-04-17 08:41:12 +00:00
|
|
|
// pin an emit messages to the sse_tx
|
2024-10-10 13:28:25 +00:00
|
|
|
let mut sse = Box::pin(response_stream);
|
2024-04-17 08:41:12 +00:00
|
|
|
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(),
|
|
|
|
}),
|
2024-02-29 15:44:20 +00:00
|
|
|
)
|
2024-04-17 08:41:12 +00:00
|
|
|
})?;
|
|
|
|
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);
|
|
|
|
}
|
2024-02-29 15:44:20 +00:00
|
|
|
|
2024-04-17 08:41:12 +00:00
|
|
|
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());
|
|
|
|
}
|
2024-02-29 15:44:20 +00:00
|
|
|
|
2024-04-17 08:41:12 +00:00
|
|
|
// 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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-07-11 14:42:58 +00:00
|
|
|
let stream = stream.chain(futures::stream::once(async {
|
|
|
|
Ok(Event::default().data("[DONE]"))
|
|
|
|
}));
|
|
|
|
|
2024-04-17 08:41:12 +00:00
|
|
|
let sse = Sse::new(stream).keep_alive(KeepAlive::default());
|
2024-02-29 15:44:20 +00:00
|
|
|
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();
|
|
|
|
|
2024-04-17 08:41:12 +00:00
|
|
|
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;
|
2024-12-06 04:52:00 +00:00
|
|
|
result.map(|(headers, input_length, generation)| {
|
|
|
|
(index, headers, input_length, generation)
|
|
|
|
})
|
2024-04-17 08:41:12 +00:00
|
|
|
};
|
|
|
|
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()
|
2024-12-06 04:52:00 +00:00
|
|
|
.map(|(index, headers, input_length, Json(generation))| {
|
2024-04-17 08:41:12 +00:00
|
|
|
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);
|
|
|
|
|
2024-12-06 04:52:00 +00:00
|
|
|
prompt_tokens += input_length;
|
2024-04-17 08:41:12 +00:00
|
|
|
completion_tokens += details.generated_tokens;
|
2024-12-06 04:52:00 +00:00
|
|
|
total_tokens += input_length + details.generated_tokens;
|
2024-04-17 08:41:12 +00:00
|
|
|
|
|
|
|
Ok(CompletionComplete {
|
2024-08-06 17:09:50 +00:00
|
|
|
finish_reason: details.finish_reason.format(true),
|
2024-04-17 08:41:12 +00:00
|
|
|
index: index as u32,
|
|
|
|
logprobs: None,
|
|
|
|
text: generation.generated_text,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.collect::<Result<Vec<_>, _>>()
|
|
|
|
.map_err(|(status, Json(err))| (status, Json(err)))?;
|
2024-02-29 15:44:20 +00:00
|
|
|
|
2024-07-03 10:56:27 +00:00
|
|
|
let response = Completion::Final(CompletionFinal {
|
2024-02-29 15:44:20 +00:00
|
|
|
id: "".to_string(),
|
|
|
|
created: current_time,
|
|
|
|
model: info.model_id.clone(),
|
|
|
|
system_fingerprint: format!(
|
|
|
|
"{}-{}",
|
|
|
|
info.version,
|
|
|
|
info.docker_label.unwrap_or("native")
|
|
|
|
),
|
2024-04-17 08:41:12 +00:00
|
|
|
choices,
|
2024-02-29 15:44:20 +00:00
|
|
|
usage: Usage {
|
2024-04-17 08:41:12 +00:00
|
|
|
prompt_tokens,
|
|
|
|
completion_tokens,
|
|
|
|
total_tokens,
|
2024-02-29 15:44:20 +00:00
|
|
|
},
|
2024-07-03 10:56:27 +00:00
|
|
|
});
|
2024-02-29 15:44:20 +00:00
|
|
|
|
2024-04-17 08:41:12 +00:00
|
|
|
// 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());
|
|
|
|
}
|
2024-02-29 15:44:20 +00:00
|
|
|
Ok((headers, Json(response)).into_response())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
/// Generate tokens
|
|
|
|
#[utoipa::path(
|
2024-06-04 13:56:56 +00:00
|
|
|
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"})),
|
|
|
|
)
|
|
|
|
)]
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
#[instrument(
|
2025-03-10 15:19:50 +00:00
|
|
|
skip_all,
|
|
|
|
fields(
|
|
|
|
parameters,
|
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
2024-06-04 13:56:56 +00:00
|
|
|
)]
|
2024-10-23 11:26:01 +00:00
|
|
|
pub(crate) async fn chat_completions(
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
Extension(infer): Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
Extension(compute_type): Extension<ComputeType>,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
Extension(info): Extension<Info>,
|
2025-03-12 08:28:47 +00:00
|
|
|
Json(mut chat): Json<ChatRequest>,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
|
2024-04-17 08:41:12 +00:00
|
|
|
let span = tracing::Span::current();
|
2024-07-08 14:03:59 +00:00
|
|
|
metrics::counter!("tgi_request_count").increment(1);
|
2024-04-16 13:02:46 +00:00
|
|
|
let ChatRequest {
|
2024-11-25 17:36:31 +00:00
|
|
|
model,
|
2024-04-16 13:02:46 +00:00
|
|
|
stream,
|
2024-09-19 18:50:37 +00:00
|
|
|
stream_options,
|
2024-09-24 21:37:17 +00:00
|
|
|
logprobs,
|
2024-04-16 13:02:46 +00:00
|
|
|
..
|
2024-09-24 21:37:17 +00:00
|
|
|
} = chat.clone();
|
2025-03-12 08:22:53 +00:00
|
|
|
|
|
|
|
tracing::debug!("Got chat_template {:?}", infer.chat_template);
|
|
|
|
let id = chat.next_tool_call_id();
|
2024-09-24 21:37:17 +00:00
|
|
|
let (generate_request, using_tools): (GenerateRequest, bool) =
|
2025-03-12 08:28:47 +00:00
|
|
|
chat.clone().try_into_generate(&infer)?;
|
2025-03-10 11:26:57 +00:00
|
|
|
span.record("parameters", format!("{:?}", generate_request.parameters));
|
2024-09-24 21:37:17 +00:00
|
|
|
let logprobs = logprobs.unwrap_or_default();
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
|
2024-11-25 17:36:31 +00:00
|
|
|
// extract model id from request if specified
|
|
|
|
let model_id = match model.as_deref() {
|
|
|
|
Some("tgi") | None => info.model_id.clone(),
|
|
|
|
Some(m_id) => m_id.to_string(),
|
|
|
|
};
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let system_fingerprint = format!("{}-{}", info.version, info.docker_label.unwrap_or("native"));
|
|
|
|
// switch on stream
|
|
|
|
if stream {
|
2025-03-12 08:28:47 +00:00
|
|
|
let (headers, response_stream) = generate_stream_internal(
|
|
|
|
infer.clone(),
|
|
|
|
compute_type.clone(),
|
|
|
|
Json(generate_request),
|
|
|
|
span.clone(),
|
|
|
|
)
|
|
|
|
.await;
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
|
2024-10-10 13:28:25 +00:00
|
|
|
let response_stream = async_stream::stream! {
|
|
|
|
let mut response_stream = Box::pin(response_stream);
|
2025-03-12 08:28:47 +00:00
|
|
|
let mut state = ChatState::new(using_tools, stream_options.clone(), system_fingerprint.clone(), model_id.clone(), logprobs, id.clone());
|
2024-10-10 13:28:25 +00:00
|
|
|
while let Some(result) = response_stream.next().await {
|
2024-11-15 13:49:19 +00:00
|
|
|
match result{
|
|
|
|
Ok(stream_token) => {
|
2025-03-12 08:22:53 +00:00
|
|
|
let events = state.push(stream_token);
|
2025-03-12 08:28:47 +00:00
|
|
|
match events{
|
|
|
|
ChatEvent::NoTool => {
|
|
|
|
chat.tools = None;
|
|
|
|
chat.response_format = None;
|
|
|
|
let (generate_request, using_tools): (GenerateRequest, bool) =
|
|
|
|
chat.clone().try_into_generate(&infer).unwrap();
|
|
|
|
assert!(!using_tools);
|
|
|
|
let (_headers, response_stream2) =
|
|
|
|
generate_stream_internal(infer.clone(), compute_type.clone(), Json(generate_request), span.clone()).await;
|
|
|
|
state = ChatState::new(using_tools, stream_options.clone(), system_fingerprint.clone(), model_id.clone(), logprobs, id.clone());
|
|
|
|
response_stream = Box::pin(response_stream2);
|
|
|
|
}
|
|
|
|
ChatEvent::Events(events) => {
|
|
|
|
for chat_complete in events{
|
|
|
|
yield Ok(Event::default().json_data(chat_complete).unwrap_or_else(|e| {
|
|
|
|
tracing::error!("Failed to serialize ChatCompletionChunk: {:?}", e);
|
|
|
|
Event::default()
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
}
|
2025-03-10 16:56:19 +00:00
|
|
|
}
|
2024-09-19 18:50:37 +00:00
|
|
|
}
|
2024-11-15 13:49:19 +00:00
|
|
|
Err(err) => yield Ok(err.into_openai_event())
|
|
|
|
}
|
2024-10-10 13:28:25 +00:00
|
|
|
}
|
|
|
|
yield Ok::<Event, Infallible>(Event::default().data("[DONE]"));
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let sse = Sse::new(response_stream).keep_alive(KeepAlive::default());
|
|
|
|
Ok((headers, sse).into_response())
|
|
|
|
} else {
|
2025-03-12 08:28:47 +00:00
|
|
|
let (mut headers, mut input_length, Json(generation)) = generate_internal(
|
|
|
|
Extension(infer.clone()),
|
|
|
|
compute_type.clone(),
|
|
|
|
Json(generate_request),
|
|
|
|
span.clone(),
|
|
|
|
)
|
|
|
|
.await?;
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
|
|
|
|
let current_time = std::time::SystemTime::now()
|
|
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
|
|
.unwrap_or_else(|_| std::time::Duration::from_secs(0))
|
|
|
|
.as_secs();
|
|
|
|
|
2024-08-27 00:19:38 +00:00
|
|
|
let (tool_calls, output) = if using_tools {
|
2025-03-12 08:28:47 +00:00
|
|
|
match crate::chat::parse_output(&generation.generated_text)? {
|
|
|
|
ChatChoice::NoTool => {
|
|
|
|
chat.tools = None;
|
|
|
|
chat.response_format = None;
|
|
|
|
let (generate_request, using_tools): (GenerateRequest, bool) =
|
|
|
|
chat.clone().try_into_generate(&infer)?;
|
|
|
|
assert!(!using_tools);
|
|
|
|
let (headers_final, input_length_final, Json(generation)) = generate_internal(
|
|
|
|
Extension(infer),
|
|
|
|
compute_type,
|
|
|
|
Json(generate_request),
|
|
|
|
span,
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
headers = headers_final;
|
|
|
|
input_length = input_length_final;
|
|
|
|
(None, Some(generation.generated_text))
|
|
|
|
}
|
|
|
|
ChatChoice::ToolCalls(tool_calls) => (Some(tool_calls), None),
|
|
|
|
}
|
2024-02-28 10:10:27 +00:00
|
|
|
} else {
|
|
|
|
(None, Some(generation.generated_text))
|
|
|
|
};
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
// build the complete response object with the full text
|
2024-07-01 13:08:05 +00:00
|
|
|
let response = CompletionType::ChatCompletion(ChatCompletion::new(
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
model_id,
|
|
|
|
system_fingerprint,
|
2024-02-28 10:10:27 +00:00
|
|
|
output,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
current_time,
|
|
|
|
generation.details.unwrap(),
|
|
|
|
logprobs,
|
2024-02-28 10:10:27 +00:00
|
|
|
tool_calls,
|
2024-12-06 04:52:00 +00:00
|
|
|
input_length,
|
2024-07-01 13:08:05 +00:00
|
|
|
));
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
|
|
|
|
// wrap generation inside a Vec to match api-inference
|
|
|
|
Ok((headers, Json(response)).into_response())
|
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
/// Tokenize inputs
|
|
|
|
#[utoipa::path(
|
2024-06-04 13:56:56 +00:00
|
|
|
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"})),
|
|
|
|
)
|
|
|
|
)]
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
#[instrument(skip_all)]
|
|
|
|
async fn tokenize(
|
|
|
|
Extension(infer): Extension<Infer>,
|
|
|
|
Json(req): Json<GenerateRequest>,
|
2024-01-26 15:07:31 +00:00
|
|
|
) -> Result<Json<TokenizeResponse>, (StatusCode, Json<ErrorResponse>)> {
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
let input = req.inputs.clone();
|
|
|
|
let encoding = infer.tokenize(req).await?;
|
2024-10-28 04:00:24 +00:00
|
|
|
let tokens = encoding_to_tokens(&encoding, &input);
|
|
|
|
Ok(Json(TokenizeResponse(tokens)))
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
}
|
|
|
|
|
2023-02-16 16:18:53 +00:00
|
|
|
/// Prometheus metrics scrape endpoint
|
|
|
|
#[utoipa::path(
|
2024-07-03 07:53:35 +00:00
|
|
|
get,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/metrics",
|
|
|
|
responses((status = 200, description = "Prometheus Metrics", body = String))
|
2023-02-16 16:18:53 +00:00
|
|
|
)]
|
|
|
|
async fn metrics(prom_handle: Extension<PrometheusHandle>) -> String {
|
|
|
|
prom_handle.render()
|
|
|
|
}
|
|
|
|
|
2024-01-29 10:20:08 +00:00
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub(crate) struct ComputeType(String);
|
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
// OpenAPI documentation
|
|
|
|
#[derive(OpenApi)]
|
|
|
|
#[openapi(
|
|
|
|
paths(
|
|
|
|
health,
|
|
|
|
get_model_info,
|
|
|
|
compat_generate,
|
|
|
|
generate,
|
|
|
|
generate_stream,
|
|
|
|
chat_completions,
|
|
|
|
completions,
|
|
|
|
tokenize,
|
|
|
|
metrics,
|
2024-08-29 14:32:38 +00:00
|
|
|
openai_get_model_info,
|
2024-10-23 11:26:01 +00:00
|
|
|
sagemaker_compatibility,
|
2024-11-04 05:44:59 +00:00
|
|
|
get_chat_tokenize,
|
2024-07-31 08:33:10 +00:00
|
|
|
),
|
|
|
|
components(
|
|
|
|
schemas(
|
|
|
|
Info,
|
|
|
|
CompatGenerateRequest,
|
2024-10-23 11:26:01 +00:00
|
|
|
SagemakerRequest,
|
2024-07-31 08:33:10 +00:00
|
|
|
GenerateRequest,
|
|
|
|
GrammarType,
|
|
|
|
ChatRequest,
|
|
|
|
Message,
|
|
|
|
MessageContent,
|
|
|
|
MessageChunk,
|
|
|
|
Url,
|
|
|
|
FunctionName,
|
|
|
|
OutputMessage,
|
|
|
|
TextMessage,
|
|
|
|
ToolCallMessage,
|
|
|
|
ToolCallDelta,
|
|
|
|
ChatCompletionComplete,
|
|
|
|
ChatCompletionChoice,
|
|
|
|
ChatCompletionDelta,
|
|
|
|
ChatCompletionChunk,
|
|
|
|
ChatCompletionLogprob,
|
|
|
|
ChatCompletionLogprobs,
|
|
|
|
ChatCompletionTopLogprob,
|
|
|
|
ChatCompletion,
|
|
|
|
CompletionRequest,
|
|
|
|
CompletionComplete,
|
2024-10-23 11:26:01 +00:00
|
|
|
SagemakerResponse,
|
|
|
|
SagemakerStreamResponse,
|
2024-07-31 08:33:10 +00:00
|
|
|
Chunk,
|
|
|
|
Completion,
|
|
|
|
CompletionFinal,
|
|
|
|
Prompt,
|
|
|
|
GenerateParameters,
|
|
|
|
PrefillToken,
|
|
|
|
Token,
|
|
|
|
GenerateResponse,
|
|
|
|
TokenizeResponse,
|
|
|
|
SimpleToken,
|
|
|
|
BestOfSequence,
|
|
|
|
Details,
|
|
|
|
FinishReason,
|
|
|
|
StreamResponse,
|
|
|
|
StreamDetails,
|
|
|
|
ErrorResponse,
|
|
|
|
GrammarType,
|
|
|
|
Usage,
|
2024-09-19 18:50:37 +00:00
|
|
|
StreamOptions,
|
2024-07-31 08:33:10 +00:00
|
|
|
DeltaToolCall,
|
|
|
|
Tool,
|
|
|
|
ToolCall,
|
|
|
|
Function,
|
|
|
|
FunctionDefinition,
|
|
|
|
ToolChoice,
|
2024-08-29 14:32:38 +00:00
|
|
|
ModelInfo,
|
2024-11-04 05:44:59 +00:00
|
|
|
ChatTokenizeResponse,
|
2025-02-21 09:30:29 +00:00
|
|
|
MessageBody,
|
2024-07-31 08:33:10 +00:00
|
|
|
)
|
|
|
|
),
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-12-13 14:50:59 +00:00
|
|
|
pub fn py_resolve_tokenizer(
|
2024-10-28 04:00:24 +00:00
|
|
|
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(())
|
|
|
|
}
|
|
|
|
|
2024-12-13 14:50:59 +00:00
|
|
|
pub fn legacy_tokenizer_handle(config_filename: Option<&PathBuf>) -> Option<()> {
|
2024-10-28 04:00:24 +00:00
|
|
|
// 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(())
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-10-18 13:19:03 +00:00
|
|
|
/// Serving method
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
|
|
pub async fn run(
|
2024-07-31 08:33:10 +00:00
|
|
|
backend: impl Backend + Send + Sync + 'static,
|
2022-10-18 13:19:03 +00:00
|
|
|
max_concurrent_requests: usize,
|
2023-03-09 14:30:54 +00:00
|
|
|
max_best_of: usize,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_stop_sequences: usize,
|
2023-08-28 09:43:47 +00:00
|
|
|
max_top_n_tokens: u32,
|
2024-06-04 13:56:56 +00:00
|
|
|
max_input_tokens: usize,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_total_tokens: usize,
|
2022-10-18 13:19:03 +00:00
|
|
|
validation_workers: usize,
|
2024-07-29 09:14:17 +00:00
|
|
|
api_key: Option<String>,
|
2024-07-31 08:33:10 +00:00
|
|
|
tokenizer_name: String,
|
|
|
|
tokenizer_config_path: Option<String>,
|
|
|
|
revision: Option<String>,
|
2024-10-25 04:39:21 +00:00
|
|
|
trust_remote_code: bool,
|
2024-07-31 08:33:10 +00:00
|
|
|
hostname: String,
|
|
|
|
port: u16,
|
|
|
|
cors_allow_origin: Option<Vec<String>>,
|
2023-06-16 14:25:11 +00:00
|
|
|
ngrok: bool,
|
2024-05-28 12:52:17 +00:00
|
|
|
_ngrok_authtoken: Option<String>,
|
|
|
|
_ngrok_edge: Option<String>,
|
2024-07-31 08:33:10 +00:00
|
|
|
disable_grammar_support: bool,
|
2024-04-17 08:41:12 +00:00
|
|
|
max_client_batch_size: usize,
|
2024-07-31 14:29:07 +00:00
|
|
|
usage_stats_level: usage_stats::UsageStatsLevel,
|
2024-11-21 18:20:15 +00:00
|
|
|
payload_limit: usize,
|
2024-06-04 13:56:56 +00:00
|
|
|
) -> Result<(), WebServerError> {
|
2024-07-31 08:33:10 +00:00
|
|
|
// 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()),
|
|
|
|
)
|
|
|
|
});
|
2023-02-03 11:43:37 +00:00
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
// Parse Huggingface hub token
|
|
|
|
let authorization_token = std::env::var("HF_TOKEN")
|
|
|
|
.or_else(|_| std::env::var("HUGGING_FACE_HUB_TOKEN"))
|
|
|
|
.ok();
|
2024-06-04 13:56:56 +00:00
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
// Tokenizer instance
|
|
|
|
// This will only be used to validate payloads
|
|
|
|
let local_path = Path::new(&tokenizer_name);
|
|
|
|
|
|
|
|
// Shared API builder initialization
|
|
|
|
let api_builder = || {
|
2025-03-18 09:37:33 +00:00
|
|
|
let mut builder = ApiBuilder::from_env().with_progress(false);
|
2025-03-05 10:59:52 +00:00
|
|
|
if let Some(token) = authorization_token {
|
|
|
|
builder = builder.with_token(Some(token));
|
|
|
|
}
|
2024-07-31 08:33:10 +00:00
|
|
|
|
|
|
|
if let Ok(cache_dir) = std::env::var("HUGGINGFACE_HUB_CACHE") {
|
|
|
|
builder = builder.with_cache_dir(cache_dir.into());
|
|
|
|
}
|
|
|
|
|
2025-03-04 15:43:50 +00:00
|
|
|
if let Ok(origin) = std::env::var("HF_HUB_USER_AGENT_ORIGIN") {
|
|
|
|
builder = builder.with_user_agent("origin", origin.as_str());
|
|
|
|
}
|
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
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
|
2024-06-04 13:56:56 +00:00
|
|
|
}
|
2024-07-31 08:33:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Type::None
|
|
|
|
};
|
|
|
|
|
|
|
|
// Load tokenizer and model info
|
|
|
|
let (
|
|
|
|
config_filename,
|
|
|
|
tokenizer_config_filename,
|
|
|
|
preprocessor_config_filename,
|
|
|
|
processor_config_filename,
|
2025-03-12 08:25:51 +00:00
|
|
|
chat_template_filename,
|
2024-07-31 08:33:10 +00:00
|
|
|
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")),
|
2025-03-12 08:25:51 +00:00
|
|
|
Some(local_path.join("chat_template.json")),
|
2024-07-31 08:33:10 +00:00
|
|
|
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();
|
2025-03-12 08:25:51 +00:00
|
|
|
let chat_template_filename = api_repo.get("chat_template.json").await.ok();
|
2024-06-04 13:56:56 +00:00
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
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,
|
2025-03-12 08:25:51 +00:00
|
|
|
chat_template_filename,
|
2024-07-31 08:33:10 +00:00
|
|
|
model_info,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
Type::Cache(cache) => {
|
2025-03-12 08:22:53 +00:00
|
|
|
tracing::info!("Cache {cache:?}");
|
2024-07-31 08:33:10 +00:00
|
|
|
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"),
|
2025-03-12 08:25:51 +00:00
|
|
|
repo.get("chat_template.json"),
|
2024-07-31 08:33:10 +00:00
|
|
|
None,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2025-03-12 08:25:51 +00:00
|
|
|
// if chat_template_filename is present, load the chat template
|
|
|
|
let chat_template: Option<crate::ChatTemplateVersions> = chat_template_filename
|
|
|
|
.and_then(|f| std::fs::read_to_string(f).ok())
|
|
|
|
.and_then(|c| {
|
|
|
|
let res = serde_json::from_str::<crate::ChatTemplateStandalone>(&c);
|
|
|
|
if let Err(e) = &res {
|
|
|
|
tracing::warn!("Could not parse chat template {e:?}");
|
|
|
|
}
|
|
|
|
res.ok().map(|t| t.chat_template)
|
|
|
|
});
|
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
// Read the JSON contents of the file as an instance of 'HubTokenizerConfig'.
|
2025-03-12 08:22:53 +00:00
|
|
|
tracing::warn!("Tokenizer_config {tokenizer_config_path:?} - {tokenizer_config_filename:?}");
|
2024-07-31 08:33:10 +00:00
|
|
|
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)
|
|
|
|
};
|
2025-03-12 08:25:51 +00:00
|
|
|
let mut tokenizer_config = tokenizer_config.unwrap_or_else(|| {
|
2024-07-31 08:33:10 +00:00
|
|
|
tracing::warn!("Could not find tokenizer config locally and no API specified");
|
|
|
|
HubTokenizerConfig::default()
|
|
|
|
});
|
|
|
|
|
2025-03-12 08:25:51 +00:00
|
|
|
if chat_template.is_some() {
|
|
|
|
tracing::info!("Using chat template from chat_template.json");
|
|
|
|
tokenizer_config.chat_template = chat_template;
|
|
|
|
}
|
|
|
|
|
2025-01-28 09:29:18 +00:00
|
|
|
let tokenizer: Result<Tokenizer, WebServerError> = {
|
2024-09-11 20:41:56 +00:00
|
|
|
use pyo3::prelude::*;
|
2025-01-28 09:29:18 +00:00
|
|
|
Python::with_gil(|py| -> PyResult<()> {
|
2024-10-28 04:00:24 +00:00
|
|
|
py_resolve_tokenizer(py, &tokenizer_name, revision.as_deref(), trust_remote_code)?;
|
2024-09-11 20:41:56 +00:00
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
.inspect_err(|err| {
|
|
|
|
tracing::error!("Failed to import python tokenizer {err}");
|
2024-10-28 04:00:24 +00:00
|
|
|
})
|
|
|
|
.or_else(|err| {
|
|
|
|
let out = legacy_tokenizer_handle(config_filename.as_ref());
|
|
|
|
out.ok_or(err)
|
|
|
|
})
|
2025-01-28 09:29:18 +00:00
|
|
|
.map_err(|_| WebServerError::Tokenizer("Unable to load tokenizer.".to_string()))?;
|
2024-10-28 04:00:24 +00:00
|
|
|
let filename = "out/tokenizer.json";
|
|
|
|
if let Ok(tok) = tokenizers::Tokenizer::from_file(filename) {
|
2025-01-28 09:29:18 +00:00
|
|
|
Ok(Tokenizer::Rust(tok))
|
2024-09-11 20:41:56 +00:00
|
|
|
} else {
|
2025-01-28 09:29:18 +00:00
|
|
|
Ok(Tokenizer::Python {
|
2024-10-28 04:00:24 +00:00
|
|
|
tokenizer_name: tokenizer_name.clone(),
|
|
|
|
revision: revision.clone(),
|
2024-11-07 13:43:38 +00:00
|
|
|
trust_remote_code,
|
2025-01-28 09:29:18 +00:00
|
|
|
})
|
2024-10-28 04:00:24 +00:00
|
|
|
}
|
|
|
|
};
|
2024-07-31 08:33:10 +00:00
|
|
|
|
|
|
|
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:?}");
|
2024-06-04 13:56:56 +00:00
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
// 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));
|
2025-02-19 20:09:12 +00:00
|
|
|
// retrieve the huggingface_hub user agent origin if set, and add the origin to telemetry
|
|
|
|
let origin = std::env::var("HF_HUB_USER_AGENT_ORIGIN").ok();
|
2024-07-31 14:29:07 +00:00
|
|
|
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,
|
2025-01-28 15:53:16 +00:00
|
|
|
backend.name(),
|
2025-02-19 20:09:12 +00:00
|
|
|
origin,
|
2024-07-31 14:29:07 +00:00
|
|
|
);
|
|
|
|
Some(usage_stats::UserAgent::new(reduced_args))
|
|
|
|
}
|
|
|
|
_ => None,
|
2024-07-31 08:33:10 +00:00
|
|
|
};
|
|
|
|
|
2025-01-28 09:29:18 +00:00
|
|
|
let stop_usage_thread = Arc::new(AtomicBool::new(false));
|
|
|
|
let stop_usage_thread_clone = stop_usage_thread.clone();
|
|
|
|
if let Some(ua) = user_agent.clone() {
|
2024-07-31 08:33:10 +00:00
|
|
|
let start_event =
|
|
|
|
usage_stats::UsageStatsEvent::new(ua.clone(), usage_stats::EventType::Start, None);
|
|
|
|
tokio::spawn(async move {
|
2025-01-28 09:29:18 +00:00
|
|
|
// send start event
|
2024-07-31 08:33:10 +00:00
|
|
|
start_event.send().await;
|
2025-01-28 09:29:18 +00:00
|
|
|
let mut last_report = Instant::now();
|
|
|
|
while !stop_usage_thread_clone.load(Ordering::Relaxed) {
|
|
|
|
if last_report.elapsed() > Duration::from_secs(900) {
|
|
|
|
let report_event = usage_stats::UsageStatsEvent::new(
|
|
|
|
ua.clone(),
|
|
|
|
usage_stats::EventType::Ping,
|
|
|
|
None,
|
|
|
|
);
|
|
|
|
report_event.send().await;
|
|
|
|
last_report = Instant::now();
|
|
|
|
}
|
|
|
|
tokio::time::sleep(Duration::from_secs(1)).await;
|
|
|
|
}
|
2024-07-31 08:33:10 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
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,
|
2025-01-28 09:29:18 +00:00
|
|
|
(tokenizer?, tokenizer_config),
|
2024-07-31 08:33:10 +00:00
|
|
|
(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,
|
2024-11-21 18:20:15 +00:00
|
|
|
payload_limit,
|
2024-07-31 08:33:10 +00:00
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
if let Some(ua) = user_agent {
|
2025-01-28 09:29:18 +00:00
|
|
|
stop_usage_thread.store(true, Ordering::Relaxed);
|
2024-07-31 08:33:10 +00:00
|
|
|
match result {
|
|
|
|
Ok(_) => {
|
|
|
|
let stop_event = usage_stats::UsageStatsEvent::new(
|
|
|
|
ua.clone(),
|
|
|
|
usage_stats::EventType::Stop,
|
|
|
|
None,
|
|
|
|
);
|
|
|
|
stop_event.send().await;
|
|
|
|
Ok(())
|
2024-06-04 13:56:56 +00:00
|
|
|
}
|
2024-07-31 08:33:10 +00:00
|
|
|
Err(e) => {
|
2024-07-31 14:29:07 +00:00
|
|
|
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;
|
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
Err(e)
|
2024-06-04 13:56:56 +00:00
|
|
|
}
|
|
|
|
}
|
2024-07-31 08:33:10 +00:00
|
|
|
} 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>,
|
2024-10-28 04:00:24 +00:00
|
|
|
(tokenizer, tokenizer_config): (Tokenizer, HubTokenizerConfig),
|
2024-07-31 08:33:10 +00:00
|
|
|
(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>,
|
2024-11-21 18:20:15 +00:00
|
|
|
payload_limit: usize,
|
2024-07-31 08:33:10 +00:00
|
|
|
) -> 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)
|
|
|
|
}
|
2024-06-04 13:56:56 +00:00
|
|
|
};
|
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
// Create state
|
2023-02-15 20:56:59 +00:00
|
|
|
let validation = Validation::new(
|
|
|
|
validation_workers,
|
|
|
|
tokenizer,
|
Adding Llava-Next (Llava 1.6) with full support. (#1709)
# What does this PR do?
- Changed all models to extract `embed_tokens` in order to enable llava
to separately call the embeddings and the core model layers.
- Added VlmCausalLM to inherit from FlashMistral in order to be
maximally supported. The only added logics sits on top and parses images
into pixel values, preallocates input_ids space for the image
embeddings, and passes them for the model.
- Added Clip for the vision tower.
- Didn't add flash for the vision tower since there's no padding anyway.
- Added heuristic (potentially incomplete) to calculate number of
features *before* calculating the clip patches (allows for easier logic
reuse of the LLM under the hood).
Still needs to be done:
- [x] Implement the image parsing in the controller side, to avoid
downloading n times per TP shard and also refusing requests too large
early and avoid issues where the truncation actually truncates the
image.
- [ ] Make sure it works with quantization properly.
- [x] Make sure it works with TP>1
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-04-09 19:32:00 +00:00
|
|
|
config,
|
2024-06-27 13:54:35 +00:00
|
|
|
preprocessor_config,
|
2023-03-09 14:30:54 +00:00
|
|
|
max_best_of,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_stop_sequences,
|
2023-08-28 09:43:47 +00:00
|
|
|
max_top_n_tokens,
|
2024-06-04 13:56:56 +00:00
|
|
|
max_input_tokens,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_total_tokens,
|
2024-07-31 08:33:10 +00:00
|
|
|
disable_grammar_support,
|
2023-02-15 20:56:59 +00:00
|
|
|
);
|
2024-06-04 13:56:56 +00:00
|
|
|
|
2023-01-31 16:04:00 +00:00
|
|
|
let infer = Infer::new(
|
2024-07-31 08:33:10 +00:00
|
|
|
backend,
|
2022-10-18 13:19:03 +00:00
|
|
|
validation,
|
2023-01-31 16:04:00 +00:00
|
|
|
max_concurrent_requests,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
tokenizer_config,
|
2024-05-27 14:03:16 +00:00
|
|
|
processor_config,
|
2023-01-31 16:04:00 +00:00
|
|
|
);
|
2022-10-18 13:19:03 +00:00
|
|
|
|
2023-04-09 18:13:28 +00:00
|
|
|
// 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)
|
2024-06-04 13:56:56 +00:00
|
|
|
.map(|x| (max_input_tokens as f64 / 100.0) * (x + 1) as f64)
|
2023-04-09 18:13:28 +00:00
|
|
|
.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"));
|
2023-04-24 15:59:00 +00:00
|
|
|
let batch_size_buckets: Vec<f64> = (0..1024).map(|x| (x + 1) as f64).collect();
|
2023-12-11 13:43:40 +00:00
|
|
|
// Speculated tokens buckets
|
2024-07-31 08:33:10 +00:00
|
|
|
// 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();
|
2023-04-09 18:13:28 +00:00
|
|
|
|
2023-02-16 16:18:53 +00:00
|
|
|
// Prometheus handler
|
2023-04-09 18:13:28 +00:00
|
|
|
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();
|
2024-07-31 08:33:10 +00:00
|
|
|
// .set_buckets_for_metric(skipped_matcher, &skipped_buckets)
|
|
|
|
// .unwrap();
|
2024-09-17 16:01:28 +00:00
|
|
|
// 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");
|
2023-02-16 16:18:53 +00:00
|
|
|
|
2024-08-16 17:43:30 +00:00
|
|
|
// 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"
|
|
|
|
);
|
2024-10-02 14:32:36 +00:00
|
|
|
metrics::describe_gauge!(
|
|
|
|
"tgi_batch_total_tokens",
|
|
|
|
metrics::Unit::Count,
|
|
|
|
"Maximum amount of tokens in total."
|
|
|
|
);
|
2024-08-16 17:43:30 +00:00
|
|
|
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"
|
|
|
|
);
|
|
|
|
|
2023-02-17 17:22:00 +00:00
|
|
|
// 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);
|
|
|
|
|
2023-04-25 11:11:18 +00:00
|
|
|
// Endpoint info
|
|
|
|
let info = Info {
|
|
|
|
model_id: model_info.model_id,
|
|
|
|
model_sha: model_info.sha,
|
2024-07-31 08:33:10 +00:00
|
|
|
// model_dtype: shard_info.dtype,
|
|
|
|
// model_device_type: shard_info.device_type,
|
2023-04-25 11:11:18 +00:00
|
|
|
model_pipeline_tag: model_info.pipeline_tag,
|
|
|
|
max_concurrent_requests,
|
|
|
|
max_best_of,
|
|
|
|
max_stop_sequences,
|
2024-06-04 13:56:56 +00:00
|
|
|
max_input_tokens,
|
2023-04-25 11:11:18 +00:00
|
|
|
max_total_tokens,
|
2024-07-31 08:33:10 +00:00
|
|
|
// waiting_served_ratio,
|
|
|
|
// max_batch_total_tokens,
|
|
|
|
// max_waiting_tokens,
|
|
|
|
// max_batch_size,
|
2023-04-25 11:11:18 +00:00
|
|
|
validation_workers,
|
2024-04-17 08:41:12 +00:00
|
|
|
max_client_batch_size,
|
2024-05-03 14:39:04 +00:00
|
|
|
router: env!("CARGO_PKG_NAME"),
|
2023-04-25 11:11:18 +00:00
|
|
|
version: env!("CARGO_PKG_VERSION"),
|
|
|
|
sha: option_env!("VERGEN_GIT_SHA"),
|
2023-05-02 13:43:19 +00:00
|
|
|
docker_label: option_env!("DOCKER_LABEL"),
|
2023-04-25 11:11:18 +00:00
|
|
|
};
|
|
|
|
|
2024-06-13 16:51:51 +00:00
|
|
|
#[allow(unused_mut)] // mut is needed for conditional compilation
|
|
|
|
let mut doc = ApiDoc::openapi();
|
|
|
|
|
|
|
|
#[cfg(feature = "google")]
|
|
|
|
{
|
2024-09-26 09:41:38 +00:00
|
|
|
use crate::vertex::__path_vertex_compatibility;
|
|
|
|
use crate::vertex::{VertexInstance, VertexRequest, VertexResponse};
|
2024-06-13 16:51:51 +00:00
|
|
|
|
|
|
|
#[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,
|
2024-06-25 23:30:10 +00:00
|
|
|
kserve_model_infer,
|
2024-06-13 16:51:51 +00:00
|
|
|
),
|
|
|
|
components(schemas(
|
|
|
|
InferenceOutput,
|
|
|
|
InferenceRequest,
|
|
|
|
LiveResponse,
|
|
|
|
MetadataServerResponse,
|
|
|
|
OutputChunk,
|
|
|
|
ReadyResponse,
|
|
|
|
))
|
|
|
|
)]
|
|
|
|
struct KServeApiDoc;
|
|
|
|
|
|
|
|
doc.merge(KServeApiDoc::openapi());
|
|
|
|
}
|
2024-02-20 13:04:51 +00:00
|
|
|
|
2024-01-22 15:29:01 +00:00
|
|
|
// Configure Swagger UI
|
2024-02-20 13:04:51 +00:00
|
|
|
let swagger_ui = SwaggerUi::new("/docs").url("/api-doc/openapi.json", doc);
|
2024-01-22 15:29:01 +00:00
|
|
|
|
|
|
|
// Define base and health routes
|
2024-07-29 09:14:17 +00:00
|
|
|
let mut base_routes = Router::new()
|
2023-02-27 13:56:58 +00:00
|
|
|
.route("/", post(compat_generate))
|
2022-10-14 13:56:21 +00:00
|
|
|
.route("/generate", post(generate))
|
2023-01-31 16:04:00 +00:00
|
|
|
.route("/generate_stream", post(generate_stream))
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
.route("/v1/chat/completions", post(chat_completions))
|
2024-02-29 15:44:20 +00:00
|
|
|
.route("/v1/completions", post(completions))
|
2024-02-20 13:04:51 +00:00
|
|
|
.route("/vertex", post(vertex_compatibility))
|
2024-10-23 11:26:01 +00:00
|
|
|
.route("/invocations", post(sagemaker_compatibility))
|
2024-07-29 09:14:17 +00:00
|
|
|
.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))
|
2024-08-06 11:51:32 +00:00
|
|
|
.route("/chat_tokenize", post(get_chat_tokenize))
|
2024-07-29 09:14:17 +00:00
|
|
|
.route("/info", get(get_model_info))
|
2022-10-18 13:19:03 +00:00
|
|
|
.route("/health", get(health))
|
2023-03-29 19:38:30 +00:00
|
|
|
.route("/ping", get(health))
|
2024-08-29 14:32:38 +00:00
|
|
|
.route("/metrics", get(metrics))
|
|
|
|
.route("/v1/models", get(openai_get_model_info));
|
2024-01-22 15:29:01 +00:00
|
|
|
|
2024-01-29 11:30:50 +00:00
|
|
|
let compute_type =
|
|
|
|
ComputeType(std::env::var("COMPUTE_TYPE").unwrap_or("gpu+optimized".to_string()));
|
2024-01-29 10:20:08 +00:00
|
|
|
|
2024-01-22 15:29:01 +00:00
|
|
|
// Combine routes and layers
|
2024-02-20 13:04:51 +00:00
|
|
|
let mut app = Router::new()
|
2024-01-22 15:29:01 +00:00
|
|
|
.merge(swagger_ui)
|
|
|
|
.merge(base_routes)
|
2024-10-23 11:26:01 +00:00
|
|
|
.merge(info_routes);
|
2024-02-20 13:04:51 +00:00
|
|
|
|
|
|
|
#[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));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-13 16:51:51 +00:00
|
|
|
#[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),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-02-20 13:04:51 +00:00
|
|
|
// add layers after routes
|
|
|
|
app = app
|
2023-04-25 11:11:18 +00:00
|
|
|
.layer(Extension(info))
|
2023-02-28 09:19:32 +00:00
|
|
|
.layer(Extension(compat_return_full_text))
|
|
|
|
.layer(Extension(infer))
|
2024-01-29 10:20:08 +00:00
|
|
|
.layer(Extension(compute_type))
|
2023-07-21 14:56:30 +00:00
|
|
|
.layer(Extension(prom_handle.clone()))
|
2023-09-27 08:40:18 +00:00
|
|
|
.layer(OtelAxumLayer::default())
|
2024-11-21 18:20:15 +00:00
|
|
|
.layer(DefaultBodyLimit::max(payload_limit))
|
2023-02-17 17:22:00 +00:00
|
|
|
.layer(cors_layer);
|
2022-10-11 08:36:51 +00:00
|
|
|
|
2024-06-04 13:56:56 +00:00
|
|
|
tracing::info!("Connected");
|
|
|
|
|
2023-06-16 14:25:11 +00:00
|
|
|
if ngrok {
|
|
|
|
#[cfg(feature = "ngrok")]
|
|
|
|
{
|
2024-05-28 12:52:17 +00:00
|
|
|
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.");
|
2023-06-16 14:25:11 +00:00
|
|
|
|
|
|
|
// 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
|
2025-01-28 09:29:18 +00:00
|
|
|
let listener = match tokio::net::TcpListener::bind(&addr).await {
|
|
|
|
Ok(listener) => listener,
|
|
|
|
Err(e) => {
|
|
|
|
tracing::error!("Failed to bind to {addr}: {e}");
|
|
|
|
return Err(WebServerError::Axum(Box::new(e)));
|
|
|
|
}
|
|
|
|
};
|
2024-05-28 12:52:17 +00:00
|
|
|
axum::serve(listener, app)
|
2023-06-16 14:25:11 +00:00
|
|
|
.with_graceful_shutdown(shutdown_signal())
|
2024-06-04 13:56:56 +00:00
|
|
|
.await
|
|
|
|
.map_err(|err| WebServerError::Axum(Box::new(err)))?;
|
2023-06-16 14:25:11 +00:00
|
|
|
}
|
2023-07-10 12:47:15 +00:00
|
|
|
Ok(())
|
2022-10-11 14:50:54 +00:00
|
|
|
}
|
2022-10-18 13:19:03 +00:00
|
|
|
|
2024-07-31 08:33:10 +00:00
|
|
|
/// 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)
|
|
|
|
}
|
|
|
|
|
2022-10-18 13:19:03 +00:00
|
|
|
/// 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");
|
2023-02-13 12:02:45 +00:00
|
|
|
opentelemetry::global::shutdown_tracer_provider();
|
2022-10-18 13:19:03 +00:00
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
|
|
|
|
/// 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,
|
2024-09-11 16:10:40 +00:00
|
|
|
InferError::IncompleteGenerationStream => StatusCode::INTERNAL_SERVER_ERROR,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
InferError::TemplateError(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
2024-08-12 14:58:40 +00:00
|
|
|
InferError::MissingTemplateVariable(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
2024-04-16 13:02:46 +00:00
|
|
|
InferError::ToolError(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
2024-10-10 13:28:25 +00:00
|
|
|
InferError::StreamSerializationError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
2023-01-31 16:04:00 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
(
|
|
|
|
status_code,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: err.to_string(),
|
2023-03-07 17:52:22 +00:00
|
|
|
error_type: err.error_type().to_string(),
|
2023-01-31 16:04:00 +00:00
|
|
|
}),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<InferError> for Event {
|
|
|
|
fn from(err: InferError) -> Self {
|
|
|
|
Event::default()
|
|
|
|
.json_data(ErrorResponse {
|
|
|
|
error: err.to_string(),
|
2023-03-07 17:52:22 +00:00
|
|
|
error_type: err.error_type().to_string(),
|
2023-01-31 16:04:00 +00:00
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
}
|
|
|
|
}
|
2024-06-04 13:56:56 +00:00
|
|
|
|
|
|
|
#[derive(Debug, Error)]
|
|
|
|
pub enum WebServerError {
|
|
|
|
#[error("Axum error: {0}")]
|
|
|
|
Axum(#[from] axum::BoxError),
|
2025-01-28 09:29:18 +00:00
|
|
|
#[error("Tokenizer error: {0}")]
|
|
|
|
Tokenizer(String),
|
2024-06-04 13:56:56 +00:00
|
|
|
}
|