DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(knowledge): add WeKnora retrieval connections (#918)
XZH8460fb7ec577
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 5275d5566..cb98739b9 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -1863,6 +1863,19 @@ class ConnectLightRagServerRequest(BaseModel):search_mode: str = ""+class ProbeWeKnoraRequest(BaseModel):+ server_url: str+ api_key: str+ knowledge_base_id: str+++class ConnectWeKnoraRequest(BaseModel):+ name: str+ server_url: str+ api_key: str+ knowledge_base_id: str++@router.post("/probe-lightrag-server")async def probe_lightrag_server_route(payload: ProbeLightRagServerRequest):"""Test-connect to an external LightRAG server before binding a KB to it.@@ -1929,6 +1942,76 @@ async def connect_lightrag_server_route(payload: ConnectLightRagServerRequest):}[email protected]("/probe-weknora")+async def probe_weknora_route(payload: ProbeWeKnoraRequest):+ """Validate a WeKnora server and knowledge-base binding without registering."""+ from deeptutor.services.rag.pipelines.weknora.probe import probe_weknora++ server_url = (payload.server_url or "").strip()+ knowledge_base_id = (payload.knowledge_base_id or "").strip()+ if not server_url or not knowledge_base_id:+ raise HTTPException(+ status_code=400,+ detail="Both server_url and knowledge_base_id are required.",+ )+ result = await probe_weknora(+ server_url,+ payload.api_key or "",+ knowledge_base_id,+ )+ return result.to_dict()++[email protected]("/connect-weknora")+async def connect_weknora_route(payload: ConnectWeKnoraRequest):+ """Connect a self-hosted WeKnora knowledge base for retrieval only."""+ from deeptutor.services.rag.pipelines.weknora.probe import probe_weknora++ name = (payload.name or "").strip()+ server_url = (payload.server_url or "").strip()+ knowledge_base_id = (payload.knowledge_base_id or "").strip()+ if not name or not server_url or not knowledge_base_id:+ raise HTTPException(+ status_code=400,+ detail="name, server_url, and knowledge_base_id are required.",+ )++ result = await probe_weknora(+ server_url,+ payload.api_key or "",+ knowledge_base_id,+ )+ if not result.ok:+ raise HTTPException(+ status_code=400,+ detail=result.error or "Could not connect to the WeKnora knowledge base.",+ )++ try:+ manager = get_kb_manager()+ entry = manager.register_weknora_kb(+ name,+ result.base_url,+ payload.api_key or "",+ result.knowledge_base_id,+ )+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))+ except HTTPException:+ raise+ except Exception as e:+ logger.error(f"Error connecting WeKnora knowledge base: {e}")+ raise HTTPException(status_code=500, detail=str(e))++ return {+ "status": "connected",+ "name": name,+ "server_url": entry["server_url"],+ "knowledge_base_id": entry["knowledge_base_id"],+ "rag_provider": entry["rag_provider"],+ }++class ListImaRequest(BaseModel):# Empty means "use the account-level credentials from the engine settings",# so the connect flow never has to re-send what is already stored.diff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.pyindex f1ff2a3a4..5d8c76a45 100644--- a/deeptutor/knowledge/kb_types.py+++ b/deeptutor/knowledge/kb_types.py@@ -29,12 +29,17 @@ flavours exist today:``lightrag_server``: nothing indexed or stored locally, retrieval offloaded toIMA's ``search_knowledge`` OpenAPI by the bound ``ima`` provider, and one IMAlibrary = one KB. See ``services/rag/pipelines/ima``.+* ``weknora`` — a pointer (``server_url`` + ``api_key`` ++ ``knowledge_base_id``) to a knowledge base the user curates in a+ self-hosted Tencent WeKnora deployment. Retrieval is offloaded to WeKnora's+ knowledge-search API by the bound ``weknora`` provider; no documents are+ copied or indexed locally. See ``services/rag/pipelines/weknora``.All connected flavours share the same lifecycle quirks: no on-disk folder under``base_dir``, no embedding reconcile, and deletion must never touch theexternal resource. The :func:`is_connected_kb` / :func:`external_root_of` helperslet the manager treat them uniformly without sprinkling ``type`` literals-across the codebase. ``subagent``, ``lightrag_server`` and ``ima`` are connected+across the codebase. ``subagent``, ``lightrag_server``, ``ima`` and ``weknora`` are connectedbut point at no folder, so :func:`external_root_of` returns ``None`` for them — asubagent is driven by its capability and the two server-backed kinds are reachedover HTTP; none resolves to a local path.@@ -74,6 +79,10 @@ LIGHTRAG_SERVER_KB_TYPE = "lightrag_server"# ``search_knowledge`` OpenAPI by the ``ima`` provider.IMA_KB_TYPE = "ima"+# A connected Tencent WeKnora knowledge base. The external service owns both+# indexing and document management; DeepTutor only stores retrieval credentials.+WEKNORA_KB_TYPE = "weknora"+# A connected MarginNote 4 library: a pointer (``device_id`` + optional# ``server_url``) to the user's MN4 study data synced via the official Add-on# API. No path on disk and no local index — MN4 objects land in a dedicated@@ -90,6 +99,7 @@ CONNECTED_KB_TYPES = frozenset(SUBAGENT_KB_TYPE,LIGHTRAG_SERVER_KB_TYPE,IMA_KB_TYPE,+ WEKNORA_KB_TYPE,MARGINNOTE4_KB_TYPE,})@@ -149,6 +159,7 @@ __all__ = ["SUBAGENT_KB_TYPE","LIGHTRAG_SERVER_KB_TYPE","IMA_KB_TYPE",+ "WEKNORA_KB_TYPE","MARGINNOTE4_KB_TYPE","CONNECTED_KB_TYPES","NON_RETRIEVABLE_KB_TYPES",diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 8a8374821..33fb61602 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -25,6 +25,7 @@ from deeptutor.knowledge.kb_types import (MARGINNOTE4_KB_TYPE,OBSIDIAN_KB_TYPE,SUBAGENT_KB_TYPE,+ WEKNORA_KB_TYPE,external_root_of,is_connected_kb,)@@ -37,6 +38,7 @@ from deeptutor.services.rag.factory import (LIGHTRAG_SERVER_PROVIDER,PAGEINDEX_OSS_PROVIDER,PAGEINDEX_PROVIDER,+ WEKNORA_PROVIDER,has_ready_provider_index,normalize_provider_name,provider_uses_embedding_versions,@@ -1028,6 +1030,50 @@ class KnowledgeBaseManager:self._save_config()return entry+ def register_weknora_kb(+ self,+ name: str,+ server_url: str,+ api_key: str,+ knowledge_base_id: str,+ *,+ description: str = "",+ ) -> dict:+ """Register a self-hosted WeKnora knowledge base as a pointer KB."""+ name = (name or "").strip()+ server_url = (server_url or "").strip().rstrip("/")+ api_key = (api_key or "").strip()+ knowledge_base_id = (knowledge_base_id or "").strip()+ if not name:+ raise ValueError("Knowledge base name is required.")+ if not server_url or not knowledge_base_id:+ raise ValueError("WeKnora server URL and knowledge base ID are required.")+ if not api_key:+ raise ValueError("A WeKnora API key is required.")++ self.config = self._load_config()+ knowledge_bases = self.config.setdefault("knowledge_bases", {})+ if name in knowledge_bases:+ raise ValueError(f"A knowledge base named '{name}' already exists.")++ now = datetime.now().isoformat()+ entry: dict[str, Any] = {+ "path": name,+ "type": WEKNORA_KB_TYPE,+ "rag_provider": WEKNORA_PROVIDER,+ "server_url": server_url,+ "api_key": api_key,+ "knowledge_base_id": knowledge_base_id,+ "description": description or f"WeKnora knowledge base: {name}",+ "status": "ready",+ "needs_reindex": False,+ "created_at": now,+ "updated_at": now,+ }+ knowledge_bases[name] = entry+ self._save_config()+ return entry+def get_knowledge_base_path(self, name: str | None = None) -> Path:"""Get path to a knowledge base.diff --git a/deeptutor/services/doctor.py b/deeptutor/services/doctor.pyindex 7a038fada..81bd16457 100644--- a/deeptutor/services/doctor.py+++ b/deeptutor/services/doctor.py@@ -243,6 +243,7 @@ def _rag_check()from deeptutor.services.rag.factory import (LIGHTRAG_SERVER_PROVIDER,+ WEKNORA_PROVIDER,normalize_provider_name,)@@ -253,6 +254,18 @@ def _rag_check(continueprovider = normalize_provider_name(str(entry.get("rag_provider") or default_provider))providers.add(provider)+ if provider == WEKNORA_PROVIDER:+ from deeptutor.services.rag.pipelines.weknora.config import config_from_entry++ try:+ weknora_config = config_from_entry(entry)+ endpoint_ok, _ = _safe_endpoint(weknora_config.base_url)+ if not endpoint_ok:+ failures.append(f"{kb_name}: invalid WeKnora server URL")+ except Exception as exc:+ failures.append(f"{kb_name}: {_redact_error(exc, None)}")+ continue+if provider != LIGHTRAG_SERVER_PROVIDER:continue@@ -268,7 +281,7 @@ def _rag_check(except Exception as exc:failures.append(f"{kb_name}: {_redact_error(exc, None)}")- for provider in sorted(providers - {LIGHTRAG_SERVER_PROVIDER}):+ for provider in sorted(providers - {LIGHTRAG_SERVER_PROVIDER, WEKNORA_PROVIDER}):try:report = preflight(provider)for check in report.get("checks", []):diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.pyindex fbf4d90c8..38b4db94d 100644--- a/deeptutor/services/rag/factory.py+++ b/deeptutor/services/rag/factory.py@@ -17,6 +17,10 @@ today:* ``ima`` — retrieval offloaded to a Tencent IMA knowledge basethe user curates in IMA. No local index: each KB isa connection pointer queried over IMA's OpenAPI.+* ``weknora`` — retrieval offloaded to a knowledge base in a+ self-hosted Tencent WeKnora deployment. No local+ index or document copy; each KB is a connection+ pointer queried over WeKnora's REST API.A KB is bound to one provider at creation time; later adds and retrieval alwaysgo through that same pipeline (enforced upstream in the knowledge router).@@ -34,6 +38,7 @@ GRAPHRAG_PROVIDER = "graphrag"LIGHTRAG_PROVIDER = "lightrag"LIGHTRAG_SERVER_PROVIDER = "lightrag-server"IMA_PROVIDER = "ima"+WEKNORA_PROVIDER = "weknora"# Providers the factory can instantiate. Unknown / legacy strings fall back to# the default with a re-index hint upstream.@@ -46,6 +51,7 @@ KNOWN_PROVIDERS = frozenset(LIGHTRAG_PROVIDER,LIGHTRAG_SERVER_PROVIDER,IMA_PROVIDER,+ WEKNORA_PROVIDER,})@@ -89,6 +95,7 @@ def version_matches_provider(entry: dict[str, Any], provider: Optional[str]) ->LIGHTRAG_PROVIDER,LIGHTRAG_SERVER_PROVIDER,IMA_PROVIDER,+ WEKNORA_PROVIDER,}return entry_provider == resolved or signature == resolved@@ -156,6 +163,13 @@ def _build_pipeline(provider: str, kb_base_dir: Optional[str], **kwargs: Any):kwargs.setdefault("kb_base_dir", kb_base_dir)return ImaPipeline(**kwargs)+ if provider == WEKNORA_PROVIDER:+ from .pipelines.weknora.pipeline import WeKnoraPipeline++ if kb_base_dir is not None:+ kwargs.setdefault("kb_base_dir", kb_base_dir)+ return WeKnoraPipeline(**kwargs)+from .pipelines.llamaindex.pipeline import LlamaIndexPipelineif kb_base_dir is not None:@@ -302,6 +316,17 @@ def list_pipelines() -> List[Dict[str, Any]]:"configured": ima_ready,"requires_api_key": True,},+ {+ "id": WEKNORA_PROVIDER,+ "name": "WeKnora",+ "description": (+ "Retrieval offloaded to a knowledge base in your self-hosted "+ "WeKnora deployment. No local index or document copy; connect "+ "to its API URL, API key, and knowledge-base ID."+ ),+ "configured": True,+ "requires_api_key": True,+ },]@@ -313,6 +338,7 @@ __all__ = ["LIGHTRAG_PROVIDER","LIGHTRAG_SERVER_PROVIDER","IMA_PROVIDER",+ "WEKNORA_PROVIDER","KNOWN_PROVIDERS","get_pipeline","has_ready_provider_index",diff --git a/deeptutor/services/rag/pipelines/weknora/__init__.py b/deeptutor/services/rag/pipelines/weknora/__init__.pynew file mode 100644index 000000000..7bfaf344a--- /dev/null+++ b/deeptutor/services/rag/pipelines/weknora/__init__.py@@ -0,0 +1,13 @@+"""Retrieval-only integration with an external Tencent WeKnora server."""++from .client import WeKnoraAPIError, WeKnoraClient+from .config import WeKnoraConfig, config_from_entry+from .pipeline import WeKnoraPipeline++__all__ = [+ "WeKnoraAPIError",+ "WeKnoraClient",+ "WeKnoraConfig",+ "WeKnoraPipeline",+ "config_from_entry",+]diff --git a/deeptutor/services/rag/pipelines/weknora/client.py b/deeptutor/services/rag/pipelines/weknora/client.pynew file mode 100644index 000000000..a9b51e153--- /dev/null+++ b/deeptutor/services/rag/pipelines/weknora/client.py@@ -0,0 +1,78 @@+"""Thin HTTP client for Tencent WeKnora's documented REST API."""++from __future__ import annotations++import logging+from typing import Any, Optional++import httpx++from .config import WeKnoraConfig++logger = logging.getLogger(__name__)+++class WeKnoraAPIError(RuntimeError):+ """Raised when WeKnora returns an error or unexpected payload."""+++class WeKnoraClient:+ def __init__(+ self,+ config: WeKnoraConfig,+ *,+ timeout: float = 60.0,+ transport: Optional[httpx.AsyncBaseTransport] = None,+ ) -> None:+ self._config = config+ self._timeout = timeout+ self._transport = transport++ def _open(self) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ base_url=self._config.base_url,+ headers={+ "Accept": "application/json",+ "X-API-Key": self._config.api_key,+ },+ timeout=self._timeout,+ transport=self._transport,+ )++ @staticmethod+ def _json(resp: httpx.Response) -> dict[str, Any]:+ if resp.status_code >= 400:+ raise WeKnoraAPIError(f"WeKnora returned {resp.status_code}: {resp.text[:300]}")+ try:+ data = resp.json()+ except Exception as exc:+ raise WeKnoraAPIError(f"WeKnora returned a non-JSON response: {exc}") from exc+ if not isinstance(data, dict):+ raise WeKnoraAPIError(f"WeKnora returned unexpected payload: {data!r}")+ return data++ async def list_knowledge_bases(self) -> list[dict[str, Any]]:+ async with self._open() as client:+ resp = await client.get("/api/v1/knowledge-bases")+ data = self._json(resp).get("data")+ if not isinstance(data, list) or not all(isinstance(item, dict) for item in data):+ raise WeKnoraAPIError("WeKnora returned an unexpected knowledge-base list.")+ return data++ async def search(self, query: str) -> list[dict[str, Any]]:+ async with self._open() as client:+ resp = await client.post(+ "/api/v1/knowledge-search",+ params={"resource_urls": "handle"},+ json={+ "query": query,+ "knowledge_base_id": self._config.knowledge_base_id,+ },+ )+ data = self._json(resp).get("data")+ if not isinstance(data, list) or not all(isinstance(item, dict) for item in data):+ raise WeKnoraAPIError("WeKnora returned unexpected search results.")+ return data+++__all__ = ["WeKnoraAPIError", "WeKnoraClient"]diff --git a/deeptutor/services/rag/pipelines/weknora/config.py b/deeptutor/services/rag/pipelines/weknora/config.pynew file mode 100644index 000000000..1a23fc0d0--- /dev/null+++ b/deeptutor/services/rag/pipelines/weknora/config.py@@ -0,0 +1,47 @@+"""Per-KB connection configuration for Tencent WeKnora."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any+++class WeKnoraNotConfiguredError(RuntimeError):+ """Raised when a KB lacks the fields needed to reach WeKnora."""+++@dataclass(frozen=True)+class WeKnoraConfig:+ base_url: str+ api_key: str+ knowledge_base_id: str+++def normalize_base_url(url: str | None) -> str:+ return (url or "").strip().rstrip("/")+++def config_from_entry(entry: dict[str, Any]) -> WeKnoraConfig:+ base_url = normalize_base_url(entry.get("server_url"))+ api_key = str(entry.get("api_key") or "").strip()+ knowledge_base_id = str(entry.get("knowledge_base_id") or "").strip()+ if not base_url or not knowledge_base_id:+ raise WeKnoraNotConfiguredError(+ "This knowledge base is not connected to WeKnora "+ "(server URL and knowledge base ID are required)."+ )+ if not api_key:+ raise WeKnoraNotConfiguredError("A WeKnora API key is required for retrieval.")+ return WeKnoraConfig(+ base_url=base_url,+ api_key=api_key,+ knowledge_base_id=knowledge_base_id,+ )+++__all__ = [+ "WeKnoraConfig",+ "WeKnoraNotConfiguredError",+ "config_from_entry",+ "normalize_base_url",+]diff --git a/deeptutor/services/rag/pipelines/weknora/pipeline.py b/deeptutor/services/rag/pipelines/weknora/pipeline.pynew file mode 100644index 000000000..0fe7f4ac5--- /dev/null+++ b/deeptutor/services/rag/pipelines/weknora/pipeline.py@@ -0,0 +1,74 @@+"""Retrieval-only RAG pipeline backed by an external WeKnora knowledge base."""++from __future__ import annotations++import logging+from typing import Any, Dict, List, Optional++from deeptutor.runtime.home import get_runtime_data_root+from deeptutor.services.rag.provider_binding import load_kb_config_entry++from .config import WeKnoraNotConfiguredError, config_from_entry++logger = logging.getLogger(__name__)++PROVIDER = "weknora"+DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")+++class WeKnoraPipeline:+ def __init__(self, kb_base_dir: Optional[str] = None, *, client_factory=None, **_: Any) -> None:+ self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR+ self._client_factory = client_factory++ def _client(self, config):+ if self._client_factory is not None:+ return self._client_factory(config)+ from .client import WeKnoraClient++ return WeKnoraClient(config)++ async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:+ try:+ config = config_from_entry(load_kb_config_entry(self.kb_base_dir, kb_name))+ except WeKnoraNotConfiguredError as exc:+ return self._error_result(query, exc, error_type="not_configured")++ try:+ chunks = await self._client(config).search(query)+ except Exception as exc:+ logger.error("WeKnora search failed for '%s': %s", kb_name, exc)+ return self._error_result(query, exc, error_type="retrieval_error")++ return {+ "query": query,+ "answer": "\n\n---\n\n".join(str(item.get("content") or "") for item in chunks),+ "content": "\n\n---\n\n".join(str(item.get("content") or "") for item in chunks),+ "sources": chunks,+ "provider": PROVIDER,+ }++ def _error_result(self, query: str, exc: Exception, *, error_type: str) -> Dict[str, Any]:+ return {+ "query": query,+ "answer": str(exc),+ "content": "",+ "sources": [],+ "provider": PROVIDER,+ "error_type": error_type,+ }++ async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:+ raise RuntimeError(+ "WeKnora knowledge bases are managed in WeKnora; DeepTutor does not "+ "upload or index their documents."+ )++ async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:+ return await self.initialize(kb_name, file_paths, **kwargs)++ async def delete(self, kb_name: str, **kwargs) -> bool:+ return True+++__all__ = ["WeKnoraPipeline", "PROVIDER"]diff --git a/deeptutor/services/rag/pipelines/weknora/probe.py b/deeptutor/services/rag/pipelines/weknora/probe.pynew file mode 100644index 000000000..748226e87--- /dev/null+++ b/deeptutor/services/rag/pipelines/weknora/probe.py@@ -0,0 +1,72 @@+"""Validate a WeKnora endpoint, API key, and knowledge-base binding."""++from __future__ import annotations++from dataclasses import asdict, dataclass+from typing import Any, Optional++from .client import WeKnoraClient+from .config import WeKnoraConfig, normalize_base_url+++@dataclass+class WeKnoraProbe:+ base_url: str+ knowledge_base_id: str+ ok: bool = False+ reachable: bool = False+ credentials_ok: bool = False+ knowledge_base_found: bool = False+ knowledge_base_name: Optional[str] = None+ error: Optional[str] = None++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++async def probe_weknora(+ server_url: str,+ api_key: str,+ knowledge_base_id: str,+ *,+ client_factory=None,+) -> WeKnoraProbe:+ base_url = normalize_base_url(server_url)+ knowledge_base_id = (knowledge_base_id or "").strip()+ api_key = (api_key or "").strip()+ probe = WeKnoraProbe(base_url=base_url, knowledge_base_id=knowledge_base_id)++ if not base_url or not knowledge_base_id or not api_key:+ probe.error = "Server URL, API key, and knowledge base ID are required."+ return probe+ if not base_url.startswith(("http://", "https://")):+ probe.error = "Server URL must start with http:// or https://."+ return probe++ config = WeKnoraConfig(+ base_url=base_url,+ api_key=api_key,+ knowledge_base_id=knowledge_base_id,+ )+ client = client_factory(config) if client_factory else WeKnoraClient(config)+ try:+ knowledge_bases = await client.list_knowledge_bases()+ except Exception as exc:+ probe.error = f"Could not validate the WeKnora connection: {exc}"+ return probe++ probe.reachable = True+ probe.credentials_ok = True+ matches = [item for item in knowledge_bases if str(item.get("id") or "") == knowledge_base_id]+ if not matches:+ probe.error = f"Knowledge base {knowledge_base_id} is not visible to this WeKnora API key."+ return probe++ probe.knowledge_base_found = True+ name = str(matches[0].get("name") or "").strip()+ probe.knowledge_base_name = name or None+ probe.ok = True+ return probe+++__all__ = ["WeKnoraProbe", "probe_weknora"]diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 1f73ea932..4d4f2b298 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -97,6 +97,29 @@ class _FakeKBManager:self.config.setdefault("knowledge_bases", {})[name] = entryreturn entry+ def register_weknora_kb(+ self,+ name: str,+ server_url: str,+ api_key: str,+ knowledge_base_id: str,+ *,+ description: str = "",+ ) -> dict:+ if name in self.config.get("knowledge_bases", {}):+ raise ValueError(f"A knowledge base named '{name}' already exists.")+ entry = {+ "path": name,+ "type": "weknora",+ "rag_provider": "weknora",+ "server_url": server_url,+ "api_key": api_key,+ "knowledge_base_id": knowledge_base_id,+ "status": "ready",+ }+ self.config.setdefault("knowledge_bases", {})[name] = entry+ return entry+class _FakeInitializer:def __init__(self, kb_name: str, base_dir: str, **_kwargs) -> None:@@ -152,6 +175,7 @@ def test_rag_providers_lists_llamaindex_and_pageindex(monkeypatch) -> None:"lightrag","lightrag-server","ima",+ "weknora",}# LlamaIndex works out of the box; PageIndex needs an API key; GraphRAG and# LightRAG are optional local engines (no API key, configured = installed).@@ -164,6 +188,8 @@ def test_rag_providers_lists_llamaindex_and_pageindex(monkeypatch) -> None:# (the per-KB endpoint is configured at connect time).assert by_id["lightrag-server"]["requires_api_key"] is Falseassert by_id["lightrag-server"]["configured"] is True+ assert by_id["weknora"]["requires_api_key"] is True+ assert by_id["weknora"]["configured"] is True# IMA is a thin HTTPS client with no install, but it does need an account# credential pair — configured here by the patched account settings.assert by_id["ima"]["requires_api_key"] is True@@ -1729,11 +1755,86 @@ def test_connect_lightrag_server_rejects_unreachable(monkeypatch, tmp_path: Pathassert "bad" not in manager.config["knowledge_bases"]+def _patch_weknora_probe(monkeypatch, *, ok: bool, error: str | None = None) -> None:+ from deeptutor.services.rag.pipelines.weknora import probe as probe_module++ async def _fake_probe(server_url: str, api_key: str, knowledge_base_id: str, **_kwargs):+ result = probe_module.WeKnoraProbe(+ base_url=server_url.rstrip("/"),+ knowledge_base_id=knowledge_base_id,+ )+ result.ok = ok+ result.reachable = ok+ result.credentials_ok = ok+ result.knowledge_base_found = ok+ result.knowledge_base_name = "Research" if ok else None+ result.error = error+ return result++ monkeypatch.setattr(probe_module, "probe_weknora", _fake_probe)+++def test_weknora_probe_and_connect_endpoints(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ _patch_weknora_probe(monkeypatch, ok=True)++ with TestClient(_build_app()) as client:+ probe = client.post(+ "/api/v1/knowledge/probe-weknora",+ json={+ "server_url": "http://localhost:8080/",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ },+ )+ connected = client.post(+ "/api/v1/knowledge/connect-weknora",+ json={+ "name": "weknora-kb",+ "server_url": "http://localhost:8080/",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ },+ )++ assert probe.status_code == 200+ assert probe.json()["ok"] is True+ assert probe.json()["knowledge_base_name"] == "Research"+ assert connected.status_code == 200+ body = connected.json()+ assert body["rag_provider"] == "weknora"+ entry = manager.config["knowledge_bases"]["weknora-kb"]+ assert entry["server_url"] == "http://localhost:8080"+ assert entry["knowledge_base_id"] == "kb-1"+++def test_connect_weknora_rejects_failed_probe(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ _patch_weknora_probe(monkeypatch, ok=False, error="Knowledge base missing")++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/connect-weknora",+ json={+ "name": "bad",+ "server_url": "http://localhost:8080",+ "api_key": "secret",+ "knowledge_base_id": "missing",+ },+ )++ assert response.status_code == 400+ assert "WeKnora" in response.json()["detail"] or "Knowledge base" in response.json()["detail"]+ assert "bad" not in manager.config["knowledge_bases"]++def test_assert_not_connected_kb_blocks_connected_writes() -> None:from fastapi import HTTPExceptionguard = knowledge_router_module._assert_not_connected_kb- for kind in ("linked", "obsidian", "lightrag_server"):+ for kind in ("linked", "obsidian", "lightrag_server", "weknora"):with pytest.raises(HTTPException) as excinfo:guard("kb", {"type": kind})assert excinfo.value.status_code == 409diff --git a/tests/cli/test_doctor_cli.py b/tests/cli/test_doctor_cli.pyindex d574856e3..030d366f3 100644--- a/tests/cli/test_doctor_cli.py+++ b/tests/cli/test_doctor_cli.py@@ -8,12 +8,40 @@ from types import SimpleNamespaceimport pytestfrom typer.testing import CliRunner-from deeptutor.services.doctor import DoctorCheck, DoctorReport, run_diagnostics+from deeptutor.services.doctor import (+ DoctorCheck,+ DoctorReport,+ _rag_check,+ run_diagnostics,+)from deeptutor_cli.main import apprunner = CliRunner()+def test_weknora_rag_check_skips_local_provider_preflight() -> None:+ def preflight(provider: str):+ raise AssertionError(f"WeKnora must not run local preflight: {provider}")++ check = _rag_check(+ {+ "knowledge_bases": {+ "remote": {+ "rag_provider": "weknora",+ "server_url": "http://localhost:8080",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ }+ }+ },+ preflight,+ )++ assert check.status == "pass"+ assert check.detail == "Ready for configured provider(s): weknora."+ assert "secret" not in check.detail++def _llm_config(**overrides):values = {"model": "gpt-4o-mini",diff --git a/tests/services/rag/test_weknora_pipeline.py b/tests/services/rag/test_weknora_pipeline.pynew file mode 100644index 000000000..6b895ff44--- /dev/null+++ b/tests/services/rag/test_weknora_pipeline.py@@ -0,0 +1,194 @@+"""Tests for the retrieval-only Tencent WeKnora pipeline."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path++import httpx+import pytest++from deeptutor.knowledge.kb_types import CONNECTED_KB_TYPES, WEKNORA_KB_TYPE+from deeptutor.knowledge.manager import KnowledgeBaseManager+from deeptutor.services.rag.factory import get_pipeline, list_pipelines, normalize_provider_name+from deeptutor.services.rag.pipelines.weknora.client import WeKnoraClient+from deeptutor.services.rag.pipelines.weknora.config import config_from_entry+from deeptutor.services.rag.pipelines.weknora.pipeline import WeKnoraPipeline+from deeptutor.services.rag.pipelines.weknora.probe import probe_weknora+++def _transport() -> httpx.MockTransport:+ def handler(request: httpx.Request) -> httpx.Response:+ assert request.headers["X-API-Key"] == "secret"+ if request.url.path == "/api/v1/knowledge-bases":+ return httpx.Response(+ 200,+ json={+ "success": True,+ "data": [+ {"id": "kb-1", "name": "Research"},+ {"id": "kb-2", "name": "Operations"},+ ],+ },+ )+ if request.url.path == "/api/v1/knowledge-search":+ body = json.loads(request.content)+ assert body == {"query": "what is AI?", "knowledge_base_id": "kb-1"}+ assert request.url.params["resource_urls"] == "handle"+ return httpx.Response(+ 200,+ json={+ "success": True,+ "data": [+ {+ "id": "chunk-1",+ "content": "Context one",+ "knowledge_id": "knowledge-1",+ "knowledge_title": "Guide",+ "knowledge_filename": "guide.pdf",+ "score": 0.9,+ },+ {"id": "chunk-2", "content": "Context two"},+ ],+ },+ )+ return httpx.Response(404, json={"success": False})++ return httpx.MockTransport(handler)+++def _config() -> object:+ return config_from_entry(+ {+ "server_url": "http://localhost:8080/",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ }+ )+++def test_config_requires_complete_binding() -> None:+ config = _config()+ assert config.base_url == "http://localhost:8080"+ assert config.knowledge_base_id == "kb-1"++ with pytest.raises(Exception, match="knowledge base ID"):+ config_from_entry({"server_url": "http://x", "api_key": "secret"})+ with pytest.raises(Exception, match="API key"):+ config_from_entry({"server_url": "http://x", "knowledge_base_id": "kb-1"})+++def test_client_search_uses_official_endpoint() -> None:+ result = asyncio.run(WeKnoraClient(_config(), transport=_transport()).search("what is AI?"))+ assert [item["id"] for item in result] == ["chunk-1", "chunk-2"]+++def test_probe_validates_visible_knowledge_base() -> None:+ probe = asyncio.run(+ probe_weknora(+ "http://localhost:8080/",+ "secret",+ "kb-1",+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ )+ assert probe.ok is True+ assert probe.reachable is True+ assert probe.credentials_ok is True+ assert probe.knowledge_base_found is True+ assert probe.knowledge_base_name == "Research"+++def test_probe_rejects_invisible_knowledge_base() -> None:+ probe = asyncio.run(+ probe_weknora(+ "http://localhost:8080",+ "secret",+ "missing",+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ )+ assert probe.ok is False+ assert probe.knowledge_base_found is False+ assert "not visible" in (probe.error or "")+++def _kb_base(tmp_path: Path, entry: dict) -> str:+ (tmp_path / "kb_config.json").write_text(+ json.dumps({"knowledge_bases": {"remote": entry}}), encoding="utf-8"+ )+ return str(tmp_path)+++def test_pipeline_returns_chunks_and_sources(tmp_path: Path) -> None:+ base = _kb_base(+ tmp_path,+ {+ "type": WEKNORA_KB_TYPE,+ "rag_provider": "weknora",+ "server_url": "http://localhost:8080",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ },+ )+ pipeline = WeKnoraPipeline(+ base,+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ result = asyncio.run(pipeline.search("what is AI?", "remote"))+ assert result["provider"] == "weknora"+ assert result["content"] == "Context one\n\n---\n\nContext two"+ assert result["sources"][0]["knowledge_title"] == "Guide"+++def test_pipeline_reports_not_configured_and_retrieval_errors(tmp_path: Path) -> None:+ pipeline = WeKnoraPipeline(+ _kb_base(tmp_path, {"type": WEKNORA_KB_TYPE, "rag_provider": "weknora"}),+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ result = asyncio.run(pipeline.search("q", "remote"))+ assert result["error_type"] == "not_configured"++ configured = WeKnoraPipeline(+ _kb_base(+ tmp_path,+ {+ "type": WEKNORA_KB_TYPE,+ "rag_provider": "weknora",+ "server_url": "http://localhost:8080",+ "api_key": "secret",+ "knowledge_base_id": "missing",+ },+ ),+ client_factory=lambda config: WeKnoraClient(+ config, transport=httpx.MockTransport(lambda request: httpx.Response(500, text="boom"))+ ),+ )+ failed = asyncio.run(configured.search("q", "remote"))+ assert failed["error_type"] == "retrieval_error"+++def test_pipeline_refuses_local_indexing(tmp_path: Path) -> None:+ pipeline = WeKnoraPipeline(str(tmp_path))+ with pytest.raises(RuntimeError, match="managed in WeKnora"):+ asyncio.run(pipeline.initialize("remote", []))+++def test_factory_routes_weknora() -> None:+ assert normalize_provider_name("WeKnora") == "weknora"+ assert type(get_pipeline("weknora", kb_base_dir="/tmp/kbs")).__name__ == "WeKnoraPipeline"+ assert any(item["id"] == "weknora" for item in list_pipelines())+++def test_manager_pointer_hides_api_key(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ entry = manager.register_weknora_kb("Remote", "http://localhost:8080/", "secret", "kb-1")+ assert WEKNORA_KB_TYPE in CONNECTED_KB_TYPES+ assert entry["server_url"] == "http://localhost:8080"+ assert not (tmp_path / "Remote").exists()++ metadata = manager.get_metadata("Remote")+ assert metadata["knowledge_base_id"] == "kb-1"+ assert "api_key" not in metadata+ assert "secret" not in str(metadata)diff --git a/tests/tools/test_rag_tool.py b/tests/tools/test_rag_tool.pyindex dc0557e63..d3b9d5a94 100644--- a/tests/tools/test_rag_tool.py+++ b/tests/tools/test_rag_tool.py@@ -49,6 +49,7 @@ class TestPipelineFactory:"lightrag","lightrag-server","ima",+ "weknora",}def test_get_pipeline_returns_singleton(self) -> None:@@ -86,6 +87,7 @@ class TestRAGServiceClassHelpers:"lightrag","lightrag-server","ima",+ "weknora",}def test_has_provider_default_true(self) -> None:diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsxindex deb0c652d..96a7d0b19 100644--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";import {AlertTriangle,Check,+ Database,ExternalLink,FolderOpen,FolderSearch,@@ -19,10 +20,12 @@ import { useImaConnection } from "@/hooks/useImaConnection";import {probeLightRagServer,probeLinkedFolder,+ probeWeKnora,type KnowledgeUploadPolicy,type LightRagServerProbe,type LinkedFolderProbe,type RagProviderSummary,+ type WeKnoraProbe,} from "@/lib/knowledge-api";import {createProviders,@@ -39,6 +42,7 @@ import ImaConnectionFields from "./ImaConnectionFields";const OBSIDIAN_SOURCE = "obsidian";const MARGINNOTE4_SOURCE = "marginnote4";const LIGHTRAG_SERVER_PROVIDER = "lightrag-server";+const WEKNORA_PROVIDER = "weknora";const EXAMPLE_INDEX_PATH = "/Users/you/knowledge_bases/my-kb";const EXAMPLE_VAULT_PATH = "/Users/you/Documents/MyVault";const EXAMPLE_SERVER_URL = "http://localhost:9621";@@ -74,6 +78,13 @@ interface CreateKbModalProps {apiKey?: string;mode?: string;}) => Promise<void>;+ /** Connect a self-hosted WeKnora knowledge base (retrieval only). */+ onConnectWeKnora: (params: {+ name: string;+ serverUrl: string;+ apiKey: string;+ knowledgeBaseId: string;+ }) => Promise<void>;/** Connect a MarginNote 4 library (its Add-on pushes objects in; no index). */onConnectMarginNote4: (params: { name: string }) => Promise<void>;/** Connect a Tencent IMA knowledge base (retrieval only, no local index). */@@ -100,6 +111,7 @@ export default function CreateKbModal({onConnectLinkedFolder,onConnectObsidian,onConnectLightRagServer,+ onConnectWeKnora,onConnectMarginNote4,onConnectIma,onConfigureProvider,@@ -127,6 +139,9 @@ export default function CreateKbModal({null,);const [serverProbing, setServerProbing] = useState(false);+ const [weKnoraKnowledgeBaseId, setWeKnoraKnowledgeBaseId] = useState("");+ const [weKnoraProbe, setWeKnoraProbe] = useState<WeKnoraProbe | null>(null);+ const [weKnoraProbing, setWeKnoraProbing] = useState(false);const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);const linkIsObsidian = linkSource === OBSIDIAN_SOURCE;@@ -184,6 +199,9 @@ export default function CreateKbModal({setServerMode("");setServerProbe(null);setServerProbing(false);+ setWeKnoraKnowledgeBaseId("");+ setWeKnoraProbe(null);+ setWeKnoraProbing(false);}, [isOpen, providers, firstLinkable, initialMode, initialSource]);// A fresh path / source invalidates a stale probe verdict.@@ -196,6 +214,11 @@ export default function CreateKbModal({setServerProbe(null);}, [serverUrl, apiKey]);+ // A fresh URL, key, or remote KB id invalidates a stale WeKnora verdict.+ useEffect(() => {+ setWeKnoraProbe(null);+ }, [serverUrl, apiKey, weKnoraKnowledgeBaseId]);+// ---- New mode (build a fresh index) ----------------------------------const activeProvider = providers.find((p) => p.id === provider);const providerNeedsKey =@@ -204,6 +227,7 @@ export default function CreateKbModal({const isPageIndexCloud = provider === "pageindex";const isPageIndexOSS = provider === "pageindex-oss";const isLightRagServer = provider === LIGHTRAG_SERVER_PROVIDER;+ const isWeKnora = provider === WEKNORA_PROVIDER;const serverModeOptions = activeProvider?.modes ?? [];const effectiveServerMode =serverMode || activeProvider?.default_mode || serverModeOptions[0] || "";@@ -226,6 +250,14 @@ export default function CreateKbModal({// The connection must pass the test before a KB is bound to it.return !!trimmedServerUrl && !!serverProbe?.ok;}+ if (isWeKnora) {+ return (+ !!trimmedServerUrl &&+ !!apiKey.trim() &&+ !!weKnoraKnowledgeBaseId.trim() &&+ !!weKnoraProbe?.ok+ );+ }return !providerUnavailable;}if (linkIsIma) return imaConnection.canSubmit;@@ -270,6 +302,31 @@ export default function CreateKbModal({}};+ const handleTestWeKnora = async () => {+ if (+ !trimmedServerUrl ||+ !apiKey.trim() ||+ !weKnoraKnowledgeBaseId.trim() ||+ weKnoraProbing+ ) {+ return;+ }+ setWeKnoraProbing(true);+ setError(null);+ try {+ const result = await probeWeKnora({+ serverUrl: trimmedServerUrl,+ apiKey: apiKey.trim(),+ knowledgeBaseId: weKnoraKnowledgeBaseId.trim(),+ });+ setWeKnoraProbe(result);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setWeKnoraProbing(false);+ }+ };+const handleSubmit = async () => {if (!canSubmit) return;setSubmitting(true);@@ -283,6 +340,13 @@ export default function CreateKbModal({apiKey: apiKey.trim(),mode: effectiveServerMode,});+ } else if (isWeKnora) {+ await onConnectWeKnora({+ name: trimmed,+ serverUrl: trimmedServerUrl,+ apiKey: apiKey.trim(),+ knowledgeBaseId: weKnoraKnowledgeBaseId.trim(),+ });} else {await onCreate({name: trimmed,@@ -322,7 +386,7 @@ export default function CreateKbModal({const submitLabel =mode === "new"- ? isLightRagServer+ ? isLightRagServer || isWeKnora? t("Connect"): t("Create"): linkIsObsidian || linkIsIma || linkIsMarginNote@@ -356,7 +420,7 @@ export default function CreateKbModal({>{submitting ? (<Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : mode === "new" && !isLightRagServer ? (+ ) : mode === "new" && !isLightRagServer && !isWeKnora ? (<Plus size={14} />) : (<Link2 size={14} />@@ -421,6 +485,20 @@ export default function CreateKbModal({onTest={handleTestServer}t={t}/>+ ) : isWeKnora ? (+ <WeKnoraFields+ serverUrl={serverUrl}+ setServerUrl={setServerUrl}+ apiKey={apiKey}+ setApiKey={setApiKey}+ knowledgeBaseId={weKnoraKnowledgeBaseId}+ setKnowledgeBaseId={setWeKnoraKnowledgeBaseId}+ submitting={submitting}+ probing={weKnoraProbing}+ probe={weKnoraProbe}+ onTest={handleTestWeKnora}+ t={t}+ />) : null}t={t}@@ -857,6 +935,139 @@ function ServerProbeVerdict({);}+function WeKnoraFields({+ serverUrl,+ setServerUrl,+ apiKey,+ setApiKey,+ knowledgeBaseId,+ setKnowledgeBaseId,+ submitting,+ probing,+ probe,+ onTest,+ t,+}: {+ serverUrl: string;+ setServerUrl: (value: string) => void;+ apiKey: string;+ setApiKey: (value: string) => void;+ knowledgeBaseId: string;+ setKnowledgeBaseId: (value: string) => void;+ submitting: boolean;+ probing: boolean;+ probe: WeKnoraProbe | null;+ onTest: () => void;+ t: TFn;+}) {+ const testDisabled =+ submitting ||+ probing ||+ serverUrl.trim().length === 0 ||+ apiKey.trim().length === 0 ||+ knowledgeBaseId.trim().length === 0;++ return (+ <div className="space-y-3">+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Server URL")}+ </label>+ <div className="flex gap-2">+ <input+ value={serverUrl}+ onChange={(event) => setServerUrl(event.target.value)}+ disabled={submitting}+ placeholder={EXAMPLE_SERVER_URL}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ <button+ type="button"+ onClick={onTest}+ disabled={testDisabled}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--ring)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {probing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Server className="h-3.5 w-3.5" />+ )}+ {t("Test connection")}+ </button>+ </div>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "The base URL of your self-hosted WeKnora deployment. Documents remain there; DeepTutor only runs retrieval searches.",+ )}+ </p>+ </div>++ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("WeKnora API key")}+ </label>+ <input+ value={apiKey}+ onChange={(event) => setApiKey(event.target.value)}+ disabled={submitting}+ type="password"+ autoComplete="off"+ placeholder={t("Required to access your WeKnora knowledge base")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ </div>++ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("WeKnora knowledge base ID")}+ </label>+ <div className="relative">+ <Database className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />+ <input+ value={knowledgeBaseId}+ onChange={(event) => setKnowledgeBaseId(event.target.value)}+ disabled={submitting}+ placeholder={t("WeKnora knowledge base ID")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] py-2 pl-9 pr-3 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ </div>+ </div>++ {probe && <WeKnoraProbeVerdict probe={probe} t={t} />}+ </div>+ );+}++function WeKnoraProbeVerdict({ probe, t }: { probe: WeKnoraProbe; t: TFn }) {+ if (!probe.ok) {+ return (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ <span className="flex items-center gap-1.5 font-medium">+ <AlertTriangle className="h-3.5 w-3.5 shrink-0" />+ {t("Could not connect")}+ </span>+ {probe.error && <p className="mt-1 leading-relaxed">{probe.error}</p>}+ </div>+ );+ }++ return (+ <div className="space-y-1 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 px-3 py-2.5 text-[12px]">+ <div className="flex items-center gap-1.5 font-medium text-emerald-700 dark:text-emerald-300">+ <Check className="h-3.5 w-3.5 shrink-0" />+ {t("Connected to WeKnora")}+ </div>+ <div className="text-[11.5px] text-[var(--muted-foreground)]">+ {probe.knowledge_base_name+ ? t("Knowledge base {{name}}", {+ name: probe.knowledge_base_name,+ })+ : probe.knowledge_base_id}+ </div>+ </div>+ );+}+function LinkModeFields({providers,linkSource,diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsxindex 0f223e313..a15d31390 100644--- a/web/components/knowledge/EngineDetail.tsx+++ b/web/components/knowledge/EngineDetail.tsx@@ -76,6 +76,7 @@ const ENGINE_ICONS: Record<string, LucideIcon> = {graphrag: Network,lightrag: Workflow,"lightrag-server": Server,+ weknora: Database,};const INSTALL_HINTS: Record<string, string> = {@@ -121,6 +122,7 @@ const ENGINE_MODEL_KINDS: Record<string, ("llm" | "embedding")[]> = {graphrag: ["llm", "embedding"],lightrag: ["llm", "embedding"],"lightrag-server": [],+ weknora: [],};const MODEL_KIND_LABEL: Record<string, string> = {diff --git a/web/components/knowledge/KnowledgeHome.tsx b/web/components/knowledge/KnowledgeHome.tsxindex 158a5259c..ba414c861 100644--- a/web/components/knowledge/KnowledgeHome.tsx+++ b/web/components/knowledge/KnowledgeHome.tsx@@ -49,6 +49,7 @@ const ENGINE_ICONS: Record<string, LucideIcon> = {graphrag: Network,lightrag: Workflow,"lightrag-server": Server,+ weknora: Database,};function EngineStatusBadge({ status }: { status: ProviderConnectionStatus }) {diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsxindex 0701107df..bb999d9e2 100644--- a/web/components/knowledge/KnowledgePage.tsx+++ b/web/components/knowledge/KnowledgePage.tsx@@ -39,6 +39,7 @@ export default function KnowledgePage() {connectObsidian,connectLinkedFolder,connectLightRagServer,+ connectWeKnora,connectMarginNote4,connectIma,} = useKnowledgeBases();@@ -314,6 +315,7 @@ export default function KnowledgePage() {onConnectLinkedFolder={connectLinkedFolder}onConnectObsidian={connectObsidian}onConnectLightRagServer={connectLightRagServer}+ onConnectWeKnora={connectWeKnora}onConnectMarginNote4={connectMarginNote4}onConnectIma={connectIma}initialMode={createPreset?.mode}diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.tsindex 8679fbc63..020a4995f 100644--- a/web/hooks/useKnowledgeBases.ts+++ b/web/hooks/useKnowledgeBases.ts@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {connectImaKnowledgeBase as connectImaApi,connectLightRagServer as connectLightRagServerApi,+ connectWeKnora as connectWeKnoraApi,connectLinkedFolder as connectLinkedFolderApi,connectMarginNote4Library as connectMarginNote4Api,connectObsidianVault as connectObsidianApi,@@ -352,6 +353,20 @@ export function useKnowledgeBases() {[load],);+ const connectWeKnora = useCallback(+ async (params: {+ name: string;+ serverUrl: string;+ apiKey: string;+ knowledgeBaseId: string;+ }) => {+ await connectWeKnoraApi(params);+ invalidateKnowledgeCaches();+ await load({ force: true, showSpinner: false });+ },+ [load],+ );+const connectIma = useCallback(async (params: {name: string;@@ -389,6 +404,7 @@ export function useKnowledgeBases() {connectObsidian,connectLinkedFolder,connectLightRagServer,+ connectWeKnora,connectMarginNote4,connectIma,};diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsindex 3b073590b..7cf062224 100644--- a/web/lib/knowledge-api.ts+++ b/web/lib/knowledge-api.ts@@ -794,6 +794,17 @@ export interface LightRagServerProbe {error: string | null;}+export interface WeKnoraProbe {+ ok: boolean;+ base_url: string;+ knowledge_base_id: string;+ reachable: boolean;+ credentials_ok: boolean;+ knowledge_base_found: boolean;+ knowledge_base_name: string | null;+ error: string | null;+}+export interface ImaKnowledgeBasePage {knowledge_bases: ImaKnowledgeBaseOption[];next_cursor: string;@@ -959,6 +970,61 @@ export async function connectLightRagServer(payload: {};}+export async function probeWeKnora(payload: {+ serverUrl: string;+ apiKey: string;+ knowledgeBaseId: string;+}): Promise<WeKnoraProbe> {+ const res = await apiFetch(apiUrl("/api/v1/knowledge/probe-weknora"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ server_url: payload.serverUrl,+ api_key: payload.apiKey,+ knowledge_base_id: payload.knowledgeBaseId,+ }),+ });+ if (!res.ok) {+ throw new Error(await readErrorDetail(res, "Failed to reach WeKnora"));+ }+ return (await res.json()) as WeKnoraProbe;+}++export async function connectWeKnora(payload: {+ name: string;+ serverUrl: string;+ apiKey: string;+ knowledgeBaseId: string;+}): Promise<{+ status: string;+ name: string;+ server_url: string;+ knowledge_base_id: string;+ rag_provider: string;+}> {+ const res = await apiFetch(apiUrl("/api/v1/knowledge/connect-weknora"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: payload.name,+ server_url: payload.serverUrl,+ api_key: payload.apiKey,+ knowledge_base_id: payload.knowledgeBaseId,+ }),+ });+ if (!res.ok) {+ throw new Error(await readErrorDetail(res, "Failed to connect WeKnora"));+ }+ invalidateKnowledgeCaches();+ return (await res.json()) as {+ status: string;+ name: string;+ server_url: string;+ knowledge_base_id: string;+ rag_provider: string;+ };+}+export async function uploadKnowledgeBaseFiles(name: string,files: File[],diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 846e8a812..fd8fb2941 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2880,9 +2880,15 @@"Image is too large": "Image is too large","Server URL": "Server URL","The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.": "The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.",+ "The base URL of your self-hosted WeKnora deployment. Documents remain there; DeepTutor only runs retrieval searches.": "The base URL of your self-hosted WeKnora deployment. Documents remain there; DeepTutor only runs retrieval searches.",+ "WeKnora API key": "WeKnora API key",+ "Required to access your WeKnora knowledge base": "Required to access your WeKnora knowledge base",+ "WeKnora knowledge base ID": "WeKnora knowledge base ID","Only if your server requires one": "Only if your server requires one","Could not connect": "Could not connect","Connected to LightRAG server": "Connected to LightRAG server",+ "Connected to WeKnora": "Connected to WeKnora",+ "Knowledge base {{name}}": "Knowledge base {{name}}","Core {{version}}": "Core {{version}}","API key accepted": "API key accepted","Open access": "Open access",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 1279f3d24..161aca1aa 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2880,9 +2880,15 @@"Image is too large": "图片过大","Server URL": "服务器地址","The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.": "你正在运行的 LightRAG 服务器的基础地址。文档在该服务器上建立索引——不会上传或复制任何内容。",+ "The base URL of your self-hosted WeKnora deployment. Documents remain there; DeepTutor only runs retrieval searches.": "你自托管的 WeKnora 服务基础地址。文档保留在该服务中,DeepTutor 只执行检索请求。",+ "WeKnora API key": "WeKnora API 密钥",+ "Required to access your WeKnora knowledge base": "访问你的 WeKnora 知识库所需",+ "WeKnora knowledge base ID": "WeKnora 知识库 ID","Only if your server requires one": "仅当你的服务器需要时填写","Could not connect": "无法连接","Connected to LightRAG server": "已连接到 LightRAG 服务器",+ "Connected to WeKnora": "已连接到 WeKnora",+ "Knowledge base {{name}}": "知识库 {{name}}","Core {{version}}": "内核 {{version}}","API key accepted": "API 密钥已通过","Open access": "开放访问",