openai.rs 88.1 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
use std::{
    collections::HashSet,
6
    fmt::Display,
7
8
9
10
    sync::Arc,
    time::{SystemTime, UNIX_EPOCH},
};

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

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

Ryan Olson's avatar
Ryan Olson committed
58
59
60
61
62
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";

63
64
const VALIDATION_PREFIX: &str = "Validation: ";

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 {
69
    std::env::var(env_llm::DYN_HTTP_BODY_LIMIT_MB)
70
71
72
73
74
75
        .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
76
77
pub type ErrorResponse = (StatusCode, Json<ErrorMessage>);

78
#[derive(Serialize, Deserialize, Debug)]
Ryan Olson's avatar
Ryan Olson committed
79
pub(crate) struct ErrorMessage {
80
81
82
83
84
85
86
87
88
89
90
    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(),
    }
91
92
}

Ryan Olson's avatar
Ryan Olson committed
93
impl ErrorMessage {
94
    /// Not Found Error
Ryan Olson's avatar
Ryan Olson committed
95
    pub fn model_not_found() -> ErrorResponse {
96
97
        let code = StatusCode::NOT_FOUND;
        let error_type = map_error_code_to_error_type(code);
98
        (
99
            code,
Ryan Olson's avatar
Ryan Olson committed
100
            Json(ErrorMessage {
101
102
103
                message: "Model not found".to_string(),
                error_type,
                code: code.as_u16(),
104
105
106
107
108
109
            }),
        )
    }

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

    /// 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
127
    pub fn internal_server_error(msg: &str) -> ErrorResponse {
128
        tracing::error!("Internal server error: {msg}");
129
130
        let code = StatusCode::INTERNAL_SERVER_ERROR;
        let error_type = map_error_code_to_error_type(code);
131
        (
132
            code,
Ryan Olson's avatar
Ryan Olson committed
133
            Json(ErrorMessage {
134
135
136
                message: msg.to_string(),
                error_type,
                code: code.as_u16(),
137
138
139
140
            }),
        )
    }

141
142
143
    /// 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.
144
    pub fn not_implemented_error<T: Display>(msg: T) -> ErrorResponse {
145
        tracing::error!("Not Implemented error: {msg}");
146
147
        let code = StatusCode::NOT_IMPLEMENTED;
        let error_type = map_error_code_to_error_type(code);
148
        (
149
            code,
Ryan Olson's avatar
Ryan Olson committed
150
            Json(ErrorMessage {
151
152
153
                message: msg.to_string(),
                error_type,
                code: code.as_u16(),
154
155
156
157
            }),
        )
    }

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

        // Then check for HttpError
182
        match err.downcast::<HttpError>() {
Ryan Olson's avatar
Ryan Olson committed
183
            Ok(http_error) => ErrorMessage::from_http_error(http_error),
184
            Err(err) => ErrorMessage::internal_server_error(&format!("{alt_msg}: {err:#}")),
185
186
187
188
        }
    }

    /// Implementers should only be able to throw 400-499 errors.
Ryan Olson's avatar
Ryan Olson committed
189
    pub fn from_http_error(err: HttpError) -> ErrorResponse {
190
        if err.code < 400 || err.code >= 500 {
Ryan Olson's avatar
Ryan Olson committed
191
            return ErrorMessage::internal_server_error(&err.message);
192
193
        }
        match StatusCode::from_u16(err.code) {
194
195
196
197
198
199
200
201
            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
202
            Err(_) => ErrorMessage::internal_server_error(&err.message),
203
204
205
206
        }
    }
}

Ryan Olson's avatar
Ryan Olson committed
207
impl From<HttpError> for ErrorMessage {
208
    fn from(err: HttpError) -> Self {
209
210
211
212
213
214
215
        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,
        }
216
217
218
    }
}

219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// 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 {
234
235
236
                message: error_message,
                error_type: map_error_code_to_error_type(StatusCode::BAD_REQUEST),
                code: StatusCode::BAD_REQUEST.as_u16(),
237
238
239
240
241
242
243
244
245
            }),
        )
            .into_response()
    } else {
        // Pass through if it is not a 422
        response
    }
}

Ryan Olson's avatar
Ryan Olson committed
246
/// Get the request ID from a primary source, or next from the headers, or lastly create a new one if not present
247
// 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
248
fn get_or_create_request_id(primary: Option<&str>, headers: &HeaderMap) -> String {
249
    // Try to get request id from trace context
250
251
252
253
    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;
254
255
    }

Ryan Olson's avatar
Ryan Olson committed
256
    // Try to get the request ID from the primary source
257
258
259
260
    if let Some(primary) = primary
        && let Ok(uuid) = uuid::Uuid::parse_str(primary)
    {
        return uuid.to_string();
Ryan Olson's avatar
Ryan Olson committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
    }

    // 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()
}

279
280
281
282
283
284
285
286
/// 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
287
async fn handler_completions(
288
    State(state): State<Arc<service_v2::State>>,
Ryan Olson's avatar
Ryan Olson committed
289
    headers: HeaderMap,
290
    Json(request): Json<NvCreateCompletionRequest>,
Ryan Olson's avatar
Ryan Olson committed
291
292
293
294
295
296
297
298
299
300
) -> 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
301
302
    let (mut connection_handle, stream_handle) =
        create_connection_monitor(context.clone(), Some(state.metrics_clone())).await;
Ryan Olson's avatar
Ryan Olson committed
303
304
305

    // possibly long running task
    // if this returns a streaming response, the stream handle will be armed and captured by the response stream
306
    let response = tokio::spawn(completions(state, request, stream_handle).in_current_span())
Ryan Olson's avatar
Ryan Olson committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
        .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> {
328
329
    use crate::protocols::openai::completions::get_prompt_batch_size;

330
331
332
    // return a 503 if the service is not ready
    check_ready(&state)?;

333
334
335
    // Validate stream_options is only used when streaming (NVBug 5662680)
    validate_completion_stream_options(&request)?;

336
337
    validate_completion_fields_generic(&request)?;

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
    // Detect batch prompts
    let batch_size = get_prompt_batch_size(&request.inner.prompt);
    let n = request.inner.n.unwrap_or(1);

    // If single prompt or single-element batch, use original flow
    if batch_size == 1 {
        return completions_single(state, request, stream_handle).await;
    }

    // Batch processing: handle multiple prompts
    completions_batch(state, request, stream_handle, batch_size, n).await
}

/// Handle single prompt completions (original logic)
#[tracing::instrument(skip_all)]
async fn completions_single(
    state: Arc<service_v2::State>,
    request: Context<NvCreateCompletionRequest>,
    stream_handle: ConnectionHandle,
) -> Result<Response, ErrorResponse> {
358
    let request_id = request.id().to_string();
359
360

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

363
364
365
366
367
368
    // 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);

369
370
    // todo - error handling should be more robust
    let engine = state
371
        .manager()
372
        .get_completions_engine(&model)
Ryan Olson's avatar
Ryan Olson committed
373
        .map_err(|_| ErrorMessage::model_not_found())?;
374

375
    let parsing_options = state.manager().get_parsing_options(&model);
376

377
    let mut response_collector = state.metrics_clone().create_response_collector(&model);
378

Ryan Olson's avatar
Ryan Olson committed
379
380
    // prepare to process any annotations
    let annotations = request.annotations();
381

382
383
384
385
386
387
    // 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);

388
389
390
391
    // issue the generate call on the engine
    let stream = engine
        .generate(request)
        .await
Ryan Olson's avatar
Ryan Olson committed
392
        .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate completions"))?;
393
394
395
396

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

Ryan Olson's avatar
Ryan Olson committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    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);
416
417

    if streaming {
418
419
        // For streaming, we'll drop the http_queue_guard on the first token
        let mut http_queue_guard = Some(http_queue_guard);
420
421
422
423
424
425
426
427
428
429
430
431
432
433
        let stream = stream
            .map(move |response| {
                // Calls observe_response() on each token
                process_response_using_event_converter_and_observe_metrics(
                    EventConverter::from(response),
                    &mut response_collector,
                    &mut http_queue_guard,
                )
            })
            .filter_map(|result| {
                use futures::future;
                // Transpose Result<Option<T>> -> Option<Result<T>>
                future::ready(result.transpose())
            });
Ryan Olson's avatar
Ryan Olson committed
434
        let stream = monitor_for_disconnects(stream, ctx, inflight_guard, stream_handle);
435

436
437
        let mut sse_stream = Sse::new(stream);

438
        if let Some(keep_alive) = state.sse_keep_alive() {
439
440
441
442
            sse_stream = sse_stream.keep_alive(KeepAlive::default().interval(keep_alive));
        }

        Ok(sse_stream.into_response())
443
    } else {
444
        // Tap the stream to collect metrics for non-streaming requests without altering items
445
        let mut http_queue_guard = Some(http_queue_guard);
446
        let stream = stream.inspect(move |response| {
447
448
449
450
451
452
            // 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,
            );
453
454
        });

455
        let response = NvCreateCompletionResponse::from_annotated_stream(stream, parsing_options)
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to fold completions stream for {}: {:?}",
                    request_id,
                    e
                );
                ErrorMessage::internal_server_error(&format!(
                    "Failed to fold completions stream for {}: {:?}",
                    request_id, e
                ))
            })?;

        inflight_guard.mark_ok();
        Ok(Json(response).into_response())
    }
}

/// Handle batch prompt completions (multiple prompts with n choices each)
#[tracing::instrument(skip_all)]
async fn completions_batch(
    state: Arc<service_v2::State>,
    request: Context<NvCreateCompletionRequest>,
    stream_handle: ConnectionHandle,
    batch_size: usize,
    n: u8,
) -> Result<Response, ErrorResponse> {
    use crate::protocols::openai::completions::extract_single_prompt;
    use futures::stream::{self, StreamExt};

    let request_id = request.id().to_string();
    let streaming = request.inner.stream.unwrap_or(false);
    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);

    let engine = state
        .manager()
        .get_completions_engine(&model)
        .map_err(|_| ErrorMessage::model_not_found())?;

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

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

    // prepare to process any annotations
    let annotations = request.annotations();

    // 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);

    // Generate streams for each prompt in the batch
    let mut all_streams = Vec::new();
    let mut first_ctx = None;

    for prompt_idx in 0..batch_size {
        // Extract single prompt at this index
        let single_prompt = extract_single_prompt(&request.inner.prompt, prompt_idx);

        // Create a new request with this single prompt
        let mut single_request = request.content().clone();
        single_request.inner.prompt = single_prompt;

        // Generate unique request_id for each prompt: original_id-{prompt_idx}
        let unique_request_id = format!("{}-{}", request.id(), prompt_idx);
        let single_request_context = Context::with_id(single_request, unique_request_id);

        // Generate stream for this prompt
        let stream = engine
            .generate(single_request_context)
            .await
            .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate completions"))?;

        // Capture context from first stream
        if first_ctx.is_none() {
            first_ctx = Some(stream.context());
        }

        // Remap choice indices: choice.index += prompt_idx * n
        let prompt_idx_u32 = prompt_idx as u32;
        let n_u32 = n as u32;
        let remapped_stream = stream.map(move |mut response| {
            if let Some(ref mut data) = response.data {
                for choice in &mut data.inner.choices {
                    choice.index += prompt_idx_u32 * n_u32;
                }
            }
            response
        });

        all_streams.push(remapped_stream);
    }

    // Merge all streams
    let merged_stream = stream::select_all(all_streams);

    // capture the context to cancel the stream if the client disconnects
    let ctx = first_ctx.expect("At least one stream should be generated");

    let annotations_vec = 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 merged_stream = stream::iter(annotations_vec).chain(merged_stream);

    if streaming {
        // For streaming, we'll drop the http_queue_guard on the first token
        let mut http_queue_guard = Some(http_queue_guard);
582
583
584
585
586
587
588
589
590
591
592
593
594
595
        let stream = merged_stream
            .map(move |response| {
                // Calls observe_response() on each token
                process_response_using_event_converter_and_observe_metrics(
                    EventConverter::from(response),
                    &mut response_collector,
                    &mut http_queue_guard,
                )
            })
            .filter_map(|result| {
                use futures::future;
                // Transpose Result<Option<T>> -> Option<Result<T>>
                future::ready(result.transpose())
            });
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
        let stream = monitor_for_disconnects(stream, ctx, inflight_guard, stream_handle);

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

        if let Some(keep_alive) = state.sse_keep_alive() {
            sse_stream = sse_stream.keep_alive(KeepAlive::default().interval(keep_alive));
        }

        Ok(sse_stream.into_response())
    } else {
        // Tap the stream to collect metrics for non-streaming requests without altering items
        let mut http_queue_guard = Some(http_queue_guard);
        let stream = merged_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,
            );
        });

        let response = NvCreateCompletionResponse::from_annotated_stream(stream, parsing_options)
618
619
620
621
622
623
624
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to fold completions stream for {}: {:?}",
                    request_id,
                    e
                );
625
626
627
628
                ErrorMessage::internal_server_error(&format!(
                    "Failed to fold completions stream for {}: {:?}",
                    request_id, e
                ))
629
630
            })?;

631
        inflight_guard.mark_ok();
632
633
634
635
        Ok(Json(response).into_response())
    }
}

636
637
#[tracing::instrument(skip_all)]
async fn embeddings(
638
    State(state): State<Arc<service_v2::State>>,
639
    headers: HeaderMap,
640
    Json(request): Json<NvCreateEmbeddingRequest>,
Ryan Olson's avatar
Ryan Olson committed
641
) -> Result<Response, ErrorResponse> {
642
643
644
    // return a 503 if the service is not ready
    check_ready(&state)?;

645
646
647
    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();
648
649
650
651
652
653
654
655

    // 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;

656
657
658
    // Create http_queue_guard early - tracks time waiting to be processed
    let http_queue_guard = state.metrics_clone().create_http_queue_guard(model);

659
660
661
662
    // todo - error handling should be more robust
    let engine = state
        .manager()
        .get_embeddings_engine(model)
Ryan Olson's avatar
Ryan Olson committed
663
        .map_err(|_| ErrorMessage::model_not_found())?;
664
665
666
667
668
669
670

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

671
672
    let mut response_collector = state.metrics_clone().create_response_collector(model);

673
674
675
676
    // issue the generate call on the engine
    let stream = engine
        .generate(request)
        .await
Ryan Olson's avatar
Ryan Olson committed
677
        .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate embeddings"))?;
678

679
680
681
682
683
684
685
686
687
688
689
    // 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,
        );
    });

690
691
    // 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
692
    let response = NvCreateEmbeddingResponse::from_annotated_stream(stream)
693
694
695
696
697
698
699
        .await
        .map_err(|e| {
            tracing::error!(
                "Failed to fold embeddings stream for {}: {:?}",
                request_id,
                e
            );
Ryan Olson's avatar
Ryan Olson committed
700
            ErrorMessage::internal_server_error("Failed to fold embeddings stream")
701
702
703
704
        })?;

    inflight.mark_ok();
    Ok(Json(response).into_response())
705
706
}

Ryan Olson's avatar
Ryan Olson committed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
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
721
722
    let (mut connection_handle, stream_handle) =
        create_connection_monitor(context.clone(), Some(state.metrics_clone())).await;
Ryan Olson's avatar
Ryan Olson committed
723

724
725
726
727
728
729
730
731
732
    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
733
734
735
736
737
738
739
740

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

741
742
743
744
745
746
747
748
749
750
751
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
/// Checks if an Annotated event represents a backend error and extracts error information.
/// Returns Some((message, status_code)) if it's an error, None otherwise.
fn extract_backend_error_if_present<T: serde::Serialize>(
    event: &Annotated<T>,
) -> Option<(String, StatusCode)> {
    #[derive(serde::Deserialize)]
    struct ErrorPayload {
        message: Option<String>,
        code: Option<u16>,
    }

    // Check if event type is "error" (from postprocessor when FinishReason::Error is encountered)
    if let Some(event_type) = &event.event
        && event_type == "error"
    {
        let comment_str = event
            .comment
            .as_ref()
            .map(|c| c.join(", "))
            .unwrap_or_else(|| "Unknown error".to_string());

        // Try to parse comment as error JSON to extract status code
        if let Ok(error_payload) = serde_json::from_str::<ErrorPayload>(&comment_str) {
            let code = error_payload
                .code
                .and_then(|c| StatusCode::from_u16(c).ok())
                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
            let message = error_payload.message.unwrap_or(comment_str);
            return Some((message, code));
        }

        return Some((comment_str, StatusCode::INTERNAL_SERVER_ERROR));
    }

    // Check if the data payload itself contains an error structure with code >= 400
    if let Some(data) = &event.data
        && let Ok(json_value) = serde_json::to_value(data)
        && let Ok(error_payload) = serde_json::from_value::<ErrorPayload>(json_value.clone())
        && let Some(code_num) = error_payload.code
        && code_num >= 400
    {
        let code = StatusCode::from_u16(code_num).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        let message = error_payload
            .message
            .unwrap_or_else(|| json_value.to_string());
        return Some((message, code));
    }

    // Check if comment contains error information (without event: error)
    if let Some(comments) = &event.comment
        && !comments.is_empty()
    {
        let comment_str = comments.join(", ");

        // Try to parse comment as error JSON with code >= 400
        if let Ok(error_payload) = serde_json::from_str::<ErrorPayload>(&comment_str)
            && let Some(code_num) = error_payload.code
            && code_num >= 400
        {
            let code = StatusCode::from_u16(code_num).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
            let message = error_payload.message.unwrap_or(comment_str);
            return Some((message, code));
        }

        // Comments present with no data AND no event type indicates error
        // (events with event types like "request_id" or "event.dynamo.test.sentinel" are annotations)
        if event.data.is_none() && event.event.is_none() {
            return Some((comment_str, StatusCode::INTERNAL_SERVER_ERROR));
        }
    }

    None
}

/// Checks if the first event in the stream is a backend error.
/// Returns Err(ErrorResponse) if error detected, Ok(stream) otherwise.
async fn check_for_backend_error(
    mut stream: impl futures::Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>>
    + Send
    + Unpin
    + 'static,
) -> Result<
    impl futures::Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send,
    ErrorResponse,
> {
    use futures::stream::StreamExt;

    // Peek at the first event
    if let Some(first_event) = stream.next().await {
        // Check if it's an error event
        if let Some((error_msg, status_code)) = extract_backend_error_if_present(&first_event) {
            return Err((
                status_code,
                Json(ErrorMessage {
                    message: error_msg,
                    error_type: map_error_code_to_error_type(status_code),
                    code: status_code.as_u16(),
                }),
            ));
        }

        // Not an error - reconstruct stream with first event
        let reconstructed_stream = futures::stream::iter(vec![first_event]).chain(stream);
        Ok(reconstructed_stream)
    } else {
        // Empty stream - this shouldn't happen but handle gracefully
        Ok(futures::stream::iter(vec![]).chain(stream))
    }
}

851
852
853
854
855
856
857
858
859
/// 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
860
861
862
863
864
    state: Arc<service_v2::State>,
    template: Option<RequestTemplate>,
    mut request: Context<NvCreateChatCompletionRequest>,
    mut stream_handle: ConnectionHandle,
) -> Result<Response, ErrorResponse> {
865
866
867
    // return a 503 if the service is not ready
    check_ready(&state)?;

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

870
871
872
873
    // 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
874
    validate_chat_completion_unsupported_fields(&request)?;
875

876
877
878
    // Handle required fields like messages shouldn't be empty.
    validate_chat_completion_required_fields(&request)?;

879
880
881
    // Validate stream_options is only used when streaming (NVBug 5662680)
    validate_chat_completion_stream_options(&request)?;

882
883
884
    // Handle Rest of Validation Errors
    validate_chat_completion_fields_generic(&request)?;

885
886
887
888
889
890
891
892
893
894
895
896
    // 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
897
    tracing::trace!("Received chat completions request: {:?}", request.content());
898
899

    // todo - decide on default
Paul Hendricks's avatar
Paul Hendricks committed
900
    let streaming = request.inner.stream.unwrap_or(false);
901
902
903
904

    // 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
905
906
907
908
909
    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);

910
911
912
    tracing::trace!("Getting chat completions engine for model: {}", model);

    let engine = state
913
        .manager()
914
        .get_chat_completions_engine(&model)
Ryan Olson's avatar
Ryan Olson committed
915
        .map_err(|_| ErrorMessage::model_not_found())?;
916

917
    let parsing_options = state.manager().get_parsing_options(&model);
918

919
920
921
922
923
    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
924
    let mut inflight_guard =
925
926
        state
            .metrics_clone()
927
            .create_inflight_guard(&model, Endpoint::ChatCompletions, streaming);
928
929
930
931
932

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

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

Ryan Olson's avatar
Ryan Olson committed
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
    // 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);

955
956
957
958
    // 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 {
959
960
961
962
        // For streaming responses, we return HTTP 200 immediately without checking for errors.
        // Once HTTP 200 OK is sent, we cannot change the status code, so any backend errors
        // must be delivered as SSE events with `event: error` in the stream (handled by
        // EventConverter and monitor_for_disconnects). This is standard SSE behavior.
963
        stream_handle.arm(); // allows the system to detect client disconnects and cancel the LLM generation
Ryan Olson's avatar
Ryan Olson committed
964

965
        let mut http_queue_guard = Some(http_queue_guard);
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
        let stream = stream
            .map(move |response| {
                // Calls observe_response() on each token
                // EventConverter will detect `event: "error"` and convert to SSE error events
                process_response_using_event_converter_and_observe_metrics(
                    EventConverter::from(response),
                    &mut response_collector,
                    &mut http_queue_guard,
                )
            })
            .filter_map(|result| {
                use futures::future;
                // Transpose Result<Option<T>> -> Option<Result<T>>
                future::ready(result.transpose())
            });
Ryan Olson's avatar
Ryan Olson committed
981
        let stream = monitor_for_disconnects(stream, ctx, inflight_guard, stream_handle);
982

983
984
        let mut sse_stream = Sse::new(stream);

985
        if let Some(keep_alive) = state.sse_keep_alive() {
986
987
988
989
            sse_stream = sse_stream.keep_alive(KeepAlive::default().interval(keep_alive));
        }

        Ok(sse_stream.into_response())
990
    } else {
991
992
993
994
995
996
997
998
999
        // Check first event for backend errors before aggregating (non-streaming only)
        let stream_with_check =
            check_for_backend_error(stream)
                .await
                .map_err(|error_response| {
                    tracing::error!(request_id, "Backend error detected: {:?}", error_response);
                    error_response
                })?;

1000
        let mut http_queue_guard = Some(http_queue_guard);
1001
        let stream = stream_with_check.inspect(move |response| {
1002
1003
1004
1005
1006
1007
            // 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,
            );
1008
1009
        });

1010
1011
1012
1013
1014
1015
        let response =
            NvCreateChatCompletionResponse::from_annotated_stream(stream, parsing_options.clone())
                .await
                .map_err(|e| {
                    tracing::error!(
                        request_id,
1016
                        "Failed to parse chat completion response: {:?}",
1017
1018
1019
                        e
                    );
                    ErrorMessage::internal_server_error(&format!(
1020
                        "Failed to parse chat completion response: {}",
1021
1022
1023
                        e
                    ))
                })?;
1024

1025
        inflight_guard.mark_ok();
1026
1027
1028
1029
        Ok(Json(response).into_response())
    }
}

1030
1031
1032
1033
1034
/// 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
1035
) -> Result<(), ErrorResponse> {
1036
1037
1038
    let inner = &request.inner;

    if inner.function_call.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1039
        return Err(ErrorMessage::not_implemented_error(
1040
1041
            VALIDATION_PREFIX.to_string()
                + "`function_call` is deprecated. Please migrate to use `tool_choice` instead.",
1042
1043
1044
1045
        ));
    }

    if inner.functions.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1046
        return Err(ErrorMessage::not_implemented_error(
1047
1048
            VALIDATION_PREFIX.to_string()
                + "`functions` is deprecated. Please migrate to use `tools` instead.",
1049
1050
1051
        ));
    }

Ryan Olson's avatar
Ryan Olson committed
1052
    Ok(())
1053
1054
}

1055
1056
1057
1058
1059
1060
1061
1062
1063
/// 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,
1064
1065
            message: VALIDATION_PREFIX.to_string()
                + "The 'messages' field cannot be empty. At least one message is required.",
1066
1067
1068
1069
1070
1071
        }));
    }

    Ok(())
}

1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
/// Validates that stream_options is only used when stream=true for chat completions (NVBug 5662680)
pub fn validate_chat_completion_stream_options(
    request: &NvCreateChatCompletionRequest,
) -> Result<(), ErrorResponse> {
    let inner = &request.inner;
    let streaming = inner.stream.unwrap_or(false);
    if !streaming && inner.stream_options.is_some() {
        return Err(ErrorMessage::from_http_error(HttpError {
            code: 400,
            message: VALIDATION_PREFIX.to_string()
                + "The 'stream_options' field is only allowed when 'stream' is set to true.",
        }));
    }
    Ok(())
}

1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
/// 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,
1098
            message: VALIDATION_PREFIX.to_string() + &e.to_string(),
1099
1100
1101
1102
        })
    })
}

1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
/// Validates that stream_options is only used when stream=true for completions (NVBug 5662680)
pub fn validate_completion_stream_options(
    request: &NvCreateCompletionRequest,
) -> Result<(), ErrorResponse> {
    let inner = &request.inner;
    let streaming = inner.stream.unwrap_or(false);
    if !streaming && inner.stream_options.is_some() {
        return Err(ErrorMessage::from_http_error(HttpError {
            code: 400,
            message: VALIDATION_PREFIX.to_string()
                + "The 'stream_options' field is only allowed when 'stream' is set to true.",
        }));
    }
    Ok(())
}

1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
/// 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,
1129
            message: VALIDATION_PREFIX.to_string() + &e.to_string(),
1130
1131
1132
1133
        })
    })
}

1134
1135
1136
/// OpenAI Responses Request Handler
///
/// This method will handle the incoming request for the /v1/responses endpoint.
Ryan Olson's avatar
Ryan Olson committed
1137
async fn handler_responses(
1138
    State((state, template)): State<(Arc<service_v2::State>, Option<RequestTemplate>)>,
Ryan Olson's avatar
Ryan Olson committed
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
    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
1151
1152
    let (mut connection_handle, _stream_handle) =
        create_connection_monitor(context.clone(), Some(state.metrics_clone())).await;
Ryan Olson's avatar
Ryan Olson committed
1153

1154
    let response = tokio::spawn(responses(state, template, request).in_current_span())
Ryan Olson's avatar
Ryan Olson committed
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
        .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> {
1176
1177
1178
    // return a 503 if the service is not ready
    check_ready(&state)?;

1179
1180
1181
1182
    // 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);

1183
1184
1185
    // 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.
1186
    if let Some(resp) = validate_response_unsupported_fields(&request) {
1187
1188
1189
1190
1191
1192
1193
        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.
1194
    if let Some(resp) = validate_response_input_is_text_only(&request) {
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
        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
1212
1213
    let request_id = request.id().to_string();
    let (request, context) = request.into_parts();
1214

1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
    let mut request: NvCreateChatCompletionRequest =
        request.try_into().map_err(|e: anyhow::Error| {
            tracing::error!(
                request_id,
                error = %e,
                "Failed to convert NvCreateResponse to NvCreateChatCompletionRequest",
            );
            ErrorMessage::not_implemented_error(
                VALIDATION_PREFIX.to_string()
                    + "Only Input::Text(_) is currently supported: "
                    + &e.to_string(),
            )
        })?;
1228

Ryan Olson's avatar
Ryan Olson committed
1229
1230
1231
1232
1233
    let request = context.map(|mut _req| {
        request.inner.stream = Some(false);
        request
    });

1234
1235
1236
1237
    tracing::trace!("Getting chat completions engine for model: {}", model);

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

1241
    let parsing_options = state.manager().get_parsing_options(&model);
1242

1243
    let mut response_collector = state.metrics_clone().create_response_collector(&model);
1244
1245
1246
1247
1248
1249
1250

    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
1251
        .map_err(|e| ErrorMessage::from_anyhow(e, "Failed to generate completions"))?;
1252

1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
    // 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,
        );
    });

1270
    // TODO: handle streaming, currently just unary
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
    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
                ))
            })?;
1285
1286
1287
1288
1289
1290
1291
1292

    // 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
1293
        ErrorMessage::internal_server_error("Failed to convert internal response")
1294
1295
1296
1297
1298
1299
1300
    })?;

    inflight_guard.mark_ok();

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

1301
1302
1303
pub fn validate_response_input_is_text_only(
    request: &NvCreateResponse,
) -> Option<impl IntoResponse> {
1304
    match &request.inner.input {
1305
        dynamo_async_openai::types::responses::Input::Text(_) => None,
1306
        _ => Some(ErrorMessage::not_implemented_error(
1307
1308
            VALIDATION_PREFIX.to_string()
                + "Only `Input::Text` is supported. Structured, multimedia, or custom input types are not yet implemented.",
1309
        )),
1310
1311
1312
1313
1314
    }
}

/// Checks for unsupported fields in the request.
/// Returns Some(response) if unsupported fields are present.
1315
1316
1317
pub fn validate_response_unsupported_fields(
    request: &NvCreateResponse,
) -> Option<impl IntoResponse> {
1318
1319
1320
    let inner = &request.inner;

    if inner.background == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
1321
        return Some(ErrorMessage::not_implemented_error(
1322
            VALIDATION_PREFIX.to_string() + "`background: true` is not supported.",
1323
1324
1325
        ));
    }
    if inner.include.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1326
        return Some(ErrorMessage::not_implemented_error(
1327
            VALIDATION_PREFIX.to_string() + "`include` is not supported.",
1328
1329
1330
        ));
    }
    if inner.instructions.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1331
        return Some(ErrorMessage::not_implemented_error(
1332
            VALIDATION_PREFIX.to_string() + "`instructions` is not supported.",
1333
1334
1335
        ));
    }
    if inner.max_tool_calls.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1336
        return Some(ErrorMessage::not_implemented_error(
1337
            VALIDATION_PREFIX.to_string() + "`max_tool_calls` is not supported.",
1338
1339
1340
        ));
    }
    if inner.previous_response_id.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1341
        return Some(ErrorMessage::not_implemented_error(
1342
            VALIDATION_PREFIX.to_string() + "`previous_response_id` is not supported.",
1343
1344
1345
        ));
    }
    if inner.prompt.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1346
        return Some(ErrorMessage::not_implemented_error(
1347
            VALIDATION_PREFIX.to_string() + "`prompt` is not supported.",
1348
1349
1350
        ));
    }
    if inner.reasoning.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1351
        return Some(ErrorMessage::not_implemented_error(
1352
            VALIDATION_PREFIX.to_string() + "`reasoning` is not supported.",
1353
1354
1355
        ));
    }
    if inner.service_tier.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1356
        return Some(ErrorMessage::not_implemented_error(
1357
            VALIDATION_PREFIX.to_string() + "`service_tier` is not supported.",
1358
1359
1360
        ));
    }
    if inner.store == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
1361
        return Some(ErrorMessage::not_implemented_error(
1362
            VALIDATION_PREFIX.to_string() + "`store: true` is not supported.",
1363
1364
1365
        ));
    }
    if inner.stream == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
1366
        return Some(ErrorMessage::not_implemented_error(
1367
            VALIDATION_PREFIX.to_string() + "`stream: true` is not supported.",
1368
1369
1370
        ));
    }
    if inner.text.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1371
        return Some(ErrorMessage::not_implemented_error(
1372
            VALIDATION_PREFIX.to_string() + "`text` is not supported.",
1373
1374
1375
        ));
    }
    if inner.tool_choice.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1376
        return Some(ErrorMessage::not_implemented_error(
1377
            VALIDATION_PREFIX.to_string() + "`tool_choice` is not supported.",
1378
1379
1380
        ));
    }
    if inner.tools.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1381
        return Some(ErrorMessage::not_implemented_error(
1382
            VALIDATION_PREFIX.to_string() + "`tools` is not supported.",
1383
1384
1385
        ));
    }
    if inner.truncation.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1386
        return Some(ErrorMessage::not_implemented_error(
1387
            VALIDATION_PREFIX.to_string() + "`truncation` is not supported.",
1388
1389
1390
        ));
    }
    if inner.user.is_some() {
Ryan Olson's avatar
Ryan Olson committed
1391
        return Some(ErrorMessage::not_implemented_error(
1392
            VALIDATION_PREFIX.to_string() + "`user` is not supported.",
1393
1394
1395
1396
1397
1398
        ));
    }

    None
}

1399
1400
// 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
1401
fn check_ready(_state: &Arc<service_v2::State>) -> Result<(), ErrorResponse> {
1402
    // if state.service_observer.stage() != ServiceStage::Ready {
Ryan Olson's avatar
Ryan Olson committed
1403
    //     return Err(ErrorMessage::service_unavailable());
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
    // }
    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(
1422
    State(state): State<Arc<service_v2::State>>,
Ryan Olson's avatar
Ryan Olson committed
1423
) -> Result<Response, ErrorResponse> {
1424
1425
1426
1427
1428
1429
1430
1431
    check_ready(&state)?;

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

1432
1433
    let models: HashSet<String> = state.manager().model_display_names();
    for model_name in models {
1434
        data.push(ModelListing {
1435
            id: model_name.clone(),
1436
1437
1438
            object: "model", // Per OpenAI spec, this should be "model"
            created,
            owned_by: "nvidia".to_string(),
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
        });
    }

    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,
1458
1459
    object: &'static str, // always "model" per OpenAI spec
    created: u64,         // Seconds since epoch
1460
1461
1462
1463
1464
1465
    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(
1466
    state: Arc<service_v2::State>,
1467
1468
1469
1470
1471
    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
1472
        .route(&path, post(handler_completions))
1473
        .layer(middleware::from_fn(smart_json_error_middleware))
1474
        .layer(axum::extract::DefaultBodyLimit::max(get_body_limit()))
1475
1476
1477
1478
1479
1480
1481
        .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(
1482
    state: Arc<service_v2::State>,
1483
    template: Option<RequestTemplate>,
1484
1485
1486
1487
1488
    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
1489
        .route(&path, post(handler_chat_completions))
1490
        .layer(middleware::from_fn(smart_json_error_middleware))
1491
        .layer(axum::extract::DefaultBodyLimit::max(get_body_limit()))
1492
        .with_state((state, template));
1493
1494
1495
    (vec![doc], router)
}

1496
1497
1498
/// 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(
1499
    state: Arc<service_v2::State>,
1500
1501
1502
1503
1504
1505
    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))
1506
        .layer(middleware::from_fn(smart_json_error_middleware))
1507
        .layer(axum::extract::DefaultBodyLimit::max(get_body_limit()))
1508
1509
1510
1511
        .with_state(state);
    (vec![doc], router)
}

1512
1513
/// List Models
pub fn list_models_router(
1514
    state: Arc<service_v2::State>,
1515
1516
1517
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    // Standard OpenAI compatible list models endpoint
1518
    let openai_path = path.unwrap_or("/v1/models".to_string());
1519
1520
1521
1522
1523
1524
    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);

1525
    (vec![doc_for_openai], router)
1526
1527
}

1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
/// 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
1538
        .route(&path, post(handler_responses))
1539
        .layer(middleware::from_fn(smart_json_error_middleware))
1540
1541
1542
1543
        .with_state((state, template));
    (vec![doc], router)
}

1544
1545
#[cfg(test)]
mod tests {
1546

1547
1548
1549
1550
1551
1552
    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;
1553
    use dynamo_async_openai::types::responses::{
1554
1555
1556
1557
        CreateResponse, Input, InputContent, InputItem, InputMessage, PromptConfig,
        Role as ResponseRole, ServiceTier, TextConfig, TextResponseFormat, ToolChoice,
        ToolChoiceMode, Truncation,
    };
1558
    use dynamo_async_openai::types::{
1559
1560
        ChatCompletionRequestMessage, ChatCompletionRequestUserMessage,
        ChatCompletionRequestUserMessageContent, CreateChatCompletionRequest,
1561
        CreateCompletionRequest,
1562
    };
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573

    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> {
1574
        Err(ModelManagerError::ModelNotFound("foo".to_string()))?
1575
1576
    }

1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
    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,
        }
    }

1608
1609
1610
    #[test]
    fn test_http_error_response_from_anyhow() {
        let err = http_error_from_engine(400).unwrap_err();
1611
1612
1613
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::BAD_REQUEST);
        assert_eq!(response.1.message, "custom error message");
1614
1615
1616
1617
1618
    }

    #[test]
    fn test_error_response_from_anyhow_out_of_range() {
        let err = http_error_from_engine(399).unwrap_err();
1619
1620
1621
        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");
1622
1623

        let err = http_error_from_engine(500).unwrap_err();
1624
1625
1626
        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");
1627
1628

        let err = http_error_from_engine(501).unwrap_err();
1629
1630
1631
        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");
1632
1633
1634
1635
1636
    }

    #[test]
    fn test_other_error_response_from_anyhow() {
        let err = other_error_from_engine().unwrap_err();
1637
1638
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::INTERNAL_SERVER_ERROR);
1639
        assert_eq!(
1640
            response.1.message,
1641
1642
1643
1644
1645
1646
1647
            format!(
                "{}: {}",
                BACKUP_ERROR_MESSAGE,
                other_error_from_engine().unwrap_err()
            )
        );
    }
1648

1649
1650
1651
1652
1653
1654
1655
1656
    #[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();
1657
1658
        let response = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
        assert_eq!(response.0, StatusCode::SERVICE_UNAVAILABLE);
1659
        assert_eq!(
1660
            response.1.message,
1661
1662
1663
1664
            "Service temporarily unavailable: All workers are busy, please retry later"
        );
    }

1665
1666
1667
    #[test]
    fn test_validate_input_is_text_only_accepts_text() {
        let request = make_base_request();
1668
        let result = validate_response_input_is_text_only(&request);
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
        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()),
        })]);
1680
        let result = validate_response_input_is_text_only(&request);
1681
1682
1683
1684
1685
1686
        assert!(result.is_some());
    }

    #[test]
    fn test_validate_unsupported_fields_accepts_clean_request() {
        let request = make_base_request();
1687
        let result = validate_response_unsupported_fields(&request);
1688
1689
1690
        assert!(result.is_none());
    }

1691
1692
1693
1694
1695
1696
1697
1698
    #[test]
    fn test_validate_unsupported_fields_accepts_parallel_tool_calls() {
        let mut request = make_base_request();
        request.inner.parallel_tool_calls = Some(true);
        let result = validate_response_unsupported_fields(&request);
        assert!(result.is_none(), "parallel_tool_calls should be supported");
    }

1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
    #[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))),
            (
                "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);
1760
            let result = validate_response_unsupported_fields(&req);
1761
1762
1763
            assert!(result.is_some(), "Expected rejection for `{field}`");
        }
    }
1764
1765
1766
1767
1768
1769
1770
1771
1772

    #[test]
    fn test_validate_chat_completion_required_fields_empty_messages() {
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![],
                ..Default::default()
            },
1773
            common: Default::default(),
1774
            nvext: None,
1775
            chat_template_args: None,
1776
            media_io_kwargs: None,
1777
            unsupported_fields: Default::default(),
1778
1779
1780
        };
        let result = validate_chat_completion_required_fields(&request);
        assert!(result.is_err());
1781
1782
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1783
            assert_eq!(
1784
                error_response.1.message,
1785
1786
1787
                format!(
                    "{VALIDATION_PREFIX}The 'messages' field cannot be empty. At least one message is required."
                )
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
            );
        }
    }

    #[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()
            },
1805
            common: Default::default(),
1806
            nvext: None,
1807
            chat_template_args: None,
1808
            media_io_kwargs: None,
1809
            unsupported_fields: Default::default(),
1810
1811
1812
1813
        };
        let result = validate_chat_completion_required_fields(&request);
        assert!(result.is_ok());
    }
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829

    #[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 ?
1830
    // Unknown fields : Done (rejected via extra_fields catch-all)
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
    // 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,
1845
            metadata: None,
1846
            unsupported_fields: Default::default(),
1847
1848
1849
1850
        };

        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1851
1852
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1853
            assert_eq!(
1854
                error_response.1.message,
1855
                format!("{VALIDATION_PREFIX}Frequency penalty must be between -2 and 2, got -3")
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
            );
        }

        // 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,
1869
            metadata: None,
1870
            unsupported_fields: Default::default(),
1871
1872
1873
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1874
1875
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1876
            assert_eq!(
1877
                error_response.1.message,
1878
                format!("{VALIDATION_PREFIX}Presence penalty must be between -2 and 2, got -3")
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
            );
        }

        // 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,
1892
            metadata: None,
1893
            unsupported_fields: Default::default(),
1894
1895
1896
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1897
1898
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1899
            assert_eq!(
1900
                error_response.1.message,
1901
                format!("{VALIDATION_PREFIX}Temperature must be between 0 and 2, got -3")
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
            );
        }

        // 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,
1915
            metadata: None,
1916
            unsupported_fields: Default::default(),
1917
1918
1919
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1920
1921
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1922
            assert_eq!(
1923
                error_response.1.message,
1924
                format!("{VALIDATION_PREFIX}Top_p must be between 0 and 1, got -3")
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
            );
        }

        // 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,
1940
            metadata: None,
1941
            unsupported_fields: Default::default(),
1942
1943
1944
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1945
1946
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1947
            assert_eq!(
1948
                error_response.1.message,
1949
                format!("{VALIDATION_PREFIX}Repetition penalty must be between 0 and 2, got -3")
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
            );
        }

        // 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,
1963
            metadata: None,
1964
            unsupported_fields: Default::default(),
1965
1966
1967
        };
        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
1968
1969
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
1970
            assert_eq!(
1971
                error_response.1.message,
1972
                format!("{VALIDATION_PREFIX}Logprobs must be between 0 and 5, got 6")
1973
1974
1975
1976
            );
        }
    }

1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
    #[test]
    fn test_metadata_field_nested() {
        use serde_json::json;

        // Test metadata field with nested object
        let request = NvCreateCompletionRequest {
            inner: CreateCompletionRequest {
                model: "test-model".to_string(),
                prompt: "Hello".into(),
                ..Default::default()
            },
            common: Default::default(),
            nvext: None,
            metadata: json!({
                "user": {"id": 1, "name": "user-1"},
                "session": {"id": "session-1", "timestamp": 1640995200}
            })
            .into(),
1995
            unsupported_fields: Default::default(),
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
        };

        let result = validate_completion_fields_generic(&request);
        assert!(result.is_ok());

        // Verify metadata is accessible
        assert!(request.metadata.is_some());
        assert_eq!(request.metadata.as_ref().unwrap()["user"]["id"], 1);
    }

2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
    #[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,
2023
            chat_template_args: None,
2024
            media_io_kwargs: None,
2025
            unsupported_fields: Default::default(),
2026
2027
2028
2029
        };

        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
2030
2031
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
2032
            assert_eq!(
2033
                error_response.1.message,
2034
                format!("{VALIDATION_PREFIX}Frequency penalty must be between -2 and 2, got -3")
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
            );
        }

        // 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,
2053
            chat_template_args: None,
2054
            media_io_kwargs: None,
2055
            unsupported_fields: Default::default(),
2056
2057
2058
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
2059
2060
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
2061
            assert_eq!(
2062
                error_response.1.message,
2063
                format!("{VALIDATION_PREFIX}Presence penalty must be between -2 and 2, got -3")
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
            );
        }

        // 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,
2082
            chat_template_args: None,
2083
            media_io_kwargs: None,
2084
            unsupported_fields: Default::default(),
2085
2086
2087
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
2088
2089
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
2090
            assert_eq!(
2091
                error_response.1.message,
2092
                format!("{VALIDATION_PREFIX}Temperature must be between 0 and 2, got -3")
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
            );
        }

        // 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,
2111
            chat_template_args: None,
2112
            media_io_kwargs: None,
2113
            unsupported_fields: Default::default(),
2114
2115
2116
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
2117
2118
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
2119
            assert_eq!(
2120
                error_response.1.message,
2121
                format!("{VALIDATION_PREFIX}Top_p must be between 0 and 1, got -3")
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
            );
        }

        // 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,
2142
            chat_template_args: None,
2143
            media_io_kwargs: None,
2144
            unsupported_fields: Default::default(),
2145
2146
2147
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
2148
2149
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
2150
            assert_eq!(
2151
                error_response.1.message,
2152
                format!("{VALIDATION_PREFIX}Repetition penalty must be between 0 and 2, got -3")
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
            );
        }

        // 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,
2171
            chat_template_args: None,
2172
            media_io_kwargs: None,
2173
            unsupported_fields: Default::default(),
2174
2175
2176
        };
        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
2177
2178
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
2179
            assert_eq!(
2180
                error_response.1.message,
2181
                format!("{VALIDATION_PREFIX}Top_logprobs must be between 0 and 20, got 25")
2182
2183
2184
            );
        }
    }
2185
2186

    #[test]
2187
2188
    fn test_chat_completions_unknown_fields_rejected() {
        // Test that known unsupported fields are rejected and all shown in error message
2189
2190
2191
2192
2193
        let json = r#"{
            "messages": [{"role": "user", "content": "Hello"}],
            "model": "test-model",
            "add_special_tokens": true,
            "documents": ["doc1"],
2194
            "chat_template": "custom"
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
        }"#;

        let request: NvCreateChatCompletionRequest = serde_json::from_str(json).unwrap();

        // Verify all unsupported fields were captured
        assert!(
            request
                .unsupported_fields
                .contains_key("add_special_tokens")
        );
        assert!(request.unsupported_fields.contains_key("documents"));
        assert!(request.unsupported_fields.contains_key("chat_template"));

        let result = validate_chat_completion_fields_generic(&request);
        assert!(result.is_err());
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
            let msg = &error_response.1.message;
            assert!(msg.contains("Unsupported parameter"));
            // Verify all fields appear in the error message
            assert!(msg.contains("add_special_tokens"));
            assert!(msg.contains("documents"));
            assert!(msg.contains("chat_template"));
        }
    }
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251

    #[test]
    fn test_completions_unsupported_fields_rejected() {
        // Test that known unsupported fields are rejected and all shown in error message
        let json = r#"{
            "model": "test-model",
            "prompt": "Hello",
            "add_special_tokens": true,
            "response_format": {"type": "json_object"}
        }"#;

        let request: NvCreateCompletionRequest = serde_json::from_str(json).unwrap();

        // Verify both unsupported fields were captured
        assert!(
            request
                .unsupported_fields
                .contains_key("add_special_tokens")
        );
        assert!(request.unsupported_fields.contains_key("response_format"));

        let result = validate_completion_fields_generic(&request);
        assert!(result.is_err());
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::BAD_REQUEST);
            let msg = &error_response.1.message;
            assert!(msg.contains("Unsupported parameter"));
            // Verify both fields appear in error message
            assert!(msg.contains("add_special_tokens"));
            assert!(msg.contains("response_format"));
        }
    }
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383

    #[tokio::test]
    async fn test_check_for_backend_error_with_error_event() {
        use crate::types::openai::chat_completions::NvCreateChatCompletionStreamResponse;
        use futures::stream;

        // Create an error event
        let error_event = Annotated::<NvCreateChatCompletionStreamResponse> {
            data: None,
            id: None,
            event: Some("error".to_string()),
            comment: Some(vec!["Backend service unavailable".to_string()]),
        };

        let test_stream = stream::iter(vec![error_event]);
        let result = check_for_backend_error(test_stream).await;

        // Should return an error
        assert!(result.is_err());
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::INTERNAL_SERVER_ERROR);
            assert_eq!(error_response.1.message, "Backend service unavailable");
        }
    }

    #[tokio::test]
    async fn test_check_for_backend_error_with_json_error_and_code() {
        use crate::types::openai::chat_completions::NvCreateChatCompletionStreamResponse;
        use futures::stream;

        // Create an error event with JSON payload containing error code in comment
        let error_json =
            r#"{"message":"prompt > max_seq_len","type":"Internal Server Error","code":500}"#;
        let error_event = Annotated::<NvCreateChatCompletionStreamResponse> {
            data: None,
            id: None,
            event: Some("error".to_string()),
            comment: Some(vec![error_json.to_string()]),
        };

        let test_stream = stream::iter(vec![error_event]);
        let result = check_for_backend_error(test_stream).await;

        // Should return an error with correct status code extracted from JSON
        assert!(result.is_err());
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::INTERNAL_SERVER_ERROR);
            assert_eq!(error_response.1.message, "prompt > max_seq_len");
            assert_eq!(error_response.1.code, 500);
        }
    }

    #[tokio::test]
    async fn test_check_for_backend_error_with_normal_event() {
        use crate::types::openai::chat_completions::NvCreateChatCompletionStreamResponse;
        use dynamo_async_openai::types::CreateChatCompletionStreamResponse;
        use futures::stream::{self, StreamExt};

        // Create a normal data event
        let normal_event = Annotated::<NvCreateChatCompletionStreamResponse> {
            data: Some(CreateChatCompletionStreamResponse {
                id: "test-id".to_string(),
                choices: vec![],
                created: 0,
                model: "test-model".to_string(),
                system_fingerprint: None,
                object: "chat.completion.chunk".to_string(),
                service_tier: None,
                usage: None,
                nvext: None,
            }),
            id: Some("msg-1".to_string()),
            event: None,
            comment: None,
        };

        let test_stream = stream::iter(vec![normal_event.clone()]);
        let result = check_for_backend_error(test_stream).await;

        // Should return Ok with the stream
        assert!(result.is_ok());
        let mut returned_stream = result.unwrap();

        // Verify we can read the event back from the stream
        let first = returned_stream.next().await;
        assert!(first.is_some());
        let first_event = first.unwrap();
        assert_eq!(first_event.id, Some("msg-1".to_string()));
    }

    #[tokio::test]
    async fn test_check_for_backend_error_with_empty_stream() {
        use crate::types::openai::chat_completions::NvCreateChatCompletionStreamResponse;
        use futures::stream::{self, StreamExt};

        // Create an empty stream
        let test_stream =
            stream::iter::<Vec<Annotated<NvCreateChatCompletionStreamResponse>>>(vec![]);
        let result = check_for_backend_error(test_stream).await;

        // Should return Ok with an empty stream
        assert!(result.is_ok());
        let mut returned_stream = result.unwrap();

        // Verify stream is empty
        let first = returned_stream.next().await;
        assert!(first.is_none());
    }

    #[tokio::test]
    async fn test_check_for_backend_error_with_comment_but_no_event_type() {
        use crate::types::openai::chat_completions::NvCreateChatCompletionStreamResponse;
        use futures::stream;

        // Create an event with comment but no event type and no data (error indicator)
        let error_event = Annotated::<NvCreateChatCompletionStreamResponse> {
            data: None,
            id: None,
            event: None,
            comment: Some(vec!["Connection timeout".to_string()]),
        };

        let test_stream = stream::iter(vec![error_event]);
        let result = check_for_backend_error(test_stream).await;

        // Should return an error based on is_backend_error_event logic
        assert!(result.is_err());
        if let Err(error_response) = result {
            assert_eq!(error_response.0, StatusCode::INTERNAL_SERVER_ERROR);
            assert_eq!(error_response.1.message, "Connection timeout");
        }
    }
2384
}