echo_full.rs 3.65 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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 std::{sync::Arc, time::Duration};

use async_stream::stream;
use async_trait::async_trait;

Neelay Shah's avatar
Neelay Shah committed
21
use dynamo_llm::protocols::openai::chat_completions::{
22
    NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
23
};
Neelay Shah's avatar
Neelay Shah committed
24
25
26
27
use dynamo_llm::types::openai::chat_completions::OpenAIChatCompletionsStreamingEngine;
use dynamo_runtime::engine::{AsyncEngine, AsyncEngineContextProvider, ResponseStream};
use dynamo_runtime::pipeline::{Error, ManyOut, SingleIn};
use dynamo_runtime::protocols::annotated::Annotated;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

/// How long to sleep between echoed tokens.
/// 50ms gives us 20 tok/s.
const TOKEN_ECHO_DELAY: Duration = Duration::from_millis(50);

/// Engine that accepts un-preprocessed requests and echos the prompt back as the response
/// Useful for testing ingress such as service-http.
struct EchoEngineFull {}
pub fn make_engine_full() -> OpenAIChatCompletionsStreamingEngine {
    Arc::new(EchoEngineFull {})
}

#[async_trait]
impl
    AsyncEngine<
43
        SingleIn<NvCreateChatCompletionRequest>,
44
        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
45
46
47
48
49
        Error,
    > for EchoEngineFull
{
    async fn generate(
        &self,
50
        incoming_request: SingleIn<NvCreateChatCompletionRequest>,
51
    ) -> Result<ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>, Error> {
52
53
54
        let (request, context) = incoming_request.transfer(());
        let deltas = request.response_generator();
        let ctx = context.context();
Paul Hendricks's avatar
Paul Hendricks committed
55
56
57
58
59
60
61
62
63
64
        let req = request.inner.messages.into_iter().last().unwrap();

        let prompt = match req {
            async_openai::types::ChatCompletionRequestMessage::User(user_msg) => {
                match user_msg.content {
                    async_openai::types::ChatCompletionRequestUserMessageContent::Text(prompt) => {
                        prompt
                    }
                    _ => anyhow::bail!("Invalid request content field, expected Content::Text"),
                }
65
            }
Paul Hendricks's avatar
Paul Hendricks committed
66
            _ => anyhow::bail!("Invalid request type, expected User message"),
67
        };
Paul Hendricks's avatar
Paul Hendricks committed
68

69
70
71
72
73
        let output = stream! {
            let mut id = 1;
            for c in prompt.chars() {
                // we are returning characters not tokens, so speed up some
                tokio::time::sleep(TOKEN_ECHO_DELAY/2).await;
Paul Hendricks's avatar
Paul Hendricks committed
74
                let inner = deltas.create_choice(0, Some(c.to_string()), None, None);
75
                let response = NvCreateChatCompletionStreamResponse {
Paul Hendricks's avatar
Paul Hendricks committed
76
77
78
                    inner,
                };
                yield Annotated{ id: Some(id.to_string()), data: Some(response), event: None, comment: None };
79
80
                id += 1;
            }
Paul Hendricks's avatar
Paul Hendricks committed
81
82

            let inner = deltas.create_choice(0, None, Some(async_openai::types::FinishReason::Stop), None);
83
            let response = NvCreateChatCompletionStreamResponse {
Paul Hendricks's avatar
Paul Hendricks committed
84
85
86
                inner,
            };
            yield Annotated { id: Some(id.to_string()), data: Some(response), event: None, comment: None };
87
        };
Paul Hendricks's avatar
Paul Hendricks committed
88

89
90
91
        Ok(ResponseStream::new(Box::pin(output), ctx))
    }
}