openai.rs 64 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
5
6
7
8
9
use std::{
    collections::HashSet,
    sync::Arc,
    time::{SystemTime, UNIX_EPOCH},
};

10
use axum::{
11
    Json, Router,
12
    body::Body,
13
    extract::State,
14
    http::Request,
Ryan Olson's avatar
Ryan Olson committed
15
    http::{HeaderMap, StatusCode},
16
    middleware::{self, Next},
17
18
    response::{
        IntoResponse, Response,
19
        sse::{KeepAlive, Sse},
20
21
22
    },
    routing::{get, post},
};
Ryan Olson's avatar
Ryan Olson committed
23
24
25
26
use dynamo_runtime::{
    pipeline::{AsyncEngineContextProvider, Context},
    protocols::annotated::AnnotationsProvider,
};
27
use futures::{StreamExt, stream};
28
29
30
use serde::{Deserialize, Serialize};

use super::{
31
32
    RouteDoc,
    disconnect::{ConnectionHandle, create_connection_monitor, monitor_for_disconnects},
33
    error::HttpError,
34
35
36
37
    metrics::{
        Endpoint, EventConverter, process_response_and_observe_metrics,
        process_response_using_event_converter_and_observe_metrics,
    },
38
    service_v2,
39
};
40
use crate::engines::ValidateRequest;
41
use crate::protocols::openai::chat_completions::aggregator::ChatCompletionAggregator;
42
use crate::protocols::openai::{
43
44
45
46
    chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionResponse},
    completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
    embeddings::{NvCreateEmbeddingRequest, NvCreateEmbeddingResponse},
    responses::{NvCreateResponse, NvResponse},
47
};
48
use crate::request_template::RequestTemplate;
49
use crate::types::Annotated;
50
51
use dynamo_runtime::logging::get_distributed_tracing_context;
use tracing::Instrument;
52

Ryan Olson's avatar
Ryan Olson committed
53
54
55
56
57
pub const DYNAMO_REQUEST_ID_HEADER: &str = "x-dynamo-request-id";

/// Dynamo Annotation for the request ID
pub const ANNOTATION_REQUEST_ID: &str = "request_id";

58
59
60
61
62
63
64
65
66
67
68
// Default axum max body limit without configuring is 2MB: https://docs.rs/axum/latest/axum/extract/struct.DefaultBodyLimit.html
/// Default body limit in bytes (45MB) to support 500k+ token payloads.
/// Can be configured at compile time using the DYN_FRONTEND_BODY_LIMIT_MB environment variable
fn get_body_limit() -> usize {
    std::env::var("DYN_HTTP_BODY_LIMIT_MB")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .map(|mb| mb * 1024 * 1024)
        .unwrap_or(45 * 1024 * 1024)
}

Ryan Olson's avatar
Ryan Olson committed
69
70
pub type ErrorResponse = (StatusCode, Json<ErrorMessage>);

71
#[derive(Serialize, Deserialize, Debug)]
Ryan Olson's avatar
Ryan Olson committed
72
pub(crate) struct ErrorMessage {
73
74
75
76
77
78
79
80
81
82
83
    message: String,
    #[serde(rename = "type")]
    error_type: String,
    code: u16,
}

fn map_error_code_to_error_type(code: StatusCode) -> String {
    match code.canonical_reason() {
        Some(reason) => reason.to_string(),
        None => "UnknownError".to_string(),
    }
84
85
}

Ryan Olson's avatar
Ryan Olson committed
86
impl ErrorMessage {
87
    /// Not Found Error
Ryan Olson's avatar
Ryan Olson committed
88
    pub fn model_not_found() -> ErrorResponse {
89
90
        let code = StatusCode::NOT_FOUND;
        let error_type = map_error_code_to_error_type(code);
91
        (
92
            code,
Ryan Olson's avatar
Ryan Olson committed
93
            Json(ErrorMessage {
94
95
96
                message: "Model not found".to_string(),
                error_type,
                code: code.as_u16(),
97
98
99
100
101
102
            }),
        )
    }

    /// Service Unavailable
    /// This is returned when the service is live, but not ready.
Ryan Olson's avatar
Ryan Olson committed
103
    pub fn _service_unavailable() -> ErrorResponse {
104
105
        let code = StatusCode::SERVICE_UNAVAILABLE;
        let error_type = map_error_code_to_error_type(code);
106
        (
107
            code,
Ryan Olson's avatar
Ryan Olson committed
108
            Json(ErrorMessage {
109
110
111
                message: "Service is not ready".to_string(),
                error_type,
                code: code.as_u16(),
112
113
114
115
116
117
118
119
            }),
        )
    }

    /// Internal Service Error
    /// Return this error when the service encounters an internal error.
    /// We should return a generic message to the client instead of the real error.
    /// Internal Services errors are the result of misconfiguration or bugs in the service.
Ryan Olson's avatar
Ryan Olson committed
120
    pub fn internal_server_error(msg: &str) -> ErrorResponse {
121
        tracing::error!("Internal server error: {msg}");
122
123
        let code = StatusCode::INTERNAL_SERVER_ERROR;
        let error_type = map_error_code_to_error_type(code);
124
        (
125
            code,
Ryan Olson's avatar
Ryan Olson committed
126
            Json(ErrorMessage {
127
128
129
                message: msg.to_string(),
                error_type,
                code: code.as_u16(),
130
131
132
133
            }),
        )
    }

134
135
136
    /// Not Implemented Error
    /// Return this error when the client requests a feature that is not yet implemented.
    /// This should be used for features that are planned but not available.
Ryan Olson's avatar
Ryan Olson committed
137
    pub fn not_implemented_error(msg: &str) -> ErrorResponse {
138
        tracing::error!("Not Implemented error: {msg}");
139
140
        let code = StatusCode::NOT_IMPLEMENTED;
        let error_type = map_error_code_to_error_type(code);
141
        (
142
            code,
Ryan Olson's avatar
Ryan Olson committed
143
            Json(ErrorMessage {
144
145
146
                message: msg.to_string(),
                error_type,
                code: code.as_u16(),
147
148
149
150
            }),
        )
    }

Neelay Shah's avatar
Neelay Shah committed
151
    /// The OAI endpoints call an [`dynamo.runtime::engine::AsyncEngine`] which are specialized to return
152
    /// an [`anyhow::Error`]. This method will convert the [`anyhow::Error`] into an [`HttpError`].
Ryan Olson's avatar
Ryan Olson committed
153
    /// If successful, it will return the [`HttpError`] as an [`ErrorMessage::internal_server_error`]
154
    /// with the details of the error.
Ryan Olson's avatar
Ryan Olson committed
155
    pub fn from_anyhow(err: anyhow::Error, alt_msg: &str) -> ErrorResponse {
156
157
158
        // First check for PipelineError::ServiceOverloaded
        if let Some(pipeline_err) =
            err.downcast_ref::<dynamo_runtime::pipeline::error::PipelineError>()
159
            && matches!(
160
161
                pipeline_err,
                dynamo_runtime::pipeline::error::PipelineError::ServiceOverloaded(_)
162
163
164
165
166
            )
        {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(ErrorMessage {
167
168
169
                    message: pipeline_err.to_string(),
                    error_type: map_error_code_to_error_type(StatusCode::SERVICE_UNAVAILABLE),
                    code: StatusCode::SERVICE_UNAVAILABLE.as_u16(),
170
171
                }),
            );
172
173
174
        }

        // Then check for HttpError
175
        match err.downcast::<HttpError>() {
Ryan Olson's avatar
Ryan Olson committed
176
177
            Ok(http_error) => ErrorMessage::from_http_error(http_error),
            Err(err) => ErrorMessage::internal_server_error(&format!("{alt_msg}: {err}")),
178
179
180
181
        }
    }

    /// Implementers should only be able to throw 400-499 errors.
Ryan Olson's avatar
Ryan Olson committed
182
    pub fn from_http_error(err: HttpError) -> ErrorResponse {
183
        if err.code < 400 || err.code >= 500 {
Ryan Olson's avatar
Ryan Olson committed
184
            return ErrorMessage::internal_server_error(&err.message);
185
186
        }
        match StatusCode::from_u16(err.code) {
187
188
189
190
191
192
193
194
            Ok(code) => (
                code,
                Json(ErrorMessage {
                    message: err.message,
                    error_type: map_error_code_to_error_type(code),
                    code: code.as_u16(),
                }),
            ),
Ryan Olson's avatar
Ryan Olson committed
195
            Err(_) => ErrorMessage::internal_server_error(&err.message),
196
197
198
199
        }
    }
}

Ryan Olson's avatar
Ryan Olson committed
200
impl From<HttpError> for ErrorMessage {
201
    fn from(err: HttpError) -> Self {
202
203
204
205
206
207
208
        ErrorMessage {
            message: err.message,
            error_type: map_error_code_to_error_type(
                StatusCode::from_u16(err.code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            ),
            code: err.code,
        }
209
210
211
    }
}

212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Problem: Currently we are using JSON from axum as the request validator. Whenever there is an invalid JSON, it will return a 422.
// But all the downstream apps that relies on openai based APIs, expects to get 400 for all these cases otherwise they fail badly
// Solution: Intercept the response from handlers and convert ANY 422 status codes to 400 with the actual error message.
pub async fn smart_json_error_middleware(request: Request<Body>, next: Next) -> Response {
    let response = next.run(request).await;

    if response.status() == StatusCode::UNPROCESSABLE_ENTITY {
        let (_parts, body) = response.into_parts();
        let body_bytes = axum::body::to_bytes(body, usize::MAX)
            .await
            .unwrap_or_default();
        let error_message = String::from_utf8_lossy(&body_bytes).to_string();
        (
            StatusCode::BAD_REQUEST,
            Json(ErrorMessage {
227
228
229
                message: error_message,
                error_type: map_error_code_to_error_type(StatusCode::BAD_REQUEST),
                code: StatusCode::BAD_REQUEST.as_u16(),
230
231
232
233
234
235
236
237
238
            }),
        )
            .into_response()
    } else {
        // Pass through if it is not a 422
        response
    }
}

Ryan Olson's avatar
Ryan Olson committed
239
/// Get the request ID from a primary source, or next from the headers, or lastly create a new one if not present
240
// TODO: Similar function exists in lib/llm/src/grpc/service/openai.rs but with different signature and simpler logic
Ryan Olson's avatar
Ryan Olson committed
241
fn get_or_create_request_id(primary: Option<&str>, headers: &HeaderMap) -> String {
242
    // Try to get request id from trace context
243
244
245
246
    if let Some(trace_context) = get_distributed_tracing_context()
        && let Some(x_dynamo_request_id) = trace_context.x_dynamo_request_id
    {
        return x_dynamo_request_id;
247
248
    }

Ryan Olson's avatar
Ryan Olson committed
249
    // Try to get the request ID from the primary source
250
251
252
253
    if let Some(primary) = primary
        && let Ok(uuid) = uuid::Uuid::parse_str(primary)
    {
        return uuid.to_string();
Ryan Olson's avatar
Ryan Olson committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    }

    // Try to get the request ID header as a string slice
    let request_id_opt = headers
        .get(DYNAMO_REQUEST_ID_HEADER)
        .and_then(|h| h.to_str().ok());

    // Try to parse the request ID as a UUID, or generate a new one if missing/invalid
    let uuid = match request_id_opt {
        Some(request_id) => {
            uuid::Uuid::parse_str(request_id).unwrap_or_else(|_| uuid::Uuid::new_v4())
        }
        None => uuid::Uuid::new_v4(),
    };

    uuid.to_string()
}

272
273
274
275
276
277
278
279
/// OpenAI Completions Request Handler
///
/// This method will handle the incoming request for the `/v1/completions endpoint`. The endpoint is a "source"
/// for an [`super::OpenAICompletionsStreamingEngine`] and will return a stream of
/// responses which will be forward to the client.
///
/// Note: For all requests, streaming or non-streaming, we always call the engine with streaming enabled. For
/// non-streaming requests, we will fold the stream into a single response as part of this handler.
Ryan Olson's avatar
Ryan Olson committed
280
async fn handler_completions(
281
    State(state): State<Arc<service_v2::State>>,
Ryan Olson's avatar
Ryan Olson committed
282
    headers: HeaderMap,
283
    Json(request): Json<NvCreateCompletionRequest>,
Ryan Olson's avatar
Ryan Olson committed
284
285
286
287
288
289
290
291
292
293
) -> Result<Response, ErrorResponse> {
    // return a 503 if the service is not ready
    check_ready(&state)?;

    // create the context for the request
    let request_id = get_or_create_request_id(request.inner.user.as_deref(), &headers);
    let request = Context::with_id(request, request_id);
    let context = request.context();

    // create the connection handles
294
295
    let (mut connection_handle, stream_handle) =
        create_connection_monitor(context.clone(), Some(state.metrics_clone())).await;
Ryan Olson's avatar
Ryan Olson committed
296
297
298

    // possibly long running task
    // if this returns a streaming response, the stream handle will be armed and captured by the response stream
299
    let response = tokio::spawn(completions(state, request, stream_handle).in_current_span())
Ryan Olson's avatar
Ryan Olson committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
        .await
        .map_err(|e| {
            ErrorMessage::internal_server_error(&format!(
                "Failed to await chat completions task: {:?}",
                e,
            ))
        })?;

    // if we got here, then we will return a response and the potentially long running task has completed successfully
    // without need to be cancelled.
    connection_handle.disarm();

    response
}

#[tracing::instrument(skip_all)]
async fn completions(
    state: Arc<service_v2::State>,
    request: Context<NvCreateCompletionRequest>,
    stream_handle: ConnectionHandle,
) -> Result<Response, ErrorResponse> {
321
322
323
    // return a 503 if the service is not ready
    check_ready(&state)?;

324
325
    validate_completion_fields_generic(&request)?;

326
    let request_id = request.id().to_string();
327
328

    // todo - decide on default
329
    let streaming = request.inner.stream.unwrap_or(false);
330

331
332
333
334
335
336
    // todo - make the protocols be optional for model name
    // todo - when optional, if none, apply a default
    let model = request.inner.model.clone();
    // Create http_queue_guard early - tracks time waiting to be processed
    let http_queue_guard = state.metrics_clone().create_http_queue_guard(&model);

337
    // update the request to always stream
Ryan Olson's avatar
Ryan Olson committed
338
339
340
341
    let request = request.map(|mut req| {
        req.inner.stream = Some(true);
        req
    });
342

343
344
    // todo - error handling should be more robust
    let engine = state
345
        .manager()
346
        .get_completions_engine(&model)
Ryan Olson's avatar
Ryan Olson committed
347
        .map_err(|_| ErrorMessage::model_not_found())?;
348

349
    let parsing_options = state.manager().get_parsing_options(&model);
350

351
    let mut response_collector = state.metrics_clone().create_response_collector(&model);
352

Ryan Olson's avatar
Ryan Olson committed
353
354
    // prepare to process any annotations
    let annotations = request.annotations();
355

356
357
358
359
360
361
    // Create inflight_guard before calling engine to ensure errors are counted
    let mut inflight_guard =
        state
            .metrics_clone()
            .create_inflight_guard(&model, Endpoint::Completions, streaming);

362
363
364
365
    // issue the generate call on the engine
    let stream = engine
        .generate(request)
        .await
Ryan Olson's avatar
Ryan Olson committed
366
        .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate completions"))?;
367
368
369
370

    // capture the context to cancel the stream if the client disconnects
    let ctx = stream.context();

Ryan Olson's avatar
Ryan Olson committed
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    let annotations = annotations.map_or(Vec::new(), |annotations| {
        annotations
            .iter()
            .filter_map(|annotation| {
                if annotation == ANNOTATION_REQUEST_ID {
                    Annotated::<NvCreateCompletionResponse>::from_annotation(
                        ANNOTATION_REQUEST_ID,
                        &request_id,
                    )
                    .ok()
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    });

    // apply any annotations to the front of the stream
    let stream = stream::iter(annotations).chain(stream);
390
391

    if streaming {
392
393
        // For streaming, we'll drop the http_queue_guard on the first token
        let mut http_queue_guard = Some(http_queue_guard);
394
        let stream = stream.map(move |response| {
395
396
397
398
399
400
            // Calls observe_response() on each token
            process_response_using_event_converter_and_observe_metrics(
                EventConverter::from(response),
                &mut response_collector,
                &mut http_queue_guard,
            )
401
        });
Ryan Olson's avatar
Ryan Olson committed
402
        let stream = monitor_for_disconnects(stream, ctx, inflight_guard, stream_handle);
403

404
405
        let mut sse_stream = Sse::new(stream);

406
        if let Some(keep_alive) = state.sse_keep_alive() {
407
408
409
410
            sse_stream = sse_stream.keep_alive(KeepAlive::default().interval(keep_alive));
        }

        Ok(sse_stream.into_response())
411
    } else {
412
        // Tap the stream to collect metrics for non-streaming requests without altering items
413
        let mut http_queue_guard = Some(http_queue_guard);
414
        let stream = stream.inspect(move |response| {
415
416
417
418
419
420
            // Calls observe_response() on each token - drops http_queue_guard on first token
            process_response_and_observe_metrics(
                response,
                &mut response_collector,
                &mut http_queue_guard,
            );
421
422
        });

423
        let response = NvCreateCompletionResponse::from_annotated_stream(stream, parsing_options)
424
425
426
427
428
429
430
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to fold completions stream for {}: {:?}",
                    request_id,
                    e
                );
Ryan Olson's avatar
Ryan Olson committed
431
                ErrorMessage::internal_server_error("Failed to fold completions stream")
432
433
            })?;

434
        inflight_guard.mark_ok();
435
436
437
438
        Ok(Json(response).into_response())
    }
}

439
440
#[tracing::instrument(skip_all)]
async fn embeddings(
441
    State(state): State<Arc<service_v2::State>>,
442
    headers: HeaderMap,
443
    Json(request): Json<NvCreateEmbeddingRequest>,
Ryan Olson's avatar
Ryan Olson committed
444
) -> Result<Response, ErrorResponse> {
445
446
447
    // return a 503 if the service is not ready
    check_ready(&state)?;

448
449
450
    let request_id = get_or_create_request_id(request.inner.user.as_deref(), &headers);
    let request = Context::with_id(request, request_id);
    let request_id = request.id().to_string();
451
452
453
454
455
456
457
458

    // Embeddings are typically not streamed, so we default to non-streaming
    let streaming = false;

    // todo - make the protocols be optional for model name
    // todo - when optional, if none, apply a default
    let model = &request.inner.model;

459
460
461
    // Create http_queue_guard early - tracks time waiting to be processed
    let http_queue_guard = state.metrics_clone().create_http_queue_guard(model);

462
463
464
465
    // todo - error handling should be more robust
    let engine = state
        .manager()
        .get_embeddings_engine(model)
Ryan Olson's avatar
Ryan Olson committed
466
        .map_err(|_| ErrorMessage::model_not_found())?;
467
468
469
470
471
472
473

    // this will increment the inflight gauge for the model
    let mut inflight =
        state
            .metrics_clone()
            .create_inflight_guard(model, Endpoint::Embeddings, streaming);

474
475
    let mut response_collector = state.metrics_clone().create_response_collector(model);

476
477
478
479
    // issue the generate call on the engine
    let stream = engine
        .generate(request)
        .await
Ryan Olson's avatar
Ryan Olson committed
480
        .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate embeddings"))?;
481

482
483
484
485
486
487
488
489
490
491
492
    // Process stream to collect metrics and drop http_queue_guard on first token
    let mut http_queue_guard = Some(http_queue_guard);
    let stream = stream.inspect(move |response| {
        // Calls observe_response() on each token - drops http_queue_guard on first token
        process_response_and_observe_metrics(
            response,
            &mut response_collector,
            &mut http_queue_guard,
        );
    });

493
494
    // Embeddings are typically returned as a single response (non-streaming)
    // so we fold the stream into a single response
Ryan Olson's avatar
Ryan Olson committed
495
    let response = NvCreateEmbeddingResponse::from_annotated_stream(stream)
496
497
498
499
500
501
502
        .await
        .map_err(|e| {
            tracing::error!(
                "Failed to fold embeddings stream for {}: {:?}",
                request_id,
                e
            );
Ryan Olson's avatar
Ryan Olson committed
503
            ErrorMessage::internal_server_error("Failed to fold embeddings stream")
504
505
506
507
        })?;

    inflight.mark_ok();
    Ok(Json(response).into_response())
508
509
}

Ryan Olson's avatar
Ryan Olson committed
510
511
512
513
514
515
516
517
518
519
520
521
522
523
async fn handler_chat_completions(
    State((state, template)): State<(Arc<service_v2::State>, Option<RequestTemplate>)>,
    headers: HeaderMap,
    Json(request): Json<NvCreateChatCompletionRequest>,
) -> Result<Response, ErrorResponse> {
    // return a 503 if the service is not ready
    check_ready(&state)?;

    // create the context for the request
    let request_id = get_or_create_request_id(request.inner.user.as_deref(), &headers);
    let request = Context::with_id(request, request_id);
    let context = request.context();

    // create the connection handles
524
525
    let (mut connection_handle, stream_handle) =
        create_connection_monitor(context.clone(), Some(state.metrics_clone())).await;
Ryan Olson's avatar
Ryan Olson committed
526

527
528
529
530
531
532
533
534
535
    let response =
        tokio::spawn(chat_completions(state, template, request, stream_handle).in_current_span())
            .await
            .map_err(|e| {
                ErrorMessage::internal_server_error(&format!(
                    "Failed to await chat completions task: {:?}",
                    e,
                ))
            })?;
Ryan Olson's avatar
Ryan Olson committed
536
537
538
539
540
541
542
543

    // if we got here, then we will return a response and the potentially long running task has completed successfully
    // without need to be cancelled.
    connection_handle.disarm();

    response
}

544
545
546
547
548
549
550
551
552
/// OpenAI Chat Completions Request Handler
///
/// This method will handle the incoming request for the /v1/chat/completions endpoint. The endpoint is a "source"
/// for an [`super::OpenAIChatCompletionsStreamingEngine`] and will return a stream of responses which will be
/// forward to the client.
///
/// Note: For all requests, streaming or non-streaming, we always call the engine with streaming enabled. For
/// non-streaming requests, we will fold the stream into a single response as part of this handler.
async fn chat_completions(
Ryan Olson's avatar
Ryan Olson committed
553
554
555
556
557
    state: Arc<service_v2::State>,
    template: Option<RequestTemplate>,
    mut request: Context<NvCreateChatCompletionRequest>,
    mut stream_handle: ConnectionHandle,
) -> Result<Response, ErrorResponse> {
558
559
560
    // return a 503 if the service is not ready
    check_ready(&state)?;

Ryan Olson's avatar
Ryan Olson committed
561
562
    let request_id = request.id().to_string();

563
564
565
566
    // Handle unsupported fields - if Some(resp) is returned by
    // validate_chat_completion_unsupported_fields,
    // then a field was used that is unsupported. We will log an error message
    // and early return a 501 NOT_IMPLEMENTED status code. Otherwise, proceeed.
Ryan Olson's avatar
Ryan Olson committed
567
    validate_chat_completion_unsupported_fields(&request)?;
568

569
570
571
    // Handle required fields like messages shouldn't be empty.
    validate_chat_completion_required_fields(&request)?;

572
573
574
    // Handle Rest of Validation Errors
    validate_chat_completion_fields_generic(&request)?;

575
576
577
578
579
580
581
582
583
584
585
586
    // Apply template values if present
    if let Some(template) = template {
        if request.inner.model.is_empty() {
            request.inner.model = template.model.clone();
        }
        if request.inner.temperature.unwrap_or(0.0) == 0.0 {
            request.inner.temperature = Some(template.temperature);
        }
        if request.inner.max_completion_tokens.unwrap_or(0) == 0 {
            request.inner.max_completion_tokens = Some(template.max_completion_tokens);
        }
    }
Ryan Olson's avatar
Ryan Olson committed
587
    tracing::trace!("Received chat completions request: {:?}", request.content());
588
589

    // todo - decide on default
Paul Hendricks's avatar
Paul Hendricks committed
590
    let streaming = request.inner.stream.unwrap_or(false);
591
592

    // update the request to always stream
Ryan Olson's avatar
Ryan Olson committed
593
594
595
596
    let request = request.map(|mut req| {
        req.inner.stream = Some(true);
        req
    });
597
598
599
600

    // todo - make the protocols be optional for model name
    // todo - when optional, if none, apply a default
    // todo - determine the proper error code for when a request model is not present
601
602
603
604
605
    let model = request.inner.model.clone();

    // Create HTTP queue guard after template resolution so labels are correct
    let http_queue_guard = state.metrics_clone().create_http_queue_guard(&model);

606
607
608
    tracing::trace!("Getting chat completions engine for model: {}", model);

    let engine = state
609
        .manager()
610
        .get_chat_completions_engine(&model)
Ryan Olson's avatar
Ryan Olson committed
611
        .map_err(|_| ErrorMessage::model_not_found())?;
612

613
    let parsing_options = state.manager().get_parsing_options(&model);
614

615
616
617
618
619
    let mut response_collector = state.metrics_clone().create_response_collector(&model);

    let annotations = request.annotations();

    // Create inflight_guard before calling engine to ensure errors are counted
620
    let mut inflight_guard =
621
622
        state
            .metrics_clone()
623
            .create_inflight_guard(&model, Endpoint::ChatCompletions, streaming);
624
625
626
627
628

    // issue the generate call on the engine
    let stream = engine
        .generate(request)
        .await
Ryan Olson's avatar
Ryan Olson committed
629
        .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate completions"))?;
630
631
632
633

    // capture the context to cancel the stream if the client disconnects
    let ctx = stream.context();

Ryan Olson's avatar
Ryan Olson committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    // prepare any requested annotations
    let annotations = annotations.map_or(Vec::new(), |annotations| {
        annotations
            .iter()
            .filter_map(|annotation| {
                if annotation == ANNOTATION_REQUEST_ID {
                    Annotated::from_annotation(ANNOTATION_REQUEST_ID, &request_id).ok()
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    });

    // apply any annotations to the front of the stream
    let stream = stream::iter(annotations).chain(stream);

651
652
653
654
    // todo - tap the stream and propagate request level metrics
    // note - we might do this as part of the post processing set to make it more generic

    if streaming {
655
        stream_handle.arm(); // allows the system to detect client disconnects and cancel the LLM generation
Ryan Olson's avatar
Ryan Olson committed
656

657
        let mut http_queue_guard = Some(http_queue_guard);
658
        let stream = stream.map(move |response| {
659
660
661
662
663
664
            // Calls observe_response() on each token
            process_response_using_event_converter_and_observe_metrics(
                EventConverter::from(response),
                &mut response_collector,
                &mut http_queue_guard,
            )
665
        });
Ryan Olson's avatar
Ryan Olson committed
666
        let stream = monitor_for_disconnects(stream, ctx, inflight_guard, stream_handle);
667

668
669
        let mut sse_stream = Sse::new(stream);

670
        if let Some(keep_alive) = state.sse_keep_alive() {
671
672
673
674
            sse_stream = sse_stream.keep_alive(KeepAlive::default().interval(keep_alive));
        }

        Ok(sse_stream.into_response())
675
    } else {
676
        let mut http_queue_guard = Some(http_queue_guard);
677
        let stream = stream.inspect(move |response| {
678
679
680
681
682
683
            // Calls observe_response() on each token - drops http_queue_guard on first token
            process_response_and_observe_metrics(
                response,
                &mut response_collector,
                &mut http_queue_guard,
            );
684
685
        });

686
687
688
689
690
691
692
693
694
695
696
697
698
699
        let response =
            NvCreateChatCompletionResponse::from_annotated_stream(stream, parsing_options.clone())
                .await
                .map_err(|e| {
                    tracing::error!(
                        request_id,
                        "Failed to fold chat completions stream for: {:?}",
                        e
                    );
                    ErrorMessage::internal_server_error(&format!(
                        "Failed to fold chat completions stream: {}",
                        e
                    ))
                })?;
700

701
        inflight_guard.mark_ok();
702
703
704
705
        Ok(Json(response).into_response())
    }
}

706
707
708
709
710
/// Checks for unsupported fields in the request.
/// Returns Some(response) if unsupported fields are present.
#[allow(deprecated)]
pub fn validate_chat_completion_unsupported_fields(
    request: &NvCreateChatCompletionRequest,
Ryan Olson's avatar
Ryan Olson committed
711
) -> Result<(), ErrorResponse> {
712
713
714
    let inner = &request.inner;

    if inner.parallel_tool_calls == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
715
        return Err(ErrorMessage::not_implemented_error(
716
717
718
719
720
            "`parallel_tool_calls: true` is not supported.",
        ));
    }

    if inner.function_call.is_some() {
Ryan Olson's avatar
Ryan Olson committed
721
        return Err(ErrorMessage::not_implemented_error(
722
723
724
725
726
            "`function_call` is deprecated. Please migrate to use `tool_choice` instead.",
        ));
    }

    if inner.functions.is_some() {
Ryan Olson's avatar
Ryan Olson committed
727
        return Err(ErrorMessage::not_implemented_error(
728
729
730
731
            "`functions` is deprecated. Please migrate to use `tools` instead.",
        ));
    }

Ryan Olson's avatar
Ryan Olson committed
732
    Ok(())
733
734
}

735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
/// Validates that required fields are present and valid in the chat completion request
pub fn validate_chat_completion_required_fields(
    request: &NvCreateChatCompletionRequest,
) -> Result<(), ErrorResponse> {
    let inner = &request.inner;

    if inner.messages.is_empty() {
        return Err(ErrorMessage::from_http_error(HttpError {
            code: 400,
            message: "The 'messages' field cannot be empty. At least one message is required."
                .to_string(),
        }));
    }

    Ok(())
}

752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
/// Validates a chat completion request and returns an error response if validation fails.
///
/// This function calls the `validate` method implemented for `NvCreateChatCompletionRequest`.
/// If validation fails, it maps the error into an OpenAI-compatible error response.
pub fn validate_chat_completion_fields_generic(
    request: &NvCreateChatCompletionRequest,
) -> Result<(), ErrorResponse> {
    request.validate().map_err(|e| {
        ErrorMessage::from_http_error(HttpError {
            code: 400,
            message: e.to_string(),
        })
    })
}

/// Validates a completion request and returns an error response if validation fails.
///
/// This function calls the `validate` method implemented for `NvCreateCompletionRequest`.
/// If validation fails, it maps the error into an OpenAI-compatible error response.
pub fn validate_completion_fields_generic(
    request: &NvCreateCompletionRequest,
) -> Result<(), ErrorResponse> {
    request.validate().map_err(|e| {
        ErrorMessage::from_http_error(HttpError {
            code: 400,
            message: e.to_string(),
        })
    })
}

782
783
784
/// OpenAI Responses Request Handler
///
/// This method will handle the incoming request for the /v1/responses endpoint.
Ryan Olson's avatar
Ryan Olson committed
785
async fn handler_responses(
786
    State((state, template)): State<(Arc<service_v2::State>, Option<RequestTemplate>)>,
Ryan Olson's avatar
Ryan Olson committed
787
788
789
790
791
792
793
794
795
796
797
798
    headers: HeaderMap,
    Json(request): Json<NvCreateResponse>,
) -> Result<Response, ErrorResponse> {
    // return a 503 if the service is not ready
    check_ready(&state)?;

    // create the context for the request
    let request_id = get_or_create_request_id(request.inner.user.as_deref(), &headers);
    let request = Context::with_id(request, request_id);
    let context = request.context();

    // create the connection handles
799
800
    let (mut connection_handle, _stream_handle) =
        create_connection_monitor(context.clone(), Some(state.metrics_clone())).await;
Ryan Olson's avatar
Ryan Olson committed
801

802
    let response = tokio::spawn(responses(state, template, request).in_current_span())
Ryan Olson's avatar
Ryan Olson committed
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
        .await
        .map_err(|e| {
            ErrorMessage::internal_server_error(&format!(
                "Failed to await chat completions task: {:?}",
                e,
            ))
        })?;

    // if we got here, then we will return a response and the potentially long running task has completed successfully
    // without need to be cancelled.
    connection_handle.disarm();

    response
}

#[tracing::instrument(level = "debug", skip_all, fields(request_id = %request.id()))]
async fn responses(
    state: Arc<service_v2::State>,
    template: Option<RequestTemplate>,
    mut request: Context<NvCreateResponse>,
) -> Result<Response, ErrorResponse> {
824
825
826
    // return a 503 if the service is not ready
    check_ready(&state)?;

827
828
829
830
    // Create http_queue_guard early - tracks time waiting to be processed
    let model = request.inner.model.clone();
    let http_queue_guard = state.metrics_clone().create_http_queue_guard(&model);

831
832
833
    // Handle unsupported fields - if Some(resp) is returned by validate_unsupported_fields,
    // then a field was used that is unsupported. We will log an error message
    // and early return a 501 NOT_IMPLEMENTED status code. Otherwise, proceeed.
834
    if let Some(resp) = validate_response_unsupported_fields(&request) {
835
836
837
838
839
840
841
        return Ok(resp.into_response());
    }

    // Handle non-text (image, audio, file) inputs - if Some(resp) is returned by
    // validate_input_is_text_only, then we are handling something other than Input::Text(_).
    // We will log an error message and early return a 501 NOT_IMPLEMENTED status code.
    // Otherwise, proceeed.
842
    if let Some(resp) = validate_response_input_is_text_only(&request) {
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
        return Ok(resp.into_response());
    }

    // Apply template values if present
    if let Some(template) = template {
        if request.inner.model.is_empty() {
            request.inner.model = template.model.clone();
        }
        if request.inner.temperature.unwrap_or(0.0) == 0.0 {
            request.inner.temperature = Some(template.temperature);
        }
        if request.inner.max_output_tokens.unwrap_or(0) == 0 {
            request.inner.max_output_tokens = Some(template.max_completion_tokens);
        }
    }
    tracing::trace!("Received chat completions request: {:?}", request.inner);

Ryan Olson's avatar
Ryan Olson committed
860
861
    let request_id = request.id().to_string();
    let (request, context) = request.into_parts();
862

Ryan Olson's avatar
Ryan Olson committed
863
    let mut request: NvCreateChatCompletionRequest = request.try_into().map_err(|e| {
864
865
866
867
868
        tracing::error!(
            request_id,
            "Failed to convert NvCreateResponse to NvCreateChatCompletionRequest: {:?}",
            e
        );
Ryan Olson's avatar
Ryan Olson committed
869
        ErrorMessage::not_implemented_error(&format!(
870
871
872
873
874
            "Only Input::Text(_) is currently supported: {}",
            e
        ))
    })?;

Ryan Olson's avatar
Ryan Olson committed
875
876
877
878
879
    let request = context.map(|mut _req| {
        request.inner.stream = Some(false);
        request
    });

880
881
882
883
    tracing::trace!("Getting chat completions engine for model: {}", model);

    let engine = state
        .manager()
884
        .get_chat_completions_engine(&model)
Ryan Olson's avatar
Ryan Olson committed
885
        .map_err(|_| ErrorMessage::model_not_found())?;
886

887
    let parsing_options = state.manager().get_parsing_options(&model);
888

889
    let mut response_collector = state.metrics_clone().create_response_collector(&model);
890
891
892
893
894
895
896

    tracing::trace!("Issuing generate call for chat completions");

    // issue the generate call on the engine
    let stream = engine
        .generate(request)
        .await
Ryan Olson's avatar
Ryan Olson committed
897
        .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate completions"))?;
898

899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
    // Create inflight_guard now that actual processing has begun
    let mut inflight_guard =
        state
            .metrics_clone()
            .create_inflight_guard(&model, Endpoint::Responses, false);

    // Process stream to collect metrics and drop http_queue_guard on first token
    let mut http_queue_guard = Some(http_queue_guard);
    let stream = stream.inspect(move |response| {
        // Calls observe_response() on each token - drops http_queue_guard on first token
        process_response_and_observe_metrics(
            response,
            &mut response_collector,
            &mut http_queue_guard,
        );
    });

916
    // TODO: handle streaming, currently just unary
917
918
919
920
921
922
923
924
925
926
927
928
929
930
    let response =
        NvCreateChatCompletionResponse::from_annotated_stream(stream, parsing_options.clone())
            .await
            .map_err(|e| {
                tracing::error!(
                    request_id,
                    "Failed to fold chat completions stream for: {:?}",
                    e
                );
                ErrorMessage::internal_server_error(&format!(
                    "Failed to fold chat completions stream: {}",
                    e
                ))
            })?;
931
932
933
934
935
936
937
938

    // Convert NvCreateChatCompletionResponse --> NvResponse
    let response: NvResponse = response.try_into().map_err(|e| {
        tracing::error!(
            request_id,
            "Failed to convert NvCreateChatCompletionResponse to NvResponse: {:?}",
            e
        );
Ryan Olson's avatar
Ryan Olson committed
939
        ErrorMessage::internal_server_error("Failed to convert internal response")
940
941
942
943
944
945
946
    })?;

    inflight_guard.mark_ok();

    Ok(Json(response).into_response())
}

947
948
949
pub fn validate_response_input_is_text_only(
    request: &NvCreateResponse,
) -> Option<impl IntoResponse> {
950
    match &request.inner.input {
951
        dynamo_async_openai::types::responses::Input::Text(_) => None,
952
953
954
        _ => Some(ErrorMessage::not_implemented_error(
            "Only `Input::Text` is supported. Structured, multimedia, or custom input types are not yet implemented.",
        )),
955
956
957
958
959
    }
}

/// Checks for unsupported fields in the request.
/// Returns Some(response) if unsupported fields are present.
960
961
962
pub fn validate_response_unsupported_fields(
    request: &NvCreateResponse,
) -> Option<impl IntoResponse> {
963
964
965
    let inner = &request.inner;

    if inner.background == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
966
        return Some(ErrorMessage::not_implemented_error(
967
968
969
970
            "`background: true` is not supported.",
        ));
    }
    if inner.include.is_some() {
Ryan Olson's avatar
Ryan Olson committed
971
        return Some(ErrorMessage::not_implemented_error(
972
973
974
975
            "`include` is not supported.",
        ));
    }
    if inner.instructions.is_some() {
Ryan Olson's avatar
Ryan Olson committed
976
        return Some(ErrorMessage::not_implemented_error(
977
978
979
980
            "`instructions` is not supported.",
        ));
    }
    if inner.max_tool_calls.is_some() {
Ryan Olson's avatar
Ryan Olson committed
981
        return Some(ErrorMessage::not_implemented_error(
982
983
984
985
            "`max_tool_calls` is not supported.",
        ));
    }
    if inner.metadata.is_some() {
Ryan Olson's avatar
Ryan Olson committed
986
        return Some(ErrorMessage::not_implemented_error(
987
988
989
990
            "`metadata` is not supported.",
        ));
    }
    if inner.parallel_tool_calls == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
991
        return Some(ErrorMessage::not_implemented_error(
992
993
994
995
            "`parallel_tool_calls: true` is not supported.",
        ));
    }
    if inner.previous_response_id.is_some() {
Ryan Olson's avatar
Ryan Olson committed
996
        return Some(ErrorMessage::not_implemented_error(
997
998
999
1000
            "`previous_response_id` is not supported.",
        ));
    }
    if inner.prompt.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1001
        return Some(ErrorMessage::not_implemented_error(
1002
1003
1004
1005
            "`prompt` is not supported.",
        ));
    }
    if inner.reasoning.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1006
        return Some(ErrorMessage::not_implemented_error(
1007
1008
1009
1010
            "`reasoning` is not supported.",
        ));
    }
    if inner.service_tier.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1011
        return Some(ErrorMessage::not_implemented_error(
1012
1013
1014
1015
            "`service_tier` is not supported.",
        ));
    }
    if inner.store == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
1016
        return Some(ErrorMessage::not_implemented_error(
1017
1018
1019
1020
            "`store: true` is not supported.",
        ));
    }
    if inner.stream == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
1021
        return Some(ErrorMessage::not_implemented_error(
1022
1023
1024
1025
            "`stream: true` is not supported.",
        ));
    }
    if inner.text.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1026
        return Some(ErrorMessage::not_implemented_error(
1027
1028
1029
1030
            "`text` is not supported.",
        ));
    }
    if inner.tool_choice.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1031
        return Some(ErrorMessage::not_implemented_error(
1032
1033
1034
1035
            "`tool_choice` is not supported.",
        ));
    }
    if inner.tools.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1036
        return Some(ErrorMessage::not_implemented_error(
1037
1038
1039
1040
            "`tools` is not supported.",
        ));
    }
    if inner.truncation.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1041
        return Some(ErrorMessage::not_implemented_error(
1042
1043
1044
1045
            "`truncation` is not supported.",
        ));
    }
    if inner.user.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1046
        return Some(ErrorMessage::not_implemented_error(
1047
1048
1049
1050
1051
1052
1053
            "`user` is not supported.",
        ));
    }

    None
}

1054
1055
// todo - abstract this to the top level lib.rs to be reused
// todo - move the service_observer to its own state/arc
Ryan Olson's avatar
Ryan Olson committed
1056
fn check_ready(_state: &Arc<service_v2::State>) -> Result<(), ErrorResponse> {
1057
    // if state.service_observer.stage() != ServiceStage::Ready {
Ryan Olson's avatar
Ryan Olson committed
1058
    //     return Err(ErrorMessage::service_unavailable());
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    // }
    Ok(())
}

/// openai compatible format
/// Example:
/// {
///  "object": "list",
///  "data": [
///    {
///      "id": "model-id-0",
///      "object": "model",
///      "created": 1686935002,
///      "owned_by": "organization-owner"
///    },
///    ]
/// }
async fn list_models_openai(
1077
    State(state): State<Arc<service_v2::State>>,
Ryan Olson's avatar
Ryan Olson committed
1078
) -> Result<Response, ErrorResponse> {
1079
1080
1081
1082
1083
1084
1085
1086
    check_ready(&state)?;

    let created = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let mut data = Vec::new();

1087
1088
    let models: HashSet<String> = state.manager().model_display_names();
    for model_name in models {
1089
        data.push(ModelListing {
1090
            id: model_name.clone(),
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
            object: "object",
            created,                        // Where would this come from? The GGUF?
            owned_by: "nvidia".to_string(), // Get organization from GGUF
        });
    }

    let out = ListModelOpenAI {
        object: "list",
        data,
    };
    Ok(Json(out).into_response())
}

#[derive(Serialize)]
struct ListModelOpenAI {
    object: &'static str, // always "list"
    data: Vec<ModelListing>,
}

#[derive(Serialize)]
struct ModelListing {
    id: String,
    object: &'static str, // always "object"
    created: u64,         //  Seconds since epoch
    owned_by: String,
}

/// Create an Axum [`Router`] for the OpenAI API Completions endpoint
/// If not path is provided, the default path is `/v1/completions`
pub fn completions_router(
1121
    state: Arc<service_v2::State>,
1122
1123
1124
1125
1126
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    let path = path.unwrap_or("/v1/completions".to_string());
    let doc = RouteDoc::new(axum::http::Method::POST, &path);
    let router = Router::new()
Ryan Olson's avatar
Ryan Olson committed
1127
        .route(&path, post(handler_completions))
1128
        .layer(middleware::from_fn(smart_json_error_middleware))
1129
        .layer(axum::extract::DefaultBodyLimit::max(get_body_limit()))
1130
1131
1132
1133
1134
1135
1136
        .with_state(state);
    (vec![doc], router)
}

/// Create an Axum [`Router`] for the OpenAI API Chat Completions endpoint
/// If not path is provided, the default path is `/v1/chat/completions`
pub fn chat_completions_router(
1137
    state: Arc<service_v2::State>,
1138
    template: Option<RequestTemplate>,
1139
1140
1141
1142
1143
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    let path = path.unwrap_or("/v1/chat/completions".to_string());
    let doc = RouteDoc::new(axum::http::Method::POST, &path);
    let router = Router::new()
Ryan Olson's avatar
Ryan Olson committed
1144
        .route(&path, post(handler_chat_completions))
1145
        .layer(middleware::from_fn(smart_json_error_middleware))
1146
        .layer(axum::extract::DefaultBodyLimit::max(get_body_limit()))
1147
        .with_state((state, template));
1148
1149
1150
    (vec![doc], router)
}

1151
1152
1153
/// Create an Axum [`Router`] for the OpenAI API Embeddings endpoint
/// If not path is provided, the default path is `/v1/embeddings`
pub fn embeddings_router(
1154
    state: Arc<service_v2::State>,
1155
1156
1157
1158
1159
1160
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    let path = path.unwrap_or("/v1/embeddings".to_string());
    let doc = RouteDoc::new(axum::http::Method::POST, &path);
    let router = Router::new()
        .route(&path, post(embeddings))
1161
        .layer(middleware::from_fn(smart_json_error_middleware))
1162
        .layer(axum::extract::DefaultBodyLimit::max(get_body_limit()))
1163
1164
1165
1166
        .with_state(state);
    (vec![doc], router)
}

1167
1168
/// List Models
pub fn list_models_router(
1169
    state: Arc<service_v2::State>,
1170
1171
1172
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    // Standard OpenAI compatible list models endpoint
1173
    let openai_path = path.unwrap_or("/v1/models".to_string());
1174
1175
1176
1177
1178
1179
    let doc_for_openai = RouteDoc::new(axum::http::Method::GET, &openai_path);

    let router = Router::new()
        .route(&openai_path, get(list_models_openai))
        .with_state(state);

1180
    (vec![doc_for_openai], router)
1181
1182
}

1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
/// Create an Axum [`Router`] for the OpenAI API Responses endpoint
/// If not path is provided, the default path is `/v1/responses`
pub fn responses_router(
    state: Arc<service_v2::State>,
    template: Option<RequestTemplate>,
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    let path = path.unwrap_or("/v1/responses".to_string());
    let doc = RouteDoc::new(axum::http::Method::POST, &path);
    let router = Router::new()
Ryan Olson's avatar
Ryan Olson committed
1193
        .route(&path, post(handler_responses))
1194
        .layer(middleware::from_fn(smart_json_error_middleware))
1195
1196
1197
1198
        .with_state((state, template));
    (vec![doc], router)
}

1199
1200
#[cfg(test)]
mod tests {
1201
1202
    use std::collections::HashMap;

1203
1204
1205
1206
1207
1208
    use super::*;
    use crate::discovery::ModelManagerError;
    use crate::protocols::openai::chat_completions::NvCreateChatCompletionRequest;
    use crate::protocols::openai::common_ext::CommonExt;
    use crate::protocols::openai::completions::NvCreateCompletionRequest;
    use crate::protocols::openai::responses::NvCreateResponse;
1209
    use dynamo_async_openai::types::responses::{
1210
1211
1212
1213
        CreateResponse, Input, InputContent, InputItem, InputMessage, PromptConfig,
        Role as ResponseRole, ServiceTier, TextConfig, TextResponseFormat, ToolChoice,
        ToolChoiceMode, Truncation,
    };
1214
    use dynamo_async_openai::types::{
1215
1216
        ChatCompletionRequestMessage, ChatCompletionRequestUserMessage,
        ChatCompletionRequestUserMessageContent, CreateChatCompletionRequest,
1217
        CreateCompletionRequest,
1218
    };
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229

    const BACKUP_ERROR_MESSAGE: &str = "Failed to generate completions";

    fn http_error_from_engine(code: u16) -> Result<(), anyhow::Error> {
        Err(HttpError {
            code,
            message: "custom error message".to_string(),
        })?
    }

    fn other_error_from_engine() -> Result<(), anyhow::Error> {
1230
        Err(ModelManagerError::ModelNotFound("foo".to_string()))?
1231
1232
    }

1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
    fn make_base_request() -> NvCreateResponse {
        NvCreateResponse {
            inner: CreateResponse {
                input: Input::Text("hello".into()),
                model: "test-model".into(),
                background: None,
                include: None,
                instructions: None,
                max_output_tokens: None,
                max_tool_calls: None,
                metadata: None,
                parallel_tool_calls: None,
                previous_response_id: None,
                prompt: None,
                reasoning: None,
                service_tier: None,
                store: None,
                stream: None,
                text: None,
                tool_choice: None,
                tools: None,
                truncation: None,
                user: None,
                temperature: None,
                top_logprobs: None,
                top_p: None,
            },
            nvext: None,
        }
    }

1264
1265
1266
    #[test]
    fn test_http_error_response_from_anyhow() {
        let err = http_error_from_engine(400).unwrap_err();
1267
1268
1269
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::BAD_REQUEST);
        assert_eq!(response.1.message, "custom error message");
1270
1271
1272
1273
1274
    }

    #[test]
    fn test_error_response_from_anyhow_out_of_range() {
        let err = http_error_from_engine(399).unwrap_err();
1275
1276
1277
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(response.1.message, "custom error message");
1278
1279

        let err = http_error_from_engine(500).unwrap_err();
1280
1281
1282
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(response.1.message, "custom error message");
1283
1284

        let err = http_error_from_engine(501).unwrap_err();
1285
1286
1287
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(response.1.message, "custom error message");
1288
1289
1290
1291
1292
    }

    #[test]
    fn test_other_error_response_from_anyhow() {
        let err = other_error_from_engine().unwrap_err();
1293
1294
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::INTERNAL_SERVER_ERROR);
1295
        assert_eq!(
1296
            response.1.message,
1297
1298
1299
1300
1301
1302
1303
            format!(
                "{}: {}",
                BACKUP_ERROR_MESSAGE,
                other_error_from_engine().unwrap_err()
            )
        );
    }
1304

1305
1306
1307
1308
1309
1310
1311
1312
    #[test]
    fn test_service_overloaded_error_response_from_anyhow() {
        use dynamo_runtime::pipeline::error::PipelineError;

        let err: anyhow::Error = PipelineError::ServiceOverloaded(
            "All workers are busy, please retry later".to_string(),
        )
        .into();
1313
1314
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::SERVICE_UNAVAILABLE);
1315
        assert_eq!(
1316
            response.1.message,
1317
1318
1319
1320
            "Service temporarily unavailable: All workers are busy, please retry later"
        );
    }

1321
1322
1323
    #[test]
    fn test_validate_input_is_text_only_accepts_text() {
        let request = make_base_request();
1324
        let result = validate_response_input_is_text_only(&request);
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
        assert!(result.is_none());
    }

    #[test]
    fn test_validate_input_is_text_only_rejects_items() {
        let mut request = make_base_request();
        request.inner.input = Input::Items(vec![InputItem::Message(InputMessage {
            kind: Default::default(),
            role: ResponseRole::User,
            content: InputContent::TextInput("structured".into()),
        })]);
1336
        let result = validate_response_input_is_text_only(&request);
1337
1338
1339
1340
1341
1342
        assert!(result.is_some());
    }

    #[test]
    fn test_validate_unsupported_fields_accepts_clean_request() {
        let request = make_base_request();
1343
        let result = validate_response_unsupported_fields(&request);
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
        assert!(result.is_none());
    }

    #[test]
    fn test_validate_unsupported_fields_detects_flags() {
        #[allow(clippy::type_complexity)]
        let unsupported_cases: Vec<(&str, Box<dyn FnOnce(&mut CreateResponse)>)> = vec![
            ("background", Box::new(|r| r.background = Some(true))),
            (
                "include",
                Box::new(|r| r.include = Some(vec!["file_search_call.results".into()])),
            ),
            (
                "instructions",
                Box::new(|r| r.instructions = Some("System prompt".into())),
            ),
            ("max_tool_calls", Box::new(|r| r.max_tool_calls = Some(3))),
            ("metadata", Box::new(|r| r.metadata = Some(HashMap::new()))),
            (
                "parallel_tool_calls",
                Box::new(|r| r.parallel_tool_calls = Some(true)),
            ),
            (
                "previous_response_id",
                Box::new(|r| r.previous_response_id = Some("prev-id".into())),
            ),
            (
                "prompt",
                Box::new(|r| {
                    r.prompt = Some(PromptConfig {
                        id: "template-id".into(),
                        version: None,
                        variables: None,
                    })
                }),
            ),
            (
                "reasoning",
                Box::new(|r| r.reasoning = Some(Default::default())),
            ),
            (
                "service_tier",
                Box::new(|r| r.service_tier = Some(ServiceTier::Auto)),
            ),
            ("store", Box::new(|r| r.store = Some(true))),
            ("stream", Box::new(|r| r.stream = Some(true))),
            (
                "text",
                Box::new(|r| {
                    r.text = Some(TextConfig {
                        format: TextResponseFormat::Text,
                    })
                }),
            ),
            (
                "tool_choice",
                Box::new(|r| r.tool_choice = Some(ToolChoice::Mode(ToolChoiceMode::Required))),
            ),
            ("tools", Box::new(|r| r.tools = Some(vec![]))),
            (
                "truncation",
                Box::new(|r| r.truncation = Some(Truncation::Auto)),
            ),
            ("user", Box::new(|r| r.user = Some("user-id".into()))),
        ];

        for (field, set_field) in unsupported_cases {
            let mut req = make_base_request();
            (set_field)(&mut req.inner);
1413
            let result = validate_response_unsupported_fields(&req);
1414
1415
1416
            assert!(result.is_some(), "Expected rejection for `{field}`");
        }
    }
1417
1418
1419
1420
1421
1422
1423
1424
1425

    #[test]
    fn test_validate_chat_completion_required_fields_empty_messages() {
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![],
                ..Default::default()
            },
1426
            common: Default::default(),
1427
            nvext: None,
1428
            chat_template_args: None,
1429
1430
1431
        };
        let result = validate_chat_completion_required_fields(&request);
        assert!(result.is_err());
1432
1433
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1434
            assert_eq!(
1435
                error_response.1.message,
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
                "The 'messages' field cannot be empty. At least one message is required."
            );
        }
    }

    #[test]
    fn test_validate_chat_completion_required_fields_with_messages() {
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                ..Default::default()
            },
1454
            common: Default::default(),
1455
            nvext: None,
1456
            chat_template_args: None,
1457
1458
1459
1460
        };
        let result = validate_chat_completion_required_fields(&request);
        assert!(result.is_ok());
    }
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495

    #[test]
    // Test for all Bad Requests Example for Chat Completion
    // 1. Echo:  Should be a boolean : Not Done
    // 2. Frequency Penalty: Should be a float between -2.0 and 2.0 : Done
    // 3. logprobs: Done
    // 4. Model Format: Should be a string : Not Done
    // 5. Prompt or Messages Validation
    // 6. Max Tokens: Should be a positive integer
    // 7. Presence Penalty: Should be a float between -2.0 and 2.0 : Done
    // 8. Stop : Should be a string or an array of strings : Not Done
    // 9. Invalid or Out of range temperature: Done
    // 10.Invalid or out of range top_p: Done
    // 11. Repetition Penalty: Should be a float between 0.0 and 2.0 : Done
    // 12. Logprobs: Should be a positive integer between 0 and 5 : Done
    // invalid or non existing user : Only empty string is not allowed validation is there. How can we check non-extisting user ?
    // add_special_tokens null or invalid : Not Done
    // guided_whitespace_pattern null or invalid : Not Done
    // "response_format": { "type": "invalid_format" } : Not Done
    // "logit_bias": { "invalid_token": "not_a_number" }, : Partial Validation is already there
    fn test_bad_base_request_for_completion() {
        // Frequency Penalty: Should be a float between -2.0 and 2.0
        let request = NvCreateCompletionRequest {
            inner: CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: "Hello".into(),
                frequency_penalty: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
        };

        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1496
1497
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1498
            assert_eq!(
1499
                error_response.1.message,
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
                "Frequency penalty must be between -2 and 2, got -3"
            );
        }

        // Presence Penalty: Should be a float between -2.0 and 2.0
        let request = NvCreateCompletionRequest {
            inner: CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: "Hello".into(),
                presence_penalty: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1517
1518
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1519
            assert_eq!(
1520
                error_response.1.message,
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
                "Presence penalty must be between -2 and 2, got -3"
            );
        }

        // Temperature: Should be a float between 0.0 and 2.0
        let request = NvCreateCompletionRequest {
            inner: CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: "Hello".into(),
                temperature: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1538
1539
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1540
            assert_eq!(
1541
                error_response.1.message,
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
                "Temperature must be between 0 and 2, got -3"
            );
        }

        // Top P: Should be a float between 0.0 and 1.0
        let request = NvCreateCompletionRequest {
            inner: CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: "Hello".into(),
                top_p: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1559
1560
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1561
            assert_eq!(
1562
                error_response.1.message,
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
                "Top_p must be between 0 and 1, got -3"
            );
        }

        // Repetition Penalty: Should be a float between 0.0 and 2.0
        let request = NvCreateCompletionRequest {
            inner: CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: "Hello".into(),
                ..Default::default()
            },
            common: CommonExt::builder()
                .repetition_penalty(-3.0)
                .build()
                .unwrap(),
            nvext: None,
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1582
1583
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1584
            assert_eq!(
1585
                error_response.1.message,
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
                "Repetition penalty must be between 0 and 2, got -3"
            );
        }

        // Logprobs: Should be a positive integer between 0 and 5
        let request = NvCreateCompletionRequest {
            inner: CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: "Hello".into(),
                logprobs: Some(6),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1603
1604
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1605
            assert_eq!(
1606
                error_response.1.message,
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
                "Logprobs must be between 0 and 5, got 6"
            );
        }
    }

    #[test]
    fn test_bad_base_request_for_chatcompletion() {
        // Frequency Penalty: Should be a float between -2.0 and 2.0
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                frequency_penalty: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
1629
            chat_template_args: None,
1630
1631
1632
1633
        };

        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
1634
1635
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1636
            assert_eq!(
1637
                error_response.1.message,
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
                "Frequency penalty must be between -2 and 2, got -3"
            );
        }

        // Presence Penalty: Should be a float between -2.0 and 2.0
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                presence_penalty: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
1657
            chat_template_args: None,
1658
1659
1660
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
1661
1662
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1663
            assert_eq!(
1664
                error_response.1.message,
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
                "Presence penalty must be between -2 and 2, got -3"
            );
        }

        // Temperature: Should be a float between 0.0 and 2.0
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                temperature: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
1684
            chat_template_args: None,
1685
1686
1687
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
1688
1689
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1690
            assert_eq!(
1691
                error_response.1.message,
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
                "Temperature must be between 0 and 2, got -3"
            );
        }

        // Top P: Should be a float between 0.0 and 1.0
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                top_p: Some(-3.0),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
1711
            chat_template_args: None,
1712
1713
1714
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
1715
1716
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1717
            assert_eq!(
1718
                error_response.1.message,
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
                "Top_p must be between 0 and 1, got -3"
            );
        }

        // Repetition Penalty: Should be a float between 0.0 and 2.0
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                ..Default::default()
            },
            common: CommonExt::builder()
                .repetition_penalty(-3.0)
                .build()
                .unwrap(),
            nvext: None,
1740
            chat_template_args: None,
1741
1742
1743
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
1744
1745
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1746
            assert_eq!(
1747
                error_response.1.message,
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
                "Repetition penalty must be between 0 and 2, got -3"
            );
        }

        // Top Logprobs: Should be a positive integer between 0 and 20
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                top_logprobs: Some(25),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
1767
            chat_template_args: None,
1768
1769
1770
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
1771
1772
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1773
            assert_eq!(
1774
                error_response.1.message,
1775
1776
1777
1778
                "Top_logprobs must be between 0 and 20, got 25"
            );
        }
    }
1779
}