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

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

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

use super::{
Ryan Olson's avatar
Ryan Olson committed
28
    disconnect::{create_connection_monitor, monitor_for_disconnects, ConnectionHandle},
29
    error::HttpError,
Ryan Olson's avatar
Ryan Olson committed
30
    metrics::{Endpoint, ResponseMetricCollector},
31
    service_v2, RouteDoc,
32
};
33
use crate::preprocessor::LLMMetricAnnotation;
34
use crate::protocols::openai::{
35
36
37
38
    chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionResponse},
    completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
    embeddings::{NvCreateEmbeddingRequest, NvCreateEmbeddingResponse},
    responses::{NvCreateResponse, NvResponse},
39
};
40
use crate::request_template::RequestTemplate;
41
use crate::types::Annotated;
42
43
use dynamo_runtime::logging::get_distributed_tracing_context;
use tracing::Instrument;
44

Ryan Olson's avatar
Ryan Olson committed
45
46
47
48
49
50
51
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";

pub type ErrorResponse = (StatusCode, Json<ErrorMessage>);

52
#[derive(Serialize, Deserialize)]
Ryan Olson's avatar
Ryan Olson committed
53
pub(crate) struct ErrorMessage {
54
55
56
    error: String,
}

Ryan Olson's avatar
Ryan Olson committed
57
impl ErrorMessage {
58
    /// Not Found Error
Ryan Olson's avatar
Ryan Olson committed
59
    pub fn model_not_found() -> ErrorResponse {
60
61
        (
            StatusCode::NOT_FOUND,
Ryan Olson's avatar
Ryan Olson committed
62
            Json(ErrorMessage {
63
64
65
66
67
68
69
                error: "Model not found".to_string(),
            }),
        )
    }

    /// Service Unavailable
    /// This is returned when the service is live, but not ready.
Ryan Olson's avatar
Ryan Olson committed
70
    pub fn _service_unavailable() -> ErrorResponse {
71
72
        (
            StatusCode::SERVICE_UNAVAILABLE,
Ryan Olson's avatar
Ryan Olson committed
73
            Json(ErrorMessage {
74
75
76
77
78
79
80
81
82
                error: "Service is not ready".to_string(),
            }),
        )
    }

    /// 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
83
    pub fn internal_server_error(msg: &str) -> ErrorResponse {
84
85
86
        tracing::error!("Internal server error: {msg}");
        (
            StatusCode::INTERNAL_SERVER_ERROR,
Ryan Olson's avatar
Ryan Olson committed
87
            Json(ErrorMessage {
88
89
90
91
92
                error: msg.to_string(),
            }),
        )
    }

93
94
95
    /// Not Implemented Error
    /// Return this error when the client requests a feature that is not yet implemented.
    /// This should be used for features that are planned but not available.
Ryan Olson's avatar
Ryan Olson committed
96
    pub fn not_implemented_error(msg: &str) -> ErrorResponse {
97
98
99
        tracing::error!("Not Implemented error: {msg}");
        (
            StatusCode::NOT_IMPLEMENTED,
Ryan Olson's avatar
Ryan Olson committed
100
            Json(ErrorMessage {
101
102
103
104
105
                error: msg.to_string(),
            }),
        )
    }

Neelay Shah's avatar
Neelay Shah committed
106
    /// The OAI endpoints call an [`dynamo.runtime::engine::AsyncEngine`] which are specialized to return
107
    /// an [`anyhow::Error`]. This method will convert the [`anyhow::Error`] into an [`HttpError`].
Ryan Olson's avatar
Ryan Olson committed
108
    /// If successful, it will return the [`HttpError`] as an [`ErrorMessage::internal_server_error`]
109
    /// with the details of the error.
Ryan Olson's avatar
Ryan Olson committed
110
    pub fn from_anyhow(err: anyhow::Error, alt_msg: &str) -> ErrorResponse {
111
        match err.downcast::<HttpError>() {
Ryan Olson's avatar
Ryan Olson committed
112
113
            Ok(http_error) => ErrorMessage::from_http_error(http_error),
            Err(err) => ErrorMessage::internal_server_error(&format!("{alt_msg}: {err}")),
114
115
116
117
        }
    }

    /// Implementers should only be able to throw 400-499 errors.
Ryan Olson's avatar
Ryan Olson committed
118
    pub fn from_http_error(err: HttpError) -> ErrorResponse {
119
        if err.code < 400 || err.code >= 500 {
Ryan Olson's avatar
Ryan Olson committed
120
            return ErrorMessage::internal_server_error(&err.message);
121
122
        }
        match StatusCode::from_u16(err.code) {
Ryan Olson's avatar
Ryan Olson committed
123
124
            Ok(code) => (code, Json(ErrorMessage { error: err.message })),
            Err(_) => ErrorMessage::internal_server_error(&err.message),
125
126
127
128
        }
    }
}

Ryan Olson's avatar
Ryan Olson committed
129
impl From<HttpError> for ErrorMessage {
130
    fn from(err: HttpError) -> Self {
Ryan Olson's avatar
Ryan Olson committed
131
        ErrorMessage { error: err.message }
132
133
134
    }
}

Ryan Olson's avatar
Ryan Olson committed
135
136
/// Get the request ID from a primary source, or next from the headers, or lastly create a new one if not present
fn get_or_create_request_id(primary: Option<&str>, headers: &HeaderMap) -> String {
137
138
139
140
141
142
143
    // Try to get request id from trace context
    if let Some(trace_context) = get_distributed_tracing_context() {
        if let Some(x_dynamo_request_id) = trace_context.x_dynamo_request_id {
            return x_dynamo_request_id;
        }
    }

Ryan Olson's avatar
Ryan Olson committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    // Try to get the request ID from the primary source
    if let Some(primary) = primary {
        if let Ok(uuid) = uuid::Uuid::parse_str(primary) {
            return uuid.to_string();
        }
    }

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

167
168
169
170
171
172
173
174
/// 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
175
async fn handler_completions(
176
    State(state): State<Arc<service_v2::State>>,
Ryan Olson's avatar
Ryan Olson committed
177
    headers: HeaderMap,
178
    Json(request): Json<NvCreateCompletionRequest>,
Ryan Olson's avatar
Ryan Olson committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
) -> 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
    let (mut connection_handle, stream_handle) = create_connection_monitor(context.clone()).await;

    // possibly long running task
    // if this returns a streaming response, the stream handle will be armed and captured by the response stream
193
    let response = tokio::spawn(completions(state, request, stream_handle).in_current_span())
Ryan Olson's avatar
Ryan Olson committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        .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> {
215
216
217
218
219
220
221
    // return a 503 if the service is not ready
    check_ready(&state)?;

    // todo - extract distributed tracing id and context id from headers
    let request_id = uuid::Uuid::new_v4().to_string();

    // todo - decide on default
222
    let streaming = request.inner.stream.unwrap_or(false);
223
224

    // update the request to always stream
Ryan Olson's avatar
Ryan Olson committed
225
226
227
228
    let request = request.map(|mut req| {
        req.inner.stream = Some(true);
        req
    });
229

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

    // todo - error handling should be more robust
    let engine = state
236
        .manager()
237
        .get_completions_engine(model)
Ryan Olson's avatar
Ryan Olson committed
238
        .map_err(|_| ErrorMessage::model_not_found())?;
239

240
    let mut inflight_guard =
241
242
243
        state
            .metrics_clone()
            .create_inflight_guard(model, Endpoint::Completions, streaming);
244

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

Ryan Olson's avatar
Ryan Olson committed
247
248
    // prepare to process any annotations
    let annotations = request.annotations();
249
250
251
252
253

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

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

Ryan Olson's avatar
Ryan Olson committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    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);
278
279

    if streaming {
280
281
282
        let stream = stream.map(move |response| {
            process_event_converter(EventConverter::from(response), &mut response_collector)
        });
Ryan Olson's avatar
Ryan Olson committed
283
        let stream = monitor_for_disconnects(stream, ctx, inflight_guard, stream_handle);
284

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

287
        if let Some(keep_alive) = state.sse_keep_alive() {
288
289
290
291
            sse_stream = sse_stream.keep_alive(KeepAlive::default().interval(keep_alive));
        }

        Ok(sse_stream.into_response())
292
    } else {
293
294
295
296
297
        // Tap the stream to collect metrics for non-streaming requests without altering items
        let stream = stream.inspect(move |response| {
            process_metrics_only(response, &mut response_collector);
        });

Ryan Olson's avatar
Ryan Olson committed
298
        let response = NvCreateCompletionResponse::from_annotated_stream(stream)
299
300
301
302
303
304
305
            .await
            .map_err(|e| {
                tracing::error!(
                    "Failed to fold completions stream for {}: {:?}",
                    request_id,
                    e
                );
Ryan Olson's avatar
Ryan Olson committed
306
                ErrorMessage::internal_server_error("Failed to fold completions stream")
307
308
            })?;

309
        inflight_guard.mark_ok();
310
311
312
313
        Ok(Json(response).into_response())
    }
}

314
315
#[tracing::instrument(skip_all)]
async fn embeddings(
316
317
    State(state): State<Arc<service_v2::State>>,
    Json(request): Json<NvCreateEmbeddingRequest>,
Ryan Olson's avatar
Ryan Olson committed
318
) -> Result<Response, ErrorResponse> {
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
    // return a 503 if the service is not ready
    check_ready(&state)?;

    // todo - extract distributed tracing id and context id from headers
    let request_id = uuid::Uuid::new_v4().to_string();

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

    // todo - error handling should be more robust
    let engine = state
        .manager()
        .get_embeddings_engine(model)
Ryan Olson's avatar
Ryan Olson committed
336
        .map_err(|_| ErrorMessage::model_not_found())?;
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351

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

    // setup context
    // todo - inherit request_id from distributed trace details
    let request = Context::with_id(request, request_id.clone());

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

    // 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
356
    let response = NvCreateEmbeddingResponse::from_annotated_stream(stream)
357
358
359
360
361
362
363
        .await
        .map_err(|e| {
            tracing::error!(
                "Failed to fold embeddings stream for {}: {:?}",
                request_id,
                e
            );
Ryan Olson's avatar
Ryan Olson committed
364
            ErrorMessage::internal_server_error("Failed to fold embeddings stream")
365
366
367
368
        })?;

    inflight.mark_ok();
    Ok(Json(response).into_response())
369
370
}

Ryan Olson's avatar
Ryan Olson committed
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
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
    let (mut connection_handle, stream_handle) = create_connection_monitor(context.clone()).await;

387
388
389
390
391
392
393
394
395
    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
396
397
398
399
400
401
402
403

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

404
405
406
407
408
409
410
411
412
/// 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
413
414
415
416
417
    state: Arc<service_v2::State>,
    template: Option<RequestTemplate>,
    mut request: Context<NvCreateChatCompletionRequest>,
    mut stream_handle: ConnectionHandle,
) -> Result<Response, ErrorResponse> {
418
419
420
    // return a 503 if the service is not ready
    check_ready(&state)?;

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

423
424
425
426
    // 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
427
    validate_chat_completion_unsupported_fields(&request)?;
428

429
430
431
    // Handle required fields like messages shouldn't be empty.
    validate_chat_completion_required_fields(&request)?;

432
433
434
435
436
437
438
439
440
441
442
443
    // 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
444
    tracing::trace!("Received chat completions request: {:?}", request.content());
445
446

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

    // update the request to always stream
Ryan Olson's avatar
Ryan Olson committed
450
451
452
453
    let request = request.map(|mut req| {
        req.inner.stream = Some(true);
        req
    });
454
455
456

    // todo - make the protocols be optional for model name
    // todo - when optional, if none, apply a default
Paul Hendricks's avatar
Paul Hendricks committed
457
    let model = &request.inner.model;
458
459
460
461
462

    // todo - determine the proper error code for when a request model is not present
    tracing::trace!("Getting chat completions engine for model: {}", model);

    let engine = state
463
        .manager()
464
        .get_chat_completions_engine(model)
Ryan Olson's avatar
Ryan Olson committed
465
        .map_err(|_| ErrorMessage::model_not_found())?;
466

467
    let mut inflight_guard =
468
469
470
        state
            .metrics_clone()
            .create_inflight_guard(model, Endpoint::ChatCompletions, streaming);
471

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

474
    tracing::trace!("Issuing generate call for chat completions");
Ryan Olson's avatar
Ryan Olson committed
475
    let annotations = request.annotations();
476
477
478
479
480

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

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

Ryan Olson's avatar
Ryan Olson committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    // 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);

503
504
505
506
    // 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 {
Ryan Olson's avatar
Ryan Olson committed
507
508
        stream_handle.arm();

509
510
511
        let stream = stream.map(move |response| {
            process_event_converter(EventConverter::from(response), &mut response_collector)
        });
Ryan Olson's avatar
Ryan Olson committed
512
        let stream = monitor_for_disconnects(stream, ctx, inflight_guard, stream_handle);
513

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

516
        if let Some(keep_alive) = state.sse_keep_alive() {
517
518
519
520
            sse_stream = sse_stream.keep_alive(KeepAlive::default().interval(keep_alive));
        }

        Ok(sse_stream.into_response())
521
    } else {
522
523
524
525
        let stream = stream.inspect(move |response| {
            process_metrics_only(response, &mut response_collector);
        });

Ryan Olson's avatar
Ryan Olson committed
526
        let response = NvCreateChatCompletionResponse::from_annotated_stream(stream)
527
528
529
530
531
532
533
            .await
            .map_err(|e| {
                tracing::error!(
                    request_id,
                    "Failed to fold chat completions stream for: {:?}",
                    e
                );
Ryan Olson's avatar
Ryan Olson committed
534
                ErrorMessage::internal_server_error(&format!(
535
536
537
538
539
                    "Failed to fold chat completions stream: {}",
                    e
                ))
            })?;

540
        inflight_guard.mark_ok();
541
542
543
544
        Ok(Json(response).into_response())
    }
}

545
546
547
548
549
/// 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
550
) -> Result<(), ErrorResponse> {
551
552
553
    let inner = &request.inner;

    if inner.parallel_tool_calls == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
554
        return Err(ErrorMessage::not_implemented_error(
555
556
557
558
559
            "`parallel_tool_calls: true` is not supported.",
        ));
    }

    if inner.stream == Some(true) && inner.tools.is_some() {
Ryan Olson's avatar
Ryan Olson committed
560
        return Err(ErrorMessage::not_implemented_error(
561
562
563
564
565
            "`stream: true` is not supported when `tools` are provided.",
        ));
    }

    if inner.function_call.is_some() {
Ryan Olson's avatar
Ryan Olson committed
566
        return Err(ErrorMessage::not_implemented_error(
567
568
569
570
571
            "`function_call` is deprecated. Please migrate to use `tool_choice` instead.",
        ));
    }

    if inner.functions.is_some() {
Ryan Olson's avatar
Ryan Olson committed
572
        return Err(ErrorMessage::not_implemented_error(
573
574
575
576
            "`functions` is deprecated. Please migrate to use `tools` instead.",
        ));
    }

Ryan Olson's avatar
Ryan Olson committed
577
    Ok(())
578
579
}

580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/// Validates that required fields are present and valid in the chat completion request
pub fn validate_chat_completion_required_fields(
    request: &NvCreateChatCompletionRequest,
) -> Result<(), ErrorResponse> {
    let inner = &request.inner;

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

    Ok(())
}

597
598
599
/// OpenAI Responses Request Handler
///
/// This method will handle the incoming request for the /v1/responses endpoint.
Ryan Olson's avatar
Ryan Olson committed
600
async fn handler_responses(
601
    State((state, template)): State<(Arc<service_v2::State>, Option<RequestTemplate>)>,
Ryan Olson's avatar
Ryan Olson committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
    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
    let (mut connection_handle, _stream_handle) = create_connection_monitor(context.clone()).await;

616
    let response = tokio::spawn(responses(state, template, request).in_current_span())
Ryan Olson's avatar
Ryan Olson committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
        .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> {
638
639
640
641
642
643
    // return a 503 if the service is not ready
    check_ready(&state)?;

    // 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.
644
    if let Some(resp) = validate_response_unsupported_fields(&request) {
645
646
647
648
649
650
651
        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.
652
    if let Some(resp) = validate_response_input_is_text_only(&request) {
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
        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
670
671
    let request_id = request.id().to_string();
    let (request, context) = request.into_parts();
672

Ryan Olson's avatar
Ryan Olson committed
673
    let mut request: NvCreateChatCompletionRequest = request.try_into().map_err(|e| {
674
675
676
677
678
        tracing::error!(
            request_id,
            "Failed to convert NvCreateResponse to NvCreateChatCompletionRequest: {:?}",
            e
        );
Ryan Olson's avatar
Ryan Olson committed
679
        ErrorMessage::not_implemented_error(&format!(
680
681
682
683
684
            "Only Input::Text(_) is currently supported: {}",
            e
        ))
    })?;

Ryan Olson's avatar
Ryan Olson committed
685
686
687
688
689
    let request = context.map(|mut _req| {
        request.inner.stream = Some(false);
        request
    });

690
691
692
693
694
695
696
    let model = &request.inner.model;

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

    let engine = state
        .manager()
        .get_chat_completions_engine(model)
Ryan Olson's avatar
Ryan Olson committed
697
        .map_err(|_| ErrorMessage::model_not_found())?;
698
699
700
701
702
703
704
705
706
707
708
709
710
711

    let mut inflight_guard =
        state
            .metrics_clone()
            .create_inflight_guard(model, Endpoint::Responses, false);

    let _response_collector = state.metrics_clone().create_response_collector(model);

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

    // TODO: handle streaming, currently just unary
Ryan Olson's avatar
Ryan Olson committed
715
    let response = NvCreateChatCompletionResponse::from_annotated_stream(stream)
716
717
718
719
720
721
722
        .await
        .map_err(|e| {
            tracing::error!(
                request_id,
                "Failed to fold chat completions stream for: {:?}",
                e
            );
Ryan Olson's avatar
Ryan Olson committed
723
            ErrorMessage::internal_server_error(&format!(
724
725
726
727
728
729
730
731
732
733
734
735
                "Failed to fold chat completions stream: {}",
                e
            ))
        })?;

    // 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
736
        ErrorMessage::internal_server_error("Failed to convert internal response")
737
738
739
740
741
742
743
    })?;

    inflight_guard.mark_ok();

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

744
745
746
pub fn validate_response_input_is_text_only(
    request: &NvCreateResponse,
) -> Option<impl IntoResponse> {
747
748
    match &request.inner.input {
        async_openai::types::responses::Input::Text(_) => None,
Ryan Olson's avatar
Ryan Olson committed
749
        _ => Some(ErrorMessage::not_implemented_error("Only `Input::Text` is supported. Structured, multimedia, or custom input types are not yet implemented.")),
750
751
752
753
754
    }
}

/// Checks for unsupported fields in the request.
/// Returns Some(response) if unsupported fields are present.
755
756
757
pub fn validate_response_unsupported_fields(
    request: &NvCreateResponse,
) -> Option<impl IntoResponse> {
758
759
760
    let inner = &request.inner;

    if inner.background == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
761
        return Some(ErrorMessage::not_implemented_error(
762
763
764
765
            "`background: true` is not supported.",
        ));
    }
    if inner.include.is_some() {
Ryan Olson's avatar
Ryan Olson committed
766
        return Some(ErrorMessage::not_implemented_error(
767
768
769
770
            "`include` is not supported.",
        ));
    }
    if inner.instructions.is_some() {
Ryan Olson's avatar
Ryan Olson committed
771
        return Some(ErrorMessage::not_implemented_error(
772
773
774
775
            "`instructions` is not supported.",
        ));
    }
    if inner.max_tool_calls.is_some() {
Ryan Olson's avatar
Ryan Olson committed
776
        return Some(ErrorMessage::not_implemented_error(
777
778
779
780
            "`max_tool_calls` is not supported.",
        ));
    }
    if inner.metadata.is_some() {
Ryan Olson's avatar
Ryan Olson committed
781
        return Some(ErrorMessage::not_implemented_error(
782
783
784
785
            "`metadata` is not supported.",
        ));
    }
    if inner.parallel_tool_calls == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
786
        return Some(ErrorMessage::not_implemented_error(
787
788
789
790
            "`parallel_tool_calls: true` is not supported.",
        ));
    }
    if inner.previous_response_id.is_some() {
Ryan Olson's avatar
Ryan Olson committed
791
        return Some(ErrorMessage::not_implemented_error(
792
793
794
795
            "`previous_response_id` is not supported.",
        ));
    }
    if inner.prompt.is_some() {
Ryan Olson's avatar
Ryan Olson committed
796
        return Some(ErrorMessage::not_implemented_error(
797
798
799
800
            "`prompt` is not supported.",
        ));
    }
    if inner.reasoning.is_some() {
Ryan Olson's avatar
Ryan Olson committed
801
        return Some(ErrorMessage::not_implemented_error(
802
803
804
805
            "`reasoning` is not supported.",
        ));
    }
    if inner.service_tier.is_some() {
Ryan Olson's avatar
Ryan Olson committed
806
        return Some(ErrorMessage::not_implemented_error(
807
808
809
810
            "`service_tier` is not supported.",
        ));
    }
    if inner.store == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
811
        return Some(ErrorMessage::not_implemented_error(
812
813
814
815
            "`store: true` is not supported.",
        ));
    }
    if inner.stream == Some(true) {
Ryan Olson's avatar
Ryan Olson committed
816
        return Some(ErrorMessage::not_implemented_error(
817
818
819
820
            "`stream: true` is not supported.",
        ));
    }
    if inner.text.is_some() {
Ryan Olson's avatar
Ryan Olson committed
821
        return Some(ErrorMessage::not_implemented_error(
822
823
824
825
            "`text` is not supported.",
        ));
    }
    if inner.tool_choice.is_some() {
Ryan Olson's avatar
Ryan Olson committed
826
        return Some(ErrorMessage::not_implemented_error(
827
828
829
830
            "`tool_choice` is not supported.",
        ));
    }
    if inner.tools.is_some() {
Ryan Olson's avatar
Ryan Olson committed
831
        return Some(ErrorMessage::not_implemented_error(
832
833
834
835
            "`tools` is not supported.",
        ));
    }
    if inner.truncation.is_some() {
Ryan Olson's avatar
Ryan Olson committed
836
        return Some(ErrorMessage::not_implemented_error(
837
838
839
840
            "`truncation` is not supported.",
        ));
    }
    if inner.user.is_some() {
Ryan Olson's avatar
Ryan Olson committed
841
        return Some(ErrorMessage::not_implemented_error(
842
843
844
845
846
847
848
            "`user` is not supported.",
        ));
    }

    None
}

849
850
// 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
851
fn check_ready(_state: &Arc<service_v2::State>) -> Result<(), ErrorResponse> {
852
    // if state.service_observer.stage() != ServiceStage::Ready {
Ryan Olson's avatar
Ryan Olson committed
853
    //     return Err(ErrorMessage::service_unavailable());
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
    // }
    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(
872
    State(state): State<Arc<service_v2::State>>,
Ryan Olson's avatar
Ryan Olson committed
873
) -> Result<Response, ErrorResponse> {
874
875
876
877
878
879
880
881
    check_ready(&state)?;

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

882
883
    let models: HashSet<String> = state.manager().model_display_names();
    for model_name in models {
884
        data.push(ModelListing {
885
            id: model_name.clone(),
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
            object: "object",
            created,                        // Where would this come from? The GGUF?
            owned_by: "nvidia".to_string(), // Get organization from GGUF
        });
    }

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

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

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

struct EventConverter<T>(Annotated<T>);

impl<T> From<Annotated<T>> for EventConverter<T> {
    fn from(annotated: Annotated<T>) -> Self {
        EventConverter(annotated)
    }
}

921
922
923
924
925
926
927
928
929
930
931
fn process_metrics_only<T>(
    annotated: &Annotated<T>,
    response_collector: &mut ResponseMetricCollector,
) {
    // update metrics
    if let Ok(Some(metrics)) = LLMMetricAnnotation::from_annotation(annotated) {
        response_collector.observe_current_osl(metrics.output_tokens);
        response_collector.observe_response(metrics.input_tokens, metrics.chunk_tokens);
    }
}

932
933
934
935
fn process_event_converter<T: Serialize>(
    annotated: EventConverter<T>,
    response_collector: &mut ResponseMetricCollector,
) -> Result<Event, axum::Error> {
936
    let mut annotated = annotated.0;
937

938
939
940
941
    // update metrics
    if let Ok(Some(metrics)) = LLMMetricAnnotation::from_annotation(&annotated) {
        response_collector.observe_current_osl(metrics.output_tokens);
        response_collector.observe_response(metrics.input_tokens, metrics.chunk_tokens);
942
943
944
945
946
947
948

        // Chomp the LLMMetricAnnotation so it's not returned in the response stream
        // TODO: add a flag to control what is returned in the SSE stream
        if annotated.event.as_deref() == Some(crate::preprocessor::ANNOTATION_LLM_METRICS) {
            annotated.event = None;
            annotated.comment = None;
        }
949
950
    }

951
    let mut event = Event::default();
952

953
954
955
    if let Some(data) = annotated.data {
        event = event.json_data(data)?;
    }
956

957
958
959
960
961
962
    if let Some(msg) = annotated.event {
        if msg == "error" {
            let msgs = annotated
                .comment
                .unwrap_or_else(|| vec!["unspecified error".to_string()]);
            return Err(axum::Error::new(msgs.join(" -- ")));
963
        }
964
965
        event = event.event(msg);
    }
966

967
968
969
970
    if let Some(comments) = annotated.comment {
        for comment in comments {
            event = event.comment(comment);
        }
971
    }
972
973

    Ok(event)
974
975
976
977
978
}

/// 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(
979
    state: Arc<service_v2::State>,
980
981
982
983
984
    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
985
        .route(&path, post(handler_completions))
986
987
988
989
990
991
992
        .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(
993
    state: Arc<service_v2::State>,
994
    template: Option<RequestTemplate>,
995
996
997
998
999
    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
1000
        .route(&path, post(handler_chat_completions))
1001
        .with_state((state, template));
1002
1003
1004
    (vec![doc], router)
}

1005
1006
1007
/// 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(
1008
    state: Arc<service_v2::State>,
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
    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))
        .with_state(state);
    (vec![doc], router)
}

1019
1020
/// List Models
pub fn list_models_router(
1021
    state: Arc<service_v2::State>,
1022
1023
1024
    path: Option<String>,
) -> (Vec<RouteDoc>, Router) {
    // Standard OpenAI compatible list models endpoint
1025
    let openai_path = path.unwrap_or("/v1/models".to_string());
1026
1027
1028
1029
1030
1031
    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);

1032
    (vec![doc_for_openai], router)
1033
1034
}

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
/// 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
1045
        .route(&path, post(handler_responses))
1046
1047
1048
1049
        .with_state((state, template));
    (vec![doc], router)
}

1050
1051
#[cfg(test)]
mod tests {
1052
1053
1054
1055
1056
1057
1058
    use std::collections::HashMap;

    use async_openai::types::responses::{
        CreateResponse, Input, InputContent, InputItem, InputMessage, PromptConfig,
        Role as ResponseRole, ServiceTier, TextConfig, TextResponseFormat, ToolChoice,
        ToolChoiceMode, Truncation,
    };
1059
1060
1061
1062
    use async_openai::types::{
        ChatCompletionRequestMessage, ChatCompletionRequestUserMessage,
        ChatCompletionRequestUserMessageContent, CreateChatCompletionRequest,
    };
1063
1064

    use super::*;
1065
1066
    use crate::discovery::ModelManagerError;
    use crate::protocols::openai::responses::NvCreateResponse;
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077

    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> {
1078
        Err(ModelManagerError::ModelNotFound("foo".to_string()))?
1079
1080
    }

1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
    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,
        }
    }

1112
1113
1114
    #[test]
    fn test_http_error_response_from_anyhow() {
        let err = http_error_from_engine(400).unwrap_err();
Ryan Olson's avatar
Ryan Olson committed
1115
        let (status, response) = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
1116
1117
1118
1119
1120
1121
1122
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(response.error, "custom error message");
    }

    #[test]
    fn test_error_response_from_anyhow_out_of_range() {
        let err = http_error_from_engine(399).unwrap_err();
Ryan Olson's avatar
Ryan Olson committed
1123
        let (status, response) = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
1124
1125
1126
1127
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(response.error, "custom error message");

        let err = http_error_from_engine(500).unwrap_err();
Ryan Olson's avatar
Ryan Olson committed
1128
        let (status, response) = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
1129
1130
1131
1132
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(response.error, "custom error message");

        let err = http_error_from_engine(501).unwrap_err();
Ryan Olson's avatar
Ryan Olson committed
1133
        let (status, response) = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
1134
1135
1136
1137
1138
1139
1140
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(response.error, "custom error message");
    }

    #[test]
    fn test_other_error_response_from_anyhow() {
        let err = other_error_from_engine().unwrap_err();
Ryan Olson's avatar
Ryan Olson committed
1141
        let (status, response) = ErrorMessage::from_anyhow(err, BACKUP_ERROR_MESSAGE);
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(
            response.error,
            format!(
                "{}: {}",
                BACKUP_ERROR_MESSAGE,
                other_error_from_engine().unwrap_err()
            )
        );
    }
1152
1153
1154
1155

    #[test]
    fn test_validate_input_is_text_only_accepts_text() {
        let request = make_base_request();
1156
        let result = validate_response_input_is_text_only(&request);
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
        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()),
        })]);
1168
        let result = validate_response_input_is_text_only(&request);
1169
1170
1171
1172
1173
1174
        assert!(result.is_some());
    }

    #[test]
    fn test_validate_unsupported_fields_accepts_clean_request() {
        let request = make_base_request();
1175
        let result = validate_response_unsupported_fields(&request);
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
        assert!(result.is_none());
    }

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

        for (field, set_field) in unsupported_cases {
            let mut req = make_base_request();
            (set_field)(&mut req.inner);
1245
            let result = validate_response_unsupported_fields(&req);
1246
1247
1248
            assert!(result.is_some(), "Expected rejection for `{field}`");
        }
    }
1249
1250
1251
1252
1253
1254
1255
1256
1257

    #[test]
    fn test_validate_chat_completion_required_fields_empty_messages() {
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![],
                ..Default::default()
            },
1258
            common: Default::default(),
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
            nvext: None,
        };
        let result = validate_chat_completion_required_fields(&request);
        assert!(result.is_err());
        if let Err((status, error_response)) = result {
            assert_eq!(status, StatusCode::BAD_REQUEST);
            assert_eq!(
                error_response.error,
                "The 'messages' field cannot be empty. At least one message is required."
            );
        }
    }

    #[test]
    fn test_validate_chat_completion_required_fields_with_messages() {
        let request = NvCreateChatCompletionRequest {
            inner: CreateChatCompletionRequest {
                model: "test-model".to_string(),
                messages: vec![ChatCompletionRequestMessage::User(
                    ChatCompletionRequestUserMessage {
                        content: ChatCompletionRequestUserMessageContent::Text("Hello".to_string()),
                        name: None,
                    },
                )],
                ..Default::default()
            },
1285
            common: Default::default(),
1286
1287
1288
1289
1290
            nvext: None,
        };
        let result = validate_chat_completion_required_fields(&request);
        assert!(result.is_ok());
    }
1291
}