Main method to generate responses. Args: messages: Input messages (list of message dicts). **kwargs: Additional arguments. Returns: list: Generated responses for each message.
(self, messages, **kwargs)
| 535 | self.logger.info("Image encoding complete!") |
| 536 | |
| 537 | def generate(self, messages, **kwargs): |
| 538 | """Main method to generate responses. |
| 539 | |
| 540 | Args: |
| 541 | messages: Input messages (list of message dicts). |
| 542 | **kwargs: Additional arguments. |
| 543 | |
| 544 | Returns: |
| 545 | list: Generated responses for each message. |
| 546 | """ |
| 547 | all_kwargs = cp.deepcopy(self.default_kwargs) |
| 548 | all_kwargs.update(kwargs) |
| 549 | |
| 550 | # Handle empty messages list |
| 551 | if not messages: |
| 552 | return [] |
| 553 | |
| 554 | # Pre-encode images (thread-safe) |
| 555 | self._pre_encode_images(messages) |
| 556 | |
| 557 | # Use dedicated thread pool to avoid resource leaks |
| 558 | max_workers = min(self.thread_num, len(messages)) |
| 559 | with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: |
| 560 | # Submit all tasks with retry on thread creation failure |
| 561 | futures = {} |
| 562 | for i, msg in enumerate(messages): |
| 563 | while True: |
| 564 | try: |
| 565 | future = executor.submit( |
| 566 | self.process_single_message, msg, all_kwargs |
| 567 | ) |
| 568 | futures[future] = i |
| 569 | break |
| 570 | except RuntimeError as e: |
| 571 | if "can't start new thread" in str(e): |
| 572 | # Wait for some tasks to complete before submitting more |
| 573 | time.sleep(0.1) |
| 574 | else: |
| 575 | raise |
| 576 | |
| 577 | # Use tqdm to display progress |
| 578 | results = [None] * len(futures) |
| 579 | |
| 580 | with tqdm(total=len(futures), desc="Processing API Requests") as pbar: |
| 581 | for future in concurrent.futures.as_completed(futures): |
| 582 | index = futures[future] |
| 583 | results[index] = future.result() |
| 584 | pbar.update(1) |
| 585 | |
| 586 | # Release base64 data before next batch |
| 587 | self._clear_message_buffers(messages) |
| 588 | self._collect_memory(trim=True) |
| 589 | |
| 590 | return results |
| 591 | |
| 592 | def shutdown(self): |
| 593 | """Shutdown and release resources.""" |