| 500 | embedding = self._get_hash_embedding(normalized_text) |
| 501 | except Exception as exc: |
| 502 | print(f"Embedding error ({self.provider}:{self.model}): {exc}") |
| 503 | self.provider = "hash" |
| 504 | self.model = "hash" |
| 505 | embedding = self._get_hash_embedding(normalized_text) |
| 506 | |
| 507 | embedding = self._resize_vector(list(embedding)) |
| 508 | self._save_cached(normalized_text, embedding) |
| 509 | return embedding |
| 510 | |
| 511 | def _batch_concurrency(self, batch_count: int) -> int: |
| 512 | """Concurrent embedding requests to issue. |
| 513 | |
| 514 | Kept modest by default: these all hit one provider endpoint, and |
| 515 | over-parallelising invites 429s that would trip the hash fallback and |
| 516 | silently degrade recommendation quality. Override with |
| 517 | PAPERFLOW_EMBED_CONCURRENCY. |
| 518 | """ |
| 519 | if batch_count <= 1: |
| 520 | return 1 |
| 521 | raw = str(os.environ.get("PAPERFLOW_EMBED_CONCURRENCY", "")).strip() |
| 522 | try: |
| 523 | configured = int(raw) if raw else 4 |
| 524 | except ValueError: |
| 525 | configured = 4 |
| 526 | return max(1, min(configured, batch_count, 8)) |
| 527 | |
| 528 | def embed_batch(self, texts: List[str], batch_size: int = 32) -> List[List[float]]: |
| 529 | normalized_texts = [self._normalize_text(text) for text in texts] |
| 530 | results: List[Optional[List[float]]] = [None] * len(normalized_texts) |
| 531 | missing_indices = [] |
| 532 | |
| 533 | for index, text in enumerate(normalized_texts): |
| 534 | if not text: |
| 535 | results[index] = [0.0] * self.dimensions |
| 536 | continue |
| 537 | cached = self._load_cached(text) |
| 538 | if cached is not None: |
| 539 | results[index] = cached |
| 540 | else: |
| 541 | missing_indices.append(index) |
| 542 | |
| 543 | if missing_indices and self.provider == "openai" and self.client is not None: |
| 544 | batches = [ |
| 545 | missing_indices[batch_start:batch_start + batch_size] |
| 546 | for batch_start in range(0, len(missing_indices), batch_size) |
| 547 | ] |
| 548 | |
| 549 | def embed_one_batch(batch_indices: List[int]) -> List[Tuple[int, List[float]]]: |