DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: merge PR #268 (embedding progress + 429 retry) with review fixes
Bingxi Zhao (Frank)0950c98e18b8
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.pyindex 79f3a008a..d621e01a7 100644--- a/deeptutor/knowledge/initializer.py+++ b/deeptutor/knowledge/initializer.py@@ -176,8 +176,20 @@ class KnowledgeBaseInitializer:)file_paths = [str(doc_file) for doc_file in doc_files]+ def _on_progress(batch_num, total_batches):+ self.progress_tracker.update(+ ProgressStage.PROCESSING_DOCUMENTS,+ f"Embedding batches: {batch_num}/{total_batches} complete",+ current=batch_num,+ total=total_batches,+ )+try:- success = await rag_service.initialize(kb_name=self.kb_name, file_paths=file_paths)+ success = await rag_service.initialize(+ kb_name=self.kb_name,+ file_paths=file_paths,+ progress_callback=_on_progress,+ )if not success:self.progress_tracker.update(ProgressStage.ERROR,diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex bca6ea132..3cac671d8 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -139,6 +139,7 @@ class ResolvedEmbeddingConfig:dimension: int = 3072request_timeout: int = 60batch_size: int = 10+ batch_delay: float = 0.0@dataclass(slots=True)@@ -501,6 +502,7 @@ def resolve_embedding_runtime_config(dimension=dimension,request_timeout=60,batch_size=10,+ batch_delay=0.0,)diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.pyindex f4d696b40..40ec30f79 100644--- a/deeptutor/services/embedding/adapters/openai_compatible.py+++ b/deeptutor/services/embedding/adapters/openai_compatible.py@@ -88,8 +88,9 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):f"Top-level keys={keys}, expected one of: data/embeddings/result/output.")- _MAX_RETRIES = 2+ _MAX_RETRIES = 5_RETRY_BACKOFF = 1.0+ _RATE_LIMIT_BACKOFF = 5.0async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:import asyncio@@ -136,6 +137,18 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):async with httpx.AsyncClient(timeout=timeout) as client:response = await client.post(url, json=payload, headers=headers)+ # Handle rate limiting (429) with retry+ if response.status_code == 429:+ retry_after = float(response.headers.get("Retry-After", 0))+ wait = max(retry_after, self._RATE_LIMIT_BACKOFF * (2 ** attempt))+ logger.warning(+ f"Rate limited (429) on attempt {attempt + 1}/{1 + self._MAX_RETRIES}, "+ f"retrying in {wait:.1f}s..."+ )+ await asyncio.sleep(wait)+ last_exc = Exception(f"HTTP 429 Too Many Requests")+ continue+if response.status_code >= 400:logger.error(f"HTTP {response.status_code} response body: {response.text}")@@ -145,10 +158,10 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):except (httpx.ReadTimeout, httpx.ConnectTimeout, httpx.PoolTimeout) as exc:last_exc = excif attempt < self._MAX_RETRIES:- wait = self._RETRY_BACKOFF * (attempt + 1)+ wait = self._RETRY_BACKOFF * (2 ** attempt)logger.warning(f"Embedding request timeout (attempt {attempt + 1}/{1 + self._MAX_RETRIES}), "- f"retrying in {wait:.0f}s..."+ f"retrying in {wait:.1f}s...")await asyncio.sleep(wait)else:@@ -156,6 +169,9 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):f"Embedding request failed after {1 + self._MAX_RETRIES} attempts: {exc}")raise+ else:+ if last_exc:+ raise last_excembeddings = self._extract_embeddings_from_response(data)if not embeddings:diff --git a/deeptutor/services/embedding/client.py b/deeptutor/services/embedding/client.pyindex 721188e13..454862a03 100644--- a/deeptutor/services/embedding/client.py+++ b/deeptutor/services/embedding/client.py@@ -60,15 +60,21 @@ class EmbeddingClient:f"(model: {self.config.model}, dimensions: {self.config.dim})")- async def embed(self, texts: List[str]) -> List[List[float]]:+ async def embed(+ self, texts: List[str], progress_callback=None+ ) -> List[List[float]]:if not texts:return []+ import asyncio+batch_size = max(1, self.config.batch_size)all_embeddings: List[List[float]] = []+ batch_delay = self.config.batch_delaytry:- for start in range(0, len(texts), batch_size):+ total_batches = (len(texts) + batch_size - 1) // batch_size+ for i, start in enumerate(range(0, len(texts), batch_size)):batch = texts[start : start + batch_size]request = EmbeddingRequest(texts=batch,@@ -77,6 +83,18 @@ class EmbeddingClient:)response = await self.adapter.embed(request)all_embeddings.extend(response.embeddings)++ # Report progress after each batch+ if progress_callback:+ try:+ progress_callback(i + 1, total_batches)+ except Exception:+ pass++ # Delay between batches to avoid rate limiting+ if i < total_batches - 1 and batch_delay > 0:+ await asyncio.sleep(batch_delay)+self.logger.debug(f"Generated {len(all_embeddings)} embeddings using "f"{self.config.binding} (batch_size={batch_size})"diff --git a/deeptutor/services/embedding/config.py b/deeptutor/services/embedding/config.pyindex beba3bcb6..107911543 100644--- a/deeptutor/services/embedding/config.py+++ b/deeptutor/services/embedding/config.py@@ -23,6 +23,7 @@ class EmbeddingConfig:dim: int = 3072request_timeout: int = 60batch_size: int = 10+ batch_delay: float = 0.0def get_embedding_config() -> EmbeddingConfig:@@ -55,5 +56,6 @@ def get_embedding_config() -> EmbeddingConfig:dim=resolved.dimension,request_timeout=max(1, resolved.request_timeout),batch_size=max(1, resolved.batch_size),+ batch_delay=max(0.0, resolved.batch_delay),)diff --git a/deeptutor/services/rag/pipelines/llamaindex.py b/deeptutor/services/rag/pipelines/llamaindex.pyindex fac75eded..7157d1c84 100644--- a/deeptutor/services/rag/pipelines/llamaindex.py+++ b/deeptutor/services/rag/pipelines/llamaindex.py@@ -42,11 +42,18 @@ class CustomEmbedding(BaseEmbedding):_client: Any = PrivateAttr()_logger: Any = PrivateAttr()+ _progress_callback: Any = PrivateAttr(default=None)def __init__(self, **kwargs):+ progress_cb = kwargs.pop("progress_callback", None)super().__init__(**kwargs)self._client = get_embedding_client()self._logger = get_logger("CustomEmbedding")+ self._progress_callback = progress_cb++ def set_progress_callback(self, callback):+ """Set progress callback fn(batch_num, total_batches)."""+ self._progress_callback = callback@classmethoddef class_name(cls) -> str:@@ -76,7 +83,9 @@ class CustomEmbedding(BaseEmbedding):async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:"""Get embeddings for multiple texts."""- return await self._client.embed(texts)+ return await self._client.embed(+ texts, progress_callback=self._progress_callback+ )def _get_query_embedding(self, query: str) -> List[float]:"""Sync version - called by LlamaIndex sync API."""@@ -88,9 +97,9 @@ class CustomEmbedding(BaseEmbedding):def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:"""Sync batch version - called by LlamaIndex for bulk embedding."""- self._logger.info(f"Embedding batch of {len(texts)} texts...")+ self._logger.info(f"Embedding {len(texts)} text chunks...")result = self._run_in_new_loop(self._aget_text_embeddings(texts))- self._logger.info(f"Batch embedding complete: {len(result)} vectors")+ self._logger.info(f"Embedding complete: {len(result)} vectors")return result@@ -153,11 +162,13 @@ class LlamaIndexPipeline:Args:kb_name: Knowledge base namefile_paths: List of file paths to process- **kwargs: Additional arguments+ **kwargs: Additional arguments (accepts progress_callback)Returns:True if successful"""+ progress_callback = kwargs.get("progress_callback")+self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files using LlamaIndex")@@ -222,6 +233,9 @@ class LlamaIndexPipeline:f"(chunking + embedding)...")+ if progress_callback and isinstance(Settings.embed_model, CustomEmbedding):+ Settings.embed_model.set_progress_callback(progress_callback)+loop = asyncio.get_event_loop()index = await loop.run_in_executor(None,@@ -241,6 +255,9 @@ class LlamaIndexPipeline:self.logger.error(traceback.format_exc())return False+ finally:+ if isinstance(Settings.embed_model, CustomEmbedding):+ Settings.embed_model.set_progress_callback(None)def _extract_pdf_text(self, file_path: Path) -> str:"""Extract text from PDF using PyMuPDF."""@@ -356,11 +373,13 @@ class LlamaIndexPipeline:Args:kb_name: Knowledge base namefile_paths: List of file paths to add- **kwargs: Additional arguments+ **kwargs: Additional arguments (accepts progress_callback)Returns:True if successful"""+ progress_callback = kwargs.get("progress_callback")+self.logger.info(f"Adding {len(file_paths)} documents to KB '{kb_name}' using LlamaIndex")kb_dir = Path(self.kb_base_dir) / kb_name@@ -369,6 +388,9 @@ class LlamaIndexPipeline:try:await self._verify_embedding_connectivity()+ if progress_callback and isinstance(Settings.embed_model, CustomEmbedding):+ Settings.embed_model.set_progress_callback(progress_callback)+# Parse new documents with centralized file routingdocuments = []classification = FileTypeRouter.classify_files(file_paths)@@ -458,6 +480,9 @@ class LlamaIndexPipeline:self.logger.error(traceback.format_exc())return False+ finally:+ if isinstance(Settings.embed_model, CustomEmbedding):+ Settings.embed_model.set_progress_callback(None)async def delete(self, kb_name: str) -> bool:"""diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.pyindex e06fae9f3..8c6251ae9 100644--- a/deeptutor/services/rag/service.py+++ b/deeptutor/services/rag/service.py@@ -84,10 +84,14 @@ class RAGService:self._pipeline = get_pipeline(self.provider, kb_base_dir=self.kb_base_dir)return self._pipeline- async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:+ async def initialize(+ self, kb_name: str, file_paths: List[str], **kwargs+ ) -> bool:self.logger.info(f"Initializing KB '{kb_name}' with provider '{self.provider}'")pipeline = self._get_pipeline()- return await pipeline.initialize(kb_name=kb_name, file_paths=file_paths, **kwargs)+ return await pipeline.initialize(+ kb_name=kb_name, file_paths=file_paths, **kwargs+ )async def search(self,