|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from dataclasses import dataclass, field |
| 3 | +from typing import AsyncIterator, Optional |
| 4 | + |
| 5 | +from litellm import ModelResponse |
| 6 | +from litellm.types.utils import Delta, StreamingChoices |
| 7 | + |
| 8 | +from codegate.pipeline.base import PipelineContext |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class OutputPipelineContext: |
| 13 | + """ |
| 14 | + Context passed between output pipeline steps. |
| 15 | +
|
| 16 | + Does not include the input context, that one is separate. |
| 17 | + """ |
| 18 | + |
| 19 | + # We store the messages that are not yet sent to the client in the buffer. |
| 20 | + # One reason for this might be that the buffer contains a secret that we want to de-obfuscate |
| 21 | + buffer: list[str] = field(default_factory=list) |
| 22 | + |
| 23 | + |
| 24 | +class OutputPipelineStep(ABC): |
| 25 | + """ |
| 26 | + Base class for output pipeline steps |
| 27 | + The process method should be implemented by subclasses and handles |
| 28 | + processing of a single chunk of the stream. |
| 29 | + """ |
| 30 | + |
| 31 | + @property |
| 32 | + @abstractmethod |
| 33 | + def name(self) -> str: |
| 34 | + """Returns the name of this pipeline step""" |
| 35 | + pass |
| 36 | + |
| 37 | + @abstractmethod |
| 38 | + async def process_chunk( |
| 39 | + self, |
| 40 | + chunk: ModelResponse, |
| 41 | + context: OutputPipelineContext, |
| 42 | + input_context: Optional[PipelineContext] = None, |
| 43 | + ) -> Optional[ModelResponse]: |
| 44 | + """ |
| 45 | + Process a single chunk of the stream. |
| 46 | +
|
| 47 | + Args: |
| 48 | + - chunk: The input chunk to process, normalized to ModelResponse |
| 49 | + - context: The output pipeline context. Can be used to store state between steps, mainly |
| 50 | + the buffer. |
| 51 | + - input_context: The input context from processing the user's input. Can include the secrets |
| 52 | + obfuscated in the user message or code snippets in the user message. |
| 53 | +
|
| 54 | + Return: |
| 55 | + - None to pause the stream |
| 56 | + - Modified or unmodified input chunk to pass through |
| 57 | + """ |
| 58 | + pass |
| 59 | + |
| 60 | + |
| 61 | +class OutputPipelineInstance: |
| 62 | + """ |
| 63 | + Handles processing of a single stream |
| 64 | + Think of this class as steps + buffer |
| 65 | + """ |
| 66 | + |
| 67 | + def __init__( |
| 68 | + self, |
| 69 | + pipeline_steps: list[OutputPipelineStep], |
| 70 | + input_context: Optional[PipelineContext] = None, |
| 71 | + ): |
| 72 | + self._input_context = input_context |
| 73 | + self._pipeline_steps = pipeline_steps |
| 74 | + self._context = OutputPipelineContext() |
| 75 | + # we won't actually buffer the chunk, but in case we need to pass |
| 76 | + # the remaining content in the buffer when the stream ends, we need |
| 77 | + # to store the parameters like model, timestamp, etc. |
| 78 | + self._buffered_chunk = None |
| 79 | + |
| 80 | + def _buffer_chunk(self, chunk: ModelResponse) -> None: |
| 81 | + """ |
| 82 | + Add chunk content to buffer. |
| 83 | + """ |
| 84 | + self._buffered_chunk = chunk |
| 85 | + for choice in chunk.choices: |
| 86 | + # the last choice has no delta or content, let's not buffer it |
| 87 | + if choice.delta is not None and choice.delta.content is not None: |
| 88 | + self._context.buffer.append(choice.delta.content) |
| 89 | + |
| 90 | + async def process_stream( |
| 91 | + self, stream: AsyncIterator[ModelResponse] |
| 92 | + ) -> AsyncIterator[ModelResponse]: |
| 93 | + """ |
| 94 | + Process a stream through all pipeline steps |
| 95 | + """ |
| 96 | + try: |
| 97 | + async for chunk in stream: |
| 98 | + # Store chunk content in buffer |
| 99 | + self._buffer_chunk(chunk) |
| 100 | + |
| 101 | + # Process chunk through each step of the pipeline |
| 102 | + current_chunk = chunk |
| 103 | + for step in self._pipeline_steps: |
| 104 | + if current_chunk is None: |
| 105 | + # Stop processing if a step returned None previously |
| 106 | + # this means that the pipeline step requested to pause the stream |
| 107 | + # instead, let's try again with the next chunk |
| 108 | + break |
| 109 | + |
| 110 | + processed_chunk = await step.process_chunk( |
| 111 | + current_chunk, self._context, self._input_context |
| 112 | + ) |
| 113 | + # the returned chunk becomes the input for the next chunk in the pipeline |
| 114 | + current_chunk = processed_chunk |
| 115 | + |
| 116 | + # we have either gone through all the steps in the pipeline and have a chunk |
| 117 | + # to return or we are paused in which case we don't yield |
| 118 | + if current_chunk is not None: |
| 119 | + # Step processed successfully, yield the chunk and clear buffer |
| 120 | + self._context.buffer.clear() |
| 121 | + yield current_chunk |
| 122 | + # else: keep buffering for next iteration |
| 123 | + |
| 124 | + except Exception as e: |
| 125 | + # Log exception and stop processing |
| 126 | + raise e |
| 127 | + finally: |
| 128 | + # Process any remaining content in buffer when stream ends |
| 129 | + if self._context.buffer: |
| 130 | + final_content = "".join(self._context.buffer) |
| 131 | + yield ModelResponse( |
| 132 | + id=self._buffered_chunk.id, |
| 133 | + choices=[ |
| 134 | + StreamingChoices( |
| 135 | + finish_reason=None, |
| 136 | + # we just put one choice in the buffer, so 0 is fine |
| 137 | + index=0, |
| 138 | + delta=Delta(content=final_content, role="assistant"), |
| 139 | + # umm..is this correct? |
| 140 | + logprobs=self._buffered_chunk.choices[0].logprobs, |
| 141 | + ) |
| 142 | + ], |
| 143 | + created=self._buffered_chunk.created, |
| 144 | + model=self._buffered_chunk.model, |
| 145 | + object="chat.completion.chunk", |
| 146 | + ) |
| 147 | + self._context.buffer.clear() |
| 148 | + |
| 149 | + # Cleanup sensitive data through the input context |
| 150 | + if self._input_context and self._input_context.sensitive: |
| 151 | + self._input_context.sensitive.secure_cleanup() |
| 152 | + |
| 153 | + |
| 154 | +class OutputPipelineProcessor: |
| 155 | + """ |
| 156 | + Since we want to provide each run of the pipeline with a fresh context, |
| 157 | + we need a factory to create new instances of the pipeline. |
| 158 | + """ |
| 159 | + |
| 160 | + def __init__(self, pipeline_steps: list[OutputPipelineStep]): |
| 161 | + self.pipeline_steps = pipeline_steps |
| 162 | + |
| 163 | + def _create_instance(self) -> OutputPipelineInstance: |
| 164 | + """Create a new pipeline instance for processing a stream""" |
| 165 | + return OutputPipelineInstance(self.pipeline_steps) |
| 166 | + |
| 167 | + async def process_stream( |
| 168 | + self, stream: AsyncIterator[ModelResponse] |
| 169 | + ) -> AsyncIterator[ModelResponse]: |
| 170 | + """Create a new pipeline instance and process the stream""" |
| 171 | + instance = self._create_instance() |
| 172 | + async for chunk in instance.process_stream(stream): |
| 173 | + yield chunk |
0 commit comments