mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 09:50:24 +08:00
* T028(Codex交付,ZC核验代提交): KeyPool多key轮换层(provider×model×key池·429冷却·单key兼容) · api_key/api_token字段兼容数组 · 三处接入(embedding/mineru/llm) · 图片描述gather+Semaphore并发化 · 303单测全过(含官方既有测试回归)
* FIX-EMB-429: 火山embedding 429根治(上游PR候选) · ①429重试按Retry-After等30s(滑窗等过) ②resolver从profile读batch_size/batch_delay(火山RPM极低必须限速) · 实测batch5/delay2s下语文reindex突破processing · 三key池x2冷却机制已验
* HARDEN-429: embedding限流重试1→8次+全冷却等待65s再取 · 单key池滑动窗口瞬时429不再报废数小时reindex整跑(08-22三烧教训) · 月度额度429仍8轮后raise不空转
* FIX-UNBOUND: 限流重试槽位for耗尽静默穿落到data引用 · 槽位1+max(MAX_RETRIES,10)兜住8轮限流 · t035镜像UnboundLocalError根因(逻辑走查复现)
* THROTTLE-GLOBAL: embedding跨实例全局节流锁 · 类级锁串行化'间隔+发帖'(多文档并行reindex各自client叠加超RPM=08-22历史库六烧终根因) · batch_delay升级为全局最小间隔 · 手动单发200而进程内全429的分歧由此闭合
* FIX-LOCK: 节流锁asyncio→threading · LlamaIndex _run_in_new_loop每线程新event loop,asyncio.Lock绑创建loop跨loop不互斥(根因三层剥洋葱终层) · 静态方法装饰修正 · 容器内3线程串行化实测2.01s通过
* PR-PREP: 中性化 fork 痕迹注释(中文→英文 provider 通用表述) · 上游v1.5.16已有_as_api_key数组支持,删我方重复实现保留上游版 · 测试148+86全过 · 密钥扫描分支历史+工作树双清(A类指纹0命中,B类28处=上游自带fixture)
* LINT: ruff format 6文件对齐CI(上游基线0债,全是我方引入) + import顺序修正
* FIX-CI: 图片处理块整体采纳上游v1.5.16版(_describe_image新签名+批量embed_contents) · 删越域的fork逐图并发测试(记档将来独立PR) · 592测全过
* FIX-CI: _build_openai_client合并壳与实现(上游sanitize保留+key池数组兼容) · placeholder_key改用primary_key(list哈希修复) · 889测全过
* fix(keypool): never refuse the only key
`KeyPool` is built even for a single-key config, and `next()` raised
`RuntimeError("All API keys are cooling down")` once every key was cooling.
For the common one-key setup that meant two 429s took every LLM and embedding
call down for the full 60s window — and it bypassed the rotation layer's own
429 handling entirely, since the RuntimeError surfaces before
`_KeyRotatingCompletions.create` can mark the strike and re-raise the real
provider error. `sdk_max_retries=0` had already handed retry duty to that
layer.
Cooling is a preference hint, not a circuit breaker: when everything is
cooling, return the key that recovers soonest and let the provider's own 429
surface to be retried.
The existing single-key test asserted the raise while calling itself
"keeps single key compatible" — it now pins the behaviour the name promises,
plus the soonest-recovery ordering for the multi-key case.
---------
Co-authored-by: interia <interia@interiadeMac-mini.local>
Co-authored-by: Frank <bingxizhao@novix.science>
197 lines
7.1 KiB
Python
197 lines
7.1 KiB
Python
"""
|
|
Base Embedding Adapter
|
|
=======================
|
|
|
|
Abstract base class for all embedding adapters.
|
|
Defines the contract that all embedding providers must implement.
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
from dataclasses import dataclass
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
from deeptutor.services.keypool import KeyPool
|
|
|
|
|
|
def looks_like_multimodal_embedding_model(model_name: Optional[str]) -> bool:
|
|
"""Best-effort guard for OpenAI-compatible multimodal embedding models."""
|
|
if not model_name:
|
|
return False
|
|
normalized = model_name.lower().replace("_", "-")
|
|
return any(
|
|
marker in normalized
|
|
for marker in (
|
|
"qwen3-vl-embedding",
|
|
"multimodal-embedding",
|
|
"vision-embedding",
|
|
"vl-embedding",
|
|
"image-embedding",
|
|
)
|
|
)
|
|
|
|
|
|
@dataclass
|
|
class EmbeddingRequest:
|
|
"""
|
|
Standard embedding request structure.
|
|
|
|
Provider-agnostic request format. Different providers interpret fields differently:
|
|
|
|
Args:
|
|
texts: List of texts to embed
|
|
model: Model name to use
|
|
dimensions: Embedding vector dimensions (optional)
|
|
input_type: Input type hint for task-aware embeddings (optional)
|
|
- Cohere: Maps to 'input_type' ("search_document", "search_query", "classification", "clustering")
|
|
- Jina: Maps to 'task' ("retrieval.passage", "retrieval.query", etc.)
|
|
- Gemini Embedding 2: Maps to retrieval-specific text instructions
|
|
- OpenAI/Ollama: Ignored
|
|
encoding_format: Output format ("float" or "base64"). ``None`` (the
|
|
default) lets each adapter decide: OpenAI-compatible gateways omit
|
|
the param entirely (several, e.g. SiliconFlow, return HTTP 400 when
|
|
it is present), while the official OpenAI SDK path pins "float".
|
|
truncate: Whether to truncate texts that exceed max tokens (default: True)
|
|
normalized: Whether to return L2-normalized embeddings (Jina/Ollama only)
|
|
late_chunking: Enable late chunking for long context (Jina v3 only)
|
|
contents: Multimodal content list of dicts like
|
|
``[{"text": "..."}, {"image": "url|data: URI"}, {"video": "..."}]``.
|
|
Adapters that support multimodal (DashScope, SiliconFlow Qwen3-VL,
|
|
Cohere v4) consume this directly; text-only adapters MUST raise
|
|
``ValueError`` if it is set so the caller can route differently.
|
|
When ``contents`` is set, ``texts`` is ignored.
|
|
enable_fusion: DashScope-specific. ``True`` fuses all multimodal items
|
|
into one vector; ``False`` (or None) returns one vector per item.
|
|
"""
|
|
|
|
texts: List[str]
|
|
model: str
|
|
dimensions: Optional[int] = None
|
|
input_type: Optional[str] = None
|
|
encoding_format: Optional[str] = None
|
|
truncate: Optional[bool] = True
|
|
normalized: Optional[bool] = True
|
|
late_chunking: Optional[bool] = False
|
|
contents: Optional[List[Dict[str, Any]]] = None
|
|
enable_fusion: Optional[bool] = None
|
|
|
|
|
|
@dataclass
|
|
class EmbeddingResponse:
|
|
"""Standard embedding response structure."""
|
|
|
|
embeddings: List[List[float]]
|
|
model: str
|
|
dimensions: int
|
|
usage: Dict[str, Any]
|
|
|
|
|
|
class EmbeddingProviderError(RuntimeError):
|
|
"""Structured error raised by embedding adapters on provider failures.
|
|
|
|
Carries the HTTP status, response body excerpt, model name, and request
|
|
URL so downstream callers (task log streams, UI surfaces) can show
|
|
actionable diagnostics instead of a bare exception string.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
message: str,
|
|
*,
|
|
status: Optional[int] = None,
|
|
body: Optional[str] = None,
|
|
model: Optional[str] = None,
|
|
url: Optional[str] = None,
|
|
provider: Optional[str] = None,
|
|
) -> None:
|
|
super().__init__(message)
|
|
self.status = status
|
|
self.body = body
|
|
self.model = model
|
|
self.url = url
|
|
self.provider = provider
|
|
|
|
def __str__(self) -> str: # noqa: D401 - succinct
|
|
parts = [super().__str__()]
|
|
if self.provider:
|
|
parts.append(f"provider={self.provider}")
|
|
if self.model:
|
|
parts.append(f"model={self.model}")
|
|
if self.status is not None:
|
|
parts.append(f"status={self.status}")
|
|
if self.url:
|
|
parts.append(f"url={self.url}")
|
|
if self.body:
|
|
snippet = self.body if len(self.body) <= 500 else self.body[:500] + "...(truncated)"
|
|
parts.append(f"body={snippet}")
|
|
return " | ".join(parts)
|
|
|
|
|
|
class BaseEmbeddingAdapter(ABC):
|
|
"""
|
|
Base class for all embedding adapters.
|
|
|
|
Each adapter implements the specific API interface for a provider
|
|
(OpenAI, Cohere, Ollama, etc.) while exposing a unified interface.
|
|
"""
|
|
|
|
# Whether this adapter turns ``EmbeddingRequest.input_type`` into a
|
|
# provider parameter. Opt-in, because doing so changes the vectors a
|
|
# provider returns for the same text: switching it on for a backend that
|
|
# previously sent no role invalidates every index already built with it.
|
|
SUPPORTS_INPUT_TYPE: bool = False
|
|
|
|
def __init__(self, config: Dict[str, Any]):
|
|
"""
|
|
Initialize the adapter with configuration.
|
|
|
|
Args:
|
|
config: Dictionary containing:
|
|
- api_key: API authentication key (optional for local)
|
|
- base_url: API endpoint URL
|
|
- model: Model name to use
|
|
- dimensions: Embedding vector dimensions
|
|
- send_dimensions: Tri-state opt-in for the `dimensions`
|
|
request param. ``True`` always sends, ``False`` never
|
|
sends, ``None`` lets the adapter decide based on the
|
|
model family (default).
|
|
- request_timeout: Request timeout in seconds
|
|
"""
|
|
raw_api_key = config.get("api_key")
|
|
keys = raw_api_key if isinstance(raw_api_key, list) else [raw_api_key]
|
|
keys = [str(key).strip() for key in keys if str(key or "").strip()]
|
|
self._key_pool = KeyPool(keys) if keys else None
|
|
self.api_key = keys[0] if keys else ""
|
|
self.base_url = config.get("base_url")
|
|
self.api_version = config.get("api_version")
|
|
self.model = config.get("model")
|
|
self.dimensions = config.get("dimensions")
|
|
self.send_dimensions: Optional[bool] = config.get("send_dimensions")
|
|
self.request_timeout = config.get("request_timeout", 60)
|
|
self.extra_headers = config.get("extra_headers") or {}
|
|
|
|
@abstractmethod
|
|
async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:
|
|
"""
|
|
Generate embeddings for a list of texts.
|
|
|
|
Args:
|
|
request: EmbeddingRequest with texts and parameters
|
|
|
|
Returns:
|
|
EmbeddingResponse with embeddings and metadata
|
|
|
|
Raises:
|
|
httpx.HTTPError: If the API request fails
|
|
"""
|
|
pass
|
|
|
|
@abstractmethod
|
|
def get_model_info(self) -> Dict[str, Any]:
|
|
"""
|
|
Return information about the configured model.
|
|
|
|
Returns:
|
|
Dictionary with model metadata (name, dimensions, etc.)
|
|
"""
|
|
pass
|