| 204 | |
| 205 | |
| 206 | class PQPool(Pool): |
| 207 | def __init__(self, client_args: ClientArgs) -> None: |
| 208 | super().__init__(client_args) # unlimited size |
| 209 | |
| 210 | # Initialize the heap with resources |
| 211 | heapify(self.queue) |
| 212 | |
| 213 | def __enter__(self, **kwargs) -> ClientArgs: |
| 214 | """Get a client from the pool and return it as a context manager.""" |
| 215 | |
| 216 | if len(self) == 0: |
| 217 | raise APIKeyPoolEmptyError("api key pool is empty") |
| 218 | |
| 219 | self._cur_resource = heappop(self.queue) |
| 220 | |
| 221 | return self._cur_resource.client_args |
| 222 | |
| 223 | def __exit__(self, exc_type, exc_value, exc_traceback) -> bool: |
| 224 | """Put the resource back in the pool.""" |
| 225 | |
| 226 | # TODO how to update the usage? |
| 227 | self._cur_usage = { |
| 228 | "prompt_tokens": 0, |
| 229 | "completion_tokens": 0, |
| 230 | "total_tokens": 0, |
| 231 | } |
| 232 | heappush(self.queue, self._cur_resource.update(self._cur_usage)) |
| 233 | if exc_type is not None: |
| 234 | # Log the exception or handle it as needed |
| 235 | logger.error(f"Client Pool Error: {exc_type}, {exc_value}") |
| 236 | return False |
| 237 | return True |
| 238 | |
| 239 | |
| 240 | class RandomPool(Pool): |
nothing calls this directly
no outgoing calls
no test coverage detected