DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
chore: prepare v1.3.2 release
Bingxi Zhao (Frank)a069b6ebf071
diff --git a/README.md b/README.mdindex f4b6fdc6b..b78286fc3 100644--- a/README.md+++ b/README.md@@ -28,6 +28,8 @@### π¦ Releases+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) β Transparent embedding endpoint URLs, RAG re-index resilience for invalid persisted vectors, memory cleanup for thinking-model output, Deep Solve runtime fix.+> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) β Stability: safer RAG routing & embedding validation, Docker persistence, IME-safe input, Windows/GBK robustness.> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) β Versioned KB indexes with re-index workflow, rebuilt Knowledge workspace, embedding auto-discovery with new adapters, Space hub.@@ -50,10 +52,10 @@> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) β LaTeX block math overhaul, LLM diagnostic probe, Docker + local LLM guidance.-> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) β Bookmarkable sessions, Snow theme, WebSocket heartbeat & auto-reconnect, embedding registry overhaul.-<details>-<summary><b>Past releases</b></summary>+<summary><b>Past releases (more than 2 weeks ago)</b></summary>++> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) β Bookmarkable sessions, Snow theme, WebSocket heartbeat & auto-reconnect, embedding registry overhaul.> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) β Question Notebook with bookmarks & categories, Mermaid in Visualize, embedding mismatch detection, Qwen/vLLM compatibility, LM Studio & llama.cpp support, and Glass theme.diff --git a/assets/releases/ver1-3-2.md b/assets/releases/ver1-3-2.mdnew file mode 100644index 000000000..1b3ec9ca0--- /dev/null+++ b/assets/releases/ver1-3-2.md@@ -0,0 +1,129 @@+# DeepTutor v1.3.2 Release Notes++**Release Date:** 2026.04.29++v1.3.2 is a focused stability release after v1.3.1. It tightens the embedding+endpoint contract, makes LlamaIndex RAG recover more cleanly from stale or+invalid indexes, and prevents reasoning-model scratchpad output from leaking+into long-term memory.++## Highlights++### Transparent Embedding Endpoint URLs++Embedding configuration is now explicit about the exact URL DeepTutor will call.+This removes the hidden "base URL vs endpoint URL" ambiguity that could make a+successful Settings test behave differently from a Knowledge Base re-index.++- **Settings now shows Endpoint URL for embeddings** - the Web settings page+ labels embedding URLs as endpoint URLs and explains that DeepTutor posts to+ the visible URL exactly, without appending `/embeddings` or `/api/embed` at+ request time.+- **Provider defaults are full endpoints** - OpenAI, OpenRouter, Jina, vLLM/LM+ Studio, and SiliconFlow default to `/embeddings`; Ollama defaults to+ `/api/embed`; Cohere defaults to `/embed`; DashScope keeps its native+ multimodal embedding endpoint.+- **Legacy base URLs are migrated safely** - saved embedding profiles using+ old-style bases such as `https://api.openai.com/v1`,+ `https://openrouter.ai/api/v1`, or `http://localhost:11434` are normalized to+ the full endpoint form and persisted back to the model catalog. Custom+ OpenAI-compatible URLs are left untouched.+- **Misconfigured endpoints fail early** - the embedding client now rejects+ known-provider URLs that point to a root/base path instead of the real+ embedding endpoint, with an actionable message before indexing starts.+- **OpenRouter embedding uses exact-URL HTTP** - public embedding providers no+ longer route through the OpenAI SDK's hidden path-appending behavior.+ `custom_openai_sdk` remains available for legacy configs, but is hidden from+ the Settings provider dropdown.+- **Connection-test diagnostics match runtime behavior** - embedding tests now+ report "POSTed exactly as shown in Settings", matching the adapter behavior+ used by RAG indexing and retrieval.++### RAG Re-index and Retrieval Resilience++The LlamaIndex pipeline now refreshes embedding state more aggressively and+turns invalid persisted vectors into clear re-index guidance instead of raw+Python or NumPy errors.++- **Cached pipelines pick up Settings changes** - initialize, search, and+ incremental add paths reconfigure LlamaIndex before use, so a long-lived+ pipeline does not keep embedding model, dimension, or endpoint settings from+ an older Settings session.+- **Embedding clients refresh when config changes** - the shared embedding+ client is recreated when the resolved runtime config changes, and the+ LlamaIndex `CustomEmbedding` adapter fingerprints the active config before+ reusing a cached client.+- **Persisted index vectors are validated before retrieval** - LlamaIndex+ storage now checks the saved vector store for null, non-numeric, non-finite,+ dropped, or inconsistent vectors before running similarity search.+- **Invalid indexes return a re-index hint** - known failures such as+ `unsupported operand type(s) for *: 'NoneType' and 'float'`, vector shape+ mismatches, and newly detected invalid persisted vectors now return+ `needs_reindex: true` with a user-facing explanation.+- **Embedding connectivity checks use the same validation path** - the+ pre-index smoke test validates provider output with the same batch validator+ used during indexing and retrieval.+- **RAG error logs are quieter when the fix is known** - classified invalid+ embedding/index failures are logged as actionable warnings instead of noisy+ full tracebacks.++### Memory Cleanup for Thinking Models++Memory refresh now strips private reasoning blocks before they can become+durable user memory.++- **Thinking tags are removed before writes** - profile and summary rewrites run+ through the shared `clean_thinking_tags()` helper after code-fence cleanup, so+ `<think>` / `<thinking>` blocks from reasoning models are not saved into+ `PROFILE.md` or `SUMMARY.md`.+- **Existing memory files self-repair on read** - if an older memory file+ already contains closed or unclosed thinking tags, reading the snapshot cleans+ the content and writes the repaired version back to disk when possible.+- **Manual memory edits use the same cleanup** - direct memory writes also pass+ through the cleaner, keeping UI edits, refreshes, and runtime reads aligned.++### Settings and Runtime Polish++- **Embedding provider choices are less confusing** - Settings no longer offers+ the legacy `custom_openai_sdk` provider in the public dropdown, while existing+ saved profiles continue to resolve for backwards compatibility.+- **Model catalog normalization is persisted** - catalog loads now save when+ normalization changes active profile/model IDs or embedding endpoint URLs,+ preventing the same migration from repeating on every startup.+- **OpenAI-compatible embedding errors are clearer** - non-JSON or HTML+ embedding responses now point to wrong endpoint/model pairings without+ incorrectly suggesting only one gateway-specific cause.+- **Deep Solve ReAct calls are aligned again** - the solver loop no longer+ passes a stale `attachments` keyword into `SolverAgent.process()`, avoiding a+ runtime `TypeError` while keeping attachment forwarding on the planner and+ replan calls where it is supported.++## Tests++- Added endpoint migration coverage for OpenAI, OpenRouter, Ollama, and custom+ embedding profiles.+- Added Settings API coverage for full endpoint provider choices and hidden+ `custom_openai_sdk`.+- Added embedding client coverage for endpoint validation, OpenRouter's raw HTTP+ adapter path, client refresh on config changes, and exact URL transparency.+- Added LlamaIndex coverage for stale embedding-client refresh, repeated+ settings reconfiguration, invalid persisted vector detection, and re-index+ hints for invalid indexes.+- Added memory coverage for closed and unclosed thinking tags, plus repair of+ existing memory files during reads.+- Ran targeted Deep Solve/RAG capability tests covering solver runtime wiring+ after the stale `attachments` argument fix.++## Upgrade Notes++- Embedding URLs in Settings should now be full endpoint URLs. Existing known+ provider profiles are migrated automatically, but custom gateways should be+ reviewed manually if they use non-standard paths.+- If Knowledge Base search still reports invalid embedding vectors, re-index the+ affected KB after confirming the active embedding provider, model, dimension,+ and endpoint URL.+- Memory files containing old `<think>` blocks will be cleaned the next time the+ Memory page or memory service reads them; this read can update the underlying+ `PROFILE.md` or `SUMMARY.md` file to persist the cleaned version.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.1...v1.3.2diff --git a/deeptutor/agents/solve/agents/solver_agent.py b/deeptutor/agents/solve/agents/solver_agent.pyindex dc754bee4..dc9e6d50f 100644--- a/deeptutor/agents/solve/agents/solver_agent.py+++ b/deeptutor/agents/solve/agents/solver_agent.py@@ -56,7 +56,6 @@ class SolverAgent(BaseAgent):scratchpad: Scratchpad,memory_context: str = "",image_url: str | None = None,- attachments: list[Any] | None = None,round_index: int | None = None,) -> dict[str, str]:"""Run one ReAct iteration for the given plan step.@@ -67,7 +66,6 @@ class SolverAgent(BaseAgent):scratchpad: Current scratchpad state.memory_context: Historical memory context string.image_url: Optional image URL for multimodal questions.- attachments: Optional chat attachments for multimodal input.Returns:dict with keys: thought, action, action_input, self_note@@ -107,11 +105,8 @@ class SolverAgent(BaseAgent):"trace_meta": trace_meta,}- llm_attachments = list(attachments or [])if image_url:- llm_attachments.append(Attachment(type="image", url=image_url))- if llm_attachments:- llm_kwargs["attachments"] = llm_attachments+ llm_kwargs["attachments"] = [Attachment(type="image", url=image_url)]chunks: list[str] = []async for chunk in self.stream_llm(**llm_kwargs):diff --git a/deeptutor/agents/solve/main_solver.py b/deeptutor/agents/solve/main_solver.pyindex 9e00dd5d7..abfd6af49 100644--- a/deeptutor/agents/solve/main_solver.py+++ b/deeptutor/agents/solve/main_solver.py@@ -450,7 +450,6 @@ class MainSolver:scratchpad=scratchpad,memory_context=step_memory_context,image_url=image_url,- attachments=attachments,round_index=round_num + 1,)diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 8774f6a0d..dbc74e016 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -127,6 +127,7 @@ def _provider_choices() -> dict[str, list[dict[str, str]]]:"default_dim": str(spec.default_dim) if spec.default_dim else "",}for name, spec in EMBEDDING_PROVIDERS.items()+ if name != "custom_openai_sdk"],key=lambda p: p["label"].lower(),)diff --git a/deeptutor/services/config/embedding_endpoint.py b/deeptutor/services/config/embedding_endpoint.pynew file mode 100644index 000000000..16bc0266c--- /dev/null+++ b/deeptutor/services/config/embedding_endpoint.py@@ -0,0 +1,115 @@+"""Embedding endpoint URL helpers.++Embedding adapters post to the configured URL exactly. These helpers keep the+user-visible Settings value aligned with provider-specific endpoint paths.+"""++from __future__ import annotations++from urllib.parse import urlparse++EMBEDDING_PROVIDER_ALIASES = {+ "google": "openai",+ "gemini": "openai",+ "huggingface": "custom",+ "lm_studio": "vllm",+ "llama_cpp": "vllm",+ "openai_compatible": "custom",+}++EMBEDDING_PROVIDER_LABELS = {+ "openai": "OpenAI",+ "openrouter": "OpenRouter",+ "jina": "Jina",+ "vllm": "vLLM / LM Studio",+ "siliconflow": "SiliconFlow",+ "ollama": "Ollama",+ "cohere": "Cohere",+}++EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS = {+ "openai": "https://api.openai.com/v1/embeddings",+ "openrouter": "https://openrouter.ai/api/v1/embeddings",+ "cohere": "https://api.cohere.com/v2/embed",+ "jina": "https://api.jina.ai/v1/embeddings",+ "ollama": "http://localhost:11434/api/embed",+ "vllm": "http://localhost:8000/v1/embeddings",+ "siliconflow": "https://api.siliconflow.cn/v1/embeddings",+ "aliyun": (+ "https://dashscope.aliyuncs.com/api/v1/services/embeddings/"+ "multimodal-embedding/multimodal-embedding"+ ),+}++EMBEDDING_PROVIDERS_REQUIRING_EMBEDDINGS_PATH = {+ "openai",+ "openrouter",+ "jina",+ "vllm",+ "siliconflow",+}+++def canonical_embedding_provider_name(name: str | None) -> str:+ value = str(name or "").strip().lower().replace("-", "_")+ return EMBEDDING_PROVIDER_ALIASES.get(value, value)+++def _same_origin_url(url: str, path: str) -> str:+ parsed = urlparse(url if "://" in url else f"http://{url}")+ if parsed.scheme and parsed.netloc:+ return f"{parsed.scheme}://{parsed.netloc}{path}"+ return url.rstrip("/") + path+++def normalize_embedding_endpoint_for_display(provider: str | None, base_url: str | None) -> str:+ """Return the full endpoint URL that should be shown and saved in Settings."""+ provider_name = canonical_embedding_provider_name(provider)+ url = str(base_url or "").strip()+ if not url:+ return EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS.get(provider_name, "")++ trimmed = url.rstrip("/")+ if provider_name in EMBEDDING_PROVIDERS_REQUIRING_EMBEDDINGS_PATH:+ if trimmed.endswith("/embeddings"):+ return trimmed+ if trimmed.endswith("/v1"):+ return f"{trimmed}/embeddings"+ if provider_name == "ollama":+ if trimmed.endswith("/api/embed"):+ return trimmed+ if trimmed.endswith("/api"):+ return f"{trimmed}/embed"+ parsed = urlparse(trimmed if "://" in trimmed else f"http://{trimmed}")+ if parsed.scheme and parsed.netloc and parsed.path in {"", "/"}:+ return _same_origin_url(trimmed, "/api/embed")+ if provider_name == "cohere":+ if trimmed.endswith("/embed"):+ return trimmed+ if trimmed.endswith("/v2"):+ return f"{trimmed}/embed"+ return url+++def embedding_endpoint_validation_error(provider: str | None, base_url: str | None) -> str | None:+ """Validate that known providers use the exact endpoint path shown to users."""+ provider_name = canonical_embedding_provider_name(provider)+ url = str(base_url or "").strip()+ if not url:+ return "Embedding endpoint URL is empty."++ parsed = urlparse(url if "://" in url else f"http://{url}")+ path = parsed.path.rstrip("/")+ label = EMBEDDING_PROVIDER_LABELS.get(provider_name, provider_name or "Embedding provider")++ if provider_name in EMBEDDING_PROVIDERS_REQUIRING_EMBEDDINGS_PATH:+ if not path.endswith("/embeddings"):+ return f"{label} embedding endpoint must end with /embeddings."+ elif provider_name == "ollama":+ if path != "/api/embed":+ return "Ollama embedding endpoint must be the full /api/embed URL."+ elif provider_name == "cohere":+ if not path.endswith("/embed"):+ return "Cohere embedding endpoint must end with /embed."++ return Nonediff --git a/deeptutor/services/config/model_catalog.py b/deeptutor/services/config/model_catalog.pyindex 311212c12..5609a6816 100644--- a/deeptutor/services/config/model_catalog.py+++ b/deeptutor/services/config/model_catalog.py@@ -8,6 +8,7 @@ from uuid import uuid4from deeptutor.services.path_service import get_path_service+from .embedding_endpoint import normalize_embedding_endpoint_for_displayfrom .env_store import get_env_storeCATALOG_PATH = get_path_service().get_settings_file("model_catalog")@@ -73,8 +74,8 @@ class ModelCatalogService:synced = Falseif self._is_catalog_pristine(catalog):synced = self._sync_active_services_from_env(catalog)- self._normalize(catalog)- if hydrated or synced:+ normalized = self._normalize(catalog)+ if hydrated or synced or normalized:self.save(catalog)return catalog@@ -432,8 +433,9 @@ class ModelCatalogService:return changed- def _normalize(self, catalog: dict[str, Any]) -> None:+ def _normalize(self, catalog: dict[str, Any]) -> bool:services = catalog.setdefault("services", {})+ changed = Falseservices.setdefault("llm", _service_shell())services.setdefault("embedding", _service_shell())services.setdefault("search", _search_shell())@@ -453,6 +455,15 @@ class ModelCatalogService:else:profile.setdefault("binding", "openai")profile.setdefault("extra_headers", {})+ if service_name == "embedding":+ before = str(profile.get("base_url") or "")+ after = normalize_embedding_endpoint_for_display(+ profile.get("binding"),+ before,+ )+ if after != before:+ profile["base_url"] = after+ changed = Truemodels = profile.setdefault("models", [])for model in models:model.setdefault("id", f"{service_name}-model-{uuid4().hex[:8]}")@@ -469,11 +480,14 @@ class ModelCatalogService:model.setdefault("supported_dimensions", "")if profiles and not service.get("active_profile_id"):service["active_profile_id"] = profiles[0]["id"]+ changed = Trueif service_name in {"llm", "embedding"}:if not service.get("active_model_id"):active_profile = self.get_active_profile(catalog, service_name)if active_profile and active_profile.get("models"):service["active_model_id"] = active_profile["models"][0]["id"]+ changed = True+ return changeddef get_active_profile(self, catalog: dict[str, Any], service_name: strdiff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex f3e8d2442..87402a466 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -17,6 +17,12 @@ from deeptutor.services.provider_registry import (find_gateway,)+from .embedding_endpoint import (+ EMBEDDING_PROVIDER_ALIASES,+ EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS,+ embedding_endpoint_validation_error,+ normalize_embedding_endpoint_for_display,+)from .env_store import EnvStore, get_env_storefrom .loader import load_config_with_mainfrom .model_catalog import ModelCatalogService, get_model_catalog_service@@ -42,16 +48,6 @@ SEARCH_ENV_FALLBACK = {LLM_LOCALHOST_PROVIDERS = ("ollama", "vllm")-EMBEDDING_PROVIDER_ALIASES = {- "google": "openai",- "gemini": "openai",- "huggingface": "custom",- "lm_studio": "vllm",- "llama_cpp": "vllm",- "openai_compatible": "custom",-}--@dataclass(frozen=True)class EmbeddingProviderSpec:"""Single embedding-provider metadata entry.@@ -81,7 +77,7 @@ class EmbeddingProviderSpec:EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {"openai": EmbeddingProviderSpec(label="OpenAI",- default_api_base="https://api.openai.com/v1/embeddings",+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["openai"],keywords=("openai", "text-embedding", "ada-002", "embedding-3"),is_local=False,api_key_envs=("OPENAI_API_KEY",),@@ -99,7 +95,7 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {"cohere": EmbeddingProviderSpec(label="Cohere",adapter="cohere",- default_api_base="https://api.cohere.com/v2/embed",+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["cohere"],keywords=("cohere", "embed-v4", "embed-english", "embed-multilingual"),is_local=False,api_key_envs=("COHERE_API_KEY",),@@ -110,7 +106,7 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {"jina": EmbeddingProviderSpec(label="Jina",adapter="jina",- default_api_base="https://api.jina.ai/v1/embeddings",+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["jina"],keywords=("jina", "jina-embeddings"),is_local=False,api_key_envs=("JINA_API_KEY",),@@ -121,7 +117,7 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {label="Ollama",adapter="ollama",mode="local",- default_api_base="http://localhost:11434/api/embed",+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["ollama"],keywords=("ollama", "nomic-embed", "mxbai", "snowflake-arctic", "all-minilm"),is_local=True,api_key_envs=(),@@ -131,7 +127,7 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {"vllm": EmbeddingProviderSpec(label="vLLM / LM Studio",mode="local",- default_api_base="http://localhost:8000/v1/embeddings",+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["vllm"],keywords=("vllm", "lmstudio"),is_local=True,api_key_envs=("HOSTED_VLLM_API_KEY",),@@ -139,7 +135,7 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {"siliconflow": EmbeddingProviderSpec(label="SiliconFlow",adapter="openai_compat",- default_api_base="https://api.siliconflow.cn/v1/embeddings",+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["siliconflow"],keywords=("siliconflow","qwen3-embedding",@@ -157,10 +153,7 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {"aliyun": EmbeddingProviderSpec(label="Aliyun DashScope",adapter="dashscope_native",- default_api_base=(- "https://dashscope.aliyuncs.com/api/v1/services/embeddings/"- "multimodal-embedding/multimodal-embedding"- ),+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["aliyun"],keywords=("dashscope", "qwen3-vl-embedding", "qwen3-embedding", "aliyun", "bailian"),is_local=False,api_key_envs=("DASHSCOPE_API_KEY",),@@ -177,11 +170,8 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {is_local=False,api_key_envs=("OPENAI_API_KEY",),),- # `custom_openai_sdk` and `openrouter` route through the official `openai`- # SDK (AsyncOpenAI), which auto-appends `/embeddings` to the configured- # base URL. Use these when the gateway documents OpenAI-SDK-style usage- # (give a /v1 base, the SDK builds the endpoint). For "exact URL, no- # appending" semantics, use `custom` (OpenAI Compatible) instead.+ # Retained for legacy configs only. Public Settings providers use exact+ # endpoint URLs and raw HTTP adapters so no request path is hidden."custom_openai_sdk": EmbeddingProviderSpec(label="Custom (OpenAI SDK)",adapter="openai_sdk",@@ -193,8 +183,8 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {),"openrouter": EmbeddingProviderSpec(label="OpenRouter",- adapter="openai_sdk",- default_api_base="https://openrouter.ai/api/v1",+ adapter="openai_compat",+ default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["openrouter"],keywords=("openrouter",),is_local=False,api_key_envs=("OPENROUTER_API_KEY",),@@ -811,6 +801,8 @@ __all__ = ["EmbeddingProviderSpec","EMBEDDING_PROVIDERS","EMBEDDING_PROVIDER_ALIASES",+ "embedding_endpoint_validation_error",+ "normalize_embedding_endpoint_for_display","NormalizedProviderConfig","ResolvedLLMConfig","ResolvedEmbeddingConfig",diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.pyindex 3c6a32255..621dec524 100644--- a/deeptutor/services/config/test_runner.py+++ b/deeptutor/services/config/test_runner.py@@ -18,7 +18,6 @@ from .context_window_detection import detect_context_windowfrom .env_store import get_env_storefrom .model_catalog import get_model_catalog_servicefrom .provider_runtime import (- EMBEDDING_PROVIDERS,resolve_embedding_runtime_config,resolve_llm_runtime_config,resolve_search_runtime_config,@@ -340,19 +339,9 @@ class ConfigTestRunner:run.emit("info", f"Resolved embedding model `{config.model}` with binding `{config.binding}`.")- # URL semantics differ by adapter family:- # * `openai_sdk` β AsyncOpenAI auto-appends `/embeddings` to base_url- # * everything else (openai_compat / cohere / jina / ollama / dashscope)- # β POSTs to `base_url` verbatim- spec = EMBEDDING_PROVIDERS.get(config.binding)- url_note = (- "OpenAI SDK appends `/embeddings`"- if spec and spec.adapter == "openai_sdk"- else "POSTed verbatim, no path appending"- )run.emit("info",- f"Request target ({url_note}): {config.base_url}",+ f"Request target (POSTed exactly as shown in Settings): {config.base_url}",)run.emit("info",diff --git a/deeptutor/services/embedding/__init__.py b/deeptutor/services/embedding/__init__.pyindex 77ef18aa4..cea07d902 100644--- a/deeptutor/services/embedding/__init__.py+++ b/deeptutor/services/embedding/__init__.py@@ -2,7 +2,7 @@Supported bindings are resolved by ``services.config.provider_runtime`` andcurrently include openai, custom, azure_openai, cohere, jina, ollama, vllm,-siliconflow, aliyun, custom_openai_sdk, and openrouter.+siliconflow, aliyun, openrouter, plus legacy custom_openai_sdk configs."""from .adapters import (diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.pyindex 7aa0f3d5d..ca646ca18 100644--- a/deeptutor/services/embedding/adapters/openai_compatible.py+++ b/deeptutor/services/embedding/adapters/openai_compatible.py@@ -209,11 +209,9 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):provider="openai_compat",)- # A 2xx response with non-JSON body means the gateway either- # doesn't expose `/v1/embeddings` (e.g. OpenRouter, which is- # chat-completion-only) or routed us to an HTML error page.- # Surface that as a structured error rather than a bare- # JSONDecodeError so the diagnostics UI can guide the user.+ # A 2xx response with non-JSON body usually means the+ # endpoint/model pairing is wrong or a gateway routed us to+ # an HTML page. Surface that as structured diagnostics.try:data = response.json()except (json.JSONDecodeError, ValueError) as exc:@@ -224,8 +222,8 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):if not body_text.strip():hint = (" The response body was empty β the endpoint may "- "not support embeddings (e.g. OpenRouter is "- "chat-completion only)."+ "not support embeddings or the selected model "+ "may not be an embedding model.")elif "text/html" in content_type.lower() or body_preview.lstrip().startswith("<"):hint = (diff --git a/deeptutor/services/embedding/adapters/openai_sdk.py b/deeptutor/services/embedding/adapters/openai_sdk.pyindex d555f5439..e0b553dec 100644--- a/deeptutor/services/embedding/adapters/openai_sdk.py+++ b/deeptutor/services/embedding/adapters/openai_sdk.py@@ -1,15 +1,8 @@-"""OpenAI SDK-based embedding adapter for OpenAI-compatible gateways.--Unlike :mod:`openai_compatible` (which POSTs to ``base_url`` verbatim via raw-httpx), this adapter wraps the official ``openai`` Python SDK. The SDK-auto-appends ``/embeddings`` to whichever ``base_url`` it's given, which-matches the convention most third-party gateways document (e.g. OpenRouter,-custom OpenAI proxies): users supply a ``/v1``-style base and the SDK builds-the endpoint.--Use this adapter when interop with an OpenAI-compatible gateway is the goal;-use :class:`OpenAICompatibleEmbeddingAdapter` when "exact URL, no path-appending" is what the user wants.+"""Legacy embedding adapter using AsyncOpenAI.++Public Settings providers use exact endpoint URLs and raw HTTP adapters so the+URL shown in Settings is the URL sent on the wire. This SDK adapter is retained+for old configs/tests that intentionally depend on AsyncOpenAI semantics."""from __future__ import annotationsdiff --git a/deeptutor/services/embedding/client.py b/deeptutor/services/embedding/client.pyindex 0a4f0179f..c6da29bee 100644--- a/deeptutor/services/embedding/client.py+++ b/deeptutor/services/embedding/client.py@@ -5,7 +5,10 @@ from __future__ import annotationsfrom typing import List, Optionalfrom deeptutor.logging import get_logger-from deeptutor.services.config.provider_runtime import EMBEDDING_PROVIDERS+from deeptutor.services.config.provider_runtime import (+ EMBEDDING_PROVIDERS,+ embedding_endpoint_validation_error,+)from .adapters import ADAPTER_BACKENDS, BaseEmbeddingAdapter, EmbeddingRequestfrom .config import EmbeddingConfig, get_embedding_config@@ -34,6 +37,14 @@ class EmbeddingClient:def __init__(self, config: Optional[EmbeddingConfig] = None):self.config = config or get_embedding_config()self.logger = get_logger("EmbeddingClient")+ endpoint = self.config.effective_url or self.config.base_url+ problem = embedding_endpoint_validation_error(self.config.binding, endpoint)+ if problem:+ raise ValueError(+ f"{problem} Current Settings endpoint is {endpoint!r}. "+ "DeepTutor sends embedding requests to the Settings URL exactly; "+ "update the visible Endpoint URL instead of relying on hidden path appending."+ )adapter_class = _resolve_adapter_class(self.config.binding)self.adapter = adapter_class({@@ -167,8 +178,9 @@ _client: Optional[EmbeddingClient] = Nonedef get_embedding_client(config: Optional[EmbeddingConfig] = None) -> EmbeddingClient:global _client- if _client is None:- _client = EmbeddingClient(config)+ resolved_config = config or get_embedding_config()+ if _client is None or _client.config != resolved_config:+ _client = EmbeddingClient(resolved_config)return _clientdiff --git a/deeptutor/services/memory/service.py b/deeptutor/services/memory/service.pyindex 72d55f174..0997e3fc3 100644--- a/deeptutor/services/memory/service.py+++ b/deeptutor/services/memory/service.py@@ -17,6 +17,7 @@ from pathlib import Pathimport refrom typing import Literal+from deeptutor.services.llm import clean_thinking_tagsfrom deeptutor.services.llm import stream as llm_streamfrom deeptutor.services.path_service import PathService, get_path_servicefrom deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store@@ -101,7 +102,17 @@ class MemoryService:if not path.exists():return ""try:- return path.read_text(encoding="utf-8").strip()+ raw = path.read_text(encoding="utf-8").strip()+ cleaned = _clean_memory_content(raw)+ if cleaned != raw:+ try:+ if cleaned:+ path.write_text(cleaned, encoding="utf-8")+ else:+ path.unlink()+ except Exception:+ pass+ return cleanedexcept Exception:return ""@@ -131,7 +142,7 @@ class MemoryService:# ββ Write βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef write_file(self, which: MemoryFile, content: str) -> MemorySnapshot:- normalized = str(content or "").strip()+ normalized = _clean_memory_content(str(content or ""))path = self._path(which)path.parent.mkdir(parents=True, exist_ok=True)if not normalized:@@ -293,7 +304,7 @@ class MemoryService:):chunks.append(c)- raw = _strip_code_fence("".join(chunks)).strip()+ raw = _clean_memory_content("".join(chunks))if not raw or raw == _NO_CHANGE:return False@@ -381,6 +392,11 @@ def _strip_code_fence(content: str) -> str:return cleaned.strip()+def _clean_memory_content(content: str) -> str:+ """Remove code fences and model scratchpad tags before durable memory writes."""+ return clean_thinking_tags(_strip_code_fence(content)).strip()++_memory_service: MemoryService | None = Nonediff --git a/deeptutor/services/rag/pipelines/llamaindex/embedding_adapter.py b/deeptutor/services/rag/pipelines/llamaindex/embedding_adapter.pyindex 465bb046c..fe5783e67 100644--- a/deeptutor/services/rag/pipelines/llamaindex/embedding_adapter.py+++ b/deeptutor/services/rag/pipelines/llamaindex/embedding_adapter.py@@ -10,10 +10,22 @@ from llama_index.core.base.embeddings.base import BaseEmbeddingfrom llama_index.core.bridge.pydantic import PrivateAttrfrom deeptutor.logging import get_logger-from deeptutor.services.embedding import get_embedding_client, get_embedding_config+from deeptutor.services.embedding import EmbeddingConfig, get_embedding_client, get_embedding_configfrom deeptutor.services.embedding.validation import validate_embedding_batch+def _config_fingerprint(config: EmbeddingConfig) -> tuple[Any, ...]:+ """Return the settings fields that affect LlamaIndex embedding behavior."""+ return (+ getattr(config, "binding", None),+ getattr(config, "model", None),+ getattr(config, "dim", None),+ getattr(config, "effective_url", None) or getattr(config, "base_url", None),+ getattr(config, "api_version", None),+ getattr(config, "send_dimensions", None),+ )++class CustomEmbedding(BaseEmbedding):"""Custom LlamaIndex embedding adapter for DeepTutor embedding providers."""@@ -22,16 +34,40 @@ class CustomEmbedding(BaseEmbedding):_progress_callback: Any = PrivateAttr(default=None)_binding: Any = PrivateAttr(default=None)_model: Any = PrivateAttr(default=None)+ _fingerprint: Any = PrivateAttr(default=None)def __init__(self, **kwargs):progress_cb = kwargs.pop("progress_callback", None)+ embedding_config = kwargs.pop("embedding_config", None)super().__init__(**kwargs)- self._client = get_embedding_client()self._logger = get_logger("CustomEmbedding")self._progress_callback = progress_cb+ client = (+ get_embedding_client(embedding_config)+ if embedding_config is not None+ else get_embedding_client()+ )+ self._bind_client(client)++ def _bind_client(self, client: Any) -> None:+ self._client = clientclient_config = getattr(self._client, "config", None)self._binding = getattr(client_config, "binding", None)self._model = getattr(client_config, "model", None)+ self._fingerprint = (+ _config_fingerprint(client_config) if client_config is not None else None+ )++ def matches_config(self, config: EmbeddingConfig) -> bool:+ """Return whether this adapter was created for the active config."""+ return self._fingerprint == _config_fingerprint(config)++ def refresh_client(self, config: EmbeddingConfig | None = None) -> Any:+ """Refresh the cached client if settings changed while the pipeline lived."""+ client = get_embedding_client(config) if config is not None else get_embedding_client()+ if client is not self._client:+ self._bind_client(client)+ return self._clientdef set_progress_callback(self, callback):"""Set progress callback fn(batch_num, total_batches)."""@@ -50,7 +86,8 @@ class CustomEmbedding(BaseEmbedding):loop.close()async def _aget_query_embedding(self, query: str) -> List[float]:- embeddings = await self._client.embed([query])+ client = self.refresh_client()+ embeddings = await client.embed([query])return validate_embedding_batch(embeddings,expected_count=1,@@ -59,7 +96,8 @@ class CustomEmbedding(BaseEmbedding):)[0]async def _aget_text_embedding(self, text: str) -> List[float]:- embeddings = await self._client.embed([text])+ client = self.refresh_client()+ embeddings = await client.embed([text])return validate_embedding_batch(embeddings,expected_count=1,@@ -68,9 +106,8 @@ class CustomEmbedding(BaseEmbedding):)[0]async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:- embeddings = await self._client.embed(- texts, progress_callback=self._progress_callback- )+ client = self.refresh_client()+ embeddings = await client.embed(texts, progress_callback=self._progress_callback)return validate_embedding_batch(embeddings,expected_count=len(texts),@@ -95,15 +132,25 @@ def configure_llamaindex_settings(logger=None) -> None:"""Configure LlamaIndex globals for DeepTutor's current embedding config."""embedding_cfg = get_embedding_config()- Settings.embed_model = CustomEmbedding()+ current = getattr(Settings, "_embed_model", None)+ configured = False+ if isinstance(current, CustomEmbedding) and current.matches_config(embedding_cfg):+ current.refresh_client(embedding_cfg)+ else:+ Settings.embed_model = CustomEmbedding(embedding_config=embedding_cfg)+ configured = TrueSettings.chunk_size = 512Settings.chunk_overlap = 50if logger is not None:- logger.info(+ message = (f"LlamaIndex configured: embedding={embedding_cfg.model} "f"({embedding_cfg.dim}D, {embedding_cfg.binding}), chunk_size=512")+ if configured:+ logger.info(message)+ else:+ logger.debug(message)def set_progress_callback(callback) -> None:@@ -120,14 +167,17 @@ async def verify_embedding_connectivity(logger=None) -> None:try:client = get_embedding_client()result = await client.embed(["connectivity test"])- if not result or not result[0]:- raise RuntimeError("Embedding API returned empty result")+ validated = validate_embedding_batch(+ result,+ expected_count=1,+ binding=getattr(client.config, "binding", None),+ model=getattr(client.config, "model", None),+ )if logger is not None:- logger.info(f"Embedding API OK (returned {len(result[0])}-dim vector)")+ logger.info(f"Embedding API OK (returned {len(validated[0])}-dim vector)")except Exception as exc:if logger is not None:logger.error(f"Embedding API connectivity check failed: {exc}")raise RuntimeError(- "Cannot reach embedding API. Please check your embedding configuration. "- f"Error: {exc}"+ f"Cannot reach embedding API. Please check your embedding configuration. Error: {exc}") from excdiff --git a/deeptutor/services/rag/pipelines/llamaindex/errors.py b/deeptutor/services/rag/pipelines/llamaindex/errors.pyindex 90a485362..73b9d6c97 100644--- a/deeptutor/services/rag/pipelines/llamaindex/errors.py+++ b/deeptutor/services/rag/pipelines/llamaindex/errors.py@@ -24,14 +24,13 @@ def search_error_result(query: str, exc: Exception) -> Dict[str, Any]:}null_vector_similarity_error = (- "unsupported operand type(s) for *" in lower- and "nonetype" in lower- and "float" in lower+ "unsupported operand type(s) for *" in lower and "nonetype" in lower and "float" in lower)shape_vector_error = "inhomogeneous shape" in lower or ("shapes" in lower and "not aligned" in lower)- if null_vector_similarity_error or shape_vector_error:+ invalid_persisted_index = "rag index contains invalid embedding vectors" in lower+ if null_vector_similarity_error or shape_vector_error or invalid_persisted_index:return {"query": query,"answer": (diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.pyindex c203c3a5e..25ebf9469 100644--- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py+++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py@@ -28,9 +28,7 @@ from .embedding_adapter import (from .errors import search_error_resultDEFAULT_KB_BASE_DIR = str(- Path(__file__).resolve().parent.parent.parent.parent.parent.parent- / "data"- / "knowledge_bases"+ Path(__file__).resolve().parent.parent.parent.parent.parent.parent / "data" / "knowledge_bases")SignatureProvider = Callable[[], EmbeddingSignature | None]@@ -61,9 +59,7 @@ class LlamaIndexPipeline:def _current_signature(self) -> EmbeddingSignature | None:return self._signature_provider()- def _cleanup_failed_version_dir(- self, storage_dir: Path, signature: Optional[Any]- ) -> None:+ def _cleanup_failed_version_dir(self, storage_dir: Path, signature: Optional[Any]) -> None:_ = signaturetry:if storage.cleanup_failed_version_dir(storage_dir):@@ -77,6 +73,7 @@ class LlamaIndexPipeline:async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:progress_callback = kwargs.get("progress_callback")+ self._configure_settings()self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files using LlamaIndex"@@ -129,6 +126,7 @@ class LlamaIndexPipeline:**kwargs,) -> Dict[str, Any]:kwargs.pop("mode", None)+ self._configure_settings()self.logger.info(f"Searching KB '{kb_name}' with query: {query[:50]}...")kb_dir = Path(self.kb_base_dir) / kb_name@@ -168,9 +166,13 @@ class LlamaIndexPipeline:return resultexcept Exception as exc:- self.logger.error(f"Search failed: {exc}")- self.logger.error(traceback.format_exc())- return search_error_result(query, exc)+ result = search_error_result(query, exc)+ if result.get("error_type"):+ self.logger.warning(f"Search failed ({result['error_type']}): {exc}")+ else:+ self.logger.error(f"Search failed: {exc}")+ self.logger.error(traceback.format_exc())+ return resultdef _embedding_mismatch_warning(self, kb_name: str) -> str:try:@@ -220,6 +222,7 @@ class LlamaIndexPipeline:async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:progress_callback = kwargs.get("progress_callback")+ self._configure_settings()self.logger.info(f"Adding {len(file_paths)} documents to KB '{kb_name}' using LlamaIndex")diff --git a/deeptutor/services/rag/pipelines/llamaindex/storage.py b/deeptutor/services/rag/pipelines/llamaindex/storage.pyindex cc5ff2ed6..be540f8dd 100644--- a/deeptutor/services/rag/pipelines/llamaindex/storage.py+++ b/deeptutor/services/rag/pipelines/llamaindex/storage.py@@ -9,6 +9,7 @@ from typing import Anyfrom llama_index.core import StorageContext, VectorStoreIndex, load_index_from_storage+from deeptutor.services.embedding.validation import validate_embedding_batchfrom deeptutor.services.rag.index_versioning import (EmbeddingSignature,find_matching_version,@@ -35,9 +36,7 @@ def cleanup_failed_version_dir(storage_dir: Path) -> bool:return False-def resolve_add_storage_plan(- kb_dir: Path, signature: EmbeddingSignature | None-) -> AddStoragePlan:+def resolve_add_storage_plan(kb_dir: Path, signature: EmbeddingSignature | None) -> AddStoragePlan:"""Choose existing/new storage dirs for incremental adds."""matching_version = find_matching_version(kb_dir, signature) if signature is not None else Noneexisting_storage = Path(str(matching_version["storage_path"])) if matching_version else None@@ -59,9 +58,7 @@ def resolve_add_storage_plan(and fallback_storage.name.startswith("version-"))storage_dir = (- fallback_storage- if fallback_is_flat- else resolve_storage_dir_for_write(kb_dir, signature)+ fallback_storage if fallback_is_flat else resolve_storage_dir_for_write(kb_dir, signature))return AddStoragePlan(existing_storage=existing_storage, storage_dir=storage_dir)@@ -72,9 +69,7 @@ def create_index(documents: list[Any], storage_dir: Path, *, show_progress: boolreturn len(documents)-def insert_documents(- existing_storage: Path, storage_dir: Path, documents: list[Any]-) -> int:+def insert_documents(existing_storage: Path, storage_dir: Path, documents: list[Any]) -> int:storage_context = StorageContext.from_defaults(persist_dir=str(existing_storage))index = load_index_from_storage(storage_context)for document in documents:@@ -83,9 +78,33 @@ def insert_documents(return len(documents)+def _validate_persisted_embeddings(index: Any) -> None:+ """Fail early when a persisted vector store contains unusable vectors."""+ vector_store = getattr(index, "vector_store", None)+ data = getattr(vector_store, "data", None)+ embedding_dict = getattr(data, "embedding_dict", None)+ if not isinstance(embedding_dict, dict) or not embedding_dict:+ return++ try:+ validate_embedding_batch(+ list(embedding_dict.values()),+ expected_count=len(embedding_dict),+ binding="llamaindex",+ model="persisted-index",+ )+ except ValueError as exc:+ raise ValueError(+ "RAG index contains invalid embedding vectors. Re-index the "+ "knowledge base with the current embedding provider/model before "+ f"querying it again. Details: {exc}"+ ) from exc++def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any]:storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))index = load_index_from_storage(storage_context)+ _validate_persisted_embeddings(index)retriever = index.as_retriever(similarity_top_k=top_k)return retriever.retrieve(query)diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex 4a8a21154..a993e89a3 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -196,6 +196,15 @@ def _patch_runtime()+def test_embedding_provider_choices_use_full_endpoint_urls() -> None:+ embedding = {item["value"]: item for item in settings_router._provider_choices()["embedding"]}++ assert embedding["openrouter"]["base_url"] == "https://openrouter.ai/api/v1/embeddings"+ assert embedding["ollama"]["base_url"] == "http://localhost:11434/api/embed"+ assert embedding["openai"]["base_url"] == "https://api.openai.com/v1/embeddings"+ assert "custom_openai_sdk" not in embedding++@pytest.fixture(autouse=True)def _reset_runtime_state() -> None:llm_config_module.clear_llm_config_cache()@@ -214,7 +223,7 @@ async def test_update_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monllm_base_url="https://old-llm.example/v1",llm_api_key="old-llm-key",embedding_model="text-embedding-old",- embedding_base_url="https://old-embedding.example/v1",+ embedding_base_url="https://old-embedding.example/v1/embeddings",embedding_api_key="old-embedding-key",)updated_catalog = _build_catalog(@@ -222,7 +231,7 @@ async def test_update_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monllm_base_url="https://new-llm.example/v1",llm_api_key="new-llm-key",embedding_model="text-embedding-new",- embedding_base_url="https://new-embedding.example/v1",+ embedding_base_url="https://new-embedding.example/v1/embeddings",embedding_api_key="new-embedding-key",)service = _FakeCatalogService(initial_catalog)@@ -249,7 +258,7 @@ async def test_update_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monassert new_llm_client.config.model == "gpt-new"assert new_embedding_client is not old_embedding_clientassert new_embedding_client.config.model == "text-embedding-new"- assert new_embedding_client.config.base_url == "https://new-embedding.example/v1"+ assert new_embedding_client.config.base_url == "https://new-embedding.example/v1/embeddings"@pytest.mark.asyncio@@ -259,7 +268,7 @@ async def test_apply_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monkllm_base_url="https://before-apply-llm.example/v1",llm_api_key="before-apply-llm-key",embedding_model="text-embedding-before-apply",- embedding_base_url="https://before-apply-embedding.example/v1",+ embedding_base_url="https://before-apply-embedding.example/v1/embeddings",embedding_api_key="before-apply-embedding-key",)applied_catalog = _build_catalog(@@ -267,7 +276,7 @@ async def test_apply_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monkllm_base_url="https://after-apply-llm.example/v1",llm_api_key="after-apply-llm-key",embedding_model="text-embedding-after-apply",- embedding_base_url="https://after-apply-embedding.example/v1",+ embedding_base_url="https://after-apply-embedding.example/v1/embeddings",embedding_api_key="after-apply-embedding-key",)service = _FakeCatalogService(initial_catalog)@@ -304,7 +313,7 @@ async def test_complete_tour_invalidates_runtime_caches(llm_base_url="https://before-tour-llm.example/v1",llm_api_key="before-tour-llm-key",embedding_model="text-embedding-before-tour",- embedding_base_url="https://before-tour-embedding.example/v1",+ embedding_base_url="https://before-tour-embedding.example/v1/embeddings",embedding_api_key="before-tour-embedding-key",)completed_catalog = _build_catalog(@@ -312,7 +321,7 @@ async def test_complete_tour_invalidates_runtime_caches(llm_base_url="https://after-tour-llm.example/v1",llm_api_key="after-tour-llm-key",embedding_model="text-embedding-after-tour",- embedding_base_url="https://after-tour-embedding.example/v1",+ embedding_base_url="https://after-tour-embedding.example/v1/embeddings",embedding_api_key="after-tour-embedding-key",)service = _FakeCatalogService(initial_catalog)diff --git a/tests/services/config/test_catalog_env_overlay.py b/tests/services/config/test_catalog_env_overlay.pyindex 8ae01db88..53c39286d 100644--- a/tests/services/config/test_catalog_env_overlay.py+++ b/tests/services/config/test_catalog_env_overlay.py@@ -202,3 +202,92 @@ def test_env_still_seeds_pristine_single_default_profile(assert profile["base_url"] == "https://api.openai.com/v1/embeddings"assert profile["api_key"] == "sk-newkey"assert profile["models"][0]["model"] == "text-embedding-3-small"+++def _write_single_embedding_profile_catalog(+ catalog_path: Path,+ *,+ binding: str,+ base_url: str,+) -> None:+ catalog_path.write_text(+ json.dumps(+ {+ "services": {+ "llm": {"active_profile_id": None, "profiles": []},+ "embedding": {+ "active_profile_id": "embedding-profile-default",+ "active_model_id": "embedding-model-default",+ "profiles": [+ {+ "id": "embedding-profile-default",+ "name": "Embedding",+ "binding": binding,+ "base_url": base_url,+ "api_key": "sk-test",+ "api_version": "",+ "extra_headers": {},+ "models": [+ {+ "id": "embedding-model-default",+ "name": "m",+ "model": "qwen/qwen3-embedding-8b",+ }+ ],+ }+ ],+ },+ "search": {"active_profile_id": None, "profiles": []},+ }+ }+ ),+ encoding="utf-8",+ )+++ ("binding", "base_url", "expected"),+ [+ (+ "openrouter",+ "https://openrouter.ai/api/v1",+ "https://openrouter.ai/api/v1/embeddings",+ ),+ ("ollama", "http://localhost:11434", "http://localhost:11434/api/embed"),+ ("ollama", "http://localhost:11434/api", "http://localhost:11434/api/embed"),+ ("openai", "https://api.openai.com/v1", "https://api.openai.com/v1/embeddings"),+ ],+)+def test_embedding_legacy_base_is_migrated_to_visible_endpoint(+ isolated_stores: tuple[Path, Path],+ binding: str,+ base_url: str,+ expected: str,+) -> None:+ catalog_path, _env_path = isolated_stores+ _write_single_embedding_profile_catalog(catalog_path, binding=binding, base_url=base_url)++ loaded = ModelCatalogService(catalog_path).load()++ profile = loaded["services"]["embedding"]["profiles"][0]+ assert profile["base_url"] == expected+ saved = json.loads(catalog_path.read_text(encoding="utf-8"))+ assert saved["services"]["embedding"]["profiles"][0]["base_url"] == expected+++def test_embedding_custom_endpoint_is_not_migrated(+ isolated_stores: tuple[Path, Path],+) -> None:+ catalog_path, _env_path = isolated_stores+ _write_single_embedding_profile_catalog(+ catalog_path,+ binding="custom",+ base_url="https://proxy.example/root",+ )++ loaded = ModelCatalogService(catalog_path).load()++ assert (+ loaded["services"]["embedding"]["profiles"][0]["base_url"]+ == "https://proxy.example/root"+ )diff --git a/tests/services/config/test_embedding_runtime.py b/tests/services/config/test_embedding_runtime.pyindex 046f847ff..d988ba2eb 100644--- a/tests/services/config/test_embedding_runtime.py+++ b/tests/services/config/test_embedding_runtime.py@@ -7,7 +7,10 @@ from pathlib import Pathimport pytestfrom deeptutor.services.config.env_store import EnvStore-from deeptutor.services.config.provider_runtime import resolve_embedding_runtime_config+from deeptutor.services.config.provider_runtime import (+ EMBEDDING_PROVIDERS,+ resolve_embedding_runtime_config,+)@pytest.fixture(autouse=True)@@ -232,8 +235,7 @@ def test_embedding_send_dimensions_catalog_wins_over_env(tmp_path: Path) -> Nonedef test_embedding_custom_openai_sdk_uses_user_supplied_base_url(tmp_path: Path) -> None:- """`custom_openai_sdk` accepts any user-supplied URL verbatim and routes- through the AsyncOpenAI client (which appends `/embeddings` itself)."""+ """Legacy `custom_openai_sdk` configs still resolve for backwards compatibility."""catalog = _build_catalog(embedding_profile={"id": "embedding-p",@@ -283,7 +285,8 @@ def test_embedding_openrouter_default_base_url_injected(tmp_path: Path) -> None:resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))assert resolved.provider_name == "openrouter"assert resolved.binding == "openrouter"- assert resolved.effective_url == "https://openrouter.ai/api/v1"+ assert resolved.effective_url == "https://openrouter.ai/api/v1/embeddings"+ assert EMBEDDING_PROVIDERS["openrouter"].adapter == "openai_compat"def test_embedding_openrouter_env_key_fallback(tmp_path: Path) -> None:diff --git a/tests/services/embedding/test_client_runtime.py b/tests/services/embedding/test_client_runtime.pyindex 490b0868f..ac8c705bb 100644--- a/tests/services/embedding/test_client_runtime.py+++ b/tests/services/embedding/test_client_runtime.py@@ -6,7 +6,12 @@ from typing import Anyimport pytest-from deeptutor.services.embedding.client import EmbeddingClient, _resolve_adapter_class+from deeptutor.services.embedding.client import (+ EmbeddingClient,+ _resolve_adapter_class,+ get_embedding_client,+ reset_embedding_client,+)from deeptutor.services.embedding.config import EmbeddingConfig@@ -31,14 +36,12 @@ class _FakeAdapter:)()-def _build_config(- binding: str, *, send_dimensions: bool | None = None-) -> EmbeddingConfig:+def _build_config(binding: str, *, send_dimensions: bool | None = None) -> EmbeddingConfig:return EmbeddingConfig(model="text-embedding-3-small",api_key="sk-test",- base_url="https://api.openai.com/v1",- effective_url="https://api.openai.com/v1",+ base_url="https://api.openai.com/v1/embeddings",+ effective_url="https://api.openai.com/v1/embeddings",binding=binding,provider_name=binding,provider_mode="standard",@@ -124,6 +127,7 @@ def test_resolve_adapter_class_supports_canonical_providers() -> None:assert _resolve_adapter_class("jina").__name__ == "JinaEmbeddingAdapter"assert _resolve_adapter_class("ollama").__name__ == "OllamaEmbeddingAdapter"assert _resolve_adapter_class("vllm").__name__ == "OpenAICompatibleEmbeddingAdapter"+ assert _resolve_adapter_class("openrouter").__name__ == "OpenAICompatibleEmbeddingAdapter"def test_resolve_adapter_class_rejects_unknown_provider() -> None:@@ -131,6 +135,68 @@ def test_resolve_adapter_class_rejects_unknown_provider() -> None:_resolve_adapter_class("huggingface")+def test_embedding_client_rejects_ollama_root_endpoint() -> None:+ cfg = EmbeddingConfig(+ model="nomic-embed-text",+ api_key="sk-no-key-required",+ base_url="http://localhost:11434",+ effective_url="http://localhost:11434",+ binding="ollama",+ provider_name="ollama",+ provider_mode="local",+ )++ with pytest.raises(ValueError, match="/api/embed"):+ EmbeddingClient(cfg)+++def test_embedding_client_rejects_openrouter_base_endpoint() -> None:+ cfg = EmbeddingConfig(+ model="qwen/qwen3-embedding-8b",+ api_key="sk-or-test",+ base_url="https://openrouter.ai/api/v1",+ effective_url="https://openrouter.ai/api/v1",+ binding="openrouter",+ provider_name="openrouter",+ provider_mode="standard",+ )++ with pytest.raises(ValueError, match="/embeddings"):+ EmbeddingClient(cfg)+++def test_get_embedding_client_refreshes_when_config_changes(monkeypatch) -> None:+ from deeptutor.services.embedding import client as client_module++ _FakeAdapter.instances = []+ first_config = _build_config("openai")+ second_config = _build_config("openai")+ second_config.model = "text-embedding-new"++ active_config = {"value": first_config}+ monkeypatch.setattr(+ client_module,+ "_resolve_adapter_class",+ lambda _b: _FakeAdapter,+ )+ monkeypatch.setattr(+ client_module,+ "get_embedding_config",+ lambda: active_config["value"],+ )++ reset_embedding_client()+ first_client = get_embedding_client()+ active_config["value"] = second_config+ second_client = get_embedding_client()+ same_second_client = get_embedding_client()++ assert first_client is not second_client+ assert second_client is same_second_client+ assert second_client.config.model == "text-embedding-new"+ reset_embedding_client()++@pytest.mark.parametrize("flag", [True, False, None])def test_embedding_client_propagates_send_dimensions_to_adapter(monkeypatch, flag: bool | Nonediff --git a/tests/services/embedding/test_url_transparency.py b/tests/services/embedding/test_url_transparency.pyindex b90c5b706..4c6dacb8d 100644--- a/tests/services/embedding/test_url_transparency.py+++ b/tests/services/embedding/test_url_transparency.py@@ -52,6 +52,15 @@ def _capture_url(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:return captured+def test_public_embedding_providers_do_not_use_openai_sdk_autopath() -> None:+ from deeptutor.services.config.provider_runtime import EMBEDDING_PROVIDERS++ for name, spec in EMBEDDING_PROVIDERS.items():+ if name == "custom_openai_sdk":+ continue+ assert spec.adapter != "openai_sdk", name++@pytest.mark.asyncioasync def test_openai_compat_url_verbatim(monkeypatch: pytest.MonkeyPatch) -> None:captured = _capture_url(monkeypatch)diff --git a/tests/services/memory/test_memory_service.py b/tests/services/memory/test_memory_service.pyindex 9121dc517..b3ef4d371 100644--- a/tests/services/memory/test_memory_service.py+++ b/tests/services/memory/test_memory_service.py@@ -34,6 +34,14 @@ async def _rewrite_stream(**_kwargs):yield "## Preferences\n- Prefer concise answers.\n\n## Context\n- Working on DeepTutor memory."+async def _thinking_rewrite_stream(**_kwargs):+ yield "<think>private reasoning</think>\n## Preferences\n- Prefer concise answers."+++async def _unclosed_thinking_stream(**_kwargs):+ yield "## Current Focus\n- Algebra\n<think>unfinished private reasoning"++def test_memory_service_refresh_turn_writes_rewritten_document(monkeypatch, tmp_path) -> None:service = _make_service(tmp_path)monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _rewrite_stream)@@ -78,3 +86,63 @@ def test_memory_service_refresh_turn_skips_when_model_returns_no_change(assert result.content == ""assert not service._path("profile").exists()assert not service._path("summary").exists()+++def test_memory_service_refresh_strips_thinking_tags(monkeypatch, tmp_path) -> None:+ service = _make_service(tmp_path)+ monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _thinking_rewrite_stream)++ import asyncio++ result = asyncio.run(+ service.refresh_from_turn(+ user_message="Please remember that I like concise answers.",+ assistant_message="Sure.",+ session_id="s1",+ capability="chat",+ language="en",+ )+ )++ assert result.changed is True+ profile = service.read_profile()+ summary = service.read_summary()+ assert "Prefer concise answers" in profile+ assert "<think" not in profile.lower()+ assert "private reasoning" not in profile+ assert "<think" not in summary.lower()+ assert "private reasoning" not in summary+++def test_memory_service_refresh_strips_unclosed_thinking_tags(monkeypatch, tmp_path) -> None:+ service = _make_service(tmp_path)+ monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _unclosed_thinking_stream)++ import asyncio++ asyncio.run(+ service.refresh_from_turn(+ user_message="Study algebra.",+ assistant_message="Done.",+ session_id="s1",+ capability="chat",+ language="en",+ )+ )++ assert service.read_profile() == "## Current Focus\n- Algebra"+ assert "<think" not in service.read_summary().lower()+++def test_memory_service_repairs_existing_thinking_tags_on_read(tmp_path) -> None:+ service = _make_service(tmp_path)+ service._path("summary").parent.mkdir(parents=True, exist_ok=True)+ service._path("summary").write_text(+ "## Current Focus\n- Algebra\n<think>old private reasoning</think>",+ encoding="utf-8",+ )++ assert service.read_summary() == "## Current Focus\n- Algebra"+ persisted = service._path("summary").read_text(encoding="utf-8")+ assert "<think" not in persisted.lower()+ assert "old private reasoning" not in persisteddiff --git a/tests/services/rag/test_llamaindex_embedding_failures.py b/tests/services/rag/test_llamaindex_embedding_failures.pyindex 2bc0085fb..c726c81ef 100644--- a/tests/services/rag/test_llamaindex_embedding_failures.py+++ b/tests/services/rag/test_llamaindex_embedding_failures.py@@ -24,6 +24,46 @@ def test_custom_embedding_rejects_null_coordinates(monkeypatch: pytest.MonkeyPatembedding._get_text_embeddings(["chunk"])+def test_custom_embedding_refreshes_stale_client(monkeypatch: pytest.MonkeyPatch) -> None:+ from deeptutor.services.rag.pipelines.llamaindex import (+ embedding_adapter as embedding_module,+ )++ class _FakeClient:+ def __init__(self, model: str, value: float) -> None:+ self.config = SimpleNamespace(+ binding="openai",+ model=model,+ dim=1,+ effective_url="https://example.test/v1/embeddings",+ base_url="https://example.test/v1/embeddings",+ api_version=None,+ send_dimensions=None,+ )+ self.value = value+ self.calls: list[list[str]] = []++ async def embed(self, texts, progress_callback=None):+ self.calls.append(list(texts))+ return [[self.value] for _ in texts]++ old_client = _FakeClient("old-embed", 1.0)+ new_client = _FakeClient("new-embed", 2.0)+ active_client = {"value": old_client}+ monkeypatch.setattr(+ embedding_module,+ "get_embedding_client",+ lambda config=None: active_client["value"],+ )++ embedding = embedding_module.CustomEmbedding()+ active_client["value"] = new_client++ assert embedding._get_query_embedding("hello") == [2.0]+ assert old_client.calls == []+ assert new_client.calls == [["hello"]]++@pytest.mark.asyncioasync def test_search_returns_reindex_hint_for_null_vector_index(tmp_path, monkeypatch: pytest.MonkeyPatch@@ -59,3 +99,59 @@ async def test_search_returns_reindex_hint_for_null_vector_index(assert result["needs_reindex"] is Trueassert "Re-index the knowledge base" in result["answer"]assert "unsupported operand" not in result["answer"]+++def test_retrieve_nodes_rejects_invalid_persisted_embeddings(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module++ class _RetrieverShouldNotRun:+ def retrieve(self, query: str): # pragma: no cover - assertion helper+ raise AssertionError("retriever should not run for invalid persisted vectors")++ fake_index = SimpleNamespace(+ vector_store=SimpleNamespace(+ data=SimpleNamespace(embedding_dict={"bad-node": [0.1, None, 0.3]})+ ),+ as_retriever=lambda similarity_top_k=5: _RetrieverShouldNotRun(),+ )++ monkeypatch.setattr(+ storage_module.StorageContext,+ "from_defaults",+ lambda persist_dir: object(),+ )+ monkeypatch.setattr(storage_module, "load_index_from_storage", lambda _ctx: fake_index)++ with pytest.raises(ValueError, match="RAG index contains invalid embedding vectors"):+ storage_module.retrieve_nodes(tmp_path, "what is this?")+++async def test_search_reconfigures_llamaindex_settings_for_cached_pipeline(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module+ from deeptutor.services.rag.pipelines.llamaindex.pipeline import LlamaIndexPipeline++ storage_dir = tmp_path / "kb" / "version-1"+ storage_dir.mkdir(parents=True)+ (storage_dir / "docstore.json").write_text("{}", encoding="utf-8")++ configure_calls: list[str] = []+ monkeypatch.setattr(+ LlamaIndexPipeline,+ "_configure_settings",+ lambda self: configure_calls.append("configure"),+ )+ monkeypatch.setattr(storage_module, "retrieve_nodes", lambda *_args, **_kwargs: [])++ pipeline = LlamaIndexPipeline(+ kb_base_dir=str(tmp_path),+ signature_provider=lambda: None,+ )+ result = await pipeline.search("what is this?", "kb")++ assert result["provider"] == "llamaindex"+ assert configure_calls == ["configure", "configure"]diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsxindex b0bc1f134..8c59e05ac 100644--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@ -1262,7 +1262,9 @@ function SettingsPageContent() {</div><div className="sm:col-span-2"><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">- {t("Base URL")}+ {activeService === "embedding"+ ? t("Endpoint URL")+ : t("Base URL")}</div><inputclassName={inputClass}@@ -1276,6 +1278,13 @@ function SettingsPageContent() {: "https://api.openai.com/v1"}/>+ {activeService === "embedding" && (+ <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.",+ )}+ </p>+ )}</div><div className="sm:col-span-2"><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">