|
| 1 | +import asyncio |
| 2 | +import math |
| 3 | +import time |
| 4 | +import uuid |
| 5 | +from typing import ( |
| 6 | + Any, |
| 7 | + AsyncGenerator, |
| 8 | + Dict, |
| 9 | + Literal, |
| 10 | + Optional, |
| 11 | + Tuple, |
| 12 | + Union, |
| 13 | +) |
| 14 | + |
| 15 | +from pydantic import BaseModel, Field |
| 16 | + |
| 17 | +from guidellm.backend import ( |
| 18 | + Backend, |
| 19 | + RequestArgs, |
| 20 | + ResponseSummary, |
| 21 | + StreamingTextResponse, |
| 22 | +) |
| 23 | +from guidellm.scheduler.scheduler import RequestsWorker |
| 24 | + |
| 25 | +__all__ = ["GenerationRequest", "BackendRequestsWorker"] |
| 26 | + |
| 27 | + |
| 28 | +class GenerationRequest(BaseModel): |
| 29 | + """ |
| 30 | + A class representing a request for generation. |
| 31 | + This class is used to encapsulate the details of a generation request, |
| 32 | + including the request ID, type, content, parameters, statistics, and constraints. |
| 33 | + It is designed to be used with the BackendRequestsWorker class to handle |
| 34 | + the generation process. |
| 35 | +
|
| 36 | + :param request_id: The unique identifier for the request. |
| 37 | + :param request_type: The type of request (e.g., text, chat). |
| 38 | + :param content: The content for the request to send to the backend. |
| 39 | + If request_type is 'text', this should be a string or list of strings |
| 40 | + which will be resolved by backend.text_completions. |
| 41 | + If request_type is 'chat', this should be a string, |
| 42 | + a list of (str, Dict[str, Union[str, Dict[str, str]], Path, Image]), |
| 43 | + or Any raw content which will be resolved by backend.chat_completions. |
| 44 | + If raw content, raw_content=True must be passed in the params. |
| 45 | + :param params: Additional parameters for the request passed in as kwargs. |
| 46 | + For an http backend, these are passed into the body of the request. |
| 47 | + :param stats: Statistics for the request, such as the number of prompt tokens. |
| 48 | + Used for tracking and reporting purposes. |
| 49 | + :param constraints: Constraints for the request, such as the maximum number |
| 50 | + of output tokens. Used for controlling the behavior of the backend. |
| 51 | + """ |
| 52 | + |
| 53 | + request_id: Optional[str] = Field( |
| 54 | + default_factory=lambda: str(uuid.uuid4()), |
| 55 | + description="The unique identifier for the request.", |
| 56 | + ) |
| 57 | + request_type: Literal["text", "chat"] = Field( |
| 58 | + default="text", |
| 59 | + description=( |
| 60 | + "The type of request (e.g., text, chat). " |
| 61 | + "If request_type is 'text', resolved by backend.text_completions. " |
| 62 | + "If request_type is 'chat', resolved by backend.chat_completions." |
| 63 | + ), |
| 64 | + ) |
| 65 | + content: Any = Field( |
| 66 | + description=( |
| 67 | + "The content for the request to send to the backend. " |
| 68 | + "If request_type is 'text', this should be a string or list of strings " |
| 69 | + "which will be resolved by backend.text_completions. " |
| 70 | + "If request_type is 'chat', this should be a string, " |
| 71 | + "a list of (str, Dict[str, Union[str, Dict[str, str]], Path, Image]), " |
| 72 | + "or Any raw content which will be resolved by backend.chat_completions. " |
| 73 | + "If raw content, raw_content=True must be passed in the params." |
| 74 | + ) |
| 75 | + ) |
| 76 | + params: Dict[str, Any] = Field( |
| 77 | + default_factory=dict, |
| 78 | + description=( |
| 79 | + "Additional parameters for the request that will be passed in as kwargs. " |
| 80 | + "For an http backend, these are passed into the body of the request. " |
| 81 | + ), |
| 82 | + ) |
| 83 | + stats: Dict[Literal["prompt_tokens"], int] = Field( |
| 84 | + default_factory=dict, |
| 85 | + description=( |
| 86 | + "Statistics for the request, such as the number of prompt tokens. " |
| 87 | + "Used for tracking and reporting purposes." |
| 88 | + ), |
| 89 | + ) |
| 90 | + constraints: Dict[Literal["output_tokens"], int] = Field( |
| 91 | + default_factory=dict, |
| 92 | + description=( |
| 93 | + "Constraints for the request, such as the maximum number of output tokens. " |
| 94 | + "Used for controlling the behavior of the backend." |
| 95 | + ), |
| 96 | + ) |
| 97 | + |
| 98 | + |
| 99 | +class BackendRequestsWorker(RequestsWorker): |
| 100 | + """ |
| 101 | + A class that handles the execution of requests using a backend. |
| 102 | + This class is responsible for sending requests to the backend, |
| 103 | + handling responses, and managing errors. |
| 104 | +
|
| 105 | + :param backend: The backend to use for handling requests. |
| 106 | + This should be an instance of Backend such as an OpenAIHTTPBackend. |
| 107 | + """ |
| 108 | + |
| 109 | + def __init__(self, backend: Backend): |
| 110 | + self.backend = backend |
| 111 | + |
| 112 | + async def resolve( |
| 113 | + self, |
| 114 | + request: GenerationRequest, |
| 115 | + start_time: float, |
| 116 | + timeout_time: float, |
| 117 | + ) -> ResponseSummary: |
| 118 | + """ |
| 119 | + Resolve a request by sending it to the backend and handling the response. |
| 120 | + This method sends the request to the backend, waits for a response, |
| 121 | + and handles any errors that may occur during the process. |
| 122 | +
|
| 123 | + :param request: The request to resolve. |
| 124 | + :param start_time: The time to start the request. |
| 125 | + :param timeout_time: The time to wait for a response before timing out. |
| 126 | + If timeout_time is math.inf, the request will not timeout. |
| 127 | + :return: A ResponseSummary object containing the response from the backend. |
| 128 | + If an error occurs, the ResponseSummary will contain the error message. |
| 129 | + """ |
| 130 | + response = None |
| 131 | + error: Optional[str] = None |
| 132 | + |
| 133 | + try: |
| 134 | + request_func, request_kwargs = self._create_request_func_kwargs(request) |
| 135 | + |
| 136 | + async def _runner(): |
| 137 | + # wrap function so we can enforce timeout and |
| 138 | + # still return the latest state from the backend |
| 139 | + async for resp in request_func(**request_kwargs): |
| 140 | + nonlocal response |
| 141 | + response = resp |
| 142 | + |
| 143 | + if (wait_time := start_time - time.time()) > 0: |
| 144 | + await asyncio.sleep(wait_time) |
| 145 | + |
| 146 | + start_time = time.time() |
| 147 | + await asyncio.wait_for( |
| 148 | + _runner(), |
| 149 | + timeout=timeout_time - time.time() if timeout_time < math.inf else None, |
| 150 | + ) |
| 151 | + |
| 152 | + if not response: |
| 153 | + raise ValueError( |
| 154 | + f"No response received for request: {request} " |
| 155 | + f"and backend: {self.backend}" |
| 156 | + ) |
| 157 | + if not isinstance(response, ResponseSummary): |
| 158 | + raise ValueError( |
| 159 | + f"Received no ResponseSummary for request: {request} " |
| 160 | + f"and backend: {self.backend}, received: {response}" |
| 161 | + ) |
| 162 | + except asyncio.TimeoutError as texc: |
| 163 | + error = str(texc) |
| 164 | + except Exception as exc: # noqa: BLE001 |
| 165 | + error = str(exc) |
| 166 | + |
| 167 | + return self._handle_response(request, response, error, start_time) |
| 168 | + |
| 169 | + def _create_request_func_kwargs( |
| 170 | + self, |
| 171 | + request: GenerationRequest, |
| 172 | + ) -> Tuple[ |
| 173 | + AsyncGenerator[Union[StreamingTextResponse, ResponseSummary], None], |
| 174 | + Dict[str, Any], |
| 175 | + ]: |
| 176 | + request_func: AsyncGenerator[ |
| 177 | + Union[StreamingTextResponse, ResponseSummary], None |
| 178 | + ] |
| 179 | + request_kwargs: Dict[str, Any] |
| 180 | + |
| 181 | + if request.request_type == "text": |
| 182 | + request_func = self.backend.text_completions |
| 183 | + request_kwargs = { |
| 184 | + "prompt": request.content, |
| 185 | + "request_id": request.request_id, |
| 186 | + "prompt_token_count": request.stats.get("prompt_tokens", None), |
| 187 | + "output_token_count": request.constraints.get("output_tokens", None), |
| 188 | + **request.params, |
| 189 | + } |
| 190 | + elif request.request_type == "chat": |
| 191 | + request_func = self.backend.chat_completions |
| 192 | + request_kwargs = { |
| 193 | + "content": request.content, |
| 194 | + "request_id": request.request_id, |
| 195 | + "prompt_token_count": request.stats.get("prompt_tokens", None), |
| 196 | + "output_token_count": request.constraints.get("output_tokens", None), |
| 197 | + **request.params, |
| 198 | + } |
| 199 | + else: |
| 200 | + raise ValueError( |
| 201 | + f"Invalid request type: {request.request_type} for {request}" |
| 202 | + ) |
| 203 | + |
| 204 | + return request_func, request_kwargs |
| 205 | + |
| 206 | + def _handle_response( |
| 207 | + self, |
| 208 | + request: GenerationRequest, |
| 209 | + response: Any, |
| 210 | + error: Optional[str], |
| 211 | + start_time: float, |
| 212 | + ) -> ResponseSummary: |
| 213 | + if response is None or not isinstance( |
| 214 | + response, (ResponseSummary, StreamingTextResponse) |
| 215 | + ): |
| 216 | + # nothing received or invalid response, fill in defaults for error |
| 217 | + if response: |
| 218 | + error = str( |
| 219 | + ValueError( |
| 220 | + f"Invalid response: {type(response)} for request: {request}; " |
| 221 | + ) |
| 222 | + ) + (error or "") |
| 223 | + |
| 224 | + return ResponseSummary( |
| 225 | + value="", |
| 226 | + request_args=RequestArgs( |
| 227 | + target=self.backend.target, |
| 228 | + headers={}, |
| 229 | + payload={}, |
| 230 | + ), |
| 231 | + start_time=start_time, |
| 232 | + end_time=time.time(), |
| 233 | + request_id=request.request_id, |
| 234 | + error=error or "Unknown error", |
| 235 | + ) |
| 236 | + |
| 237 | + if isinstance(response, StreamingTextResponse): |
| 238 | + return ResponseSummary( |
| 239 | + value=response.value, |
| 240 | + request_args=RequestArgs( |
| 241 | + target=self.backend.target, |
| 242 | + headers={}, |
| 243 | + payload={}, |
| 244 | + ), |
| 245 | + start_time=response.start_time, |
| 246 | + end_time=time.time(), |
| 247 | + request_prompt_tokens=request.stats.get("prompt_tokens", None), |
| 248 | + request_output_tokens=None, |
| 249 | + response_prompt_tokens=None, |
| 250 | + response_output_tokens=response.iter_count, |
| 251 | + request_id=request.request_id, |
| 252 | + error=error or "Unknown error", |
| 253 | + ) |
| 254 | + |
| 255 | + response.error = error |
| 256 | + |
| 257 | + return response |
0 commit comments