|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +from abc import ABC, abstractmethod |
| 17 | +from typing import AsyncGenerator, List, Tuple |
| 18 | + |
| 19 | +from nemoguardrails.rails.llm.config import OutputRailsStreamingConfig |
| 20 | + |
| 21 | + |
| 22 | +class BufferStrategy(ABC): |
| 23 | + @classmethod |
| 24 | + @abstractmethod |
| 25 | + def from_config(cls, config: OutputRailsStreamingConfig) -> "BufferStrategy": |
| 26 | + pass |
| 27 | + |
| 28 | + # The abstract method is not async to ensure the return type |
| 29 | + # matches the async generator in the concrete implementation. |
| 30 | + @abstractmethod |
| 31 | + def __call__( |
| 32 | + self, streaming_handler |
| 33 | + ) -> AsyncGenerator[Tuple[List[str], str], None]: |
| 34 | + pass |
| 35 | + |
| 36 | + @abstractmethod |
| 37 | + def generate_chunk_str(self, *args, **kwargs) -> str: |
| 38 | + pass |
| 39 | + |
| 40 | + |
| 41 | +class RollingBuffer(BufferStrategy): |
| 42 | + """A minimal buffer strategy that buffers chunks and yields them when the buffer is full. |
| 43 | +
|
| 44 | + Args: |
| 45 | + buffer_context_size (int): The number of tokens carried over from the previous chunk to provide context for continuity in processing. |
| 46 | + buffer_chunk_size (int): The number of tokens in each processing chunk. This is the size of the token block on which output rails are applied. |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, buffer_context_size: int = 5, buffer_chunk_size: int = 10): |
| 50 | + self.buffer_context_size = buffer_context_size |
| 51 | + self.buffer_chunk_size = buffer_chunk_size |
| 52 | + self.last_index = 0 |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def from_config(cls, config: OutputRailsStreamingConfig): |
| 56 | + return cls( |
| 57 | + buffer_context_size=config.context_size, buffer_chunk_size=config.chunk_size |
| 58 | + ) |
| 59 | + |
| 60 | + async def __call__( |
| 61 | + self, streaming_handler |
| 62 | + ) -> AsyncGenerator[Tuple[List[str], str], None]: |
| 63 | + buffer = [] |
| 64 | + index = 0 |
| 65 | + |
| 66 | + async for chunk in streaming_handler: |
| 67 | + buffer.append(chunk) |
| 68 | + index += 1 |
| 69 | + |
| 70 | + if len(buffer) >= self.buffer_chunk_size: |
| 71 | + yield ( |
| 72 | + # we apply output rails on the buffer |
| 73 | + buffer[-self.buffer_chunk_size - self.buffer_context_size :], |
| 74 | + # generate_chunk_str is what gets printed in the console or yield to user |
| 75 | + # to avoid repeating the already streamed/printed chunk |
| 76 | + self.generate_chunk_str( |
| 77 | + buffer[-self.buffer_chunk_size - self.buffer_context_size :], |
| 78 | + index, |
| 79 | + ), |
| 80 | + ) |
| 81 | + buffer = buffer[-self.buffer_context_size :] |
| 82 | + |
| 83 | + # Yield any remaining buffer if it's not empty |
| 84 | + if buffer: |
| 85 | + yield ( |
| 86 | + buffer, |
| 87 | + self.generate_chunk_str( |
| 88 | + buffer[-self.buffer_chunk_size - self.buffer_context_size :], index |
| 89 | + ), |
| 90 | + ) |
| 91 | + |
| 92 | + def generate_chunk_str(self, buffer, current_index) -> str: |
| 93 | + if current_index <= self.last_index: |
| 94 | + return "" |
| 95 | + |
| 96 | + new_chunks = buffer[self.last_index - current_index :] |
| 97 | + self.last_index = current_index |
| 98 | + # TODO: something causes duplicate whitespaces between tokens, figure out why, |
| 99 | + # If using `return "".join(new_chunks)` works, then the issue might be elsewhere in the code where the chunks are being generated or processed. |
| 100 | + # Ensure that the chunks themselves do not contain extra spaces. |
| 101 | + # WAR: return "".join(new_chunks) |
| 102 | + return "".join(new_chunks) |
| 103 | + |
| 104 | + |
| 105 | +def get_buffer_strategy(config: OutputRailsStreamingConfig) -> BufferStrategy: |
| 106 | + # TODO: use a factory function or class |
| 107 | + # currently we only have RollingBuffer, in future we use a registry |
| 108 | + return RollingBuffer.from_config(config) |
0 commit comments