Batch embedder specifically designed for DashScope API
| 734 | |
| 735 | # Batch Embedding Components for DashScope |
| 736 | class DashScopeBatchEmbedder(DataComponent): |
| 737 | """Batch embedder specifically designed for DashScope API""" |
| 738 | |
| 739 | def __init__(self, embedder, batch_size: int = 100, embedding_cache_file_name: str = "default") -> None: |
| 740 | super().__init__(batch_size=batch_size) |
| 741 | self.embedder = embedder |
| 742 | self.batch_size = batch_size |
| 743 | if self.batch_size > 25: |
| 744 | log.warning(f"DashScope batch embedder initialization, batch size: {self.batch_size}, note that DashScope batch embedding size cannot exceed 25, automatically set to 25") |
| 745 | self.batch_size = 25 |
| 746 | self.cache_path = f'./embedding_cache/{embedding_cache_file_name}_{self.embedder.__class__.__name__}_dashscope_embeddings.pkl' |
| 747 | |
| 748 | def call( |
| 749 | self, input: BatchEmbedderInputType, model_kwargs: Optional[Dict] = {}, force_recreate: bool = False |
| 750 | ) -> BatchEmbedderOutputType: |
| 751 | """ |
| 752 | Batch call to DashScope embedder |
| 753 | |
| 754 | Args: |
| 755 | input: List of input texts |
| 756 | model_kwargs: Model parameters |
| 757 | force_recreate: Whether to force recreation |
| 758 | |
| 759 | Returns: |
| 760 | Batch embedding output |
| 761 | """ |
| 762 | # Check cache first |
| 763 | |
| 764 | if not force_recreate and os.path.exists(self.cache_path): |
| 765 | try: |
| 766 | with open(self.cache_path, 'rb') as f: |
| 767 | embeddings = pickle.load(f) |
| 768 | log.info(f"Loaded cached DashScope embeddings from: {self.cache_path}") |
| 769 | return embeddings |
| 770 | except Exception as e: |
| 771 | log.warning(f"Failed to load cache file {self.cache_path}: {e}, proceeding with fresh embedding") |
| 772 | |
| 773 | if isinstance(input, str): |
| 774 | input = [input] |
| 775 | |
| 776 | n = len(input) |
| 777 | embeddings: List[EmbedderOutput] = [] |
| 778 | |
| 779 | log.info(f"Starting DashScope batch embedding processing, total {n} texts, batch size: {self.batch_size}") |
| 780 | |
| 781 | for i in tqdm( |
| 782 | range(0, n, self.batch_size), |
| 783 | desc="DashScope batch embedding", |
| 784 | disable=False, |
| 785 | ): |
| 786 | batch_input = input[i : min(i + self.batch_size, n)] |
| 787 | |
| 788 | try: |
| 789 | # Use correct calling method: directly call embedder instance |
| 790 | batch_output = self.embedder( |
| 791 | input=batch_input, model_kwargs=model_kwargs |
| 792 | ) |
| 793 | embeddings.append(batch_output) |