Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(knowledge): add Tencent IMA as a connected knowledge engine

Bingxi Zhao (Frank)e1c669f02a2b
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 5cefa1d6a..3ee940155 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -1657,6 +1657,87 @@ async def connect_lightrag_server_route(payload: ConnectLightRagServerRequest):
}
+class ProbeImaRequest(BaseModel):
+ client_id: str
+ api_key: str
+ knowledge_base_id: str
+
+
+class ConnectImaRequest(BaseModel):
+ name: str
+ client_id: str
+ api_key: str
+ knowledge_base_id: str
+
+
[email protected]("/probe-ima")
+async def probe_ima_route(payload: ProbeImaRequest):
+ """Test-connect to a Tencent IMA knowledge base before binding a KB to it.
+
+ Returns the verdict (credentials accepted? does the library id resolve, and
+ what is it called?) so the UI can confirm before any registration happens.
+ Creates nothing.
+ """
+ from deeptutor.services.rag.pipelines.ima.probe import probe_knowledge_base
+
+ result = await probe_knowledge_base(
+ payload.client_id,
+ payload.api_key,
+ payload.knowledge_base_id,
+ )
+ return result.to_dict()
+
+
[email protected]("/connect-ima")
+async def connect_ima_route(payload: ConnectImaRequest):
+ """Connect a Tencent IMA knowledge base as a retrieval-only knowledge base.
+
+ Re-probes server-side (never trusts the client's verdict), then registers a
+ pointer (``type: ima``). Retrieval is offloaded to IMA's ``search_knowledge``
+ OpenAPI — no copy, no local index.
+ """
+ from deeptutor.services.rag.pipelines.ima.probe import probe_knowledge_base
+
+ name = (payload.name or "").strip()
+ if not name:
+ raise HTTPException(status_code=400, detail="Knowledge base name is required.")
+
+ result = await probe_knowledge_base(
+ payload.client_id,
+ payload.api_key,
+ payload.knowledge_base_id,
+ )
+ if not result.ok:
+ raise HTTPException(
+ status_code=400,
+ detail=result.error or "Could not connect to the IMA knowledge base.",
+ )
+
+ try:
+ manager = get_kb_manager()
+ entry = manager.register_ima_kb(
+ name,
+ payload.client_id,
+ payload.api_key,
+ payload.knowledge_base_id,
+ description=result.description or "",
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e))
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Error connecting IMA knowledge base: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+ return {
+ "status": "connected",
+ "name": name,
+ "knowledge_base_id": entry["knowledge_base_id"],
+ "rag_provider": entry["rag_provider"],
+ }
+
+
@router.get("/list", response_model=list[KnowledgeBaseInfo])
async def list_knowledge_bases():
"""List all available knowledge bases with their details."""
diff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.py
index ddd9c7976..fe18bf075 100644
--- a/deeptutor/knowledge/kb_types.py
+++ b/deeptutor/knowledge/kb_types.py
@@ -3,7 +3,7 @@
A KB entry's ``type`` field tells the rest of the system how to treat it.
Most KBs are the default *indexed* kind (chunk → embed → retrieve via an RAG
provider) and carry no ``type``. *Connected* KBs are pointers: their content
-lives outside ``data/knowledge_bases`` and we never copy or re-index it. Two
+lives outside ``data/knowledge_bases`` and we never copy or re-index it. These
flavours exist today:
* ``obsidian`` — a pointer (``vault_path``) to a folder of Markdown the user
@@ -24,15 +24,20 @@ flavours exist today:
``/query`` endpoint and the bound ``rag_provider`` (``lightrag-server``) shapes
the result for the ``rag`` tool. One server instance = one workspace = one KB.
See ``services/rag/pipelines/lightrag_server``.
+* ``ima`` — a pointer (``client_id`` + ``api_key`` + ``knowledge_base_id``) to a
+ knowledge base the user keeps in Tencent IMA. Same shape as
+ ``lightrag_server``: nothing indexed or stored locally, retrieval offloaded to
+ IMA's ``search_knowledge`` OpenAPI by the bound ``ima`` provider, and one IMA
+ library = one KB. See ``services/rag/pipelines/ima``.
All connected flavours share the same lifecycle quirks: no on-disk folder under
``base_dir``, no embedding reconcile, and deletion must never touch the
external resource. The :func:`is_connected_kb` / :func:`external_root_of` helpers
let the manager treat them uniformly without sprinkling ``type`` literals
-across the codebase. ``subagent`` and ``lightrag_server`` are connected but point
-at no folder, so :func:`external_root_of` returns ``None`` for them — a subagent
-is driven by its capability and a LightRAG server is reached over HTTP; neither
-resolves to a local path.
+across the codebase. ``subagent``, ``lightrag_server`` and ``ima`` are connected
+but point at no folder, so :func:`external_root_of` returns ``None`` for them — a
+subagent is driven by its capability and the two server-backed kinds are reached
+over HTTP; none resolves to a local path.
Kept in its own low-level module so both :mod:`deeptutor.knowledge.manager`
and the capability layer can import it without a cycle.
@@ -63,10 +68,22 @@ SUBAGENT_KB_TYPE = "subagent"
# ``/query`` endpoint by the ``lightrag-server`` provider.
LIGHTRAG_SERVER_KB_TYPE = "lightrag_server"
+# A connected Tencent IMA knowledge base: a pointer (``client_id`` + ``api_key``
+# + ``knowledge_base_id``) to a library the user curates in IMA. No path on disk
+# and no local index — retrieval is offloaded over HTTPS to IMA's
+# ``search_knowledge`` OpenAPI by the ``ima`` provider.
+IMA_KB_TYPE = "ima"
+
# Every pointer/connected KB type. Membership here is what makes the manager
# skip the index pipeline, the orphan prune and the embedding reconcile.
CONNECTED_KB_TYPES = frozenset(
- {OBSIDIAN_KB_TYPE, LINKED_KB_TYPE, SUBAGENT_KB_TYPE, LIGHTRAG_SERVER_KB_TYPE}
+ {
+ OBSIDIAN_KB_TYPE,
+ LINKED_KB_TYPE,
+ SUBAGENT_KB_TYPE,
+ LIGHTRAG_SERVER_KB_TYPE,
+ IMA_KB_TYPE,
+ }
)
@@ -91,6 +108,7 @@ __all__ = [
"LINKED_KB_TYPE",
"SUBAGENT_KB_TYPE",
"LIGHTRAG_SERVER_KB_TYPE",
+ "IMA_KB_TYPE",
"CONNECTED_KB_TYPES",
"is_connected_kb",
"external_root_of",
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index e42da8860..12963b6eb 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -18,6 +18,7 @@ import sys
from typing import Any
from deeptutor.knowledge.kb_types import (
+ IMA_KB_TYPE,
LIGHTRAG_SERVER_KB_TYPE,
LINKED_KB_TYPE,
OBSIDIAN_KB_TYPE,
@@ -29,6 +30,7 @@ from deeptutor.knowledge.manifest import iter_kb_documents
from deeptutor.services.file_io import atomic_write_json
from deeptutor.services.rag.factory import (
DEFAULT_PROVIDER,
+ IMA_PROVIDER,
KNOWN_PROVIDERS,
LIGHTRAG_SERVER_PROVIDER,
has_ready_provider_index,
@@ -878,6 +880,58 @@ class KnowledgeBaseManager:
self._save_config()
return entry
+ def register_ima_kb(
+ self,
+ name: str,
+ client_id: str,
+ api_key: str,
+ knowledge_base_id: str,
+ *,
+ description: str = "",
+ ) -> dict:
+ """Register a pointer to a Tencent IMA knowledge base as a connected KB.
+
+ Like the other connected types this creates no folder under ``base_dir``
+ and runs no index pipeline: it records a ``type: ima`` entry whose
+ credentials and library id the ``ima`` provider queries over IMA's
+ OpenAPI. IMA owns indexing entirely. Callers should validate the binding
+ with the probe helper first; this only guards basic invariants. Raises
+ ``ValueError`` on a missing field or a name clash.
+ """
+ name = (name or "").strip()
+ client_id = (client_id or "").strip()
+ 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 client_id or not api_key:
+ raise ValueError("IMA Client ID and API Key are required.")
+ if not knowledge_base_id:
+ raise ValueError("IMA knowledge base ID 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": IMA_KB_TYPE,
+ "rag_provider": IMA_PROVIDER,
+ "client_id": client_id,
+ "api_key": api_key,
+ "knowledge_base_id": knowledge_base_id,
+ "description": description or f"Tencent IMA: {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.
@@ -1023,6 +1077,10 @@ class KnowledgeBaseManager:
# LightRAG server pointer (the URL is safe to surface; the API
# key deliberately is not).
"server_url": kb_config.get("server_url"),
+ # IMA pointer. The library id identifies which IMA knowledge
+ # base this KB reads; the client id and API key are credentials
+ # and are deliberately absent from this allowlist.
+ "knowledge_base_id": kb_config.get("knowledge_base_id"),
# Subagent connection fields (None for non-subagent KBs).
"agent_kind": kb_config.get("agent_kind"),
"cwd": kb_config.get("cwd"),
@@ -1155,6 +1213,9 @@ class KnowledgeBaseManager:
# the backend, so it is deliberately not surfaced here.
if kb_config.get("server_url"):
metadata["server_url"] = kb_config.get("server_url")
+ # Same split for IMA: the library id is shown, the credentials are not.
+ if kb_config.get("knowledge_base_id"):
+ metadata["knowledge_base_id"] = kb_config.get("knowledge_base_id")
metadata.update(self._embedding_fields(kb_config))
diff --git a/deeptutor/knowledge/manifest.py b/deeptutor/knowledge/manifest.py
index aa648e3db..37a5e4c63 100644
--- a/deeptutor/knowledge/manifest.py
+++ b/deeptutor/knowledge/manifest.py
@@ -35,6 +35,7 @@ from pathlib import Path
from typing import Any
from deeptutor.knowledge.kb_types import (
+ IMA_KB_TYPE,
LIGHTRAG_SERVER_KB_TYPE,
SUBAGENT_KB_TYPE,
external_root_of,
@@ -60,6 +61,7 @@ UNAVAILABLE_MISSING = "missing"
# as non-enumerable instead.
_NON_DOCUMENT_KB_TYPES: dict[str, str] = {
LIGHTRAG_SERVER_KB_TYPE: UNAVAILABLE_REMOTE,
+ IMA_KB_TYPE: UNAVAILABLE_REMOTE,
SUBAGENT_KB_TYPE: UNAVAILABLE_AGENT,
}
diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.py
index 768dd4fad..43598db90 100644
--- a/deeptutor/services/rag/factory.py
+++ b/deeptutor/services/rag/factory.py
@@ -14,6 +14,9 @@ today:
* ``lightrag-server`` — retrieval offloaded to an external, standalone
LightRAG server the user runs. No local index: each
KB is a connection pointer queried over HTTP.
+* ``ima`` — retrieval offloaded to a Tencent IMA knowledge base
+ the user curates in IMA. No local index: each KB is
+ a connection pointer queried over IMA's OpenAPI.
A KB is bound to one provider at creation time; later adds and retrieval always
go through that same pipeline (enforced upstream in the knowledge router).
@@ -29,6 +32,7 @@ PAGEINDEX_PROVIDER = "pageindex"
GRAPHRAG_PROVIDER = "graphrag"
LIGHTRAG_PROVIDER = "lightrag"
LIGHTRAG_SERVER_PROVIDER = "lightrag-server"
+IMA_PROVIDER = "ima"
# Providers the factory can instantiate. Unknown / legacy strings fall back to
# the default with a re-index hint upstream.
@@ -39,6 +43,7 @@ KNOWN_PROVIDERS = frozenset(
GRAPHRAG_PROVIDER,
LIGHTRAG_PROVIDER,
LIGHTRAG_SERVER_PROVIDER,
+ IMA_PROVIDER,
}
)
@@ -80,6 +85,7 @@ def version_matches_provider(entry: dict[str, Any], provider: Optional[str]) ->
GRAPHRAG_PROVIDER,
LIGHTRAG_PROVIDER,
LIGHTRAG_SERVER_PROVIDER,
+ IMA_PROVIDER,
}
return entry_provider == resolved or signature == resolved
@@ -140,6 +146,13 @@ def _build_pipeline(provider: str, kb_base_dir: Optional[str], **kwargs: Any):
kwargs.setdefault("kb_base_dir", kb_base_dir)
return LightRagServerPipeline(**kwargs)
+ if provider == IMA_PROVIDER:
+ from .pipelines.ima.pipeline import ImaPipeline
+
+ if kb_base_dir is not None:
+ kwargs.setdefault("kb_base_dir", kb_base_dir)
+ return ImaPipeline(**kwargs)
+
from .pipelines.llamaindex.pipeline import LlamaIndexPipeline
if kb_base_dir is not None:
@@ -245,6 +258,20 @@ def list_pipelines() -> List[Dict[str, Any]]:
"modes": lightrag_server_modes,
"default_mode": lightrag_server_default_mode,
},
+ {
+ "id": IMA_PROVIDER,
+ "name": "Tencent IMA",
+ "description": (
+ "Retrieval offloaded to a knowledge base you keep in Tencent IMA. "
+ "No local index and no copy — connect a KB to its IMA library and "
+ "query it over IMA's OpenAPI. Documents are added in IMA itself."
+ ),
+ # Always available: a thin HTTPS client with no install and no global
+ # credential. Client ID, API key and library id are per-KB, set at
+ # connect time.
+ "configured": True,
+ "requires_api_key": False,
+ },
]
@@ -254,6 +281,7 @@ __all__ = [
"GRAPHRAG_PROVIDER",
"LIGHTRAG_PROVIDER",
"LIGHTRAG_SERVER_PROVIDER",
+ "IMA_PROVIDER",
"KNOWN_PROVIDERS",
"get_pipeline",
"has_ready_provider_index",
diff --git a/deeptutor/services/rag/pipelines/ima/__init__.py b/deeptutor/services/rag/pipelines/ima/__init__.py
new file mode 100644
index 000000000..8e4521808
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/ima/__init__.py
@@ -0,0 +1,15 @@
+"""Retrieval-only RAG pipeline backed by a Tencent IMA knowledge base.
+
+A KB bound to the ``ima`` provider is a connection pointer to a library the user
+keeps in IMA (https://ima.qq.com) and curates there. DeepTutor never indexes or
+stores anything locally: retrieval calls IMA's ``search_knowledge`` OpenAPI
+(passages only — DeepTutor's chat LLM still writes the answer), and the
+credentials plus knowledge base id are configured per-KB. See ``client`` for the
+wire and ``probe`` for the connect-time health check.
+"""
+
+from __future__ import annotations
+
+from .pipeline import ImaPipeline
+
+__all__ = ["ImaPipeline"]
diff --git a/deeptutor/services/rag/pipelines/ima/client.py b/deeptutor/services/rag/pipelines/ima/client.py
new file mode 100644
index 000000000..d86d37688
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/ima/client.py
@@ -0,0 +1,161 @@
+"""Thin async HTTP client for Tencent IMA's knowledge-base OpenAPI.
+
+Every IMA call is ``POST https://ima.qq.com/openapi/wiki/v1/<method>`` with a
+JSON body, authenticated by two headers, and answers with a
+``{"code", "msg", "data"}`` envelope where ``code == 0`` means success. Only the
+two read-only calls DeepTutor needs are wrapped:
+
+* ``search_knowledge`` — retrieval inside one knowledge base. Returns matching
+ items with a ``highlight_content`` snippet, cursor-paginated.
+* ``get_knowledge_base`` — a KB's name/description, used to confirm at connect
+ time that the credentials work and the id resolves.
+
+Writing to IMA is deliberately out of scope: a connected KB is a read-only
+pointer, and documents are added in IMA itself.
+
+Mirrors :class:`LightRagServerClient`: a fresh :class:`httpx.AsyncClient` per
+call so the object is safe to construct once and reuse, and an injectable
+``transport`` so tests can stub the wire without a live server.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Optional
+
+import httpx
+
+from .config import ImaConfig
+
+logger = logging.getLogger(__name__)
+
+API_BASE_URL = "https://ima.qq.com"
+_API_PREFIX = "/openapi/wiki/v1"
+
+# Envelope codes worth naming. IMA returns hundreds of business codes; these are
+# the two classes a caller reacts to differently from a generic failure.
+_CREDENTIAL_CODES = frozenset({20004})
+_RATE_LIMIT_CODES = frozenset({20002, 110021})
+
+# ``search_knowledge`` is cursor-paginated. Retrieval feeds an LLM prompt, so a
+# couple of pages is plenty — this bounds the calls a single search can make.
+_MAX_SEARCH_PAGES = 3
+
+
+class ImaAPIError(RuntimeError):
+ """Raised when IMA returns an error envelope or an unexpected payload."""
+
+
+class ImaAuthError(ImaAPIError):
+ """Raised when IMA rejects the client id / API key pair."""
+
+
+class ImaRateLimitError(ImaAPIError):
+ """Raised when IMA rate-limits the request."""
+
+
+class ImaClient:
+ """Stateless wrapper over the IMA knowledge-base OpenAPI."""
+
+ def __init__(
+ self,
+ config: ImaConfig,
+ *,
+ timeout: float = 30.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=API_BASE_URL,
+ headers={
+ "Content-Type": "application/json",
+ "ima-openapi-clientid": self._config.client_id,
+ "ima-openapi-apikey": self._config.api_key,
+ },
+ timeout=self._timeout,
+ transport=self._transport,
+ )
+
+ async def _post(self, method: str, body: dict[str, Any]) -> dict[str, Any]:
+ """POST one IMA method and return its unwrapped ``data`` object."""
+ async with self._open() as client:
+ resp = await client.post(f"{_API_PREFIX}/{method}", json=body)
+ if resp.status_code == 429:
+ raise ImaRateLimitError("IMA rate limit reached. Try again shortly.")
+ try:
+ payload = resp.json()
+ except Exception as exc:
+ raise ImaAPIError(
+ f"IMA returned a non-JSON response with status {resp.status_code}"
+ ) from exc
+ if not isinstance(payload, dict):
+ raise ImaAPIError(f"IMA returned an unexpected payload: {payload!r}")
+
+ code = payload.get("code")
+ message = str(payload.get("msg") or "").strip()
+ if code == 0:
+ data = payload.get("data")
+ return data if isinstance(data, dict) else {}
+ if code in _CREDENTIAL_CODES:
+ raise ImaAuthError(message or "IMA rejected the client ID / API key.")
+ if code in _RATE_LIMIT_CODES:
+ raise ImaRateLimitError(message or "IMA rate limit reached.")
+ raise ImaAPIError(message or f"IMA request failed with code {code}.")
+
+ # ----- retrieval ------------------------------------------------------
+
+ async def search_knowledge(self, query: str, *, limit: int) -> list[dict[str, Any]]:
+ """Return up to *limit* matching items from the bound knowledge base.
+
+ Each item is ``{"media_id", "title", "parent_folder_id",
+ "highlight_content"}``. Pages are followed until the result is full,
+ IMA reports the end of the list, or the page budget runs out.
+ """
+ items: list[dict[str, Any]] = []
+ cursor = ""
+ for _ in range(_MAX_SEARCH_PAGES):
+ data = await self._post(
+ "search_knowledge",
+ {
+ "query": query,
+ "cursor": cursor,
+ "knowledge_base_id": self._config.knowledge_base_id,
+ },
+ )
+ page = data.get("info_list")
+ if isinstance(page, list):
+ items.extend(entry for entry in page if isinstance(entry, dict))
+ cursor = str(data.get("next_cursor") or "")
+ if len(items) >= limit or data.get("is_end") or not cursor:
+ break
+ return items[:limit]
+
+ # ----- probing --------------------------------------------------------
+
+ async def get_knowledge_base(self) -> dict[str, Any]:
+ """Return the bound knowledge base's info, or ``{}`` when unknown.
+
+ Doubles as the credential check: bad credentials raise
+ :class:`ImaAuthError`, while a well-formed but unknown id simply yields
+ no entry for it.
+ """
+ kb_id = self._config.knowledge_base_id
+ data = await self._post("get_knowledge_base", {"ids": [kb_id]})
+ infos = data.get("infos")
+ if not isinstance(infos, dict):
+ return {}
+ info = infos.get(kb_id)
+ return info if isinstance(info, dict) else {}
+
+
+__all__ = [
+ "API_BASE_URL",
+ "ImaClient",
+ "ImaAPIError",
+ "ImaAuthError",
+ "ImaRateLimitError",
+]
diff --git a/deeptutor/services/rag/pipelines/ima/config.py b/deeptutor/services/rag/pipelines/ima/config.py
new file mode 100644
index 000000000..1169966f8
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/ima/config.py
@@ -0,0 +1,82 @@
+"""Per-KB connection config for the Tencent IMA engine.
+
+IMA credentials (``client_id`` + ``api_key``, issued at
+https://ima.qq.com/agent-interface) identify a *person*, and a knowledge base id
+identifies one of that person's libraries. Both are stored per-KB in
+``kb_config.json`` — the same place a ``lightrag-server`` KB keeps its endpoint —
+rather than as one global account key:
+
+* on a multi-user deployment each user connects their own IMA account, so
+ nobody retrieves through somebody else's credentials;
+* connecting is self-contained, with no separate global settings surface to fill
+ in first.
+
+This module is the single seam that reads that binding into a typed config; it
+holds no global state and imports no HTTP client (the client lives in
+``client.py``).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+# IMA exposes exactly one retrieval call (``search_knowledge``) with no mode
+# knob, so a KB bound to this engine has no per-KB search mode to pick. The
+# empty tuple keeps the shared provider-mode plumbing happy while telling the
+# UI there is nothing to offer.
+SUPPORTED_MODES: tuple[str, ...] = ()
+DEFAULT_MODE = ""
+
+
+class ImaNotConfiguredError(RuntimeError):
+ """Raised when a KB is missing the credentials or the knowledge base id."""
+
+
+@dataclass(frozen=True)
+class ImaConfig:
+ """A KB's resolved connection to one Tencent IMA knowledge base."""
+
+ client_id: str
+ api_key: str
+ knowledge_base_id: str
+
+
+def config_from_entry(entry: dict[str, Any]) -> ImaConfig:
+ """Build an :class:`ImaConfig` from a ``kb_config.json`` KB entry.
+
+ Raises :class:`ImaNotConfiguredError` when any of the three required fields
+ is missing, so retrieval fails with a clear message instead of an opaque
+ HTTP error from IMA.
+ """
+ client_id = str(entry.get("client_id") or "").strip()
+ api_key = str(entry.get("api_key") or "").strip()
+ knowledge_base_id = str(entry.get("knowledge_base_id") or "").strip()
+ missing = [
+ label
+ for label, value in (
+ ("client ID", client_id),
+ ("API key", api_key),
+ ("knowledge base ID", knowledge_base_id),
+ )
+ if not value
+ ]
+ if missing:
+ raise ImaNotConfiguredError(
+ "This knowledge base is not fully connected to Tencent IMA "
+ f"(missing {', '.join(missing)}). Re-create it with complete credentials."
+ )
+ return ImaConfig(
+ client_id=client_id,
+ api_key=api_key,
+ knowledge_base_id=knowledge_base_id,
+ )
+
+
+__all__ = [
+ "SUPPORTED_MODES",
+ "DEFAULT_MODE",
+ "ImaNotConfiguredError",
+ "ImaConfig",
+ "config_from_entry",
+]
diff --git a/deeptutor/services/rag/pipelines/ima/pipeline.py b/deeptutor/services/rag/pipelines/ima/pipeline.py
new file mode 100644
index 000000000..e7f86969d
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/ima/pipeline.py
@@ -0,0 +1,147 @@
+"""Retrieval-only pipeline backed by a Tencent IMA knowledge base.
+
+Implements the same contract as the other pipelines (see ``..base.RAGPipeline``)
+but owns no index: an ``ima`` KB is a connection pointer (``type: ima`` in
+``kb_config.json``) to a library the user keeps in IMA and curates there. Only
+:meth:`search` does real work — it reads the KB's credentials, asks IMA for
+matching passages, and shapes them for the ``rag`` tool. Documents are added in
+IMA, so :meth:`initialize` / :meth:`add_documents` are not part of this engine's
+job and fail with a clear message; :meth:`delete` is a no-op because deleting the
+KB only drops DeepTutor's pointer (handled by the manager) and must never touch
+the user's IMA library.
+"""
+
+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 ImaNotConfiguredError, config_from_entry
+
+logger = logging.getLogger(__name__)
+
+PROVIDER = "ima"
+DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
+
+# How many matched passages one retrieval feeds into the prompt. IMA returns a
+# highlight snippet per item rather than whole documents, so this is a passage
+# budget, not a document budget.
+_DEFAULT_TOP_K = 10
+
+
+class ImaPipeline:
+ """Query a Tencent IMA knowledge base on behalf of a connected KB."""
+
+ def __init__(self, kb_base_dir: Optional[str] = None, *, client_factory=None, **_: Any) -> None:
+ self.logger = logging.getLogger(__name__)
+ self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR
+ # Injection seam for tests: (config) -> client. None uses the real client.
+ self._client_factory = client_factory
+
+ # ----- helpers --------------------------------------------------------
+
+ def _client(self, config):
+ if self._client_factory is not None:
+ return self._client_factory(config)
+ from .client import ImaClient
+
+ return ImaClient(config)
+
+ @staticmethod
+ def _top_k(kwargs: dict[str, Any]) -> int:
+ try:
+ requested = int(kwargs.get("top_k") or _DEFAULT_TOP_K)
+ except (TypeError, ValueError):
+ return _DEFAULT_TOP_K
+ return max(1, min(requested, 50))
+
+ # ----- retrieval ------------------------------------------------------
+
+ 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 ImaNotConfiguredError as exc:
+ return self._error_result(query, exc, error_type="not_configured")
+
+ try:
+ items = await self._client(config).search_knowledge(query, limit=self._top_k(kwargs))
+ except Exception as exc:
+ self.logger.error("IMA search failed for '%s': %s", kb_name, exc)
+ return self._error_result(query, exc, error_type="retrieval_error")
+
+ sources = _sources_from_items(items)
+ content = _render_context(sources)
+ return {
+ "query": query,
+ "answer": content,
+ "content": content,
+ "sources": sources,
+ "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,
+ }
+
+ # ----- indexing (not applicable — owned by IMA) ------------------------
+
+ async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ raise RuntimeError(
+ "Tencent IMA knowledge bases are indexed by IMA; DeepTutor does not "
+ "build or store their index. Add documents in IMA directly."
+ )
+
+ async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ return await self.initialize(kb_name, file_paths, **kwargs)
+
+ # ----- lifecycle ------------------------------------------------------
+
+ async def delete(self, kb_name: str, **kwargs) -> bool:
+ # The KB is only a pointer; the manager removes its config entry. Never
+ # touch the user's IMA library. Nothing local to clean up here.
+ return True
+
+
+def _sources_from_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Map IMA search items into DeepTutor's ``sources`` shape.
+
+ ``highlight_content`` is the matched snippet IMA returns; items whose match
+ was on the title alone carry none and are still listed, so the model can see
+ the document exists even without a quotable passage.
+ """
+ sources: list[dict[str, Any]] = []
+ for item in items:
+ title = str(item.get("title") or "").strip()
+ media_id = str(item.get("media_id") or "").strip()
+ if not title and not media_id:
+ continue
+ sources.append(
+ {
+ "title": title or media_id,
+ "content": str(item.get("highlight_content") or "").strip(),
+ "source": title or media_id,
+ "chunk_id": media_id,
+ }
+ )
+ return sources
+
+
+def _render_context(sources: list[dict[str, Any]]) -> str:
+ """Flatten retrieved snippets into the grounded context block."""
+ blocks = [
+ f"[{index}] {source['title']}\n{source['content']}".rstrip()
+ for index, source in enumerate(sources, start=1)
+ ]
+ return "\n\n".join(blocks)
+
+
+__all__ = ["ImaPipeline", "PROVIDER"]
diff --git a/deeptutor/services/rag/pipelines/ima/probe.py b/deeptutor/services/rag/pipelines/ima/probe.py
new file mode 100644
index 000000000..5ee0f3d85
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/ima/probe.py
@@ -0,0 +1,102 @@
+"""Probe a Tencent IMA knowledge base before connecting a KB to it.
+
+Connecting is cheap and reversible, but wrong credentials or a mistyped
+knowledge base id should fail loudly at connect time rather than silently at
+every later query. One ``get_knowledge_base`` round-trip answers both questions
+the UI needs to confirm: are the credentials accepted, and does the id resolve to
+a library we can name back to the user?
+
+Always returns an :class:`ImaProbe` (never raises); ``ok`` is the single boolean
+the caller gates on, with ``error`` explaining any failure.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+from typing import Any, Optional
+
+from .client import ImaAuthError, ImaClient
+from .config import ImaConfig
+
+
+@dataclass
+class ImaProbe:
+ knowledge_base_id: str
+ ok: bool = False
+ credentials_ok: bool = False
+ knowledge_base_name: Optional[str] = None
+ description: Optional[str] = None
+ error: Optional[str] = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+async def probe_knowledge_base(
+ client_id: str,
+ api_key: str,
+ knowledge_base_id: str,
+ *,
+ client_factory=None,
+) -> ImaProbe:
+ """Check that *knowledge_base_id* is reachable with the given credentials.
+
+ ``client_factory`` (config → client) is an injection seam for tests; in
+ production it defaults to a real :class:`ImaClient`.
+ """
+ client_id = (client_id or "").strip()
+ api_key = (api_key or "").strip()
+ knowledge_base_id = (knowledge_base_id or "").strip()
+
+ probe = ImaProbe(knowledge_base_id=knowledge_base_id)
+ missing = [
+ label
+ for label, value in (
+ ("Client ID", client_id),
+ ("API key", api_key),
+ ("knowledge base ID", knowledge_base_id),
+ )
+ if not value
+ ]
+ if missing:
+ probe.error = f"{', '.join(missing)} is required."
+ return probe
+
+ config = ImaConfig(
+ client_id=client_id,
+ api_key=api_key,
+ knowledge_base_id=knowledge_base_id,
+ )
+ client = client_factory(config) if client_factory else ImaClient(config)
+
+ try:
+ info = await client.get_knowledge_base()
+ except ImaAuthError as exc:
+ probe.error = f"IMA rejected these credentials: {exc}"
+ return probe
+ except Exception as exc:
+ probe.error = f"Could not reach Tencent IMA: {exc}"
+ return probe
+
+ # The call is credential-gated, so reaching this point means they were
+ # accepted — an unknown id just yields no entry.
+ probe.credentials_ok = True
+ if not info:
+ probe.error = (
+ "The credentials work, but no knowledge base matches this ID. "
+ "Check the ID in IMA and try again."
+ )
+ return probe
+
+ probe.knowledge_base_name = _opt_str(info.get("name"))
+ probe.description = _opt_str(info.get("description"))
+ probe.ok = True
+ return probe
+
+
+def _opt_str(value: Any) -> Optional[str]:
+ text = str(value).strip() if value is not None else ""
+ return text or None
+
+
+__all__ = ["ImaProbe", "probe_knowledge_base"]
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 196adce61..53f356708 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -140,6 +140,7 @@ def test_rag_providers_lists_llamaindex_and_pageindex() -> None:
"graphrag",
"lightrag",
"lightrag-server",
+ "ima",
}
# LlamaIndex works out of the box; PageIndex needs an API key; GraphRAG and
# LightRAG are optional local engines (no API key, configured = installed).
@@ -151,10 +152,16 @@ def test_rag_providers_lists_llamaindex_and_pageindex() -> None:
# (the per-KB endpoint is configured at connect time).
assert by_id["lightrag-server"]["requires_api_key"] is False
assert by_id["lightrag-server"]["configured"] is True
+ # Same for IMA: a thin HTTPS client, credentials bound per-KB at connect
+ # time rather than gated by one global key.
+ assert by_id["ima"]["requires_api_key"] is False
+ assert by_id["ima"]["configured"] is True
# Mode-aware engines advertise their retrieval modes; vector engines don't.
assert "hybrid" in by_id["lightrag"]["modes"]
assert "mix" in by_id["lightrag-server"]["modes"]
assert not by_id["llamaindex"].get("modes")
+ # IMA exposes a single retrieval call, so it advertises no modes.
+ assert not by_id["ima"].get("modes")
def test_set_rag_provider_mode_persists_validates_and_reflects() -> None:
diff --git a/tests/knowledge/test_ima_kb.py b/tests/knowledge/test_ima_kb.py
new file mode 100644
index 000000000..638733752
--- /dev/null
+++ b/tests/knowledge/test_ima_kb.py
@@ -0,0 +1,122 @@
+"""Manager handling of Tencent IMA KBs (``type: ima`` pointers).
+
+An IMA KB is a connection pointer to a library the user keeps in IMA: no on-disk
+folder under ``base_dir``, no local index, and deleting it must only drop our
+pointer (never touch the user's IMA library). The stored credentials must never
+leak into surfaced metadata. Mirrors the LightRAG-server pointer guarantees.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.knowledge.kb_types import CONNECTED_KB_TYPES, IMA_KB_TYPE
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+
+def _register(manager: KnowledgeBaseManager, name: str = "IMA") -> dict:
+ return manager.register_ima_kb(name, "cid", "secret", "kb-1")
+
+
+def test_ima_is_a_connected_type() -> None:
+ assert IMA_KB_TYPE in CONNECTED_KB_TYPES
+
+
+def test_register_writes_pointer(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+
+ entry = manager.register_ima_kb("IMA", " cid ", " secret ", " kb-1 ")
+
+ assert entry["type"] == IMA_KB_TYPE
+ assert entry["rag_provider"] == "ima"
+ assert entry["client_id"] == "cid" # trimmed
+ assert entry["api_key"] == "secret"
+ assert entry["knowledge_base_id"] == "kb-1"
+ assert entry["status"] == "ready"
+ assert entry["needs_reindex"] is False
+ # No KB folder is created under base_dir.
+ assert not (manager.base_dir / "IMA").exists()
+
+
+def test_register_keeps_the_probed_description(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+
+ entry = manager.register_ima_kb("IMA", "cid", "secret", "kb-1", description="My notes")
+
+ assert entry["description"] == "My notes"
+
+
+ "args",
+ [
+ ("", "cid", "secret", "kb-1"),
+ ("IMA", "", "secret", "kb-1"),
+ ("IMA", "cid", "", "kb-1"),
+ ("IMA", "cid", "secret", ""),
+ ],
+)
+def test_register_rejects_missing_fields(tmp_path, args) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ with pytest.raises(ValueError):
+ manager.register_ima_kb(*args)
+
+
+def test_register_rejects_duplicate_name(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ _register(manager)
+ with pytest.raises(ValueError, match="already exists"):
+ _register(manager)
+
+
+def test_get_metadata_hides_credentials(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ _register(manager)
+
+ meta = manager.get_metadata("IMA")
+
+ assert meta["type"] == IMA_KB_TYPE
+ assert meta["knowledge_base_id"] == "kb-1"
+ assert "api_key" not in meta
+ assert "client_id" not in meta
+
+
+def test_get_info_hides_credentials(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ _register(manager)
+
+ metadata = manager.get_info("IMA")["metadata"]
+
+ assert metadata["knowledge_base_id"] == "kb-1"
+ assert "api_key" not in metadata
+ assert "client_id" not in metadata
+
+
+def test_delete_only_drops_the_pointer(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ _register(manager)
+
+ assert manager.delete_knowledge_base("IMA", confirm=True) is True
+ assert "IMA" not in manager.list_knowledge_bases()
+
+
+def test_has_no_local_document_root(tmp_path) -> None:
+ # Nothing of an IMA KB lives on this machine, so there is no folder to walk.
+ from deeptutor.knowledge.manifest import document_root
+
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ entry = _register(manager)
+
+ assert document_root(manager.base_dir / "IMA", entry) is None
+
+
+def test_documents_are_reported_as_non_enumerable(tmp_path) -> None:
+ # IMA holds the documents behind its API; reporting "0 documents" would lie.
+ from deeptutor.knowledge.manifest import UNAVAILABLE_REMOTE, build_manifest
+
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ entry = _register(manager)
+
+ manifest = build_manifest(name="IMA", kb_dir=manager.base_dir / "IMA", entry=entry)
+
+ assert manifest.unavailable == UNAVAILABLE_REMOTE
+ assert manifest.total == 0
diff --git a/tests/services/rag/test_ima_pipeline.py b/tests/services/rag/test_ima_pipeline.py
new file mode 100644
index 000000000..ade7d6c5b
--- /dev/null
+++ b/tests/services/rag/test_ima_pipeline.py
@@ -0,0 +1,432 @@
+"""Unit tests for the Tencent IMA (retrieval-only) RAG pipeline.
+
+The engine is a thin HTTPS client over IMA's knowledge-base OpenAPI. We exercise:
+
+* the client wire shapes (POST path, auth headers, ``{code,msg,data}`` envelope,
+ cursor pagination, error-code mapping) against an injected
+ ``httpx.MockTransport`` — no network,
+* the connect-time probe verdict (credentials accepted / library resolves),
+* the pipeline's ``search`` (reads the per-KB binding from ``kb_config.json``,
+ shapes the result, and fails cleanly when unconfigured/unreachable),
+* factory routing and that indexing is refused (IMA owns the index).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+
+from deeptutor.services.rag.factory import get_pipeline, normalize_provider_name
+from deeptutor.services.rag.pipelines.ima.client import (
+ API_BASE_URL,
+ ImaAPIError,
+ ImaAuthError,
+ ImaClient,
+ ImaRateLimitError,
+)
+from deeptutor.services.rag.pipelines.ima.config import (
+ ImaConfig,
+ ImaNotConfiguredError,
+ config_from_entry,
+)
+from deeptutor.services.rag.pipelines.ima.pipeline import ImaPipeline
+from deeptutor.services.rag.pipelines.ima.probe import probe_knowledge_base
+
+CONFIG = ImaConfig(client_id="cid", api_key="key", knowledge_base_id="kb-1")
+
+
+def _client(handler) -> ImaClient:
+ return ImaClient(CONFIG, transport=httpx.MockTransport(handler))
+
+
+def _ok(data: dict) -> httpx.Response:
+ return httpx.Response(200, json={"code": 0, "msg": "ok", "data": data})
+
+
+# ---------------------------------------------------------------------------
+# config
+# ---------------------------------------------------------------------------
+
+
+class TestConfigFromEntry:
+ def test_full_entry_resolves(self) -> None:
+ config = config_from_entry(
+ {"client_id": " cid ", "api_key": "key", "knowledge_base_id": "kb-1"}
+ )
+ assert config == CONFIG
+
+ @pytest.mark.parametrize(
+ "entry",
+ [
+ {},
+ {"client_id": "cid"},
+ {"client_id": "cid", "api_key": "key"},
+ {"api_key": "key", "knowledge_base_id": "kb-1"},
+ {"client_id": "", "api_key": "key", "knowledge_base_id": "kb-1"},
+ ],
+ )
+ def test_incomplete_entry_raises(self, entry: dict) -> None:
+ with pytest.raises(ImaNotConfiguredError):
+ config_from_entry(entry)
+
+ def test_error_names_the_missing_fields(self) -> None:
+ with pytest.raises(ImaNotConfiguredError) as exc:
+ config_from_entry({"client_id": "cid"})
+ message = str(exc.value)
+ assert "API key" in message and "knowledge base ID" in message
+
+
+# ---------------------------------------------------------------------------
+# client
+# ---------------------------------------------------------------------------
+
+
+class TestClientWire:
+ def test_search_posts_credentials_and_body(self) -> None:
+ seen: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen["url"] = str(request.url)
+ seen["headers"] = dict(request.headers)
+ seen["body"] = json.loads(request.content)
+ return _ok({"info_list": [], "is_end": True, "next_cursor": ""})
+
+ asyncio.run(_client(handler).search_knowledge("q", limit=5))
+
+ assert seen["url"] == f"{API_BASE_URL}/openapi/wiki/v1/search_knowledge"
+ assert seen["headers"]["ima-openapi-clientid"] == "cid"
+ assert seen["headers"]["ima-openapi-apikey"] == "key"
+ # cursor is required by IMA and empty on the first page.
+ assert seen["body"] == {"query": "q", "cursor": "", "knowledge_base_id": "kb-1"}
+
+ def test_search_follows_cursor_until_end(self) -> None:
+ pages = [
+ {
+ "info_list": [{"media_id": "m1", "title": "A", "highlight_content": "a"}],
+ "is_end": False,
+ "next_cursor": "c2",
+ },
+ {
+ "info_list": [{"media_id": "m2", "title": "B", "highlight_content": "b"}],
+ "is_end": True,
+ "next_cursor": "",
+ },
+ ]
+ cursors: list[str] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content)
+ cursors.append(body["cursor"])
+ return _ok(pages[len(cursors) - 1])
+
+ items = asyncio.run(_client(handler).search_knowledge("q", limit=10))
+
+ assert cursors == ["", "c2"]
+ assert [item["media_id"] for item in items] == ["m1", "m2"]
+
+ def test_search_stops_once_limit_is_reached(self) -> None:
+ calls = 0
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal calls
+ calls += 1
+ return _ok(
+ {
+ "info_list": [
+ {"media_id": "m1", "title": "A"},
+ {"media_id": "m2", "title": "B"},
+ ],
+ "is_end": False,
+ "next_cursor": "more",
+ }
+ )
+
+ items = asyncio.run(_client(handler).search_knowledge("q", limit=2))
+
+ assert calls == 1
+ assert len(items) == 2
+
+ def test_search_page_budget_bounds_pagination(self) -> None:
+ # A server that never reports the end must not spin forever.
+ calls = 0
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal calls
+ calls += 1
+ return _ok({"info_list": [], "is_end": False, "next_cursor": "always-more"})
+
+ asyncio.run(_client(handler).search_knowledge("q", limit=50))
+
+ assert calls == 3
+
+ def test_credential_code_maps_to_auth_error(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"code": 20004, "msg": "bad key"})
+
+ with pytest.raises(ImaAuthError, match="bad key"):
+ asyncio.run(_client(handler).get_knowledge_base())
+
+ def test_rate_limit_code_maps_to_rate_limit_error(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"code": 110021, "msg": "slow down"})
+
+ with pytest.raises(ImaRateLimitError):
+ asyncio.run(_client(handler).get_knowledge_base())
+
+ def test_http_429_maps_to_rate_limit_error(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(429, text="too many")
+
+ with pytest.raises(ImaRateLimitError):
+ asyncio.run(_client(handler).get_knowledge_base())
+
+ def test_other_business_code_raises_with_message(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"code": 100001, "msg": "bad param"})
+
+ with pytest.raises(ImaAPIError, match="bad param"):
+ asyncio.run(_client(handler).get_knowledge_base())
+
+ def test_non_json_response_raises(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, text="<html>nope</html>")
+
+ with pytest.raises(ImaAPIError):
+ asyncio.run(_client(handler).get_knowledge_base())
+
+ def test_get_knowledge_base_unwraps_the_bound_id(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert json.loads(request.content) == {"ids": ["kb-1"]}
+ return _ok({"infos": {"kb-1": {"id": "kb-1", "name": "My Library"}}})
+
+ info = asyncio.run(_client(handler).get_knowledge_base())
+
+ assert info["name"] == "My Library"
+
+ def test_get_knowledge_base_returns_empty_for_unknown_id(self) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return _ok({"infos": {}})
+
+ assert asyncio.run(_client(handler).get_knowledge_base()) == {}
+
+
+# ---------------------------------------------------------------------------
+# probe
+# ---------------------------------------------------------------------------
+
+
+class _StubClient:
+ def __init__(self, *, info: dict | None = None, error: Exception | None = None) -> None:
+ self._info = info or {}
+ self._error = error
+
+ async def get_knowledge_base(self) -> dict:
+ if self._error is not None:
+ raise self._error
+ return self._info
+
+
+class TestProbe:
+ def test_ok_when_library_resolves(self) -> None:
+ probe = asyncio.run(
+ probe_knowledge_base(
+ "cid",
+ "key",
+ "kb-1",
+ client_factory=lambda _c: _StubClient(
+ info={"name": "My Library", "description": "notes"}
+ ),
+ )
+ )
+ assert probe.ok is True
+ assert probe.credentials_ok is True
+ assert probe.knowledge_base_name == "My Library"
+ assert probe.description == "notes"
+ assert probe.error is None
+
+ def test_unknown_id_is_not_ok_but_credentials_are(self) -> None:
+ probe = asyncio.run(
+ probe_knowledge_base(
+ "cid", "key", "kb-x", client_factory=lambda _c: _StubClient(info={})
+ )
+ )
+ assert probe.ok is False
+ assert probe.credentials_ok is True
+ assert "no knowledge base matches" in (probe.error or "")
+
+ def test_auth_error_reports_credentials(self) -> None:
+ probe = asyncio.run(
+ probe_knowledge_base(
+ "cid",
+ "bad",
+ "kb-1",
+ client_factory=lambda _c: _StubClient(error=ImaAuthError("rejected")),
+ )
+ )
+ assert probe.ok is False
+ assert probe.credentials_ok is False
+ assert "rejected" in (probe.error or "")
+
+ def test_transport_failure_is_reported(self) -> None:
+ probe = asyncio.run(
+ probe_knowledge_base(
+ "cid",
+ "key",
+ "kb-1",
+ client_factory=lambda _c: _StubClient(error=RuntimeError("offline")),
+ )
+ )
+ assert probe.ok is False
+ assert "Could not reach" in (probe.error or "")
+
+ @pytest.mark.parametrize(
+ "args",
+ [("", "key", "kb-1"), ("cid", "", "kb-1"), ("cid", "key", "")],
+ )
+ def test_missing_input_short_circuits(self, args: tuple[str, str, str]) -> None:
+ probe = asyncio.run(probe_knowledge_base(*args))
+ assert probe.ok is False
+ assert "is required" in (probe.error or "")
+
+
+# ---------------------------------------------------------------------------
+# pipeline
+# ---------------------------------------------------------------------------
+
+
+def _kb_config(tmp_path: Path, entry: dict) -> str:
+ base = tmp_path / "kbs"
+ base.mkdir(parents=True, exist_ok=True)
+ (base / "kb_config.json").write_text(
+ json.dumps({"knowledge_bases": {"IMA": entry}}), encoding="utf-8"
+ )
+ return str(base)
+
+
+class _SearchStub:
+ def __init__(self, items: list[dict] | None = None, error: Exception | None = None) -> None:
+ self._items = items or []
+ self._error = error
+ self.limit: int | None = None
+
+ async def search_knowledge(self, query: str, *, limit: int) -> list[dict]:
+ self.limit = limit
+ if self._error is not None:
+ raise self._error
+ return self._items
+
+
+class TestPipelineSearch:
+ def test_search_shapes_snippets_into_context_and_sources(self, tmp_path) -> None:
+ base = _kb_config(
+ tmp_path,
+ {
+ "type": "ima",
+ "rag_provider": "ima",
+ "client_id": "cid",
+ "api_key": "key",
+ "knowledge_base_id": "kb-1",
+ },
+ )
+ stub = _SearchStub(
+ [
+ {"media_id": "m1", "title": "Alpha", "highlight_content": "alpha text"},
+ {"media_id": "m2", "title": "Beta", "highlight_content": "beta text"},
+ ]
+ )
+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)
+
+ result = asyncio.run(pipeline.search("q", "IMA"))
+
+ assert result["provider"] == "ima"
+ assert "error_type" not in result
+ assert [s["title"] for s in result["sources"]] == ["Alpha", "Beta"]
+ assert result["sources"][0]["chunk_id"] == "m1"
+ assert "[1] Alpha" in result["content"]
+ assert "alpha text" in result["content"]
+ assert result["answer"] == result["content"]
+
+ def test_title_only_match_is_kept_without_a_snippet(self, tmp_path) -> None:
+ base = _kb_config(
+ tmp_path,
+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},
+ )
+ stub = _SearchStub([{"media_id": "m1", "title": "Alpha"}])
+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)
+
+ result = asyncio.run(pipeline.search("q", "IMA"))
+
+ assert result["sources"][0]["content"] == ""
+ assert result["content"].strip() == "[1] Alpha"
+
+ def test_unidentifiable_item_is_dropped(self, tmp_path) -> None:
+ base = _kb_config(
+ tmp_path,
+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},
+ )
+ stub = _SearchStub([{"highlight_content": "orphan"}])
+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)
+
+ assert asyncio.run(pipeline.search("q", "IMA"))["sources"] == []
+
+ def test_top_k_is_clamped(self, tmp_path) -> None:
+ base = _kb_config(
+ tmp_path,
+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},
+ )
+ stub = _SearchStub()
+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)
+
+ asyncio.run(pipeline.search("q", "IMA", top_k=999))
+
+ assert stub.limit == 50
+
+ def test_unconfigured_kb_reports_not_configured(self, tmp_path) -> None:
+ base = _kb_config(tmp_path, {"type": "ima", "rag_provider": "ima"})
+ pipeline = ImaPipeline(kb_base_dir=base)
+
+ result = asyncio.run(pipeline.search("q", "IMA"))
+
+ assert result["error_type"] == "not_configured"
+ assert result["content"] == ""
+ assert result["sources"] == []
+
+ def test_transport_failure_reports_retrieval_error(self, tmp_path) -> None:
+ base = _kb_config(
+ tmp_path,
+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},
+ )
+ pipeline = ImaPipeline(
+ kb_base_dir=base,
+ client_factory=lambda _c: _SearchStub(error=RuntimeError("offline")),
+ )
+
+ result = asyncio.run(pipeline.search("q", "IMA"))
+
+ assert result["error_type"] == "retrieval_error"
+ assert "offline" in result["answer"]
+
+
+class TestPipelineLifecycle:
+ def test_indexing_is_refused(self, tmp_path) -> None:
+ pipeline = ImaPipeline(kb_base_dir=str(tmp_path))
+ with pytest.raises(RuntimeError, match="indexed by IMA"):
+ asyncio.run(pipeline.initialize("IMA", ["a.pdf"]))
+ with pytest.raises(RuntimeError, match="indexed by IMA"):
+ asyncio.run(pipeline.add_documents("IMA", ["a.pdf"]))
+
+ def test_delete_is_a_noop(self, tmp_path) -> None:
+ pipeline = ImaPipeline(kb_base_dir=str(tmp_path))
+ assert asyncio.run(pipeline.delete("IMA")) is True
+
+
+class TestFactoryRouting:
+ def test_provider_name_is_known(self) -> None:
+ assert normalize_provider_name("ima") == "ima"
+
+ def test_factory_builds_the_ima_pipeline(self) -> None:
+ assert isinstance(get_pipeline("ima"), ImaPipeline)
diff --git a/tests/tools/test_rag_tool.py b/tests/tools/test_rag_tool.py
index 97ab28f89..5da409a04 100644
--- a/tests/tools/test_rag_tool.py
+++ b/tests/tools/test_rag_tool.py
@@ -47,6 +47,7 @@ class TestPipelineFactory:
"graphrag",
"lightrag",
"lightrag-server",
+ "ima",
}
def test_get_pipeline_returns_singleton(self) -> None:
@@ -82,6 +83,7 @@ class TestRAGServiceClassHelpers:
"graphrag",
"lightrag",
"lightrag-server",
+ "ima",
}
def test_has_provider_default_true(self) -> None: