http-service.rs 13.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use anyhow::Error;
use async_stream::stream;
Neelay Shah's avatar
Neelay Shah committed
18
use dynamo_llm::http::service::{
19
20
21
22
23
    error::HttpError,
    metrics::{Endpoint, RequestType, Status},
    service_v2::HttpService,
    Metrics,
};
Neelay Shah's avatar
Neelay Shah committed
24
use dynamo_llm::protocols::{
25
    openai::{
26
        chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse},
27
        completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
28
29
30
    },
    Annotated,
};
Neelay Shah's avatar
Neelay Shah committed
31
use dynamo_runtime::{
32
33
34
35
36
    pipeline::{
        async_trait, AsyncEngine, AsyncEngineContextProvider, ManyOut, ResponseStream, SingleIn,
    },
    CancellationToken,
};
37
38
39
use prometheus::{proto::MetricType, Registry};
use reqwest::StatusCode;
use std::sync::Arc;
40
41
42

struct CounterEngine {}

Paul Hendricks's avatar
Paul Hendricks committed
43
#[allow(deprecated)]
44
45
46
#[async_trait]
impl
    AsyncEngine<
47
        SingleIn<NvCreateChatCompletionRequest>,
48
        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
49
50
51
52
53
        Error,
    > for CounterEngine
{
    async fn generate(
        &self,
54
        request: SingleIn<NvCreateChatCompletionRequest>,
55
    ) -> Result<ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>, Error> {
56
57
58
        let (request, context) = request.transfer(());
        let ctx = context.context();

Paul Hendricks's avatar
Paul Hendricks committed
59
60
        // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
        let max_tokens = request.inner.max_tokens.unwrap_or(0) as u64;
61

62
        // let generator = NvCreateChatCompletionStreamResponse::generator(request.model.clone());
63
64
65
66
67
        let generator = request.response_generator();

        let stream = stream! {
            tokio::time::sleep(std::time::Duration::from_millis(max_tokens)).await;
            for i in 0..10 {
Paul Hendricks's avatar
Paul Hendricks committed
68
69
                let inner = generator.create_choice(i,Some(format!("choice {i}")), None, None);

70
                let output = NvCreateChatCompletionStreamResponse {
Paul Hendricks's avatar
Paul Hendricks committed
71
72
73
74
                    inner,
                };

                yield Annotated::from_data(output);
75
76
77
78
79
80
81
82
83
84
85
86
            }
        };

        Ok(ResponseStream::new(Box::pin(stream), ctx))
    }
}

struct AlwaysFailEngine {}

#[async_trait]
impl
    AsyncEngine<
87
        SingleIn<NvCreateChatCompletionRequest>,
88
        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
89
90
91
92
93
        Error,
    > for AlwaysFailEngine
{
    async fn generate(
        &self,
94
        _request: SingleIn<NvCreateChatCompletionRequest>,
95
    ) -> Result<ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>, Error> {
96
97
98
99
100
101
102
103
        Err(HttpError {
            code: 403,
            message: "Always fail".to_string(),
        })?
    }
}

#[async_trait]
104
105
106
107
108
109
impl
    AsyncEngine<
        SingleIn<NvCreateCompletionRequest>,
        ManyOut<Annotated<NvCreateCompletionResponse>>,
        Error,
    > for AlwaysFailEngine
110
111
112
{
    async fn generate(
        &self,
113
        _request: SingleIn<NvCreateCompletionRequest>,
114
    ) -> Result<ManyOut<Annotated<NvCreateCompletionResponse>>, Error> {
115
116
117
118
119
120
121
122
        Err(HttpError {
            code: 401,
            message: "Always fail".to_string(),
        })?
    }
}

fn compare_counter(
123
    metrics: &Metrics,
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    model: &str,
    endpoint: &Endpoint,
    request_type: &RequestType,
    status: &Status,
    expected: u64,
) {
    assert_eq!(
        metrics.get_request_counter(model, endpoint, request_type, status),
        expected,
        "model: {}, endpoint: {:?}, request_type: {:?}, status: {:?}",
        model,
        endpoint.as_str(),
        request_type.as_str(),
        status.as_str()
    );
}

fn compute_index(endpoint: &Endpoint, request_type: &RequestType, status: &Status) -> usize {
    let endpoint = match endpoint {
        Endpoint::Completions => 0,
        Endpoint::ChatCompletions => 1,
145
        Endpoint::Embeddings => todo!(),
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    };

    let request_type = match request_type {
        RequestType::Unary => 0,
        RequestType::Stream => 1,
    };

    let status = match status {
        Status::Success => 0,
        Status::Error => 1,
    };

    endpoint * 4 + request_type * 2 + status
}

161
fn compare_counters(metrics: &Metrics, model: &str, expected: &[u64; 8]) {
162
163
164
165
166
    for endpoint in &[Endpoint::Completions, Endpoint::ChatCompletions] {
        for request_type in &[RequestType::Unary, RequestType::Stream] {
            for status in &[Status::Success, Status::Error] {
                let index = compute_index(endpoint, request_type, status);
                compare_counter(
167
                    metrics,
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
                    model,
                    endpoint,
                    request_type,
                    status,
                    expected[index],
                );
            }
        }
    }
}

fn inc_counter(
    endpoint: Endpoint,
    request_type: RequestType,
    status: Status,
    expected: &mut [u64; 8],
) {
    let index = compute_index(&endpoint, &request_type, &status);
    expected[index] += 1;
}

Paul Hendricks's avatar
Paul Hendricks committed
189
#[allow(deprecated)]
190
191
#[tokio::test]
async fn test_http_service() {
192
    let service = HttpService::builder().port(8989).build().unwrap();
193
194
    let state = service.state_clone();
    let manager = state.manager();
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212

    let token = CancellationToken::new();
    let cancel_token = token.clone();
    let task = tokio::spawn(async move { service.run(token.clone()).await });

    let registry = Registry::new();

    let counter = Arc::new(CounterEngine {});
    let result = manager.add_chat_completions_model("foo", counter);
    assert!(result.is_ok());

    let failure = Arc::new(AlwaysFailEngine {});
    let result = manager.add_chat_completions_model("bar", failure.clone());
    assert!(result.is_ok());

    let result = manager.add_completions_model("bar", failure);
    assert!(result.is_ok());

213
    let metrics = state.metrics_clone();
214
215
216
217
218
    metrics.register(&registry).unwrap();

    let mut foo_counters = [0u64; 8];
    let mut bar_counters = [0u64; 8];

219
220
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
221
222
223

    let client = reqwest::Client::new();

Paul Hendricks's avatar
Paul Hendricks committed
224
225
226
227
228
229
230
231
232
233
    let message = async_openai::types::ChatCompletionRequestMessage::User(
        async_openai::types::ChatCompletionRequestUserMessage {
            content: async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                "hi".to_string(),
            ),
            name: None,
        },
    );

    let mut request = async_openai::types::CreateChatCompletionRequestArgs::default()
234
        .model("foo")
Paul Hendricks's avatar
Paul Hendricks committed
235
        .messages(vec![message])
236
        .build()
Paul Hendricks's avatar
Paul Hendricks committed
237
238
239
240
241
242
243
        .expect("Failed to build request");

    // let mut request = ChatCompletionRequest::builder()
    //     .model("foo")
    //     .add_user_message("hi")
    //     .build()
    //     .unwrap();
244
245
246

    // ==== ChatCompletions / Stream / Success ====
    request.stream = Some(true);
Paul Hendricks's avatar
Paul Hendricks committed
247
248

    // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    request.max_tokens = Some(3000);

    let response = client
        .post("http://localhost:8989/v1/chat/completions")
        .json(&request)
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success(), "{:?}", response);

    tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
    assert_eq!(metrics.get_inflight_count("foo"), 1);

    // process byte stream
    let _ = response.bytes().await.unwrap();

    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Stream,
        Status::Success,
        &mut foo_counters,
    );
272
273
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326

    // check registry and look or the request duration histogram
    let families = registry.gather();
    let histogram_metric_family = families
        .into_iter()
        .find(|m| m.get_name() == "nv_llm_http_service_request_duration_seconds")
        .expect("Histogram metric not found");

    assert_eq!(
        histogram_metric_family.get_field_type(),
        MetricType::HISTOGRAM
    );

    let histogram_metric = histogram_metric_family.get_metric();

    assert_eq!(histogram_metric.len(), 1); // We have one metric with label model

    let metric = &histogram_metric[0];
    let histogram = metric.get_histogram();

    let buckets = histogram.get_bucket();

    let mut found = false;

    for bucket in buckets {
        let upper_bound = bucket.get_upper_bound();
        let cumulative_count = bucket.get_cumulative_count();

        println!(
            "Bucket upper bound: {}, count: {}",
            upper_bound, cumulative_count
        );

        // Since our observation is 2.5, it should fall into the bucket with upper bound 4.0
        if upper_bound >= 4.0 {
            assert_eq!(
                cumulative_count, 1,
                "Observation should be counted in the 4.0 bucket"
            );
            found = true;
        } else {
            assert_eq!(
                cumulative_count, 0,
                "No observations should be in this bucket"
            );
        }
    }

    assert!(found, "The expected bucket was not found");
    // ==== ChatCompletions / Stream / Success ====

    // ==== ChatCompletions / Unary / Success ====
    request.stream = Some(false);
Paul Hendricks's avatar
Paul Hendricks committed
327
328

    // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
    request.max_tokens = Some(0);

    let future = client
        .post("http://localhost:8989/v1/chat/completions")
        .json(&request)
        .send();

    let response = future.await.unwrap();

    assert!(response.status().is_success(), "{:?}", response);
    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Unary,
        Status::Success,
        &mut foo_counters,
    );
345
346
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
347
348
349
350
    // ==== ChatCompletions / Unary / Success ====

    // ==== ChatCompletions / Stream / Error ====
    request.model = "bar".to_string();
Paul Hendricks's avatar
Paul Hendricks committed
351
352

    // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    request.max_tokens = Some(0);
    request.stream = Some(true);

    let response = client
        .post("http://localhost:8989/v1/chat/completions")
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Stream,
        Status::Error,
        &mut bar_counters,
    );
370
371
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    // ==== ChatCompletions / Stream / Error ====

    // ==== ChatCompletions / Unary / Error ====
    request.stream = Some(false);

    let response = client
        .post("http://localhost:8989/v1/chat/completions")
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Unary,
        Status::Error,
        &mut bar_counters,
    );
391
392
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
393
394
395
    // ==== ChatCompletions / Unary / Error ====

    // ==== Completions / Unary / Error ====
396
    let mut request = async_openai::types::CreateCompletionRequestArgs::default()
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        .model("bar")
        .prompt("hi")
        .build()
        .unwrap();

    let response = client
        .post("http://localhost:8989/v1/completions")
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    inc_counter(
        Endpoint::Completions,
        RequestType::Unary,
        Status::Error,
        &mut bar_counters,
    );
416
417
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
    // ==== Completions / Unary / Error ====

    // ==== Completions / Stream / Error ====
    request.stream = Some(true);

    let response = client
        .post("http://localhost:8989/v1/completions")
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    inc_counter(
        Endpoint::Completions,
        RequestType::Stream,
        Status::Error,
        &mut bar_counters,
    );
437
438
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    // ==== Completions / Stream / Error ====

    // =========== Test Invalid Request ===========
    // send a completion request to a chat endpoint
    request.stream = Some(false);

    let response = client
        .post("http://localhost:8989/v1/chat/completions")
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(
        response.status(),
        StatusCode::UNPROCESSABLE_ENTITY,
        "{:?}",
        response
    );

    // =========== Query /metrics endpoint ===========
    let response = client
        .get("http://localhost:8989/metrics")
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success(), "{:?}", response);
    println!("{}", response.text().await.unwrap());

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}