Skip to content

Build and run agents you can see, understand and trust.

feat(rag): add RAG module in agentscope and support distributed&multi-tenant&multi-session RAG service (#1926)

DavdGaodb6f8863dac7
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 5462e0fea..5a8062ef9 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -8,7 +8,7 @@ You should conduct a strict code review. Each requirement is labeled with priori
## 1. Code Quality
### [MUST] Lazy Loading
-- Third-party library dependencies should be imported at the point of use, avoid centralized imports at file top
+- **Third-party library** dependencies should be imported at the point of use, avoid centralized imports at file top
- The `Third-party library` refers to libraries not included in the `dependencies` variable in `pyproject.toml`.
- For base class imports, use factory pattern:
```python
@@ -38,6 +38,7 @@ After understanding the code intent, check if it can be optimized:
- New features must include unit tests
- New dependencies need to be added to the corresponding section in `pyproject.toml`
- Dependencies for non-core scenarios should not be added to the minimal dependency list
+- Test assertions MUST compare the entire data structure rather than asserting individual fields, so reviewers can quickly understand the test intent. For random or non-deterministic fields, use `AnyString` and `AnyValue` from `tests/utils.py` for matching
## 4. Code Standards
diff --git a/README.md b/README.md
index e1323c819..201591fc8 100644
--- a/README.md
+++ b/README.md
@@ -73,6 +73,8 @@ rather than constraining them with strict prompts and opinionated orchestrations
## News
<!-- BEGIN NEWS -->
+- **[2026-06] `FEAT`:** Distributed & Multi-Tenancy & Multi-Session RAG service supported. [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
+- **[2026-06] `FEAT`:** RAG supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `INTE`:** Mem0 supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/en)
- **[2026-06] `FEAT`:** Agent Team supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
- **[2026-05] `RELS`:** AgentScope 2.0 released! [Docs](https://docs.agentscope.io/)
diff --git a/README_zh.md b/README_zh.md
index c731a2d86..e432138c3 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -79,6 +79,8 @@ AgentScope 2.0 是一款面向生产、易于使用的智能体框架,提供
## 新闻
<!-- BEGIN NEWS -->
+- **[2026-06] `功能`:** 支持分布式 & 多租户 & 多会话 RAG 服务。 [文档](https://docs.agentscope.io/latest/en/deploy/agent-team)
+- **[2026-06] `功能`:** 支持多模态 RAG。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [文档](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `集成`:** 集成 Mem0 长期记忆。 [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/zh)
- **[2026-06] `功能`:** 支持 Agent Team。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/agent-team)
- **[2026-05] `发布`:** AgentScope 2.0 已发布![文档](https://docs.agentscope.io/)
diff --git a/docs/NEWS.md b/docs/NEWS.md
index 1c4dda906..847a01e4a 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,6 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-06] `FEAT`:** Distributed & Multi-Tenancy & Multi-Session RAG service supported. [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
+- **[2026-06] `FEAT`:** RAG supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `INTE`:** Mem0 supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/en)
- **[2026-06] `FEAT`:** Agent Team supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
- **[2026-05] `RELS`:** AgentScope 2.0 released! [Docs](https://docs.agentscope.io/)
\ No newline at end of file
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index 40c6af90c..6b6c6f1bd 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,6 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-06] `功能`:** 支持分布式 & 多租户 & 多会话 RAG 服务。 [文档](https://docs.agentscope.io/latest/en/deploy/agent-team)
+- **[2026-06] `功能`:** 支持多模态 RAG。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [文档](https://docs.agentscope.io/latest/en/building-blocks/rag)
- **[2026-06] `集成`:** 集成 Mem0 长期记忆。 [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/zh)
- **[2026-06] `功能`:** 支持 Agent Team。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/agent-team)
- **[2026-05] `发布`:** AgentScope 2.0 已发布![文档](https://docs.agentscope.io/)
\ No newline at end of file
diff --git a/examples/agent_service/main.py b/examples/agent_service/main.py
index 031af30b6..5b91325e9 100644
--- a/examples/agent_service/main.py
+++ b/examples/agent_service/main.py
@@ -8,10 +8,12 @@ from fastapi.middleware.cors import CORSMiddleware
from agentscope.app import create_app, SubAgentTemplate
from agentscope.app.message_bus import InMemoryMessageBus
+from agentscope.app.rag.knowledge_base_manager import CollectionPerKbManager
from agentscope.app.storage import RedisStorage
from agentscope.app.workspace_manager import LocalWorkspaceManager
from agentscope.mcp import MCPClient, StdioMCPConfig, HttpMCPConfig
from agentscope.permission import PermissionContext, PermissionMode
+from agentscope.rag import QdrantStore
default_mcps = [
MCPClient(
@@ -36,11 +38,15 @@ if os.getenv("AMAP_API_KEY"):
),
)
+storage = RedisStorage(
+ host="localhost",
+ port=6379,
+)
+
+vector_store = QdrantStore(location=":memory:")
+
app = create_app(
- storage=RedisStorage(
- host="localhost",
- port=6379,
- ),
+ storage=storage,
message_bus=InMemoryMessageBus(),
# -- To use a Redis-backed message bus instead (recommended for
# -- multi-process / production deployments), uncomment the lines
@@ -59,6 +65,13 @@ app = create_app(
# The default MCP servers that will be added into the workspace
default_mcps=default_mcps,
),
+ # Knowledge base feature — backed by an in-memory Qdrant store. The
+ # CollectionPerKbManager allocates one collection per knowledge base,
+ # so any embedding dimension is allowed.
+ knowledge_base_manager=CollectionPerKbManager(
+ storage=storage,
+ vector_store=vector_store,
+ ),
# Customize your own subagent templates
custom_subagent_templates=[
SubAgentTemplate(
diff --git a/examples/long_term_memory/mem0/oss_demo.py b/examples/long_term_memory/mem0/oss_demo.py
index cc2134f35..737d64328 100644
--- a/examples/long_term_memory/mem0/oss_demo.py
+++ b/examples/long_term_memory/mem0/oss_demo.py
@@ -186,9 +186,7 @@ async def main() -> None:
embedding_model = DashScopeEmbeddingModel(
credential=DashScopeCredential(api_key=api_key),
model="text-embedding-v4",
- parameters=DashScopeEmbeddingModel.Parameters(
- dimensions=1536, # matches mem0's Qdrant default
- ),
+ dimensions=1536, # matches mem0's Qdrant default
)
# Explicit vector-store config (here we just spell out mem0's
diff --git a/examples/rag/README.md b/examples/rag/README.md
new file mode 100644
index 000000000..3ea503bf3
--- /dev/null
+++ b/examples/rag/README.md
@@ -0,0 +1,36 @@
+# RAG Examples
+
+Two library-mode walk-throughs of `agentscope.rag` — no FastAPI service, no manager, no message bus. Each script wires the building blocks (parser, chunker, embedding model, vector store, `KnowledgeBase` handle) by hand so the data flow is visible end-to-end.
+
+| Script | What it shows |
+| --- | --- |
+| [`index_and_search.py`](./index_and_search.py) | The minimal pipeline: parse → chunk → embed → insert, then `KnowledgeBase.search`. Start here. |
+| [`integrate_with_agent.py`](./integrate_with_agent.py) | Attaches the same `KnowledgeBase` to an `Agent` via `RAGMiddleware`, in both `static` (auto-inject) and `agentic` (tool-driven) modes. |
+
+Both examples use an in-memory Qdrant store (`location=":memory:"`) and the DashScope `text-embedding-v4` model, so no external services are required.
+
+## Install
+
+```bash
+# From PyPI
+uv pip install "agentscope[rag]"
+
+# Or from source (repo root)
+uv pip install -e ".[rag]"
+```
+
+`integrate_with_agent.py` additionally uses `DashScopeChatModel`, which is already in the base `agentscope` dependencies.
+
+## Run
+
+```bash
+export DASHSCOPE_API_KEY=sk-...
+
+python examples/rag/index_and_search.py
+python examples/rag/integrate_with_agent.py
+```
+
+## Service mode
+
+The two scripts above are library-mode — you drive the pipeline yourself in a single process. For the full service-mode experience (FastAPI endpoints for knowledge base CRUD, document upload, indexing workers, and search), see [`examples/agent_service`](../agent_service) for the backend and [`examples/web_ui`](../web_ui) for the chat-style UI.
+
diff --git a/examples/rag/index_and_search.py b/examples/rag/index_and_search.py
new file mode 100644
index 000000000..bca34dad3
--- /dev/null
+++ b/examples/rag/index_and_search.py
@@ -0,0 +1,183 @@
+# -*- coding: utf-8 -*-
+"""Library-mode RAG walk-through — no FastAPI service, no manager.
+
+End-to-end demo of the building blocks in :mod:`agentscope.rag`:
+
+1. **Vector store** — :class:`QdrantStore` (in-memory here; swap to
+ ``url=...`` for a real Qdrant server).
+2. **Parser** — :class:`TextParser` turning raw bytes into ``Section``
+ objects.
+3. **Chunker** — :class:`ApproxTokenChunker` splitting sections into
+ ``Chunk`` objects (the indexable unit).
+4. **Embedding** — any :class:`EmbeddingModelBase` subclass; we use the
+ DashScope text-embedding model.
+5. **KnowledgeBase** — the runtime handle that ties (embedding, vector
+ store, collection) together and exposes
+ ``insert_document`` / ``search`` / ``list_documents`` /
+ ``delete_document``. This is what :class:`RAGMiddleware` consumes.
+
+The pipeline:
+
+ bytes ── parser ──► Section[] ── chunker ──► Chunk[]
+ │
+ ▼
+ knowledge.insert_document(chunks)
+ │
+ ▼
+ embed → store on the bound collection
+
+Search mirrors the same shape: hand the query to
+``knowledge.search(...)``, get ``VectorSearchResult`` back.
+
+Run with::
+
+ DASHSCOPE_API_KEY=sk-... python examples/rag/index_and_search.py
+"""
+import asyncio
+import os
+
+from agentscope.credential import DashScopeCredential
+from agentscope.embedding import DashScopeEmbeddingModel
+from agentscope.message import TextBlock
+from agentscope.rag import (
+ ApproxTokenChunker,
+ KnowledgeBase,
+ QdrantStore,
+ TextParser,
+)
+
+
+COLLECTION = "demo-kb"
+
+# A toy corpus inlined as bytes so the example has no on-disk
+# dependencies. In real use these would come from uploaded files or
+# blob-store reads.
+DOCUMENTS: dict[str, bytes] = {
+ "cats.md": (
+ b"# Cats\n\n"
+ b"Cats are small carnivorous mammals. They are popular as pets "
+ b"because of their playful and affectionate nature.\n\n"
+ b"Domestic cats sleep around 12-16 hours per day. They are most "
+ b"active at dawn and dusk (crepuscular behaviour).\n"
+ ),
+ "agentscope.md": (
+ b"# AgentScope\n\n"
+ b"AgentScope is a developer-centric framework for building "
+ b"multi-agent LLM applications. It emphasises transparency, "
+ b"controllability, and a clear separation between agent logic "
+ b"and infrastructure.\n\n"
+ b"Its RAG module ships a parser/chunker/embedding/vector-store "
+ b"pipeline that can be wired up without the FastAPI service.\n"
+ ),
+}
+
+
+async def build_index(
+ knowledge: KnowledgeBase,
+ parser: TextParser,
+ chunker: ApproxTokenChunker,
+) -> None:
+ """Parse → chunk → insert for every demo document.
+
+ Embedding and vector-store insertion are encapsulated inside
+ ``knowledge.insert_document`` — caller side only has to bring
+ pre-chunked content.
+ """
+ for filename, file_bytes in DOCUMENTS.items():
+ # 1. Parse: bytes → list[Section]
+ sections = await parser.parse(file=file_bytes, filename=filename)
+
+ # 2. Chunk: list[Section] → list[Chunk]
+ chunks = await chunker.chunk(sections)
+
+ # 3. Insert: embeds every chunk under one document id. The
+ # returned id is yours to keep for later
+ # ``delete_document``.
+ document_id = await knowledge.insert_document(
+ chunks,
+ document_metadata={"filename": filename},
+ )
+ print(
+ f" indexed {filename!r} as document_id={document_id} "
+ f"({len(chunks)} chunk(s))",
+ )
+
+
+async def search(
+ knowledge: KnowledgeBase,
+ query: str,
+ top_k: int = 3,
+) -> None:
+ """Run a search via the :class:`KnowledgeBase` handle and print hits."""
+ results = await knowledge.search(queries=[query], top_k=top_k)
+
+ print(f"\nQuery: {query!r}")
+ if not results:
+ print(" (no hits)")
+ return
+ for rank, result in enumerate(results, start=1):
+ # Only text chunks are printable as-is.
+ snippet = (
+ result.chunk.content.text
+ if isinstance(result.chunk.content, TextBlock)
+ else "<non-text chunk>"
+ )
+ snippet = snippet.replace("\n", " ").strip()
+ if len(snippet) > 120:
+ snippet = snippet[:117] + "..."
+ print(
+ f" [{rank}] score={result.score:.4f} "
+ f"source={result.chunk.source} "
+ f"document_id={result.document_id}\n"
+ f" {snippet}",
+ )
+
+
+async def main() -> None:
+ """The main entry point of the example."""
+ api_key = os.environ.get("DASHSCOPE_API_KEY")
+ if not api_key:
+ raise RuntimeError(
+ "Set DASHSCOPE_API_KEY before running this example.",
+ )
+
+ # The building blocks. All of these are also what the service-mode
+ # (``create_app``) wiring uses internally — the only difference is
+ # that here you drive them yourself.
+ embedding_model = DashScopeEmbeddingModel(
+ credential=DashScopeCredential(api_key=api_key),
+ model="text-embedding-v4",
+ dimensions=1024,
+ )
+ parser = TextParser()
+ chunker = ApproxTokenChunker(chunk_size=256, overlap=32)
+ store = QdrantStore(location=":memory:")
+
+ # ``QdrantStore`` is an async context manager — entering it opens
+ # the client connection; exiting closes it.
+ async with store:
+ # One :class:`KnowledgeBase` handle bundles (embedding, vector
+ # store, collection) together so the rest of this example
+ # never has to repeat the wiring. The collection is created
+ # lazily on the first operation (`build_index`).
+ knowledge = KnowledgeBase(
+ name="demo-kb",
+ description="A toy corpus on cats and AgentScope.",
+ embedding_model=embedding_model,
+ vector_store=store,
+ collection=COLLECTION,
+ )
+
+ print("Indexing demo corpus ...")
+ await build_index(knowledge, parser, chunker)
+
+ # A couple of search queries that demonstrate scoring.
+ await search(knowledge, "When are cats most active?")
+ await search(
+ knowledge,
+ "What framework lets me build multi-agent apps?",
+ )
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/rag/integrate_with_agent.py b/examples/rag/integrate_with_agent.py
new file mode 100644
index 000000000..e69cfde4a
--- /dev/null
+++ b/examples/rag/integrate_with_agent.py
@@ -0,0 +1,198 @@
+# -*- coding: utf-8 -*-
+"""Wire :class:`RAGMiddleware` into an :class:`Agent` — library mode.
+
+The middleware in :mod:`agentscope.middleware._rag` is the agent-side
+half of RAG: given one or more :class:`~agentscope.rag.KnowledgeBase`
+handles (each pairing an embedding model with a vector-store
+collection), the middleware drives search on each new user turn and
+feeds the matched chunks into the model context.
+
+This example reuses the indexing pipeline shown in ``index_and_search.py``
+(parse → chunk → embed → insert) and then attaches the same knowledge base
+to two agents — one per mode:
+
+- ``"static"``: on the first reasoning step of a reply, embed the
+ user's question, search, and inject the top hits as a one-shot
+ :class:`HintBlock` into the agent's context. The model sees the
+ matched snippets but never "decides" to search.
+- ``"agentic"`` (the default): expose a ``search_knowledge`` tool. The
+ model decides when (and what) to search, the same way it decides any
+ other tool call.
+
+Run with::
+
+ DASHSCOPE_API_KEY=sk-... python examples/rag/integrate_with_agent.py
+"""
+import asyncio
+import os
+
+from agentscope.agent import Agent
+from agentscope.credential import DashScopeCredential
+from agentscope.embedding import DashScopeEmbeddingModel
+from agentscope.message import UserMsg
+from agentscope.middleware import RAGMiddleware
+from agentscope.model import DashScopeChatModel
+from agentscope.rag import (
+ ApproxTokenChunker,
+ KnowledgeBase,
+ QdrantStore,
+ TextParser,
+)
+from agentscope.tool import Toolkit
+
+
+COLLECTION = "demo-kb"
+
+KNOWLEDGE: dict[str, bytes] = {
+ "company-policy.md": (
+ b"# Acme Remote Work Policy\n\n"
+ b"Employees may work remotely up to three days per week. "
+ b"Wednesdays are mandatory in-office days for the whole "
+ b"engineering org so cross-team syncs land on a predictable "
+ b"day.\n\n"
+ b"Equipment stipend: each new hire receives a USD 1,500 "
+ b"one-off stipend for a home-office setup. Receipts must be "
+ b"submitted within 90 days of the start date.\n"
+ ),
+ "release-notes.md": (
+ b"# AgentScope 3.0 release notes\n\n"
+ b"- New ``agentscope.rag`` module: pluggable parser, chunker, "
+ b"embedding, and vector-store backends.\n"
+ b"- ``RAGMiddleware`` ships in two modes -- ``static`` for "
+ b"automatic injection, ``agentic`` for tool-driven search.\n"
+ b"- Knowledge base service supports embedded and dedicated "
+ b"worker deployments through a single message-bus channel.\n"
+ ),
+}
+
+
+async def index_corpus(knowledge: KnowledgeBase) -> None:
+ """Index the demo corpus into the knowledge base.
+
+ Identical pipeline to ``examples/rag/index_and_search.py`` — extracted
+ as a helper here so the agent-side wiring stays the focus. Each source
+ file becomes one logical document; ``KnowledgeBase.insert_document``
+ embeds and inserts every chunk in a single batch.
+ """
+ parser = TextParser()
+ chunker = ApproxTokenChunker(chunk_size=256, overlap=32)
+ for filename, file_bytes in KNOWLEDGE.items():
+ sections = await parser.parse(file=file_bytes, filename=filename)
+ chunks = await chunker.chunk(sections)
+ await knowledge.insert_document(
+ chunks,
+ document_metadata={"filename": filename},
+ )
+
+
+def build_agent(
+ name: str,
+ *,
+ chat_model: DashScopeChatModel,
+ rag_mw: RAGMiddleware,
+) -> Agent:
+ """Construct an :class:`Agent` with the RAG middleware attached.
+
+ The middleware is just one entry in the ``middlewares=`` list; it
+ composes with every other middleware (tool offload, mem0, ...) the
+ agent uses.
+ """
+ return Agent(
+ name=name,
+ system_prompt=(
+ "You are a concise assistant. Use matched context when "
+ "available; if you don't know, say so."
+ ),
+ model=chat_model,
+ toolkit=Toolkit(),
+ middlewares=[rag_mw],
+ )
+
+
+async def ask(agent: Agent, question: str) -> None:
+ """Run one reply and print the final assistant message."""
+ print(f"\n[{agent.name}] user: {question}")
+ reply = await agent.reply(UserMsg(name="user", content=question))
+ print(f"[{agent.name}] assistant: {reply.get_text_content()}")
+
+
+async def main() -> None:
+ """The main entry point of the example."""
+ api_key = os.environ.get("DASHSCOPE_API_KEY")
+ if not api_key:
+ raise RuntimeError(
+ "Set DASHSCOPE_API_KEY before running this example.",
+ )
+
+ credential = DashScopeCredential(api_key=api_key)
+ chat_model = DashScopeChatModel(
+ credential=credential,
+ model="qwen-plus",
+ stream=False,
+ )
+ embedding_model = DashScopeEmbeddingModel(
+ credential=credential,
+ model="text-embedding-v4",
+ dimensions=1024,
+ )
+
+ store = QdrantStore(location=":memory:")
+ async with store:
+ # One :class:`KnowledgeBase` handle binds embedding + vector store +
+ # collection together. ``insert_document`` / ``search`` /
+ # ``list_documents`` all go through it, and the backing
+ # collection is created lazily on first use.
+ knowledge = KnowledgeBase(
+ name="acme-handbook",
+ description="Acme HR policies and AgentScope 3.0 release notes.",
+ embedding_model=embedding_model,
+ vector_store=store,
+ collection=COLLECTION,
+ )
+
+ await index_corpus(knowledge)
+
+ # ---- Mode 1: static ----
+ # Search is automatic on the first reasoning step. The injected
+ # ``HintBlock`` is one-shot (removed after the model call) so it
+ # doesn't poison the next turn.
+ static_mw = RAGMiddleware(
+ knowledge_bases=[knowledge],
+ parameters=RAGMiddleware.Parameters(
+ mode="static",
+ top_k=3,
+ emit_hint_event=False,
+ ),
+ )
+ static_agent = build_agent(
+ "rag-static-agent",
+ chat_model=chat_model,
+ rag_mw=static_mw,
+ )
+ await ask(
+ static_agent,
+ "How many remote days per week does Acme allow?",
+ )
+
+ # ---- Mode 2: agentic ----
+ # The middleware exposes a ``search_knowledge`` tool instead of
+ # auto-injecting. The model decides when to call it; it may
+ # also pass ``knowledge_bases=[...]`` to scope the search when
+ # multiple knowledge bases are bound.
+ agentic_mw = RAGMiddleware(
+ knowledge_bases=[knowledge],
+ parameters=RAGMiddleware.Parameters(mode="agentic", top_k=3),
+ )
+ agentic_agent = build_agent(
+ "rag-agentic-agent",
+ chat_model=chat_model,
+ rag_mw=agentic_mw,
+ )
+ await ask(
+ agentic_agent,
+ "Summarise what's new in the AgentScope 3.0 release notes.",
+ )
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/web_ui/frontend/src/App.tsx b/examples/web_ui/frontend/src/App.tsx
index 85f40da53..9584518e1 100644
--- a/examples/web_ui/frontend/src/App.tsx
+++ b/examples/web_ui/frontend/src/App.tsx
@@ -7,9 +7,11 @@ import { RouteError } from '@/components/error/RouteError';
import { AppLayout } from '@/components/layout/AppLayout';
import { buildChatTour } from '@/components/tour/chatTourSteps';
import { TourCard } from '@/components/tour/TourCard';
+import { UploadProvider } from '@/context/UploadContext';
import { useTranslation } from '@/i18n/useI18n';
import { ChatPage } from '@/pages/chat';
import { CredentialPage } from '@/pages/credential';
+import { KnowledgePage } from '@/pages/knowledge';
import { SchedulePage } from '@/pages/schedule';
import { SetupPage } from '@/pages/setup';
@@ -44,6 +46,8 @@ const router = createBrowserRouter([
},
{ path: '/schedule', element: <SchedulePage /> },
{ path: '/credential', element: <CredentialPage /> },
+ { path: '/knowledge', element: <KnowledgePage /> },
+ { path: '/knowledge/:kbId', element: <KnowledgePage /> },
],
},
],
@@ -68,7 +72,9 @@ function App() {
shadowOpacity="0.6"
cardTransition={{ type: 'spring', duration: 0.4 }}
>
- <RouterProvider router={router} />
+ <UploadProvider>
+ <RouterProvider router={router} />
+ </UploadProvider>
<Toaster richColors position="top-right" />
</Onborda>
</OnbordaProvider>
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 78512276d..4a8abdcf7 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -6,3 +6,4 @@ export { chatApi } from './chat';
export { workspaceApi } from './workspace';
export { scheduleApi } from './schedule';
export { modelApi, ttsModelApi } from './model';
+export { knowledgeBaseApi } from './knowledgeBase';
diff --git a/examples/web_ui/frontend/src/api/knowledgeBase.ts b/examples/web_ui/frontend/src/api/knowledgeBase.ts
new file mode 100644
index 000000000..b6f1f1f63
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/knowledgeBase.ts
@@ -0,0 +1,179 @@
+import { ApiError, client, getBaseUrl, getUserId } from './client';
+import type {
+ CreateKnowledgeBaseRequest,
+ CreateKnowledgeBaseResponse,
+ KbMiddlewareParametersSchemaResponse,
+ KnowledgeBaseView,
+ ListKbEmbeddingModelsResponse,
+ ListKnowledgeBasesResponse,
+ ListKnowledgeDocumentsResponse,
+ ListKnowledgeDocumentStatusResponse,
+ ListSupportedContentTypesResponse,
+ SearchKnowledgeBaseRequest,
+ SearchKnowledgeBaseResponse,
+ UpdateKnowledgeBaseRequest,
+ UploadKnowledgeDocumentResponse,
+} from './types';
+
+/**
+ * Callback invoked while bytes are pushed across the wire.
+ *
+ * - `loaded` — bytes already sent.
+ * - `total` — total bytes (may be 0 when the browser cannot compute it,
+ * e.g. for chunked encodings).
+ */
+export interface UploadProgress {
+ loaded: number;
+ total: number;
+}
+
+export interface UploadDocumentOptions {
+ /** Fired with byte-level progress while the body is streamed. */
+ onProgress?: (progress: UploadProgress) => void;
+ /**
+ * Caller-supplied abort signal. Aborting before the server has
+ * responded rejects the returned promise with a `DOMException` of
+ * `name === "AbortError"`; aborting after a response has come back
+ * is a no-op.
+ */
+ signal?: AbortSignal;
+}
+
+/**
+ * XHR-based upload — `fetch` does not surface byte-level send
+ * progress in any current browser, so multipart uploads that drive a
+ * progress UI have to fall back to XMLHttpRequest.
+ */
+function uploadDocumentXhr(
+ knowledgeBaseId: string,
+ file: File,
+ options: UploadDocumentOptions = {},
+): Promise<UploadKnowledgeDocumentResponse> {
+ const { onProgress, signal } = options;
+ const formData = new FormData();
+ formData.append('file', file);
+
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(new DOMException('Aborted', 'AbortError'));
+ return;
+ }
+
+ const xhr = new XMLHttpRequest();
+ const url = new URL(`/knowledge_bases/${knowledgeBaseId}/documents`, getBaseUrl());
+ xhr.open('POST', url.toString(), true);
+ xhr.setRequestHeader('X-User-ID', getUserId());
+
+ const onAbort = () => xhr.abort();
+ signal?.addEventListener('abort', onAbort, { once: true });
+
+ const cleanup = () => signal?.removeEventListener('abort', onAbort);
+
+ if (xhr.upload && onProgress) {
+ xhr.upload.onprogress = (e) => {
+ onProgress({
+ loaded: e.loaded,
+ total: e.lengthComputable ? e.total : 0,
+ });
+ };
+ }
+
+ xhr.onload = () => {
+ cleanup();
+ if (xhr.status >= 200 && xhr.status < 300) {
+ try {
+ resolve(JSON.parse(xhr.responseText) as UploadKnowledgeDocumentResponse);
+ } catch (e) {
+ reject(e);
+ }
+ return;
+ }
+ let detail = xhr.responseText || xhr.statusText;
+ try {
+ const json = JSON.parse(xhr.responseText) as {
+ detail?: unknown;
+ };
+ if (typeof json.detail === 'string') detail = json.detail;
+ else if (json.detail !== undefined) detail = JSON.stringify(json.detail);
+ } catch {
+ // keep raw text
+ }
+ reject(new ApiError(xhr.status, detail));
+ };
+ xhr.onerror = () => {
+ cleanup();
+ reject(new ApiError(0, 'Network error'));
+ };
+ xhr.onabort = () => {
+ cleanup();
+ reject(new DOMException('Aborted', 'AbortError'));
+ };
+
+ xhr.send(formData);
+ });
+}
+
+/**
+ * Client for the `/knowledge_bases` router.
+ */
+export const knowledgeBaseApi = {
+ list: () => client.get<ListKnowledgeBasesResponse>('/knowledge_bases/'),
+
+ listEmbeddingModels: () =>
+ client.get<ListKbEmbeddingModelsResponse>('/knowledge_bases/embedding_models'),
+
+ /** Fetch the JSON Schema describing the KB middleware's tunable params. */
+ middlewareParametersSchema: () =>
+ client.get<KbMiddlewareParametersSchemaResponse>(
+ '/knowledge_bases/middleware/parameters_schema',
+ ),
+
+ /** List the union of media types + extensions every parser accepts. */
+ supportedContentTypes: () =>
+ client.get<ListSupportedContentTypesResponse>('/knowledge_bases/supported_content_types'),
+
+ create: (body: CreateKnowledgeBaseRequest) =>
+ client.post<CreateKnowledgeBaseResponse>('/knowledge_bases/', body),
+
+ update: (knowledgeBaseId: string, body: UpdateKnowledgeBaseRequest) =>
+ client.patch<KnowledgeBaseView>(`/knowledge_bases/${knowledgeBaseId}`, body),
+
+ delete: (knowledgeBaseId: string) => client.delete(`/knowledge_bases/${knowledgeBaseId}`),
+
+ /** List every document registered against a knowledge base. */
+ listDocuments: (knowledgeBaseId: string) =>
+ client.get<ListKnowledgeDocumentsResponse>(`/knowledge_bases/${knowledgeBaseId}/documents`),
+
+ /**
+ * Batch-query lifecycle status for a list of documents.
+ *
+ * Missing ids are silently omitted by the server, so the response
+ * may be shorter than the input. An empty `ids` short-circuits
+ * locally — the backend treats an empty list as a 200 with
+ * `items: []`, but skipping the round-trip is friendlier to the
+ * polling loop.
+ */
+ getDocumentStatus: (knowledgeBaseId: string, ids: string[]) => {
+ if (ids.length === 0) {
+ return Promise.resolve<ListKnowledgeDocumentStatusResponse>({
+ items: [],
+ });
+ }
+ return client.get<ListKnowledgeDocumentStatusResponse>(
+ `/knowledge_bases/${knowledgeBaseId}/documents/status`,
+ { ids: ids.join(',') },
+ );
+ },
+
+ uploadDocument: (knowledgeBaseId: string, file: File, options?: UploadDocumentOptions) =>
+ uploadDocumentXhr(knowledgeBaseId, file, options),
+
+ deleteDocument: (knowledgeBaseId: string, documentId: string) =>
+ client.delete(`/knowledge_bases/${knowledgeBaseId}/documents/${documentId}`),
+
+ search: (knowledgeBaseId: string, body: SearchKnowledgeBaseRequest) =>
+ client.post<SearchKnowledgeBaseResponse>(
+ `/knowledge_bases/${knowledgeBaseId}/search`,
+ body,
+ ),
+};
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index b3429754d..7a5950487 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -93,6 +93,8 @@ export interface SessionConfig {
fallback_chat_model_config: ChatModelConfig | null;
/** TTS model configuration. null means TTS is not enabled. */
tts_model_config: TTSModelConfig | null;
+ /** Knowledge bases attached to this session + KB middleware parameters. */
+ knowledge_config: SessionKnowledgeConfig | null;
workspace_id: string;
}
@@ -123,6 +125,8 @@ export interface CreateSessionRequest {
fallback_chat_model_config?: ChatModelConfig | null;
/** Optional TTS model. Omit (or pass null) for no TTS. */
tts_model_config?: TTSModelConfig | null;
+ /** Optional knowledge base attachment. Omit (or null) for none. */
+ knowledge_config?: SessionKnowledgeConfig | null;
}
export interface CreateSessionResponse {
@@ -146,6 +150,13 @@ export interface UpdateSessionRequest {
* - set to a value → replace the existing TTS config
*/
tts_model_config?: TTSModelConfig | null;
+ /**
+ * New knowledge base attachment. PATCH semantics:
+ * - omit the field → leave unchanged
+ * - set to `null` → detach every knowledge base
+ * - set to a value → replace the existing attachment
+ */
+ knowledge_config?: SessionKnowledgeConfig | null;
permission_mode?: PermissionMode;
}
@@ -235,6 +246,7 @@ export interface JSONSchemaProperty {
default?: unknown;
const?: unknown;
anyOf?: Array<{ type: string }>;
+ enum?: unknown[];
title?: string;
writeOnly?: boolean;
minimum?: number;
@@ -441,6 +453,226 @@ export interface ListModelResponse {
total: number;
}
+// ─── Embedding ────────────────────────────────────────────────────────────────
+
+export interface EmbeddingModelConfig {
+ type: string;
+ credential_id: string;
+ model: string;
+ /**
+ * Output vector dimensions, pinned at config time. Required because
+ * the backend uses it to size the vector store collection and to
+ * validate against the manager's `DimensionPolicy`.
+ */
+ dimensions: number;
+ parameters: Record<string, unknown>;
+}
+
+export interface EmbeddingModelCard {
+ type: 'embedding_model';
+ name: string;
+ label: string;
+ status: 'active' | 'deprecated' | 'sunset';
+ input_types: string[];
+ output_types: string[];
+ context_size: number | null;
+ /** Default output dimensions for this model. */
+ dimensions: number;
+ /**
+ * If set, the only dimensions this model can produce (Matryoshka).
+ * `null` means the model is fixed-dim at `dimensions`.
+ */
+ supported_dimensions: number[] | null;
+ parameter_schema: Record<string, unknown>;
+ parameter_overrides: Record<string, Record<string, unknown>>;
+}
+
+// ─── Knowledge Base ───────────────────────────────────────────────────────────
+
+/**
+ * Knowledge base view as exposed by the API. Mirrors
+ * :class:`agentscope.app._router._schema.KnowledgeBaseView`.
+ *
+ * Internal `user_id` / `collection_name` are stripped — the front-end
+ * has no business introspecting either.
+ */
+export interface KnowledgeBaseView {
+ id: string;
+ name: string;
+ description: string;
+ embedding_model_config: EmbeddingModelConfig;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ListKnowledgeBasesResponse {
+ knowledge_bases: KnowledgeBaseView[];
+ total: number;
+}
+
+export interface CreateKnowledgeBaseRequest {
+ name: string;
+ description?: string;
+ embedding_model_config: EmbeddingModelConfig;
+}
+
+export interface CreateKnowledgeBaseResponse {
+ knowledge_base_id: string;
+}
+
+/**
+ * Body for `PATCH /knowledge_bases/{id}`. Only mutable fields can be
+ * sent; the embedding model is pinned at creation time and cannot
+ * change because the underlying collection is sized to its dimension.
+ */
+export interface UpdateKnowledgeBaseRequest {
+ name?: string;
+ description?: string;
+}
+
+/**
+ * Lifecycle states a document can be in. Mirrors
+ * :class:`agentscope.app.storage.KnowledgeDocumentStatus`.
+ *
+ * - `pending` — accepted, blob stored, indexing not yet started.
+ * - `parsing` / `chunking` / `indexing` — worker phases.
+ * - `ready` — chunks committed to the vector store.
+ * - `error` — terminal failure; `error` field carries the reason.
+ */
+export type KnowledgeDocumentStatus =
+ | 'pending'
+ | 'parsing'
+ | 'chunking'
+ | 'indexing'
+ | 'ready'
+ | 'error';
+
+/**
+ * Document view returned by `/knowledge_bases/{id}/documents` and
+ * `/knowledge_bases/{id}/documents/status`. Mirrors
+ * :class:`agentscope.app._router._schema.KnowledgeDocumentView`.
+ */
+export interface KnowledgeDocumentView {
+ id: string;
+ filename: string;
+ size: number;
+ content_type: string | null;
+ status: KnowledgeDocumentStatus;
+ error: string | null;
+ chunk_count: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ListKnowledgeDocumentsResponse {
+ documents: KnowledgeDocumentView[];
+ total: number;
+}
+
+export interface ListKnowledgeDocumentStatusResponse {
+ items: KnowledgeDocumentView[];
+}
+
+export interface UploadKnowledgeDocumentResponse {
+ document_id: string;
+ filename: string;
+ status: KnowledgeDocumentStatus;
+}
+
+export interface SearchKnowledgeBaseRequest {
+ query: string;
+ top_k?: number;
+}
+
+/**
+ * Lightweight chunk shape returned inside `VectorSearchResult`. Mirrors
+ * :class:`agentscope.rag.Chunk` — content is the raw `TextBlock` /
+ * `DataBlock` discriminated union the backend ships.
+ */
+export interface KnowledgeChunk {
+ content: { type: 'text'; text: string; id?: string } | { type: string; [key: string]: unknown };
+ source: string;
+ chunk_index: number;
+ total_chunks: number;
+ metadata: Record<string, unknown>;
+}
+
+/**
+ * One vector search hit returned by the knowledge base search endpoint.
+ * Mirrors :class:`agentscope.rag.VectorSearchResult` on the backend.
+ */
+export interface VectorSearchResult {
+ score: number;
+ document_id: string;
+ chunk: KnowledgeChunk;
+}
+
+export interface SearchKnowledgeBaseResponse {
+ results: VectorSearchResult[];
+ total: number;
+}
+
+/**
+ * Mirrors :class:`agentscope.app.rag.knowledge_base_manager.DimensionPolicyKind`.
+ */
+export type DimensionPolicyKind = 'any' | 'fixed' | 'locked_by_existing';
+
+/**
+ * Mirrors :class:`agentscope.app.rag.knowledge_base_manager.DimensionPolicy`.
+ */
+export interface DimensionPolicy {
+ kind: DimensionPolicyKind;
+ dimension: number | null;
+}
+
+/** One credential and the embedding models it can serve, post-policy. */
+export interface KbEmbeddingProvider {
+ credential: CredentialRecord;
+ models: EmbeddingModelCard[];
+}
+
+/**
+ * Response of `GET /knowledge_bases/embedding_models`.
+ *
+ * Server-side already filtered models by the manager's
+ * :class:`DimensionPolicy` and narrowed matryoshka cards to the
+ * locked dimension when applicable. The policy is included so the
+ * UI can render an explanatory banner.
+ */
+export interface ListKbEmbeddingModelsResponse {
+ providers: KbEmbeddingProvider[];
+ policy: DimensionPolicy;
+}
+
+/**
+ * Session-level knowledge base attachment. Persisted on
+ * :class:`SessionConfig.knowledge_config` and translated into a
+ * `KnowledgeBaseMiddleware` at chat-run time.
+ *
+ * `parameters` holds the user-tunable middleware fields verbatim — its
+ * accepted keys/values are described by the JSON Schema returned from
+ * `GET /knowledge_bases/middleware/parameters_schema`.
+ */
+export interface SessionKnowledgeConfig {
+ knowledge_base_ids: string[];
+ parameters: Record<string, unknown>;
+}
+
+/** Response of `GET /knowledge_bases/middleware/parameters_schema`. */
+export interface KbMiddlewareParametersSchemaResponse {
+ parameter_schema: Record<string, unknown>;
+}
+
+/** Response of `GET /knowledge_bases/supported_content_types`. */
+export interface ListSupportedContentTypesResponse {
+ /** Union of IANA media types every registered parser handles. */
+ media_types: string[];
+ /** Union of filename extensions (each starting with `.`). */
+ extensions: string[];
+}
+
+// ─── TTS ──────────────────────────────────────────────────────────────────────
+
export interface TTSModelCard {
type: 'tts_model';
name: string;
diff --git a/examples/web_ui/frontend/src/components/dialog/CreateKnowledgeBaseDialog.tsx b/examples/web_ui/frontend/src/components/dialog/CreateKnowledgeBaseDialog.tsx
new file mode 100644
index 000000000..bf6a4fc1e
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/dialog/CreateKnowledgeBaseDialog.tsx
@@ -0,0 +1,246 @@
+import { CircleAlert, Info, Loader2, PlusCircle } from 'lucide-react';
+import { useEffect, useMemo, useState } from 'react';
+
+import type { EmbeddingModelCard, EmbeddingModelConfig } from '@/api';
+import { DimensionSelect } from '@/components/select/DimensionSelect';
+import { EmbeddingSelect } from '@/components/select/EmbeddingSelect';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog.tsx';
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field.tsx';
+import { Input } from '@/components/ui/input.tsx';
+import { Textarea } from '@/components/ui/textarea.tsx';
+import { useKbEmbeddingModels } from '@/hooks/useKbEmbeddingModels';
+import { useKnowledgeBases } from '@/hooks/useKnowledgeBases';
+import { useTranslation } from '@/i18n/useI18n.ts';
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onCreated?: (knowledgeBaseId: string) => void;
+ onAddCredential?: () => void;
+ /**
+ * Bumped externally (e.g. after a credential is created) to ask the
+ * embedding selector to refetch its options.
+ */
+ credentialRefetchTrigger?: number;
+}
+
+interface SelectedEmbedding {
+ type: string;
+ credentialId: string;
+ model: string;
+ card: EmbeddingModelCard;
+}
+
+export function CreateKnowledgeBaseDialog({
+ open,
+ onOpenChange,
+ onCreated,
+ onAddCredential,
+ credentialRefetchTrigger,
+}: Props) {
+ const { t } = useTranslation();
+ const { create } = useKnowledgeBases();
+ const { providers, policy, loading } = useKbEmbeddingModels(credentialRefetchTrigger);
+
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [selected, setSelected] = useState<SelectedEmbedding | null>(null);
+ const [dimension, setDimension] = useState<number | null>(null);
+ const [submitting, setSubmitting] = useState(false);
+ const [errorKey, setErrorKey] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open) {
+ setName('');
+ setDescription('');
+ setSelected(null);
+ setDimension(null);
+ setErrorKey(null);
+ setSubmitting(false);
+ }
+ }, [open]);
+
+ const dimensionOptions = useMemo<number[] | null>(() => {
+ if (!selected) return null;
+ const sd = selected.card.supported_dimensions;
+ return sd && sd.length > 0 ? sd : [selected.card.dimensions];
+ }, [selected]);
+
+ const handleSelectEmbedding = (sel: SelectedEmbedding) => {
+ setSelected(sel);
+ const sd = sel.card.supported_dimensions;
+ const defaultDim =
+ sd && sd.length > 0
+ ? sd.includes(sel.card.dimensions)
+ ? sel.card.dimensions
+ : sd[0]
+ : sel.card.dimensions;
+ setDimension(defaultDim);
+ };
+
+ const handleSubmit = async () => {
+ if (!name.trim()) {
+ setErrorKey('dialog-knowledge-base-create.errors.nameRequired');
+ return;
+ }
+ if (!selected) {
+ setErrorKey('dialog-knowledge-base-create.errors.embeddingRequired');
+ return;
+ }
+ if (dimension == null || dimension <= 0) {
+ setErrorKey('dialog-knowledge-base-create.errors.dimensionRequired');
+ return;
+ }
+ setErrorKey(null);
+ setSubmitting(true);
+ try {
+ const config: EmbeddingModelConfig = {
+ type: selected.type,
+ credential_id: selected.credentialId,
+ model: selected.model,
+ dimensions: dimension,
+ parameters: {},
+ };
+ const knowledgeBaseId = await create({
+ name: name.trim(),
+ description: description.trim(),
+ embedding_model_config: config,
+ });
+ onCreated?.(knowledgeBaseId);
+ onOpenChange(false);
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const isLockedPolicy = policy && policy.kind !== 'any';
+ const noCompatibleModels = !loading && providers.length === 0;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="!w-[500px] !max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{t('dialog-knowledge-base-create.title')}</DialogTitle>
+ <DialogDescription>
+ {t('dialog-knowledge-base-create.description')}
+ </DialogDescription>
+ </DialogHeader>
+
+ {isLockedPolicy && policy?.dimension != null && (
+ <Alert>
+ <Info className="size-4" />
+ <AlertTitle>
+ {t('dialog-knowledge-base-create.policy.lockedTitle', {
+ dimension: policy.dimension,
+ })}
+ </AlertTitle>
+ <AlertDescription>
+ {t('dialog-knowledge-base-create.policy.lockedDescription', {
+ dimension: policy.dimension,
+ })}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {noCompatibleModels && (
+ <Alert variant="destructive">
+ <CircleAlert className="size-4" />
+ <AlertTitle>
+ {t('dialog-knowledge-base-create.policy.noCompatibleTitle')}
+ </AlertTitle>
+ <AlertDescription>
+ {isLockedPolicy && policy?.dimension != null
+ ? t('dialog-knowledge-base-create.policy.noCompatibleLocked', {
+ dimension: policy.dimension,
+ })
+ : t('dialog-knowledge-base-create.policy.noCompatibleAny')}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ <FieldGroup>
+ <Field>
+ <FieldLabel>{t('dialog-knowledge-base-create.name.label')}</FieldLabel>
+ <Input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t('dialog-knowledge-base-create.name.placeholder')}
+ disabled={submitting}
+ />
+ </Field>
+ <Field>
+ <FieldLabel>
+ {t('dialog-knowledge-base-create.descriptionField.label')}
+ </FieldLabel>
+ <Textarea
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder={t(
+ 'dialog-knowledge-base-create.descriptionField.placeholder',
+ )}
+ disabled={submitting}
+ rows={3}
+ />
+ </Field>
+ <Field orientation="horizontal">
+ <FieldLabel>
+ {t('dialog-knowledge-base-create.embeddingModel.label')}
+ </FieldLabel>
+ <EmbeddingSelect
+ value={
+ selected
+ ? {
+ type: selected.type,
+ credential_id: selected.credentialId,
+ model: selected.model,
+ }
+ : null
+ }
+ providers={providers}
+ loading={loading}
+ onChange={handleSelectEmbedding}
+ onAddCredential={onAddCredential}
+ />
+ </Field>
+ <Field orientation="horizontal">
+ <FieldLabel>{t('dialog-knowledge-base-create.dimension.label')}</FieldLabel>
+ <DimensionSelect
+ value={dimension}
+ options={dimensionOptions}
+ onChange={setDimension}
+ disabled={submitting}
+ />
+ </Field>
+ {errorKey && <p className="text-destructive text-sm">{t(errorKey)}</p>}
+ </FieldGroup>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ disabled={submitting}
+ >
+ <CircleAlert className="size-3.5" />
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={handleSubmit} disabled={submitting || noCompatibleModels}>
+ {submitting ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <PlusCircle className="size-3.5" />
+ )}
+ {submitting ? t('common.creating') : t('common.create')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/dialog/EditKnowledgeBaseDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditKnowledgeBaseDialog.tsx
new file mode 100644
index 000000000..7ffd58e5a
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/dialog/EditKnowledgeBaseDialog.tsx
@@ -0,0 +1,139 @@
+import { CheckCircle, CircleAlert, Loader2 } from 'lucide-react';
+import { useEffect, useState } from 'react';
+
+import type { KnowledgeBaseView } from '@/api';
+import { Badge } from '@/components/ui/badge.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog.tsx';
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field.tsx';
+import { Input } from '@/components/ui/input.tsx';
+import { Textarea } from '@/components/ui/textarea.tsx';
+import { useKnowledgeBases } from '@/hooks/useKnowledgeBases';
+import { useTranslation } from '@/i18n/useI18n.ts';
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ knowledgeBase: KnowledgeBaseView | null;
+ onUpdated?: (view: KnowledgeBaseView) => void;
+}
+
+/**
+ * Dialog to edit a knowledge base's mutable fields. Embedding model
+ * is shown as a read-only badge because it's pinned at creation time
+ * (the underlying collection is sized to its dimension).
+ */
+export function EditKnowledgeBaseDialog({ open, onOpenChange, knowledgeBase, onUpdated }: Props) {
+ const { t } = useTranslation();
+ const { update } = useKnowledgeBases();
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+ const [errorKey, setErrorKey] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (open && knowledgeBase) {
+ setName(knowledgeBase.name);
+ setDescription(knowledgeBase.description ?? '');
+ setErrorKey(null);
+ setSubmitting(false);
+ }
+ }, [open, knowledgeBase]);
+
+ const handleSubmit = async () => {
+ if (!knowledgeBase) return;
+ const trimmedName = name.trim();
+ if (!trimmedName) {
+ setErrorKey('dialog-knowledge-base-edit.errors.nameRequired');
+ return;
+ }
+ setErrorKey(null);
+ setSubmitting(true);
+ try {
+ const view = await update(knowledgeBase.id, {
+ name: trimmedName,
+ description: description.trim(),
+ });
+ onUpdated?.(view);
+ onOpenChange(false);
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const embeddingModelLabel = knowledgeBase
+ ? `${knowledgeBase.embedding_model_config.model} · ${knowledgeBase.embedding_model_config.dimensions}d`
+ : '';
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="!w-[500px] !max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{t('dialog-knowledge-base-edit.title')}</DialogTitle>
+ <DialogDescription>
+ {t('dialog-knowledge-base-edit.description')}
+ </DialogDescription>
+ </DialogHeader>
+ <FieldGroup>
+ <Field>
+ <FieldLabel>{t('dialog-knowledge-base-edit.name.label')}</FieldLabel>
+ <Input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t('dialog-knowledge-base-edit.name.placeholder')}
+ disabled={submitting}
+ />
+ </Field>
+ <Field>
+ <FieldLabel>
+ {t('dialog-knowledge-base-edit.descriptionField.label')}
+ </FieldLabel>
+ <Textarea
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder={t(
+ 'dialog-knowledge-base-edit.descriptionField.placeholder',
+ )}
+ disabled={submitting}
+ rows={3}
+ />
+ </Field>
+ <Field orientation="horizontal">
+ <FieldLabel>
+ {t('dialog-knowledge-base-edit.embeddingModel.label')}
+ </FieldLabel>
+ <Badge variant="secondary" className="font-mono">
+ {embeddingModelLabel}
+ </Badge>
+ </Field>
+ {errorKey && <p className="text-destructive text-sm">{t(errorKey)}</p>}
+ </FieldGroup>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ disabled={submitting}
+ >
+ <CircleAlert className="size-3.5" />
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={handleSubmit} disabled={submitting}>
+ {submitting ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <CheckCircle className="size-3.5" />
+ )}
+ {submitting ? t('common.saving') : t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/drawer/KnowledgeSearchDrawer.tsx b/examples/web_ui/frontend/src/components/drawer/KnowledgeSearchDrawer.tsx
new file mode 100644
index 000000000..45db3ff5a
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/drawer/KnowledgeSearchDrawer.tsx
@@ -0,0 +1,199 @@
+import { FlaskConical, Loader2, Search } from 'lucide-react';
+import { useState } from 'react';
+
+import type { VectorSearchResult } from '@/api';
+import { Badge } from '@/components/ui/badge.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty.tsx';
+import { Input } from '@/components/ui/input.tsx';
+import { Label } from '@/components/ui/label.tsx';
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet.tsx';
+import { Textarea } from '@/components/ui/textarea.tsx';
+import { useKnowledgeBases } from '@/hooks/useKnowledgeBases';
+import { useTranslation } from '@/i18n/useI18n.ts';
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ knowledgeBaseId: string;
+ knowledgeBaseName: string;
+}
+
+/**
+ * Right-side drawer for ad-hoc retrieval testing on a knowledge base.
+ * The user types a query, picks `top_k`, and inspects ranked chunks.
+ */
+export function KnowledgeSearchDrawer({
+ open,
+ onOpenChange,
+ knowledgeBaseId,
+ knowledgeBaseName,
+}: Props) {
+ const { t } = useTranslation();
+ const { search } = useKnowledgeBases();
+ const [query, setQuery] = useState('');
+ const [topK, setTopK] = useState(5);
+ const [loading, setLoading] = useState(false);
+ const [results, setResults] = useState<VectorSearchResult[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const handleSearch = async () => {
+ const trimmed = query.trim();
+ if (!trimmed) return;
+ setLoading(true);
+ setError(null);
+ try {
+ const res = await search(knowledgeBaseId, {
+ query: trimmed,
+ top_k: topK,
+ });
+ setResults(res.results);
+ } catch (e) {
+ setError((e as Error).message || String(e));
+ setResults(null);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="flex w-full sm:!max-w-[480px] flex-col gap-y-4 p-4">
+ <SheetHeader className="px-0">
+ <SheetTitle className="flex items-center gap-x-2">
+ <FlaskConical className="size-4" />
+ {t('knowledge.test.title')}
+ </SheetTitle>
+ <SheetDescription className="truncate">
+ {t('knowledge.test.description', { name: knowledgeBaseName })}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex flex-col gap-y-3 px-0">
+ <div className="flex flex-col gap-y-1.5">
+ <Label htmlFor="kb-test-query" className="text-xs">
+ {t('knowledge.test.queryLabel')}
+ </Label>
+ <Textarea
+ id="kb-test-query"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('knowledge.test.queryPlaceholder')}
+ rows={3}
+ disabled={loading}
+ />
+ </div>
+ <div className="flex items-center gap-x-3">
+ <div className="flex items-center gap-x-2">
+ <Label htmlFor="kb-test-topk" className="text-xs">
+ {t('knowledge.test.topKLabel')}
+ </Label>
+ <Input
+ id="kb-test-topk"
+ type="number"
+ min={1}
+ max={50}
+ value={topK}
+ onChange={(e) =>
+ setTopK(Math.max(1, Math.min(50, Number(e.target.value) || 1)))
+ }
+ className="w-20"
+ disabled={loading}
+ />
+ </div>
+ <Button
+ className="ml-auto"
+ size="sm"
+ onClick={handleSearch}
+ disabled={loading || !query.trim()}
+ >
+ {loading ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <Search className="size-3.5" />
+ )}
+ {t('knowledge.test.searchButton')}
+ </Button>
+ </div>
+ {error && <p className="text-destructive text-sm">{error}</p>}
+ </div>
+
+ <div className="flex-1 overflow-y-auto px-0">
+ {results === null ? null : results.length === 0 ? (
+ <Empty className="border-none py-4">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Search />
+ </EmptyMedia>
+ <EmptyTitle>{t('knowledge.test.emptyTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('knowledge.test.emptyDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <div className="flex flex-col gap-y-3">
+ {results.map((hit, idx) => (
+ <ResultCard
+ key={`${hit.document_id}-${idx}`}
+ hit={hit}
+ index={idx}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+
+ <SheetFooter className="px-0">
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ {t('common.close')}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function ResultCard({ hit, index }: { hit: VectorSearchResult; index: number }) {
+ const { t } = useTranslation();
+ const text =
+ hit.chunk.content && typeof hit.chunk.content === 'object' && 'text' in hit.chunk.content
+ ? String(hit.chunk.content.text ?? '')
+ : JSON.stringify(hit.chunk.content);
+
+ return (
+ <div className="rounded-md border bg-card p-3 flex flex-col gap-y-2">
+ <div className="flex items-center gap-x-2 text-xs text-muted-foreground">
+ <Badge variant="secondary" className="font-mono">
+ #{index + 1}
+ </Badge>
+ <Badge variant="outline" className="font-mono">
+ {t('knowledge.test.score')}: {hit.score.toFixed(4)}
+ </Badge>
+ <span className="ml-auto truncate" title={hit.chunk.source}>
+ {hit.chunk.source}
+ </span>
+ </div>
+ <p className="text-sm whitespace-pre-wrap break-words">{text}</p>
+ <div className="text-xs text-muted-foreground">
+ {t('knowledge.test.chunkPosition', {
+ index: hit.chunk.chunk_index + 1,
+ total: hit.chunk.total_chunks,
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/form/SchemaForm.tsx b/examples/web_ui/frontend/src/components/form/SchemaForm.tsx
index c6b2699d3..d55ee8857 100644
--- a/examples/web_ui/frontend/src/components/form/SchemaForm.tsx
+++ b/examples/web_ui/frontend/src/components/form/SchemaForm.tsx
@@ -2,6 +2,13 @@ import type { JSONSchema, JSONSchemaProperty } from '@/api';
import { Checkbox } from '@/components/ui/checkbox';
import { Field, FieldDescription, FieldGroup, FieldLabel } from '@/components/ui/field.tsx';
import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
const DEFAULT_SKIP_FIELDS = new Set(['id', 'type']);
@@ -28,6 +35,18 @@ function effectiveType(prop: JSONSchemaProperty): string {
return prop.type ?? prop.anyOf?.find((t) => t.type !== 'null')?.type ?? 'string';
}
+/** Surface enum values whether they appear at the property root or inside an
+ * `anyOf` variant (Pydantic puts `Literal[...]` directly on the property and
+ * `Literal[...] | None` on the non-null `anyOf` branch). */
+function enumValues(prop: JSONSchemaProperty): unknown[] | null {
+ if (prop.enum) return prop.enum;
+ for (const variant of prop.anyOf ?? []) {
+ const v = (variant as JSONSchemaProperty).enum;
+ if (v) return v;
+ }
+ return null;
+}
+
function inferStep(type: string): number | string | undefined {
if (type === 'integer') return 1;
if (type === 'number') return 'any';
@@ -73,6 +92,7 @@ export function SchemaForm({
const isPassword = prop.format === 'password';
const isTextarea = prop.format === 'textarea';
const isNumber = type === 'number' || type === 'integer';
+ const enumOpts = enumValues(prop);
const label = labelFor?.(key, prop) ?? prop.title ?? key.replace(/_/g, ' ');
const placeholder = placeholderFor?.(key, prop) ?? prop.description;
@@ -95,6 +115,32 @@ export function SchemaForm({
);
}
+ if (enumOpts) {
+ const currentStr =
+ current === undefined || current === null ? '' : String(current);
+ return (
+ <Field key={key}>
+ <FieldLabel htmlFor={fieldId}>
+ {label}
+ {isRequired && <span className="text-destructive ml-0.5">*</span>}
+ </FieldLabel>
+ <Select value={currentStr} onValueChange={(v) => onChange(key, v)}>
+ <SelectTrigger id={fieldId} className="w-full">
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent>
+ {enumOpts.map((opt) => (
+ <SelectItem key={String(opt)} value={String(opt)}>
+ {String(opt)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {description && <FieldDescription>{description}</FieldDescription>}
+ </Field>
+ );
+ }
+
if (isTextarea) {
return (
<Field key={key}>
diff --git a/examples/web_ui/frontend/src/components/knowledge/KnowledgeDocumentsPanel.tsx b/examples/web_ui/frontend/src/components/knowledge/KnowledgeDocumentsPanel.tsx
new file mode 100644
index 000000000..d173a2b4c
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/knowledge/KnowledgeDocumentsPanel.tsx
@@ -0,0 +1,481 @@
+import { AlertCircle, CheckCircle2, FileText, Loader2, Plus, Trash2, X } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { toast } from 'sonner';
+
+import { knowledgeBaseApi } from '@/api';
+import type { KnowledgeDocumentStatus, KnowledgeDocumentView } from '@/api';
+import { DeleteDialog } from '@/components/dialog/DeleteDialog.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty.tsx';
+import { useUploadContext } from '@/context/UploadContext';
+import { isInFlight } from '@/context/uploadTypes';
+import type { UploadPhase, UploadTask } from '@/context/uploadTypes';
+import { useDocumentStatusPolling } from '@/hooks/useDocumentStatusPolling';
+import { useKnowledgeDocuments } from '@/hooks/useKnowledgeDocuments';
+import { useKnowledgeSupportedContentTypes } from '@/hooks/useKnowledgeSupportedContentTypes';
+import { cn } from '@/lib/utils';
+
+interface KnowledgeDocumentsPanelProps {
+ knowledgeBaseId: string;
+}
+
+/**
+ * A row that the panel renders. Either a server-side document (the
+ * canonical record after upload returns) or a still-uploading local
+ * task. Uploads that have already produced a `documentId` are routed
+ * through the server row so the panel never double-renders one.
+ */
+type Row =
+ | { kind: 'server'; doc: KnowledgeDocumentView; localTask: UploadTask | null }
+ | { kind: 'local'; task: UploadTask };
+
+const TERMINAL_SERVER_STATUSES: KnowledgeDocumentStatus[] = ['ready', 'error'];
+
+function formatSize(bytes: number): string {
+ if (!bytes) return '—';
+ const units = ['B', 'KB', 'MB', 'GB'];
+ let value = bytes;
+ let i = 0;
+ while (value >= 1024 && i < units.length - 1) {
+ value /= 1024;
+ i++;
+ }
+ return `${value.toFixed(value >= 100 || i === 0 ? 0 : 1)} ${units[i]}`;
+}
+
+function StatusBadge({ phase }: { phase: UploadPhase }) {
+ const { t } = useTranslation();
+ const label = t(`knowledge.document.status.${phase}`);
+ const tone = (() => {
+ switch (phase) {
+ case 'ready':
+ return 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-400';
+ case 'error':
+ return 'bg-destructive/10 text-destructive';
+ case 'cancelled':
+ return 'bg-muted text-muted-foreground';
+ case 'queued':
+ case 'uploading':
+ case 'pending':
+ case 'parsing':
+ case 'chunking':
+ case 'indexing':
+ default:
+ return 'bg-primary/10 text-primary';
+ }
+ })();
+ return (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-x-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium',
+ tone,
+ )}
+ >
+ {phase === 'ready' ? (
+ <CheckCircle2 className="size-3" />
+ ) : phase === 'error' ? (
+ <AlertCircle className="size-3" />
+ ) : phase === 'cancelled' ? null : (
+ <Loader2 className="size-3 animate-spin" />
+ )}
+ {label}
+ </span>
+ );
+}
+
+interface RowViewProps {
+ row: Row;
+ onCancel: (taskId: string) => void;
+ onDismiss: (taskId: string) => void;
+ onDelete: (doc: KnowledgeDocumentView) => void;
+}
+
+function RowView({ row, onCancel, onDismiss, onDelete }: RowViewProps) {
+ const { t } = useTranslation();
+
+ const filename = row.kind === 'server' ? row.doc.filename : row.task.filename;
+ const size = row.kind === 'server' ? row.doc.size : row.task.size;
+
+ // Phase resolution — the local task wins while the server hasn't
+ // caught up; once the server says `ready` / `error`, that's the
+ // truth.
+ const phase: UploadPhase = (() => {
+ if (row.kind === 'local') return row.task.phase;
+ const localPhase = row.localTask?.phase;
+ if (
+ localPhase &&
+ !TERMINAL_SERVER_STATUSES.includes(row.doc.status as KnowledgeDocumentStatus)
+ ) {
+ return localPhase;
+ }
+ return row.doc.status;
+ })();
+
+ // Progress bar logic: byte-level during `uploading`; otherwise a
+ // coarse phase-derived value so the user gets visible movement.
+ const { progressValue, indeterminate } = (() => {
+ if (phase === 'uploading' && row.kind === 'local') {
+ if (!row.task.size) return { progressValue: 0, indeterminate: true };
+ return {
+ progressValue: Math.min(100, Math.round((row.task.loaded / row.task.size) * 100)),
+ indeterminate: false,
+ };
+ }
+ switch (phase) {
+ case 'queued':
+ return { progressValue: 5, indeterminate: false };
+ case 'pending':
+ return { progressValue: 35, indeterminate: true };
+ case 'parsing':
+ return { progressValue: 55, indeterminate: true };
+ case 'chunking':
+ return { progressValue: 75, indeterminate: true };
+ case 'indexing':
+ return { progressValue: 90, indeterminate: true };
+ case 'ready':
+ return { progressValue: 100, indeterminate: false };
+ default:
+ return { progressValue: 0, indeterminate: false };
+ }
+ })();
+
+ const error = row.kind === 'local' ? row.task.error : row.doc.error;
+ const chunkCount = row.kind === 'server' ? row.doc.chunk_count : row.task.documentId ? 0 : 0;
+
+ const taskIdForCancel =
+ row.kind === 'local' ? row.task.taskId : (row.localTask?.taskId ?? null);
+
+ const showProgress = phase !== 'ready' && phase !== 'cancelled';
+
+ return (
+ <div className="border-border bg-card flex flex-col gap-y-2 rounded-lg border p-3">
+ <div className="flex items-start gap-x-3">
+ <FileText className="text-muted-foreground mt-0.5 size-4 shrink-0" />
+ <div className="flex min-w-0 flex-1 flex-col gap-y-0.5">
+ <div className="flex items-center gap-x-2">
+ <span className="truncate text-sm font-medium">{filename}</span>
+ <StatusBadge phase={phase} />
+ </div>
+ <div className="text-muted-foreground flex items-center gap-x-2 text-xs">
+ <span>{formatSize(size)}</span>
+ {chunkCount > 0 && (
+ <>
+ <span>·</span>
+ <span>
+ {t('knowledge.document.chunkCount', {
+ count: chunkCount,
+ })}
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-x-1">
+ {phase === 'queued' || phase === 'uploading' ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => taskIdForCancel && onCancel(taskIdForCancel)}
+ aria-label={t('knowledge.document.actions.cancel')}
+ >
+ <X className="size-3.5" />
+ </Button>
+ ) : phase === 'cancelled' || phase === 'error' ? (
+ row.kind === 'local' ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => onDismiss(row.task.taskId)}
+ aria-label={t('knowledge.document.actions.dismiss')}
+ >
+ <X className="size-3.5" />
+ </Button>
+ ) : (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => onDelete(row.doc)}
+ aria-label={t('knowledge.document.actions.remove')}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ )
+ ) : row.kind === 'server' ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => onDelete(row.doc)}
+ aria-label={t('knowledge.document.actions.remove')}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ {showProgress && (
+ <div className="bg-muted relative h-1 w-full overflow-hidden rounded-full">
+ <div
+ className={cn(
+ 'h-full rounded-full transition-all',
+ phase === 'error' ? 'bg-destructive' : 'bg-primary',
+ indeterminate && 'animate-pulse',
+ )}
+ style={{ width: `${progressValue}%` }}
+ />
+ </div>
+ )}
+ {phase === 'error' && error && <p className="text-destructive text-xs">{error}</p>}
+ </div>
+ );
+}
+
+export function KnowledgeDocumentsPanel({ knowledgeBaseId }: KnowledgeDocumentsPanelProps) {
+ const { t } = useTranslation();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [dragOver, setDragOver] = useState(false);
+ const [deleteTarget, setDeleteTarget] = useState<KnowledgeDocumentView | null>(null);
+
+ const { enqueue, cancel, dismiss, tasksForKb, clearFinishedForKb } = useUploadContext();
+ const { documents, refetch } = useKnowledgeDocuments(knowledgeBaseId);
+ const tasks = tasksForKb(knowledgeBaseId);
+ const { statuses } = useDocumentStatusPolling({
+ knowledgeBaseId,
+ documents,
+ });
+ const { mediaTypes, extensions } = useKnowledgeSupportedContentTypes();
+
+ // Lowercased extension set used to gate `handleFiles`. Built once
+ // per render — the underlying list is shared across the app via a
+ // module-level cache so this stays cheap.
+ const extensionSet = useMemo(
+ () => new Set(extensions.map((ext) => ext.toLowerCase())),
+ [extensions],
+ );
+ // `<input accept>` takes a comma-separated string of MIME types and
+ // `.ext` tokens. We hand it both because browsers diverge on which
+ // they honour for any given filename — extensions filter the picker
+ // dialog, MIME types catch programmatic drops.
+ const acceptAttr = useMemo(
+ () => [...extensions, ...mediaTypes].join(','),
+ [extensions, mediaTypes],
+ );
+
+ // Refetch the canonical list whenever a polled doc reaches a
+ // terminal state — this is the single hook that pulls in the worker's
+ // final `chunk_count` and any updates to `error`.
+ const terminalIdsKey = useMemo(() => {
+ const ids: string[] = [];
+ for (const id of Object.keys(statuses)) {
+ const s = statuses[id];
+ if (s.status === 'ready' || s.status === 'error') ids.push(id);
+ }
+ return ids.join(',');
+ }, [statuses]);
+ const lastRefetchedKey = useRef('');
+ useEffect(() => {
+ if (!terminalIdsKey) return;
+ if (terminalIdsKey === lastRefetchedKey.current) return;
+ lastRefetchedKey.current = terminalIdsKey;
+ void refetch();
+ }, [terminalIdsKey, refetch]);
+
+ // Merge tasks + documents into a single ordered row list.
+ const rows: Row[] = useMemo(() => {
+ const tasksByDocId = new Map<string, UploadTask>();
+ const tasksWithoutDoc: UploadTask[] = [];
+ for (const task of tasks) {
+ if (task.documentId) tasksByDocId.set(task.documentId, task);
+ else tasksWithoutDoc.push(task);
+ }
+ const docRows: Row[] = documents.map((doc) => ({
+ kind: 'server',
+ doc,
+ localTask: tasksByDocId.get(doc.id) ?? null,
+ }));
+ const localRows: Row[] = tasksWithoutDoc.map((task) => ({
+ kind: 'local',
+ task,
+ }));
+ // Local-only rows go first (they're either uploading or queued
+ // — both are user-visible "I just hit upload" states).
+ return [...localRows, ...docRows];
+ }, [documents, tasks]);
+
+ const onUploadClick = useCallback(() => {
+ fileInputRef.current?.click();
+ }, []);
+
+ const handleFiles = useCallback(
+ (files: FileList | File[]) => {
+ const arr = Array.from(files);
+ if (arr.length === 0) return;
+ // When the capability list hasn't loaded yet, allow everything
+ // through — the backend still rejects unsupported uploads.
+ // Once we have the list, filter client-side by extension
+ // (`file.type` is unreliable across browsers/OSes).
+ const accepted: File[] = [];
+ for (const f of arr) {
+ if (extensionSet.size === 0) {
+ accepted.push(f);
+ continue;
+ }
+ const dot = f.name.lastIndexOf('.');
+ const ext = dot >= 0 ? f.name.slice(dot).toLowerCase() : '';
+ if (ext && extensionSet.has(ext)) {
+ accepted.push(f);
+ } else {
+ toast.error(
+ t('knowledge.document.unsupportedExtension', {
+ name: f.name,
+ }),
+ );
+ }
+ }
+ if (accepted.length === 0) return;
+ enqueue(knowledgeBaseId, accepted);
+ },
+ [enqueue, knowledgeBaseId, extensionSet, t],
+ );
+
+ const onFileInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files) handleFiles(e.target.files);
+ // Reset so picking the same file twice re-fires the change.
+ e.target.value = '';
+ },
+ [handleFiles],
+ );
+
+ const onDrop = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ setDragOver(false);
+ if (e.dataTransfer.files) handleFiles(e.dataTransfer.files);
+ },
+ [handleFiles],
+ );
+
+ const onDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ setDragOver(true);
+ }, []);
+
+ const onDragLeave = useCallback(() => setDragOver(false), []);
+
+ const handleDelete = useCallback(async () => {
+ if (!deleteTarget) return;
+ try {
+ await knowledgeBaseApi.deleteDocument(knowledgeBaseId, deleteTarget.id);
+ await refetch();
+ } catch {
+ toast.error(t('knowledge.document.deleteError'));
+ }
+ }, [deleteTarget, knowledgeBaseId, refetch, t]);
+
+ const hasFinishedLocalTasks = tasks.some((t) => !isInFlight(t.phase));
+
+ const totalCount = rows.length;
+
+ return (
+ <div className="flex flex-col gap-y-4">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-semibold">
+ {t('knowledge.document.countLabel', { count: totalCount })}
+ </h3>
+ <div className="flex items-center gap-x-2">
+ {hasFinishedLocalTasks && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => clearFinishedForKb(knowledgeBaseId)}
+ >
+ {t('knowledge.document.actions.clearFinished')}
+ </Button>
+ )}
+ <Button variant="outline" size="sm" onClick={onUploadClick}>
+ <Plus className="size-3.5" />
+ {t('knowledge.document.uploadButtonShort')}
+ </Button>
+ </div>
+ </div>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept={acceptAttr || undefined}
+ className="hidden"
+ onChange={onFileInputChange}
+ />
+
+ <div
+ onDrop={onDrop}
+ onDragOver={onDragOver}
+ onDragLeave={onDragLeave}
+ className={cn(
+ 'rounded-lg border border-dashed transition-colors',
+ dragOver ? 'border-primary bg-primary/5' : 'border-border bg-transparent',
+ )}
+ >
+ {rows.length === 0 ? (
+ <Empty className="border-none py-6">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <FileText />
+ </EmptyMedia>
+ <EmptyTitle>{t('knowledge.document.emptyTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('knowledge.document.emptyDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button variant="outline" size="sm" onClick={onUploadClick}>
+ <Plus className="size-3.5" />
+ {t('knowledge.document.uploadButton')}
+ </Button>
+ <p className="text-muted-foreground mt-2 text-xs">
+ {t('knowledge.document.dropHintIdle')}
+ </p>
+ </EmptyContent>
+ </Empty>
+ ) : (
+ <div className="flex flex-col gap-y-2 p-2">
+ {rows.map((row) => (
+ <RowView
+ key={
+ row.kind === 'server'
+ ? `srv-${row.doc.id}`
+ : `tsk-${row.task.taskId}`
+ }
+ row={row}
+ onCancel={cancel}
+ onDismiss={dismiss}
+ onDelete={setDeleteTarget}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+
+ <DeleteDialog
+ open={deleteTarget !== null}
+ onOpenChange={(open) => {
+ if (!open) setDeleteTarget(null);
+ }}
+ title={t('knowledge.document.deleteConfirmTitle')}
+ description={t('knowledge.document.deleteConfirmDescription', {
+ name: deleteTarget?.filename ?? '',
+ })}
+ onConfirm={handleDelete}
+ />
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
index e92eb4e2f..60aeb9a30 100644
--- a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
+++ b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
@@ -1,4 +1,12 @@
-import { BotMessageSquare, Calendars, Compass, KeyRound, Languages, Settings } from 'lucide-react';
+import {
+ BotMessageSquare,
+ Calendars,
+ Compass,
+ KeyRound,
+ Languages,
+ LibraryBig,
+ Settings,
+} from 'lucide-react';
import { useOnborda } from 'onborda';
import { useNavigate, useLocation } from 'react-router-dom';
@@ -90,6 +98,16 @@ export function AppSidebar() {
<KeyRound />
</SidebarMenuButton>
</SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ tooltip={{ children: t('common.knowledge'), hidden: false }}
+ isActive={location.pathname === '/knowledge'}
+ onClick={() => navigate('/knowledge')}
+ className="px-2"
+ >
+ <LibraryBig />
+ </SidebarMenuButton>
+ </SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
diff --git a/examples/web_ui/frontend/src/components/panel/KnowledgeBasePanel.tsx b/examples/web_ui/frontend/src/components/panel/KnowledgeBasePanel.tsx
new file mode 100644
index 000000000..10d4eb306
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/panel/KnowledgeBasePanel.tsx
@@ -0,0 +1,156 @@
+import { FileX, Search, SearchX } from 'lucide-react';
+import { useMemo, useState } from 'react';
+
+import type { KnowledgeBaseView, SessionKnowledgeConfig } from '@/api';
+import { PanelEmpty } from '@/components/panel/PanelEmpty';
+import { Badge } from '@/components/ui/badge';
+import { Checkbox } from '@/components/ui/checkbox';
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';
+import { Item, ItemContent, ItemDescription, ItemTitle } from '@/components/ui/item';
+import { useTranslation } from '@/i18n/useI18n';
+
+interface KnowledgeBasePanelProps {
+ /** The user's knowledge bases. */
+ knowledgeBases: KnowledgeBaseView[];
+ /** Whether the KB list is still loading. */
+ loading?: boolean;
+ /**
+ * Current attachment for this session. `null` means no KBs attached
+ * and the panel renders with an empty selection.
+ */
+ value: SessionKnowledgeConfig | null;
+ /**
+ * Persist a new attachment to the session. The owner is responsible
+ * for awaiting the backend round-trip and refreshing session state.
+ * Pass `null` to detach every KB.
+ */
+ onChange: (next: SessionKnowledgeConfig | null) => void;
+ /** Disable the entire panel — e.g. when no session is selected. */
+ disabled?: boolean;
+}
+
+/**
+ * Pure content body for the Knowledge Base dock panel: a search box and
+ * a checkbox list of the user's KBs.
+ *
+ * Middleware parameter editing lives in
+ * {@link KnowledgeBaseParametersPopover}, which the owner mounts in the
+ * panel header's `actions` slot — that keeps this body focused on
+ * picking KBs rather than mixing two unrelated forms in the same scroll
+ * area.
+ */
+export function KnowledgeBasePanel({
+ knowledgeBases,
+ loading = false,
+ value,
+ onChange,
+ disabled = false,
+}: KnowledgeBasePanelProps) {
+ const { t } = useTranslation();
+ const [search, setSearch] = useState('');
+
+ const selectedIds = useMemo(() => new Set(value?.knowledge_base_ids ?? []), [value]);
+
+ const filtered = search
+ ? knowledgeBases.filter((kb) => kb.name.toLowerCase().includes(search.toLowerCase()))
+ : knowledgeBases;
+
+ const toggleKb = (kbId: string, checked: boolean) => {
+ const next = new Set(selectedIds);
+ if (checked) next.add(kbId);
+ else next.delete(kbId);
+ const ids = Array.from(next);
+ if (ids.length === 0) {
+ onChange(null);
+ return;
+ }
+ onChange({
+ knowledge_base_ids: ids,
+ parameters: value?.parameters ?? {},
+ });
+ };
+
+ return (
+ <div className="flex flex-col flex-1 min-h-0 gap-y-2">
+ <span className="text-muted-foreground text-sm">
+ {t('panel.knowledge.description')}
+ </span>
+ <InputGroup>
+ <InputGroupInput
+ placeholder={t('panel.knowledge.searchPlaceholder')}
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ disabled={disabled}
+ />
+ <InputGroupAddon align="inline-end">
+ <Search />
+ </InputGroupAddon>
+ </InputGroup>
+
+ <div className="flex flex-col flex-1 min-h-0 gap-y-3 overflow-y-auto">
+ {loading ? (
+ <div className="flex flex-1 items-center justify-center">
+ <p className="text-muted-foreground text-sm">{t('panel.loading')}</p>
+ </div>
+ ) : filtered.length === 0 ? (
+ <PanelEmpty
+ icon={search ? SearchX : FileX}
+ title={
+ search ? t('panel.search.emptyTitle') : t('panel.knowledge.emptyTitle')
+ }
+ description={
+ search
+ ? t('panel.search.emptyDescription', { query: search })
+ : t('panel.knowledge.emptyDescription')
+ }
+ />
+ ) : (
+ <div className="flex flex-col gap-y-2">
+ {filtered.map((kb) => {
+ const isSelected = selectedIds.has(kb.id);
+ const inputId = `kb-${kb.id}`;
+ return (
+ <Item
+ key={kb.id}
+ variant="outline"
+ data-selected={isSelected || undefined}
+ >
+ <Checkbox
+ id={inputId}
+ checked={isSelected}
+ disabled={disabled}
+ onCheckedChange={(checked) => toggleKb(kb.id, !!checked)}
+ />
+ <ItemContent>
+ <ItemTitle>
+ <label htmlFor={inputId} className="cursor-pointer">
+ {kb.name}
+ </label>
+ </ItemTitle>
+ {kb.description ? (
+ <ItemDescription>{kb.description}</ItemDescription>
+ ) : null}
+ <div className="flex flex-wrap gap-1 mt-1">
+ <Badge
+ variant="outline"
+ className="text-[10px] px-1 py-0"
+ >
+ {kb.embedding_model_config.model}
+ </Badge>
+ <Badge
+ variant="outline"
+ className="text-[10px] px-1 py-0"
+ >
+ {kb.embedding_model_config.dimensions}d
+ </Badge>
+ </div>
+ </ItemContent>
+ </Item>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/panel/PanelDock.tsx b/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
index f32d97733..de2cd7227 100644
--- a/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
+++ b/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
@@ -7,12 +7,13 @@ import {
ResizablePanel,
ResizablePanelGroup,
} from '@/components/ui/resizable.tsx';
+import { Separator } from '@/components/ui/separator';
/**
* Identifier for a dockable panel. Used both as the React key and to
* look its descriptor up in {@link PanelDockProps.panels}.
*/
-export type PanelKey = 'plan' | 'mcp' | 'skill' | 'permission';
+export type PanelKey = 'plan' | 'mcp' | 'skill' | 'permission' | 'knowledge';
/**
* The presentation of a single panel: header chrome plus its already
@@ -24,6 +25,13 @@ export interface PanelDescriptor {
title: ReactNode;
/** Optional leading icon shown next to the title. */
icon?: ReactNode;
+ /**
+ * Optional header-bar actions rendered to the left of the close
+ * button — typically `<Button variant="ghost" size="icon-sm">` items
+ * that open popovers / dropdowns (e.g. a parameters popover that
+ * would otherwise crowd the panel body).
+ */
+ actions?: ReactNode;
/**
* The panel body. Constructed by the owner with live data
* (e.g. `<TaskPanel tasksContext={...} />`) so it always reflects
@@ -69,22 +77,26 @@ const PANEL_MIN_HEIGHT = '6rem';
interface PanelProps {
title: ReactNode;
icon?: ReactNode;
+ actions?: ReactNode;
onClose: () => void;
children: ReactNode;
}
/**
* Generic panel chrome: a bordered container with a title bar (icon +
- * title + close button) and a flexible body. Content components are
- * rendered as `children` and should not draw their own header/border.
+ * title + optional actions + close button) and a flexible body. Content
+ * components are rendered as `children` and should not draw their own
+ * header/border.
*
* @param title - Header title.
* @param icon - Optional leading icon.
+ * @param actions - Optional nodes rendered to the left of the close
+ * button (e.g. a settings popover trigger).
* @param onClose - Called when the close button is clicked.
* @param children - The panel body.
* @returns The panel chrome element.
*/
-export const Panel = ({ title, icon, onClose, children }: PanelProps) => {
+export const Panel = ({ title, icon, actions, onClose, children }: PanelProps) => {
return (
<div className="flex flex-1 flex-col border rounded-sm h-full py-1 min-h-0">
<div className="flex items-center justify-between px-2">
@@ -92,9 +104,18 @@ export const Panel = ({ title, icon, onClose, children }: PanelProps) => {
{icon}
{title}
</span>
- <Button variant="ghost" size="icon-sm" onClick={onClose}>
- <X />
- </Button>
+ <div className="flex items-center gap-x-0.5">
+ {actions}
+ {actions ? (
+ <Separator
+ orientation="vertical"
+ className="mx-0.5 data-vertical:h-4 data-vertical:self-center"
+ />
+ ) : null}
+ <Button variant="ghost" size="icon-sm" onClick={onClose}>
+ <X />
+ </Button>
+ </div>
</div>
<div className="flex flex-1 flex-col min-h-0 overflow-auto px-2">{children}</div>
</div>
@@ -144,6 +165,7 @@ export const PanelDock = ({ layout, panels, onClosePanel }: PanelDockProps) => {
<Panel
title={descriptor.title}
icon={descriptor.icon}
+ actions={descriptor.actions}
onClose={() => onClosePanel(key)}
>
{descriptor.content}
diff --git a/examples/web_ui/frontend/src/components/popover/KnowledgeBaseParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/KnowledgeBaseParametersPopover.tsx
new file mode 100644
index 000000000..caa3fa6f5
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/popover/KnowledgeBaseParametersPopover.tsx
@@ -0,0 +1,277 @@
+import { ChevronDown, SlidersHorizontal } from 'lucide-react';
+import { useEffect, useState } from 'react';
+
+import type { JSONSchema, JSONSchemaProperty, SessionKnowledgeConfig } from '@/api';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import {
+ Popover,
+ PopoverContent,
+ PopoverDescription,
+ PopoverHeader,
+ PopoverTitle,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import { Switch } from '@/components/ui/switch';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useTranslation } from '@/i18n/useI18n';
+
+interface Props {
+ /**
+ * The current session-knowledge config. The popover edits its
+ * `parameters` dict; `knowledge_base_ids` is preserved verbatim.
+ * `null` means no KBs are attached — the trigger is then disabled
+ * because there is nothing for the parameters to act on.
+ */
+ value: SessionKnowledgeConfig | null;
+ /** JSON Schema describing the middleware's tunable parameters. */
+ schema: JSONSchema | null;
+ /** Persist a new config back to the session. */
+ onChange: (next: SessionKnowledgeConfig | null) => void;
+ /** Force-disable the trigger regardless of `value` (e.g. no session). */
+ disabled?: boolean;
+}
+
+type ParamValue = string | number | boolean | null | undefined;
+
+/** Look through `anyOf` to find the property's effective scalar type and
+ * any enum constraint. Pydantic renders `Literal[...]` directly and
+ * `Literal[...] | None` inside the non-null `anyOf` branch. */
+function resolve(prop: JSONSchemaProperty): {
+ type: string;
+ enumValues: unknown[] | null;
+} {
+ if (prop.type && prop.type !== 'null') {
+ return { type: prop.type, enumValues: prop.enum ?? null };
+ }
+ for (const variant of prop.anyOf ?? []) {
+ const v = variant as JSONSchemaProperty;
+ if (v.type && v.type !== 'null') {
+ return { type: v.type, enumValues: v.enum ?? prop.enum ?? null };
+ }
+ }
+ return { type: 'string', enumValues: prop.enum ?? null };
+}
+
+/**
+ * Trigger + popover that edits the `KnowledgeBaseMiddleware` parameters
+ * for the active session.
+ *
+ * Schema-driven (entries come from
+ * `KnowledgeBaseMiddleware.Parameters.model_json_schema()`) but with a
+ * hand-rolled label/control grid so labels stay flush-left and inputs
+ * align in a single right-hand column — same pattern as
+ * {@link ModelParametersPopover}. Enums render as
+ * {@link LlmSelect}-style `DropdownMenu` triggers instead of the native
+ * `<Select>` used by the shared {@link SchemaForm}.
+ *
+ * The trigger is disabled until at least one knowledge base is selected
+ * — until then the parameters have nothing to apply to.
+ */
+export function KnowledgeBaseParametersPopover({
+ value,
+ schema,
+ onChange,
+ disabled = false,
+}: Props) {
+ const { t } = useTranslation();
+
+ // Local draft so number inputs can transiently hold empty strings
+ // without racing the persisted `value.parameters`. Kept in sync with
+ // the source of truth whenever it changes (session switch, etc.).
+ const [paramValues, setParamValues] = useState<Record<string, ParamValue>>(
+ (value?.parameters ?? {}) as Record<string, ParamValue>,
+ );
+ useEffect(() => {
+ setParamValues((value?.parameters ?? {}) as Record<string, ParamValue>);
+ }, [value]);
+
+ const handleParamChange = (key: string, val: ParamValue) => {
+ const next = { ...paramValues, [key]: val };
+ if (val === undefined) delete next[key];
+ setParamValues(next);
+ // Without any selected KB the middleware isn't installed, so a
+ // parameter edit has nowhere to land. The trigger is disabled in
+ // that state, but guard here as a belt-and-braces check.
+ if (!value || value.knowledge_base_ids.length === 0) return;
+ onChange({
+ knowledge_base_ids: value.knowledge_base_ids,
+ parameters: next as Record<string, unknown>,
+ });
+ };
+
+ const hasSelection = !!value && value.knowledge_base_ids.length > 0;
+ const triggerDisabled = disabled || !schema || !hasSelection;
+
+ const entries = Object.entries(schema?.properties ?? {});
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={triggerDisabled}
+ aria-label={t('panel.knowledge.parametersTitle')}
+ title={t('panel.knowledge.parametersTitle')}
+ >
+ <SlidersHorizontal />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ className="w-80 max-h-[28rem] overflow-y-auto"
+ // Stop the popover from forwarding pointer/key events back
+ // up to the parent panel header, which would otherwise
+ // dismiss focus mid-edit.
+ onPointerDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <PopoverHeader>
+ <PopoverTitle>{t('panel.knowledge.parametersTitle')}</PopoverTitle>
+ <PopoverDescription>
+ {t('panel.knowledge.parametersDescription')}
+ </PopoverDescription>
+ </PopoverHeader>
+ {schema && entries.length > 0 ? (
+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3">
+ {entries.map(([key, prop]) => {
+ const { type, enumValues } = resolve(prop);
+ const id = `kb-mw-${key}`;
+ const label = prop.title ?? key.replace(/_/g, ' ');
+ const current = paramValues[key];
+
+ let control: React.ReactNode;
+ if (type === 'boolean') {
+ control = (
+ <Switch
+ id={id}
+ checked={current !== undefined ? !!current : !!prop.default}
+ onCheckedChange={(checked) =>
+ handleParamChange(key, !!checked)
+ }
+ />
+ );
+ } else if (enumValues) {
+ const displayValue =
+ current !== undefined && current !== null
+ ? String(current)
+ : prop.default != null
+ ? String(prop.default)
+ : '';
+ control = (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ id={id}
+ variant="outline"
+ size="sm"
+ className="justify-between gap-1 w-full"
+ >
+ <span className="truncate">{displayValue}</span>
+ <ChevronDown className="size-3.5 opacity-50 shrink-0" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="min-w-[var(--radix-dropdown-menu-trigger-width)] max-h-60 overflow-y-auto"
+ >
+ <DropdownMenuRadioGroup
+ value={displayValue}
+ onValueChange={(v) => handleParamChange(key, v)}
+ >
+ {enumValues.map((opt) => (
+ <DropdownMenuRadioItem
+ key={String(opt)}
+ value={String(opt)}
+ >
+ {String(opt)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ } else if (type === 'number' || type === 'integer') {
+ control = (
+ <Input
+ id={id}
+ type="number"
+ value={
+ current === undefined || current === null
+ ? ''
+ : String(current)
+ }
+ min={prop.minimum}
+ max={prop.maximum}
+ step={type === 'integer' ? 1 : 'any'}
+ placeholder={
+ prop.default != null ? String(prop.default) : undefined
+ }
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === '') {
+ handleParamChange(key, undefined);
+ return;
+ }
+ const parsed =
+ type === 'integer'
+ ? parseInt(raw, 10)
+ : parseFloat(raw);
+ handleParamChange(
+ key,
+ Number.isNaN(parsed) ? raw : parsed,
+ );
+ }}
+ />
+ );
+ } else {
+ control = (
+ <Input
+ id={id}
+ type="text"
+ value={
+ current === undefined || current === null
+ ? ''
+ : String(current)
+ }
+ placeholder={
+ prop.default != null ? String(prop.default) : undefined
+ }
+ onChange={(e) => handleParamChange(key, e.target.value)}
+ />
+ );
+ }
+
+ return (
+ <Tooltip key={key}>
+ <TooltipTrigger asChild>
+ <div className="col-span-2 grid grid-cols-subgrid items-center">
+ <Label htmlFor={id} className="whitespace-nowrap">
+ {label}
+ </Label>
+ {control}
+ </div>
+ </TooltipTrigger>
+ {prop.description && (
+ <TooltipContent side="left">
+ {prop.description}
+ </TooltipContent>
+ )}
+ </Tooltip>
+ );
+ })}
+ </div>
+ ) : null}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/select/DimensionSelect.tsx b/examples/web_ui/frontend/src/components/select/DimensionSelect.tsx
new file mode 100644
index 000000000..787ce3a5b
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/select/DimensionSelect.tsx
@@ -0,0 +1,74 @@
+import { ChevronDown } from 'lucide-react';
+
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useTranslation } from '@/i18n/useI18n.ts';
+
+interface Props {
+ /** Currently selected dimension. */
+ value?: number | null;
+ /** Allowed dimensions. ``null`` means no model picked yet. */
+ options: number[] | null;
+ onChange?: (dimension: number) => void;
+ disabled?: boolean;
+}
+
+/**
+ * Dimension picker for embedding models. Renders:
+ *
+ * - a placeholder when no model is selected;
+ * - a read-only badge when only one dimension is allowed
+ * (fixed-dim model, or matryoshka narrowed by server policy);
+ * - a dropdown when multiple dimensions are allowed (matryoshka
+ * under an ``ANY`` policy).
+ */
+export function DimensionSelect({ value, options, onChange, disabled }: Props) {
+ const { t } = useTranslation();
+
+ if (options === null || options.length === 0) {
+ return (
+ <span className="text-sm text-muted-foreground">
+ {t('dimension-select.pickModelFirst')}
+ </span>
+ );
+ }
+
+ if (options.length === 1) {
+ return (
+ <Badge variant="secondary" className="font-mono">
+ {options[0]}d
+ </Badge>
+ );
+ }
+
+ const display = value != null ? `${value}d` : t('dimension-select.placeholder');
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="justify-between gap-1"
+ disabled={disabled}
+ >
+ <span className="truncate font-mono">{display}</span>
+ <ChevronDown className="size-3.5 opacity-50" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-32">
+ {options.map((dim) => (
+ <DropdownMenuItem key={dim} onSelect={() => onChange?.(dim)}>
+ <span className="font-mono">{dim}d</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/select/EmbeddingSelect.tsx b/examples/web_ui/frontend/src/components/select/EmbeddingSelect.tsx
new file mode 100644
index 000000000..cf6528262
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/select/EmbeddingSelect.tsx
@@ -0,0 +1,146 @@
+import { ChevronDown, PlusCircle } from 'lucide-react';
+
+import type { EmbeddingModelCard, KbEmbeddingProvider } from '@/api';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useTranslation } from '@/i18n/useI18n.ts';
+
+interface SelectedEmbedding {
+ type: string;
+ credentialId: string;
+ model: string;
+ card: EmbeddingModelCard;
+}
+
+interface Props {
+ value?: { type: string; credential_id: string; model: string } | null;
+ providers: KbEmbeddingProvider[];
+ loading?: boolean;
+ onChange?: (selected: SelectedEmbedding) => void;
+ onAddCredential?: () => void;
+ /** Override the trigger label shown when no model is selected. */
+ placeholder?: string;
+}
+
+/**
+ * Embedding model picker. Consumes a pre-grouped, server-filtered
+ * list of providers (one entry per credential) and emits the chosen
+ * model's full :class:`EmbeddingModelCard` so the caller can derive
+ * the dimension separately.
+ */
+export function EmbeddingSelect({
+ value,
+ providers,
+ loading,
+ onChange,
+ onAddCredential,
+ placeholder,
+}: Props) {
+ const { t } = useTranslation();
+
+ // Group providers by credential type for the existing two-level UI
+ // (provider type → credential → models).
+ const groups: Record<string, KbEmbeddingProvider[]> = {};
+ for (const provider of providers) {
+ const type = (provider.credential.data.type as string) ?? 'unknown';
+ if (!groups[type]) groups[type] = [];
+ groups[type].push(provider);
+ }
+ const hasOptions = Object.keys(groups).length > 0;
+
+ const handleSelect = (type: string, credentialId: string, card: EmbeddingModelCard) => {
+ onChange?.({ type, credentialId, model: card.name, card });
+ };
+
+ const displayLabel = value?.model
+ ? value.model
+ : loading
+ ? t('embedding-select.loading')
+ : (placeholder ?? t('embedding-select.placeholder'));
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm" className="justify-between gap-1">
+ <span className="truncate">{displayLabel}</span>
+ <ChevronDown className="size-3.5 opacity-50" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-48 max-h-72 overflow-y-auto">
+ {!loading && !hasOptions ? (
+ <div className="px-2 py-3 text-center text-sm text-muted-foreground">
+ <p className="font-medium">{t('embedding-select.empty.title')}</p>
+ <p className="text-xs mt-1">{t('embedding-select.empty.description')}</p>
+ </div>
+ ) : (
+ Object.entries(groups).map(([type, items], idx) => {
+ const isSingle = items.length === 1;
+ return (
+ <DropdownMenuGroup key={type}>
+ {idx > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuLabel>
+ {type.replace(/_credential$/, '')}
+ </DropdownMenuLabel>
+ {isSingle
+ ? items[0].models.map((m) => (
+ <DropdownMenuItem
+ key={m.name}
+ onSelect={() =>
+ handleSelect(type, items[0].credential.id, m)
+ }
+ >
+ {m.label}
+ </DropdownMenuItem>
+ ))
+ : items.map(({ credential, models }) => {
+ const credName =
+ (credential.data.name as string) ||
+ credential.id.slice(0, 8);
+ return (
+ <DropdownMenuSub key={credential.id}>
+ <DropdownMenuSubTrigger>
+ {credName}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-60 overflow-y-auto">
+ {models.map((m) => (
+ <DropdownMenuItem
+ key={m.name}
+ onSelect={() =>
+ handleSelect(
+ type,
+ credential.id,
+ m,
+ )
+ }
+ >
+ {m.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ })}
+ </DropdownMenuGroup>
+ );
+ })
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={onAddCredential}>
+ <PlusCircle className="size-4" />
+ <span>{t('embedding-select.addCredential')}</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/examples/web_ui/frontend/src/context/UploadContext.tsx b/examples/web_ui/frontend/src/context/UploadContext.tsx
new file mode 100644
index 000000000..db9943d53
--- /dev/null
+++ b/examples/web_ui/frontend/src/context/UploadContext.tsx
@@ -0,0 +1,421 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useReducer,
+ useRef,
+ type ReactNode,
+} from 'react';
+
+import { MAX_CONCURRENT_UPLOADS, isTerminal, type UploadTask } from './uploadTypes';
+import { knowledgeBaseApi } from '@/api';
+import type { KnowledgeDocumentStatus } from '@/api';
+
+/**
+ * Public contract the surrounding app sees. Exposed via the React
+ * context value.
+ */
+interface UploadContextValue {
+ tasks: UploadTask[];
+ /** Enqueue one or more files against a knowledge base. */
+ enqueue: (knowledgeBaseId: string, files: File[]) => UploadTask[];
+ /**
+ * Abort an upload task. Effects depend on the current phase:
+ *
+ * - `queued` — removed from the queue.
+ * - `uploading` — XHR is aborted, then the task transitions to
+ * `cancelled`.
+ * - server-side phases — no-op (the worker has already taken over;
+ * route through the regular document-delete flow instead).
+ * - terminal phases — equivalent to `dismiss`.
+ */
+ cancel: (taskId: string) => void;
+ /** Drop a terminal task from the list (UI dismissal). */
+ dismiss: (taskId: string) => void;
+ /** Drop every terminal task for a knowledge base. */
+ clearFinishedForKb: (knowledgeBaseId: string) => void;
+ /**
+ * Filtered tasks for a knowledge base id. Cached by reference per
+ * (knowledgeBaseId, tasks-list-identity) so consumers can pass it
+ * straight into React dependency arrays.
+ */
+ tasksForKb: (knowledgeBaseId: string) => UploadTask[];
+ /**
+ * Apply server-side status snapshots from the polling hook.
+ * Lookup is keyed by `documentId`; tasks without a documentId
+ * (still uploading) are skipped.
+ */
+ applyServerStatuses: (
+ knowledgeBaseId: string,
+ items: Array<{
+ id: string;
+ status: KnowledgeDocumentStatus;
+ error: string | null;
+ }>,
+ ) => void;
+ /**
+ * Document ids the consumer should be polling. Filtered to tasks
+ * that have a documentId AND a non-terminal server-side phase.
+ */
+ pollableDocumentIds: (knowledgeBaseId: string) => string[];
+}
+
+const UploadContext = createContext<UploadContextValue | null>(null);
+
+// ───────── Reducer ────────────────────────────────────────────────────
+
+type Action =
+ | { type: 'ADD'; tasks: UploadTask[] }
+ | { type: 'START_UPLOAD'; taskId: string }
+ | { type: 'PROGRESS'; taskId: string; loaded: number; total: number }
+ | {
+ type: 'UPLOAD_DONE';
+ taskId: string;
+ documentId: string;
+ status: KnowledgeDocumentStatus;
+ }
+ | { type: 'UPLOAD_FAILED'; taskId: string; error: string }
+ | { type: 'CANCEL'; taskId: string }
+ | { type: 'REMOVE'; taskId: string }
+ | {
+ type: 'SERVER_STATUS';
+ knowledgeBaseId: string;
+ items: Array<{
+ id: string;
+ status: KnowledgeDocumentStatus;
+ error: string | null;
+ }>;
+ }
+ | { type: 'CLEAR_FINISHED'; knowledgeBaseId: string };
+
+function reducer(state: UploadTask[], action: Action): UploadTask[] {
+ switch (action.type) {
+ case 'ADD':
+ return [...state, ...action.tasks];
+ case 'START_UPLOAD':
+ return state.map((t) =>
+ t.taskId === action.taskId ? { ...t, phase: 'uploading', loaded: 0 } : t,
+ );
+ case 'PROGRESS':
+ return state.map((t) =>
+ t.taskId === action.taskId
+ ? {
+ ...t,
+ loaded: action.loaded,
+ // Allow upload progress to refine an unknown size
+ // (browser couldn't compute it at enqueue time).
+ size: t.size || action.total,
+ }
+ : t,
+ );
+ case 'UPLOAD_DONE':
+ return state.map((t) =>
+ t.taskId === action.taskId
+ ? {
+ ...t,
+ documentId: action.documentId,
+ phase: action.status,
+ loaded: t.size,
+ }
+ : t,
+ );
+ case 'UPLOAD_FAILED':
+ return state.map((t) =>
+ t.taskId === action.taskId ? { ...t, phase: 'error', error: action.error } : t,
+ );
+ case 'CANCEL':
+ return state.map((t) =>
+ t.taskId === action.taskId ? { ...t, phase: 'cancelled' } : t,
+ );
+ case 'REMOVE':
+ return state.filter((t) => t.taskId !== action.taskId);
+ case 'SERVER_STATUS': {
+ const byId = new Map(action.items.map((i) => [i.id, i]));
+ return state.map((t) => {
+ if (t.knowledgeBaseId !== action.knowledgeBaseId) return t;
+ if (!t.documentId) return t;
+ const match = byId.get(t.documentId);
+ if (!match) return t;
+ // Client-side terminal phases (`cancelled`) win — the
+ // server might still drive the doc to `ready`, but the
+ // user has signalled they no longer care.
+ if (t.phase === 'cancelled') return t;
+ if (t.phase === match.status && t.error === match.error) {
+ return t;
+ }
+ return {
+ ...t,
+ phase: match.status,
+ error: match.error,
+ };
+ });
+ }
+ case 'CLEAR_FINISHED':
+ return state.filter(
+ (t) => t.knowledgeBaseId !== action.knowledgeBaseId || !isTerminal(t.phase),
+ );
+ }
+}
+
+function newTaskId(): string {
+ if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
+ return crypto.randomUUID();
+ }
+ return `upload-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
+}
+
+interface UploadProviderProps {
+ children: ReactNode;
+}
+
+/**
+ * Mutable side-state for XHR controllers and scheduling flags.
+ *
+ * Lazy-initialised inside `useRef` (the factory form) so we never read
+ * `.current` during the initial render — and because the structure is
+ * a fixed shape of mutable maps, we can stash everything in a single
+ * `useRef` without violating the "no reading refs during render" rule:
+ * the reducer is the source of truth for render-relevant state, and
+ * these maps hold only opaque side-effects (Files, AbortControllers).
+ */
+interface UploadProviderRefs {
+ /** Map of taskId → File payload (kept off state; not serialisable). */
+ files: Map<string, File>;
+ /** Map of taskId → AbortController to cancel the in-flight XHR. */
+ controllers: Map<string, AbortController>;
+ /** Tasks the scheduler has already kicked off this lifetime. */
+ started: Set<string>;
+}
+
+export function UploadProvider({ children }: UploadProviderProps) {
+ const [tasks, dispatch] = useReducer(reducer, [] as UploadTask[]);
+ const refsRef = useRef<UploadProviderRefs | null>(null);
+ if (refsRef.current === null) {
+ refsRef.current = {
+ files: new Map(),
+ controllers: new Map(),
+ started: new Set(),
+ };
+ }
+
+ const startUpload = useCallback((task: UploadTask) => {
+ const refs = refsRef.current!;
+ const file = refs.files.get(task.taskId);
+ if (!file) {
+ dispatch({
+ type: 'UPLOAD_FAILED',
+ taskId: task.taskId,
+ error: 'Internal error: missing file payload.',
+ });
+ return;
+ }
+ const controller = new AbortController();
+ refs.controllers.set(task.taskId, controller);
+ dispatch({ type: 'START_UPLOAD', taskId: task.taskId });
+
+ knowledgeBaseApi
+ .uploadDocument(task.knowledgeBaseId, file, {
+ signal: controller.signal,
+ onProgress: ({ loaded, total }) => {
+ dispatch({
+ type: 'PROGRESS',
+ taskId: task.taskId,
+ loaded,
+ total,
+ });
+ },
+ })
+ .then((response) => {
+ dispatch({
+ type: 'UPLOAD_DONE',
+ taskId: task.taskId,
+ documentId: response.document_id,
+ status: response.status,
+ });
+ })
+ .catch((err: unknown) => {
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ // Already handled by the cancel() path.
+ return;
+ }
+ const message = err instanceof Error ? err.message : 'Upload failed.';
+ dispatch({
+ type: 'UPLOAD_FAILED',
+ taskId: task.taskId,
+ error: message,
+ });
+ })
+ .finally(() => {
+ refs.controllers.delete(task.taskId);
+ refs.files.delete(task.taskId);
+ });
+ }, []);
+
+ // Scheduler — fires after every state change. Idempotent thanks to
+ // `refs.started`, so StrictMode's double-effect is harmless.
+ useEffect(() => {
+ const refs = refsRef.current!;
+ const running = tasks.filter((t) => t.phase === 'uploading').length;
+ const queued = tasks.filter((t) => t.phase === 'queued');
+ const slots = MAX_CONCURRENT_UPLOADS - running;
+ if (slots <= 0 || queued.length === 0) return;
+ for (const task of queued.slice(0, slots)) {
+ if (refs.started.has(task.taskId)) continue;
+ refs.started.add(task.taskId);
+ startUpload(task);
+ }
+ }, [tasks, startUpload]);
+
+ const enqueue = useCallback((knowledgeBaseId: string, files: File[]): UploadTask[] => {
+ const refs = refsRef.current!;
+ const now = Date.now();
+ const newTasks = files.map((file): UploadTask => {
+ const taskId = newTaskId();
+ refs.files.set(taskId, file);
+ return {
+ taskId,
+ knowledgeBaseId,
+ filename: file.name,
+ size: file.size,
+ documentId: null,
+ phase: 'queued',
+ loaded: 0,
+ error: null,
+ createdAt: now,
+ };
+ });
+ dispatch({ type: 'ADD', tasks: newTasks });
+ return newTasks;
+ }, []);
+
+ const cancel = useCallback(
+ (taskId: string) => {
+ const refs = refsRef.current!;
+ const task = tasks.find((t) => t.taskId === taskId);
+ if (!task) return;
+ if (task.phase === 'queued') {
+ refs.files.delete(taskId);
+ dispatch({ type: 'REMOVE', taskId });
+ return;
+ }
+ if (task.phase === 'uploading') {
+ refs.controllers.get(taskId)?.abort();
+ dispatch({ type: 'CANCEL', taskId });
+ return;
+ }
+ if (isTerminal(task.phase)) {
+ dispatch({ type: 'REMOVE', taskId });
+ }
+ // Server-side phases are not cancellable here; the caller
+ // should use the regular document-delete API instead.
+ },
+ [tasks],
+ );
+
+ const dismiss = useCallback((taskId: string) => {
+ dispatch({ type: 'REMOVE', taskId });
+ }, []);
+
+ const clearFinishedForKb = useCallback((knowledgeBaseId: string) => {
+ dispatch({ type: 'CLEAR_FINISHED', knowledgeBaseId });
+ }, []);
+
+ const applyServerStatuses = useCallback<UploadContextValue['applyServerStatuses']>(
+ (knowledgeBaseId, items) => {
+ dispatch({ type: 'SERVER_STATUS', knowledgeBaseId, items });
+ },
+ [],
+ );
+
+ // `tasksForKb` and `pollableDocumentIds` need stable references per
+ // (knowledgeBaseId, tasks) tuple so downstream effects don't churn.
+ const byKb = useMemo(() => {
+ const out = new Map<string, UploadTask[]>();
+ for (const t of tasks) {
+ const list = out.get(t.knowledgeBaseId);
+ if (list) list.push(t);
+ else out.set(t.knowledgeBaseId, [t]);
+ }
+ return out;
+ }, [tasks]);
+
+ const tasksForKb = useCallback(
+ (knowledgeBaseId: string): UploadTask[] => byKb.get(knowledgeBaseId) ?? [],
+ [byKb],
+ );
+
+ const pollableDocumentIds = useCallback(
+ (knowledgeBaseId: string): string[] => {
+ const list = byKb.get(knowledgeBaseId);
+ if (!list) return [];
+ const out: string[] = [];
+ for (const t of list) {
+ if (!t.documentId) continue;
+ // `uploading` / `queued` have no documentId yet; only
+ // server-side non-terminal phases are pollable.
+ if (
+ t.phase === 'pending' ||
+ t.phase === 'parsing' ||
+ t.phase === 'chunking' ||
+ t.phase === 'indexing'
+ ) {
+ out.push(t.documentId);
+ }
+ }
+ return out;
+ },
+ [byKb],
+ );
+
+ // Warn before navigation when in-flight tasks would be lost.
+ // `uploading` tasks die with the page; server-side phases survive,
+ // so they do not trigger the warning.
+ useEffect(() => {
+ const hasInFlightUpload = tasks.some(
+ (t) => t.phase === 'queued' || t.phase === 'uploading',
+ );
+ if (!hasInFlightUpload) return;
+ const handler = (e: BeforeUnloadEvent) => {
+ e.preventDefault();
+ // Chrome / Edge require returnValue to be set.
+ e.returnValue = '';
+ };
+ window.addEventListener('beforeunload', handler);
+ return () => window.removeEventListener('beforeunload', handler);
+ }, [tasks]);
+
+ const value = useMemo<UploadContextValue>(
+ () => ({
+ tasks,
+ enqueue,
+ cancel,
+ dismiss,
+ clearFinishedForKb,
+ tasksForKb,
+ applyServerStatuses,
+ pollableDocumentIds,
+ }),
+ [
+ tasks,
+ enqueue,
+ cancel,
+ dismiss,
+ clearFinishedForKb,
+ tasksForKb,
+ applyServerStatuses,
+ pollableDocumentIds,
+ ],
+ );
+
+ return <UploadContext.Provider value={value}>{children}</UploadContext.Provider>;
+}
+
+export function useUploadContext(): UploadContextValue {
+ const ctx = useContext(UploadContext);
+ if (!ctx) {
+ throw new Error('useUploadContext must be used inside <UploadProvider>');
+ }
+ return ctx;
+}
diff --git a/examples/web_ui/frontend/src/context/uploadTypes.ts b/examples/web_ui/frontend/src/context/uploadTypes.ts
new file mode 100644
index 000000000..5dd36814b
--- /dev/null
+++ b/examples/web_ui/frontend/src/context/uploadTypes.ts
@@ -0,0 +1,44 @@
+import type { KnowledgeDocumentStatus } from '@/api';
+
+/**
+ * Lifecycle states a client-visible upload task can be in.
+ *
+ * The first two (`queued`, `uploading`) are pure client states. After
+ * the upload endpoint returns we mirror the server's
+ * :type:`KnowledgeDocumentStatus`. `cancelled` is also a client-side
+ * terminal — set when the user aborts before the upload completes.
+ */
+export type UploadPhase = 'queued' | 'uploading' | KnowledgeDocumentStatus | 'cancelled';
+
+export interface UploadTask {
+ /** Stable client-side id; survives across React renders. */
+ taskId: string;
+ knowledgeBaseId: string;
+ filename: string;
+ /** Total bytes; `0` only when the browser cannot compute it. */
+ size: number;
+ /** Server-assigned document id — `null` until upload returns 201. */
+ documentId: string | null;
+ phase: UploadPhase;
+ /** Bytes uploaded so far; meaningful only during `uploading`. */
+ loaded: number;
+ /** Human-readable failure reason; non-null only when `phase === 'error'`. */
+ error: string | null;
+ createdAt: number;
+}
+
+export function isTerminal(phase: UploadPhase): boolean {
+ return phase === 'ready' || phase === 'error' || phase === 'cancelled';
+}
+
+export function isInFlight(phase: UploadPhase): boolean {
+ return !isTerminal(phase);
+}
+
+/**
+ * Maximum number of upload tasks transferring bytes at once. Queued
+ * tasks above this cap wait until a slot frees up. Server-side phases
+ * (`pending`/`parsing`/…) do not count against the cap — they finish
+ * out of band.
+ */
+export const MAX_CONCURRENT_UPLOADS = 3;
diff --git a/examples/web_ui/frontend/src/hooks/useDocumentStatusPolling.ts b/examples/web_ui/frontend/src/hooks/useDocumentStatusPolling.ts
new file mode 100644
index 000000000..9c6b02044
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useDocumentStatusPolling.ts
@@ -0,0 +1,136 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+
+import { knowledgeBaseApi } from '@/api';
+import type { KnowledgeDocumentView } from '@/api';
+import { useUploadContext } from '@/context/UploadContext';
+
+const POLL_INTERVAL_MS = 1500;
+
+/**
+ * Document ids the polling loop should track each tick. Combines:
+ *
+ * - documents the local `UploadProvider` is still expecting transitions
+ * for (so a freshly-uploaded file polls without waiting for the next
+ * list refresh);
+ * - documents the caller knows are non-terminal from a server list
+ * (so a page reload mid-indexing keeps polling without lifting the
+ * upload through the provider).
+ *
+ * Ids that resolve to a terminal state (`ready` / `error`) drop out
+ * automatically — the polling loop stops as soon as the union becomes
+ * empty.
+ */
+interface PollingInput {
+ knowledgeBaseId: string | null;
+ /** Currently-listed server documents. */
+ documents: KnowledgeDocumentView[];
+}
+
+interface PollingResult {
+ /** Most-recent status views, keyed by document id. */
+ statuses: Record<string, KnowledgeDocumentView>;
+ /** True while the loop is actively scheduling refreshes. */
+ polling: boolean;
+}
+
+/**
+ * Conditional polling — only schedules a request when there is at least
+ * one non-terminal document id to watch. The loop self-stops as soon as
+ * every tracked id reaches `ready` / `error`, and rewires automatically
+ * when new ids enter the set (a fresh upload, a re-mount, etc.).
+ *
+ * Single source of truth for the `UploadProvider`'s server-side phase
+ * mirror: every tick that returns items is fanned out through
+ * `applyServerStatuses`, so the in-flight upload cards reflect the
+ * worker's progress without any extra wiring at the call site.
+ */
+export function useDocumentStatusPolling({
+ knowledgeBaseId,
+ documents,
+}: PollingInput): PollingResult {
+ const { pollableDocumentIds, applyServerStatuses } = useUploadContext();
+
+ // Server-side non-terminal docs from the list (catches reload state).
+ const docIds = useMemo(() => {
+ const out: string[] = [];
+ for (const d of documents) {
+ if (d.status !== 'ready' && d.status !== 'error') {
+ out.push(d.id);
+ }
+ }
+ return out;
+ }, [documents]);
+
+ // Stable, sorted union of server-side non-terminal docs (catches
+ // reload state) and locally-tracked in-flight docs from the upload
+ // provider. Used both as the request payload and as the effect
+ // dependency key so dropping/adding a single id triggers exactly
+ // one effect re-run.
+ const watchIdsKey = useMemo(() => {
+ const set = new Set<string>(docIds);
+ if (knowledgeBaseId) {
+ for (const id of pollableDocumentIds(knowledgeBaseId)) {
+ set.add(id);
+ }
+ }
+ return Array.from(set).sort().join(',');
+ }, [docIds, knowledgeBaseId, pollableDocumentIds]);
+
+ const [statuses, setStatuses] = useState<Record<string, KnowledgeDocumentView>>({});
+
+ // Mutable refs keep the running interval alive across re-renders
+ // without forcing the effect to restart on every state change.
+ const inflightRef = useRef<AbortController | null>(null);
+
+ useEffect(() => {
+ if (!knowledgeBaseId) return;
+ const ids = watchIdsKey ? watchIdsKey.split(',') : [];
+ if (ids.length === 0) return;
+
+ let cancelled = false;
+
+ const tick = async () => {
+ if (cancelled) return;
+ inflightRef.current?.abort();
+ const controller = new AbortController();
+ inflightRef.current = controller;
+ try {
+ const { items } = await knowledgeBaseApi.getDocumentStatus(knowledgeBaseId, ids);
+ if (cancelled) return;
+ setStatuses((prev) => {
+ const next = { ...prev };
+ for (const item of items) next[item.id] = item;
+ return next;
+ });
+ applyServerStatuses(
+ knowledgeBaseId,
+ items.map((i) => ({
+ id: i.id,
+ status: i.status,
+ error: i.error,
+ })),
+ );
+ } catch {
+ // Swallow transient errors — the next tick will retry.
+ // We deliberately don't surface a toast: a flaky network
+ // shouldn't spam the user while indexing is in the
+ // background.
+ }
+ };
+
+ // Fire immediately so the first reading lands without waiting a
+ // full poll interval (important right after an upload).
+ void tick();
+ const handle = window.setInterval(tick, POLL_INTERVAL_MS);
+ return () => {
+ cancelled = true;
+ inflightRef.current?.abort();
+ window.clearInterval(handle);
+ };
+ }, [knowledgeBaseId, watchIdsKey, applyServerStatuses]);
+
+ return {
+ statuses,
+ polling: watchIdsKey.length > 0,
+ };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useKbEmbeddingModels.ts b/examples/web_ui/frontend/src/hooks/useKbEmbeddingModels.ts
new file mode 100644
index 000000000..da9187204
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useKbEmbeddingModels.ts
@@ -0,0 +1,39 @@
+import { useCallback, useEffect, useState } from 'react';
+
+import { knowledgeBaseApi } from '@/api';
+import type { DimensionPolicy, KbEmbeddingProvider } from '@/api';
+
+/**
+ * Fetches the list of embedding models a user can pick at KB-creation
+ * time. Server-side already filtered by the manager's
+ * :class:`DimensionPolicy`; the UI just renders.
+ *
+ * Refetches when ``refetchTrigger`` changes (e.g. after a credential
+ * was created), mirroring the contract used by other selectors.
+ */
+export function useKbEmbeddingModels(refetchTrigger?: number) {
+ const [providers, setProviders] = useState<KbEmbeddingProvider[]>([]);
+ const [policy, setPolicy] = useState<DimensionPolicy | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+
+ const refetch = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const res = await knowledgeBaseApi.listEmbeddingModels();
+ setProviders(res.providers);
+ setPolicy(res.policy);
+ } catch (e) {
+ setError(e as Error);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ refetch();
+ }, [refetch, refetchTrigger]);
+
+ return { providers, policy, loading, error, refetch };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useKnowledgeBaseMiddlewareSchema.ts b/examples/web_ui/frontend/src/hooks/useKnowledgeBaseMiddlewareSchema.ts
new file mode 100644
index 000000000..844603215
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useKnowledgeBaseMiddlewareSchema.ts
@@ -0,0 +1,72 @@
+import { useEffect, useState } from 'react';
+
+import { knowledgeBaseApi } from '@/api';
+import type { JSONSchema } from '@/api';
+
+/**
+ * Module-level cache for the KB middleware parameter schema.
+ *
+ * The schema is class-static on the backend (derived from
+ * :class:`KnowledgeBaseMiddleware.Parameters.model_json_schema()`),
+ * so a single fetch per page load is enough. Several mounted
+ * `KnowledgeBasePanel`s would otherwise each fire the request — the
+ * cache de-duplicates concurrent callers, too.
+ */
+let cached: JSONSchema | null = null;
+let inflight: Promise<JSONSchema> | null = null;
+
+async function fetchSchema(): Promise<JSONSchema> {
+ if (cached) return cached;
+ if (inflight) return inflight;
+ inflight = knowledgeBaseApi
+ .middlewareParametersSchema()
+ .then((res) => {
+ cached = res.parameter_schema as unknown as JSONSchema;
+ return cached;
+ })
+ .finally(() => {
+ inflight = null;
+ });
+ return inflight;
+}
+
+/**
+ * Fetch the parameter schema for the session-level
+ * `KnowledgeBaseMiddleware`.
+ *
+ * Returns the schema once available; `null` while loading. The schema
+ * is shared across all callers via a module-level cache.
+ */
+export function useKnowledgeBaseMiddlewareSchema(): {
+ schema: JSONSchema | null;
+ loading: boolean;
+ error: Error | null;
+} {
+ const [schema, setSchema] = useState<JSONSchema | null>(cached);
+ const [loading, setLoading] = useState(cached === null);
+ const [error, setError] = useState<Error | null>(null);
+
+ useEffect(() => {
+ if (cached) {
+ setSchema(cached);
+ return;
+ }
+ let cancelled = false;
+ setLoading(true);
+ fetchSchema()
+ .then((s) => {
+ if (!cancelled) setSchema(s);
+ })
+ .catch((e) => {
+ if (!cancelled) setError(e as Error);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return { schema, loading, error };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useKnowledgeBases.ts b/examples/web_ui/frontend/src/hooks/useKnowledgeBases.ts
new file mode 100644
index 000000000..b66631e9e
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useKnowledgeBases.ts
@@ -0,0 +1,116 @@
+import { useCallback, useEffect, useState } from 'react';
+
+import { knowledgeBaseApi } from '@/api';
+import type {
+ CreateKnowledgeBaseRequest,
+ KnowledgeBaseView,
+ SearchKnowledgeBaseRequest,
+ UpdateKnowledgeBaseRequest,
+} from '@/api';
+
+/**
+ * Knowledge base CRUD + search wrapper.
+ *
+ * Loads the caller's knowledge bases from `/knowledge_bases/` on mount
+ * and refetches after every mutation, so the UI stays consistent with
+ * the server-side state.
+ */
+export function useKnowledgeBases() {
+ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBaseView[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [creating, setCreating] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+
+ const refetch = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const { knowledge_bases } = await knowledgeBaseApi.list();
+ setKnowledgeBases(knowledge_bases);
+ } catch (e) {
+ setError(e as Error);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ refetch();
+ }, [refetch]);
+
+ /** Create a new knowledge base and refresh the list. */
+ const create = useCallback(
+ async (body: CreateKnowledgeBaseRequest): Promise<string> => {
+ setCreating(true);
+ setError(null);
+ try {
+ const { knowledge_base_id } = await knowledgeBaseApi.create(body);
+ await refetch();
+ return knowledge_base_id;
+ } catch (e) {
+ setError(e as Error);
+ throw e;
+ } finally {
+ setCreating(false);
+ }
+ },
+ [refetch],
+ );
+
+ /** Permanently delete a knowledge base and refresh the list. */
+ const remove = useCallback(
+ async (knowledgeBaseId: string) => {
+ await knowledgeBaseApi.delete(knowledgeBaseId);
+ await refetch();
+ },
+ [refetch],
+ );
+
+ /** Update mutable fields on a knowledge base and refresh the list. */
+ const update = useCallback(
+ async (
+ knowledgeBaseId: string,
+ body: UpdateKnowledgeBaseRequest,
+ ): Promise<KnowledgeBaseView> => {
+ const view = await knowledgeBaseApi.update(knowledgeBaseId, body);
+ await refetch();
+ return view;
+ },
+ [refetch],
+ );
+
+ /** Upload a document into a knowledge base. */
+ const uploadDocument = useCallback(
+ (knowledgeBaseId: string, file: File) =>
+ knowledgeBaseApi.uploadDocument(knowledgeBaseId, file),
+ [],
+ );
+
+ /** Delete a document from a knowledge base. */
+ const deleteDocument = useCallback(
+ (knowledgeBaseId: string, documentId: string) =>
+ knowledgeBaseApi.deleteDocument(knowledgeBaseId, documentId),
+ [],
+ );
+
+ /** Search a knowledge base by natural-language query. */
+ const search = useCallback(
+ (knowledgeBaseId: string, body: SearchKnowledgeBaseRequest) =>
+ knowledgeBaseApi.search(knowledgeBaseId, body),
+ [],
+ );
+
+ return {
+ knowledgeBases,
+ loading,
+ creating,
+ error,
+ refetch,
+ create,
+ remove,
+ update,
+ uploadDocument,
+ deleteDocument,
+ search,
+ };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useKnowledgeDocuments.ts b/examples/web_ui/frontend/src/hooks/useKnowledgeDocuments.ts
new file mode 100644
index 000000000..115f5cd53
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useKnowledgeDocuments.ts
@@ -0,0 +1,47 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { knowledgeBaseApi } from '@/api';
+import type { KnowledgeDocumentView } from '@/api';
+
+/**
+ * Owns the document list for a single knowledge base.
+ *
+ * Re-fetches on mount, when `knowledgeBaseId` changes, and via the
+ * caller-driven `refetch`. The upload page should call `refetch` after
+ * a successful upload (so the new `pending` row appears) and again
+ * whenever a polling tick lifts a row to a terminal state (so
+ * `chunk_count` reflects the worker's final commit).
+ */
+export function useKnowledgeDocuments(knowledgeBaseId: string | null) {
+ const [documents, setDocuments] = useState<KnowledgeDocumentView[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+ // Discards stale responses if the user switches KBs mid-flight.
+ const requestSeq = useRef(0);
+
+ const refetch = useCallback(async () => {
+ if (!knowledgeBaseId) {
+ setDocuments([]);
+ return;
+ }
+ const seq = ++requestSeq.current;
+ setLoading(true);
+ setError(null);
+ try {
+ const { documents: list } = await knowledgeBaseApi.listDocuments(knowledgeBaseId);
+ if (seq !== requestSeq.current) return;
+ setDocuments(list);
+ } catch (e) {
+ if (seq !== requestSeq.current) return;
+ setError(e as Error);
+ } finally {
+ if (seq === requestSeq.current) setLoading(false);
+ }
+ }, [knowledgeBaseId]);
+
+ useEffect(() => {
+ void refetch();
+ }, [refetch]);
+
+ return { documents, loading, error, refetch, setDocuments };
+}
diff --git a/examples/web_ui/frontend/src/hooks/useKnowledgeSupportedContentTypes.ts b/examples/web_ui/frontend/src/hooks/useKnowledgeSupportedContentTypes.ts
new file mode 100644
index 000000000..254516a53
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useKnowledgeSupportedContentTypes.ts
@@ -0,0 +1,78 @@
+import { useEffect, useState } from 'react';
+
+import { knowledgeBaseApi } from '@/api';
+import type { ListSupportedContentTypesResponse } from '@/api';
+
+/**
+ * Module-level cache for the KB-parser capability list.
+ *
+ * The set of supported media types / extensions is fixed at app
+ * startup — it is derived from the parser registry handed to
+ * `create_app()`, which never changes for the lifetime of the process.
+ * One fetch per page load is enough, and several mounted document
+ * panels share the same cached value.
+ */
+let cached: ListSupportedContentTypesResponse | null = null;
+let inflight: Promise<ListSupportedContentTypesResponse> | null = null;
+
+async function fetchSupported(): Promise<ListSupportedContentTypesResponse> {
+ if (cached) return cached;
+ if (inflight) return inflight;
+ inflight = knowledgeBaseApi
+ .supportedContentTypes()
+ .then((res) => {
+ cached = res;
+ return res;
+ })
+ .finally(() => {
+ inflight = null;
+ });
+ return inflight;
+}
+
+/**
+ * Fetch the parser-supported upload types.
+ *
+ * Returns the union of media types and extensions once available; an
+ * empty placeholder while loading. The result is shared across all
+ * callers via a module-level cache.
+ */
+export function useKnowledgeSupportedContentTypes(): {
+ mediaTypes: string[];
+ extensions: string[];
+ loading: boolean;
+ error: Error | null;
+} {
+ const [data, setData] = useState<ListSupportedContentTypesResponse | null>(cached);
+ const [loading, setLoading] = useState(cached === null);
+ const [error, setError] = useState<Error | null>(null);
+
+ useEffect(() => {
+ if (cached) {
+ setData(cached);
+ return;
+ }
+ let cancelled = false;
+ setLoading(true);
+ fetchSupported()
+ .then((res) => {
+ if (!cancelled) setData(res);
+ })
+ .catch((e) => {
+ if (!cancelled) setError(e as Error);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return {
+ mediaTypes: data?.media_types ?? [],
+ extensions: data?.extensions ?? [],
+ loading,
+ error,
+ };
+}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index cea794fd8..64144acfc 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -17,6 +17,7 @@
"error": "Something went wrong",
"information": "Information",
"interrupted": "Interrupted",
+ "knowledge": "Knowledge Bases",
"loading": "Loading...",
"model": "Model",
"name": "Name",
@@ -173,6 +174,58 @@
"title": "Edit Credential",
"description": "Update the saved credential for this provider."
},
+ "dialog-knowledge-base-create": {
+ "title": "Create knowledge base",
+ "description": "Create a new knowledge base using an embedding model.",
+ "name": {
+ "label": "Name",
+ "placeholder": "My knowledge base"
+ },
+ "descriptionField": {
+ "label": "Description",
+ "placeholder": "Describe what this knowledge base is for."
+ },
+ "embeddingModel": {
+ "label": "Embedding model"
+ },
+ "dimension": {
+ "label": "Dimension"
+ },
+ "policy": {
+ "lockedTitle": "Dimension is locked to {{dimension}}d",
+ "lockedDescription": "This server already pins all knowledge bases to {{dimension}}-dim embeddings. Only compatible models are listed below.",
+ "noCompatibleTitle": "No compatible embedding models",
+ "noCompatibleAny": "None of your credentials expose an embedding model. Add a credential first.",
+ "noCompatibleLocked": "None of your credentials expose a model that can produce {{dimension}}-dim embeddings."
+ },
+ "errors": {
+ "nameRequired": "Please give the knowledge base a name.",
+ "embeddingRequired": "Please pick an embedding model.",
+ "dimensionRequired": "Please pick a dimension."
+ }
+ },
+ "dialog-knowledge-base-edit": {
+ "title": "Edit knowledge base",
+ "description": "Update the knowledge base name and description.",
+ "name": {
+ "label": "Name",
+ "placeholder": "My knowledge base"
+ },
+ "descriptionField": {
+ "label": "Description",
+ "placeholder": "Describe what this knowledge base is for."
+ },
+ "embeddingModel": {
+ "label": "Embedding model"
+ },
+ "errors": {
+ "nameRequired": "Please give the knowledge base a name."
+ }
+ },
+ "dialog-knowledge-base-delete": {
+ "title": "Delete knowledge base",
+ "description": "This will permanently delete the knowledge base \"{{name}}\" and all of its indexed documents. This action cannot be undone."
+ },
"credential": {
"noProviders": "No providers available",
"noConfigs": "No configurations",
@@ -192,6 +245,70 @@
"outputTypes": "Output",
"availableTTSModels": "TTS Models"
},
+ "knowledge": {
+ "subtitle": "Manage knowledge bases used by your agents",
+ "selectHint": "No knowledge base selected",
+ "selectHintDescription": "Select a knowledge base from the sidebar to view its details.",
+ "deleteEntity": "knowledge base",
+ "list": {
+ "label": "Knowledge bases",
+ "emptyTitle": "No knowledge bases",
+ "emptyDescription": "Create a knowledge base to start indexing documents.",
+ "createButton": "Create knowledge base"
+ },
+ "document": {
+ "label": "Documents",
+ "emptyTitle": "No documents",
+ "emptyDescription": "Upload a document to index it into this knowledge base.",
+ "uploadButton": "Upload document",
+ "uploadButtonShort": "Upload",
+ "countLabel": "Documents ({{count}})",
+ "size": "Size",
+ "chunks": "Chunks",
+ "chunkCount_one": "{{count}} chunk",
+ "chunkCount_other": "{{count}} chunks",
+ "uploadedAt": "Uploaded {{when}}",
+ "deleteEntity": "document",
+ "deleteConfirmTitle": "Delete document",
+ "deleteConfirmDescription": "Delete \"{{name}}\"? This removes the document and every indexed chunk. This action cannot be undone.",
+ "deleteError": "Could not delete document.",
+ "dropHint": "Drop files here to upload",
+ "dropHintIdle": "or drop files here",
+ "invalidFile": "\"{{name}}\" could not be added.",
+ "unsupportedExtension": "\"{{name}}\" was skipped — file type not supported.",
+ "status": {
+ "queued": "Queued",
+ "uploading": "Uploading",
+ "pending": "Awaiting worker",
+ "parsing": "Parsing",
+ "chunking": "Chunking",
+ "indexing": "Indexing",
+ "ready": "Ready",
+ "error": "Error",
+ "cancelled": "Cancelled"
+ },
+ "actions": {
+ "cancel": "Cancel",
+ "retry": "Retry",
+ "dismiss": "Dismiss",
+ "remove": "Remove",
+ "clearFinished": "Clear finished"
+ }
+ },
+ "test": {
+ "button": "Test",
+ "title": "Test retrieval",
+ "description": "Probe \"{{name}}\" with an ad-hoc query.",
+ "queryLabel": "Query",
+ "queryPlaceholder": "Type a natural-language question…",
+ "topKLabel": "Top K",
+ "searchButton": "Search",
+ "score": "score",
+ "chunkPosition": "Chunk {{index}} of {{total}}",
+ "emptyTitle": "No matches",
+ "emptyDescription": "No chunks scored above the threshold for this query."
+ }
+ },
"llm-select": {
"placeholder": "Select a model",
"fallbackPlaceholder": "Fallback model",
@@ -205,6 +322,20 @@
"clear": "Clear selection",
"noFallback": "No fallback"
},
+ "embedding-select": {
+ "placeholder": "Select an embedding model",
+ "loading": "Loading…",
+ "empty": {
+ "title": "No embedding models available",
+ "description": "Add a credential that supports embedding to get started."
+ },
+ "addCredential": "Add Credential",
+ "clear": "Clear selection"
+ },
+ "dimension-select": {
+ "placeholder": "Select a dimension",
+ "pickModelFirst": "Pick a model first"
+ },
"permission-mode": {
"placeholder": "Select permission mode",
"trigger-tooltip": "Permission Mode",
@@ -371,6 +502,16 @@
"emptyTitle": "No skills",
"emptyDescription": "Add a skill to equip the workspace."
},
+ "knowledge": {
+ "title": "Knowledge Bases",
+ "description": "Knowledge bases the agent can retrieve from.",
+ "searchPlaceholder": "Search knowledge bases",
+ "emptyTitle": "No knowledge bases",
+ "emptyDescription": "Create one on the Knowledge Bases page first.",
+ "parametersTitle": "Retrieval settings",
+ "parametersDescription": "Knowledge base retrieval settings.",
+ "selectedCount": "{{count}} attached"
+ },
"permission": {
"title": "Permissions",
"description": "The permissions applied in this session.",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index d486e71ac..a858578a9 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -17,6 +17,7 @@
"error": "出错了",
"information": "信息",
"interrupted": "已中断",
+ "knowledge": "知识库",
"loading": "加载中...",
"model": "模型",
"name": "名称",
@@ -173,6 +174,58 @@
"title": "编辑凭证",
"description": "更新该提供商已保存的凭证。"
},
+ "dialog-knowledge-base-create": {
+ "title": "创建知识库",
+ "description": "使用 Embedding 模型创建新的知识库。",
+ "name": {
+ "label": "名称",
+ "placeholder": "我的知识库"
+ },
+ "descriptionField": {
+ "label": "描述",
+ "placeholder": "描述知识库用途"
+ },
+ "embeddingModel": {
+ "label": "Embedding 模型"
+ },
+ "dimension": {
+ "label": "维度"
+ },
+ "policy": {
+ "lockedTitle": "维度已锁定为 {{dimension}}d",
+ "lockedDescription": "当前实例已要求所有知识库使用 {{dimension}} 维 embedding,下面仅展示兼容的模型。",
+ "noCompatibleTitle": "暂无可用 Embedding 模型",
+ "noCompatibleAny": "你的凭证中没有任何可用的 Embedding 模型,请先添加凭证。",
+ "noCompatibleLocked": "你的凭证中没有任何模型支持 {{dimension}} 维 embedding。"
+ },
+ "errors": {
+ "nameRequired": "请填写知识库名称。",
+ "embeddingRequired": "请选择 Embedding 模型。",
+ "dimensionRequired": "请选择 Embedding 维度。"
+ }
+ },
+ "dialog-knowledge-base-edit": {
+ "title": "编辑知识库",
+ "description": "修改知识库的名称与描述。",
+ "name": {
+ "label": "名称",
+ "placeholder": "我的知识库"
+ },
+ "descriptionField": {
+ "label": "描述",
+ "placeholder": "描述知识库用途"
+ },
+ "embeddingModel": {
+ "label": "Embedding 模型"
+ },
+ "errors": {
+ "nameRequired": "请填写知识库名称。"
+ }
+ },
+ "dialog-knowledge-base-delete": {
+ "title": "删除知识库",
+ "description": "此操作将永久删除知识库 \"{{name}}\" 及其所有已索引文档,且无法撤销。"
+ },
"credential": {
"noProviders": "暂无可用提供商",
"noConfigs": "暂无配置",
@@ -192,6 +245,70 @@
"outputTypes": "输出模态",
"availableTTSModels": "语音合成模型"
},
+ "knowledge": {
+ "subtitle": "管理 Agent 使用的知识库",
+ "selectHint": "未选择知识库",
+ "selectHintDescription": "从左侧选择一个知识库以查看详情。",
+ "deleteEntity": "知识库",
+ "list": {
+ "label": "知识库",
+ "emptyTitle": "暂无知识库",
+ "emptyDescription": "创建知识库以开始索引文档。",
+ "createButton": "创建知识库"
+ },
+ "document": {
+ "label": "文档",
+ "emptyTitle": "暂无文档",
+ "emptyDescription": "上传文档以索引到该知识库中。",
+ "uploadButton": "上传文档",
+ "uploadButtonShort": "上传",
+ "countLabel": "文档({{count}})",
+ "size": "大小",
+ "chunks": "分块",
+ "chunkCount_one": "{{count}} 个分块",
+ "chunkCount_other": "{{count}} 个分块",
+ "uploadedAt": "{{when}} 上传",
+ "deleteEntity": "文档",
+ "deleteConfirmTitle": "删除文档",
+ "deleteConfirmDescription": "确认删除 \"{{name}}\"?该操作将一并移除文档及其全部已索引分块,且不可撤销。",
+ "deleteError": "删除文档失败。",
+ "dropHint": "拖拽文件到此处上传",
+ "dropHintIdle": "或拖拽文件到此处",
+ "invalidFile": "\"{{name}}\" 添加失败。",
+ "unsupportedExtension": "\"{{name}}\" 已跳过——不支持该文件类型。",
+ "status": {
+ "queued": "排队中",
+ "uploading": "上传中",
+ "pending": "等待处理",
+ "parsing": "解析中",
+ "chunking": "分块中",
+ "indexing": "建立索引",
+ "ready": "已就绪",
+ "error": "失败",
+ "cancelled": "已取消"
+ },
+ "actions": {
+ "cancel": "取消",
+ "retry": "重试",
+ "dismiss": "关闭",
+ "remove": "删除",
+ "clearFinished": "清除已完成"
+ }
+ },
+ "test": {
+ "button": "测试",
+ "title": "检索测试",
+ "description": "在 \"{{name}}\" 上发起一次临时检索。",
+ "queryLabel": "查询",
+ "queryPlaceholder": "输入自然语言问题…",
+ "topKLabel": "Top K",
+ "searchButton": "搜索",
+ "score": "分值",
+ "chunkPosition": "第 {{index}} / {{total}} 段",
+ "emptyTitle": "无匹配",
+ "emptyDescription": "本次查询没有返回任何分块。"
+ }
+ },
"llm-select": {
"placeholder": "选择模型",
"fallbackPlaceholder": "兜底模型",
@@ -205,6 +322,20 @@
"clear": "清除选择",
"noFallback": "无兜底模型"
},
+ "embedding-select": {
+ "placeholder": "选择 Embedding 模型",
+ "loading": "加载中…",
+ "empty": {
+ "title": "暂无可用的 Embedding 模型",
+ "description": "请先添加支持 Embedding 的凭证。"
+ },
+ "addCredential": "添加凭证",
+ "clear": "清除选择"
+ },
+ "dimension-select": {
+ "placeholder": "选择维度",
+ "pickModelFirst": "请先选择 Embedding 模型"
+ },
"permission-mode": {
"placeholder": "选择权限模式",
"trigger-tooltip": "权限模式",
@@ -371,6 +502,16 @@
"emptyTitle": "暂无技能",
"emptyDescription": "添加技能为工作区配备能力。"
},
+ "knowledge": {
+ "title": "知识库",
+ "description": "智能体可检索的知识库。",
+ "searchPlaceholder": "搜索知识库",
+ "emptyTitle": "暂无知识库",
+ "emptyDescription": "请先在「知识库」页面创建一个。",
+ "parametersTitle": "检索配置",
+ "parametersDescription": "知识库检索参数设置",
+ "selectedCount": "已挂载 {{count}} 个"
+ },
"permission": {
"title": "权限",
"description": "本会话应用的权限。",
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index aeb043e53..20b038288 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -1,19 +1,21 @@
import type { PermissionContext } from '@agentscope-ai/agentscope/permission';
import type { TaskContext } from '@agentscope-ai/agentscope/state';
-import { BookText, ChevronDown, ListTodo, PanelRight, ShieldCheck } from 'lucide-react';
+import { BookText, ChevronDown, Database, ListTodo, PanelRight, ShieldCheck } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
-import type { ChatModelConfig, TTSModelConfig } from '@/api';
+import type { ChatModelConfig, SessionKnowledgeConfig, TTSModelConfig } from '@/api';
import { sessionApi } from '@/api';
import MCPSvg from '@/assets/images/mcp.svg?react';
import { ChatContent } from '@/components/chat/ChatContent.tsx';
import { SubagentHitlCard } from '@/components/chat/SubagentHitlCard';
import { CreateCredentialDialog } from '@/components/dialog/CreateCredentialDialog';
+import { KnowledgeBasePanel } from '@/components/panel/KnowledgeBasePanel';
import { McpPanel } from '@/components/panel/McpPanel';
import { PanelDock, type PanelDescriptor, type PanelKey } from '@/components/panel/PanelDock.tsx';
import { PermissionPanel } from '@/components/panel/PermissionPanel';
import { SkillPanel } from '@/components/panel/SkillPanel';
import { TaskPanel } from '@/components/panel/TaskPanel';
+import { KnowledgeBaseParametersPopover } from '@/components/popover/KnowledgeBaseParametersPopover';
import { ModelParametersPopover } from '@/components/popover/ModelParametersPopover';
import { LlmSelect } from '@/components/select/LlmSelect';
import { PermissionModeSelect } from '@/components/select/PermissionModeSelect.tsx';
@@ -32,6 +34,8 @@ import {
} from '@/components/ui/resizable.tsx';
import { SidebarTrigger } from '@/components/ui/sidebar';
import { useAvailableModels } from '@/hooks/useAvailableModels';
+import { useKnowledgeBaseMiddlewareSchema } from '@/hooks/useKnowledgeBaseMiddlewareSchema';
+import { useKnowledgeBases } from '@/hooks/useKnowledgeBases';
import { useMessages } from '@/hooks/useMessages';
import { useSessions } from '@/hooks/useSessions';
import { useWorkspace } from '@/hooks/useWorkspace.ts';
@@ -132,6 +136,8 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
null,
);
const [selectedTTSModel, setSelectedTTSModel] = useState<TTSModelConfig | null>(null);
+ const [selectedKnowledgeConfig, setSelectedKnowledgeConfig] =
+ useState<SessionKnowledgeConfig | null>(null);
const [selectedPermissionMode, setSelectedPermissionMode] = useState<string>('default');
const [credentialOpen, setCredentialOpen] = useState(false);
const [credentialRefetchTrigger, setCredentialRefetchTrigger] = useState(0);
@@ -168,6 +174,8 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
addSkill,
removeSkill,
} = useWorkspace(agentId, sessionId);
+ const { knowledgeBases, loading: knowledgeBasesLoading } = useKnowledgeBases();
+ const { schema: kbMiddlewareSchema } = useKnowledgeBaseMiddlewareSchema();
// Toggle a panel open/closed from the top-bar buttons.
const togglePanel = useCallback((key: PanelKey) => {
@@ -188,6 +196,28 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
[panelLayout],
);
+ /**
+ * Persist a knowledge-base attachment change. `null` detaches every
+ * knowledge base from this session, removing the `RAGMiddleware`.
+ *
+ * Declared above `panels` (rather than alongside the other model
+ * handlers below) because `panels` is built inside `useMemo` and
+ * references this handler eagerly — a later `const` would still be
+ * in the temporal dead zone when the memo factory runs on first
+ * render.
+ *
+ * @param config - New attachment, or `null` to detach all.
+ */
+ const handleKnowledgeConfigChange = useCallback(
+ async (config: SessionKnowledgeConfig | null) => {
+ if (!sessionId || !agentId) return;
+ setSelectedKnowledgeConfig(config);
+ await sessionApi.update(sessionId, agentId, { knowledge_config: config });
+ await refetchSessions();
+ },
+ [sessionId, agentId, refetchSessions],
+ );
+
// Build the panel descriptors with live data. Rebuilt on every
// data change so the dock always renders the latest state — the
// dock itself stays free of any data dependency.
@@ -236,6 +266,36 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
icon: <ShieldCheck className="size-4" />,
content: <PermissionPanel permissionContext={permissionContext} />,
},
+ knowledge: {
+ title: (
+ <span className="flex items-center gap-x-2">
+ {t('panel.knowledge.title')}
+ {selectedKnowledgeConfig?.knowledge_base_ids.length ? (
+ <Badge variant="outline">
+ {selectedKnowledgeConfig.knowledge_base_ids.length}
+ </Badge>
+ ) : null}
+ </span>
+ ),
+ icon: <Database className="size-4" />,
+ actions: (
+ <KnowledgeBaseParametersPopover
+ value={selectedKnowledgeConfig}
+ schema={kbMiddlewareSchema}
+ onChange={handleKnowledgeConfigChange}
+ disabled={!sessionId}
+ />
+ ),
+ content: (
+ <KnowledgeBasePanel
+ knowledgeBases={knowledgeBases}
+ loading={knowledgeBasesLoading}
+ value={selectedKnowledgeConfig}
+ onChange={handleKnowledgeConfigChange}
+ disabled={!sessionId}
+ />
+ ),
+ },
}),
[
t,
@@ -249,6 +309,12 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
addSkill,
removeSkill,
permissionContext,
+ knowledgeBases,
+ knowledgeBasesLoading,
+ selectedKnowledgeConfig,
+ kbMiddlewareSchema,
+ handleKnowledgeConfigChange,
+ sessionId,
],
);
@@ -277,6 +343,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
setSelectedModel(null);
setSelectedFallbackModel(null);
setSelectedTTSModel(null);
+ setSelectedKnowledgeConfig(null);
}, [sessionId]);
const selectedModelCard = useMemo(() => {
@@ -381,6 +448,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
setSelectedFallbackModel(view.session.config.fallback_chat_model_config ?? null);
setSelectedTTSModel(view.session.config.tts_model_config ?? null);
+ setSelectedKnowledgeConfig(view.session.config.knowledge_config ?? null);
}, [view, groups, sessionId, agentId]);
// Sync selectedPermissionMode when the session changes. Same
@@ -534,6 +602,14 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
<ShieldCheck />
{t('panel.permission.title')}
</DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={isPanelOpen('knowledge')}
+ onCheckedChange={() => togglePanel('knowledge')}
+ onSelect={(e) => e.preventDefault()}
+ >
+ <Database />
+ {t('panel.knowledge.title')}
+ </DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/examples/web_ui/frontend/src/pages/credential/index.tsx b/examples/web_ui/frontend/src/pages/credential/index.tsx
index 7399bc2bb..0301ccb25 100644
--- a/examples/web_ui/frontend/src/pages/credential/index.tsx
+++ b/examples/web_ui/frontend/src/pages/credential/index.tsx
@@ -362,7 +362,7 @@ export const CredentialPage = () => {
return (
<div className="flex h-full w-full">
{/* Left sidebar */}
- <Sidebar collapsible="none" className="w-72 border-r">
+ <Sidebar collapsible="none" className="border-r">
<SidebarHeader className={'flex flex-col mt-5 gap-y-1'}>
<div className="text-lg font-semibold">{t('common.credential')}</div>
<div className="text-muted-foreground text-xs">{t('credential.subtitle')}</div>
diff --git a/examples/web_ui/frontend/src/pages/knowledge/index.tsx b/examples/web_ui/frontend/src/pages/knowledge/index.tsx
new file mode 100644
index 000000000..f1485c44c
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/knowledge/index.tsx
@@ -0,0 +1,261 @@
+import { Ellipsis, Files, FlaskConical, Pencil, Plus, Trash2 } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import type { KnowledgeBaseView } from '@/api';
+import { CreateCredentialDialog } from '@/components/dialog/CreateCredentialDialog.tsx';
+import { CreateKnowledgeBaseDialog } from '@/components/dialog/CreateKnowledgeBaseDialog.tsx';
+import { DeleteDialog } from '@/components/dialog/DeleteDialog.tsx';
+import { EditKnowledgeBaseDialog } from '@/components/dialog/EditKnowledgeBaseDialog.tsx';
+import { KnowledgeSearchDrawer } from '@/components/drawer/KnowledgeSearchDrawer.tsx';
+import { KnowledgeDocumentsPanel } from '@/components/knowledge/KnowledgeDocumentsPanel.tsx';
+import { Button } from '@/components/ui/button.tsx';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu.tsx';
+import {
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty.tsx';
+import { Separator } from '@/components/ui/separator.tsx';
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarFooter,
+ SidebarGroup,
+ SidebarGroupAction,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarMenu,
+ SidebarMenuAction,
+ SidebarMenuButton,
+ SidebarMenuItem,
+} from '@/components/ui/sidebar.tsx';
+import { useKnowledgeBases } from '@/hooks/useKnowledgeBases.ts';
+
+interface DetailPanelProps {
+ knowledgeBase?: KnowledgeBaseView;
+ onTest?: () => void;
+}
+
+function DetailPanel({ knowledgeBase, onTest }: DetailPanelProps) {
+ const { t } = useTranslation();
+
+ if (!knowledgeBase) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Empty className="border-none">
+ <EmptyHeader>
+ <EmptyTitle>{t('knowledge.selectHint')}</EmptyTitle>
+ <EmptyDescription>{t('knowledge.selectHintDescription')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-y-6 p-6 overflow-y-auto h-full">
+ {/* Header */}
+ <div className="flex items-start justify-between gap-x-4">
+ <div className="flex flex-col gap-y-1 min-w-0">
+ <h2 className="text-lg font-semibold truncate">{knowledgeBase.name}</h2>
+ {knowledgeBase.description ? (
+ <p className="text-sm text-muted-foreground">{knowledgeBase.description}</p>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-x-2 shrink-0">
+ <Button size="sm" variant="outline" onClick={onTest}>
+ <FlaskConical className="size-3.5" />
+ {t('knowledge.test.button')}
+ </Button>
+ </div>
+ </div>
+
+ <Separator />
+
+ {/* Documents */}
+ <KnowledgeDocumentsPanel knowledgeBaseId={knowledgeBase.id} />
+ </div>
+ );
+}
+
+export const KnowledgePage = () => {
+ const navigate = useNavigate();
+ const { kbId: urlKbId } = useParams<{ kbId?: string }>();
+ const { t } = useTranslation();
+
+ const { knowledgeBases, remove, refetch } = useKnowledgeBases();
+ const [selectedKbId, setSelectedKbId] = useState<string | undefined>(urlKbId);
+ const [createDialogOpen, setCreateDialogOpen] = useState(false);
+ const [credentialOpen, setCredentialOpen] = useState(false);
+ const [credentialRefetchTrigger, setCredentialRefetchTrigger] = useState(0);
+
+ const [editTarget, setEditTarget] = useState<KnowledgeBaseView | null>(null);
+ const [deleteTarget, setDeleteTarget] = useState<KnowledgeBaseView | null>(null);
+ const [testOpen, setTestOpen] = useState(false);
+
+ const selectedKb = knowledgeBases.find((kb) => kb.id === selectedKbId);
+
+ const handleCreated = async (knowledgeBaseId: string) => {
+ await refetch();
+ setSelectedKbId(knowledgeBaseId);
+ navigate(`/knowledge/${knowledgeBaseId}`);
+ };
+
+ const handleConfirmDelete = async () => {
+ if (!deleteTarget) return;
+ const id = deleteTarget.id;
+ await remove(id);
+ await refetch();
+ if (selectedKbId === id) {
+ setSelectedKbId(undefined);
+ navigate('/knowledge');
+ }
+ };
+
+ return (
+ <div className="flex size-full">
+ <Sidebar collapsible="none" className="border-r">
+ <SidebarHeader className={'flex flex-col mt-5 gap-y-1'}>
+ <div className="text-lg font-semibold">{t('common.knowledge')}</div>
+ <div className="text-muted-foreground text-xs">{t('knowledge.subtitle')}</div>
+ </SidebarHeader>
+ <SidebarContent className="my-5">
+ <SidebarGroup>
+ <SidebarGroupLabel>{t('knowledge.list.label')}</SidebarGroupLabel>
+ <SidebarGroupAction>
+ <Button
+ size="icon-xs"
+ variant="default"
+ onClick={() => setCreateDialogOpen(true)}
+ >
+ <Plus />
+ </Button>
+ </SidebarGroupAction>
+ <SidebarGroupContent>
+ {knowledgeBases.length === 0 ? (
+ <Empty className="border-none py-4 min-h-50">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Files />
+ </EmptyMedia>
+ <EmptyTitle>{t('knowledge.list.emptyTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {t('knowledge.list.emptyDescription')}
+ </EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setCreateDialogOpen(true)}
+ >
+ <Plus />
+ {t('knowledge.list.createButton')}
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : (
+ <SidebarMenu>
+ {knowledgeBases.map((kb) => {
+ return (
+ <SidebarMenuItem key={kb.id}>
+ <SidebarMenuButton
+ isActive={urlKbId === kb.id}
+ onClick={() => {
+ setSelectedKbId(kb.id);
+ navigate(`/knowledge/${kb.id}`);
+ }}
+ >
+ <span className="truncate">{kb.name}</span>
+ </SidebarMenuButton>
+ <SidebarMenuAction showOnHover>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Ellipsis />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="right"
+ align="start"
+ >
+ <DropdownMenuItem
+ onClick={() => setEditTarget(kb)}
+ >
+ <Pencil />
+ {t('common.edit')}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteTarget(kb)}
+ >
+ <Trash2 />
+ {t('common.delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SidebarMenuAction>
+ </SidebarMenuItem>
+ );
+ })}
+ </SidebarMenu>
+ )}
+ </SidebarGroupContent>
+ </SidebarGroup>
+ </SidebarContent>
+ <SidebarFooter />
+ </Sidebar>
+ <main className="flex-1 min-h-0 overflow-hidden">
+ <DetailPanel knowledgeBase={selectedKb} onTest={() => setTestOpen(true)} />
+ </main>
+ <CreateKnowledgeBaseDialog
+ open={createDialogOpen}
+ onOpenChange={setCreateDialogOpen}
+ onCreated={handleCreated}
+ onAddCredential={() => setCredentialOpen(true)}
+ credentialRefetchTrigger={credentialRefetchTrigger}
+ />
+ <CreateCredentialDialog
+ open={credentialOpen}
+ onOpenChange={setCredentialOpen}
+ onCreated={() => setCredentialRefetchTrigger((n) => n + 1)}
+ />
+ <EditKnowledgeBaseDialog
+ open={editTarget !== null}
+ onOpenChange={(open) => {
+ if (!open) setEditTarget(null);
+ }}
+ knowledgeBase={editTarget}
+ onUpdated={() => refetch()}
+ />
+ <DeleteDialog
+ open={deleteTarget !== null}
+ onOpenChange={(open) => {
+ if (!open) setDeleteTarget(null);
+ }}
+ title={t('dialog-knowledge-base-delete.title')}
+ description={t('dialog-knowledge-base-delete.description', {
+ name: deleteTarget?.name ?? '',
+ })}
+ onConfirm={handleConfirmDelete}
+ />
+ {selectedKb && (
+ <KnowledgeSearchDrawer
+ open={testOpen}
+ onOpenChange={setTestOpen}
+ knowledgeBaseId={selectedKb.id}
+ knowledgeBaseName={selectedKb.name}
+ />
+ )}
+ </div>
+ );
+};
diff --git a/pyproject.toml b/pyproject.toml
index 146eefb77..daac05461 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -76,6 +76,17 @@ workspace = [
tools = [
"ripgrep",
]
+# ------------ RAG ------------
+rag = [
+ "qdrant-client",
+ "pypdf",
+ "python-pptx",
+]
+
+# ------------ S3-compatible blob store ------------
+s3 = [
+ "aioboto3",
+]
# ------------ Long-term memory ------------
# Required by `agentscope.middleware._longterm_memory.Mem0Middleware`.
@@ -93,6 +104,8 @@ full = [
"agentscope[storage]",
"agentscope[workspace]",
"agentscope[tools]",
+ "agentscope[rag]",
+ "agentscope[s3]",
"agentscope[mem0]",
]
@@ -107,6 +120,14 @@ dev = [
"myst_parser",
"matplotlib",
"fakeredis",
+ # S3-backend testing — moto[server] spins up an in-process S3, the
+ # store-under-test (`S3BlobStore`) uses aioboto3, and boto3 is the
+ # sync client the test fixtures use to seed/verify buckets.
+ "moto[server,s3]",
+ "aioboto3",
+ "boto3",
+ # RAG parser tests — used to generate PDF fixtures in-memory
+ "reportlab",
]
[project.urls]
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.py
index 20a61fbff..ad2dfc8d0 100644
--- a/src/agentscope/app/_app.py
+++ b/src/agentscope/app/_app.py
@@ -3,11 +3,14 @@
from typing import Type, TYPE_CHECKING, Any
from ._lifespan import lifespan
+from .rag.blob_store import BlobStoreBase, LocalBlobStore
+from .rag.knowledge_base_manager import KnowledgeBaseManagerBase
from .workspace_manager import WorkspaceManagerBase
from ._router import (
agent_router,
chat_router,
credential_router,
+ knowledge_base_router,
model_router,
tts_model_router,
schedule_router,
@@ -19,6 +22,12 @@ from .message_bus import MessageBus
from .storage import StorageBase
from ..agent import Agent
from ..credential import CredentialFactory, CredentialBase
+from ..rag import (
+ ApproxTokenChunker,
+ ChunkerBase,
+ ParserBase,
+ TextParser,
+)
from .._version import __version__
@@ -34,6 +43,11 @@ def create_app(
storage: StorageBase,
message_bus: MessageBus,
workspace_manager: WorkspaceManagerBase,
+ knowledge_base_manager: KnowledgeBaseManagerBase | None = None,
+ knowledge_parsers: list[ParserBase] | dict[str, ParserBase] | None = None,
+ knowledge_chunker: ChunkerBase | None = None,
+ blob_store: BlobStoreBase | None = None,
+ enable_index_worker: bool = True,
*,
extra_credentials: list[Type[CredentialBase]] | None = None,
extra_middlewares: list[FastAPIMiddleware] | None = None,
@@ -85,6 +99,48 @@ def create_app(
``__aenter__`` / ``__aexit__``) is managed by the app
lifespan. Pass a :class:`~agentscope.app._manager.
LocalWorkspaceManager` for local-directory workspaces.
+ knowledge_base_manager (`KnowledgeBaseManagerBase | None`, \
+ optional):
+ The knowledge base manager that owns knowledge base
+ lifecycle and serves
+ :class:`~agentscope.rag.KnowledgeBase`
+ runtime handles to both HTTP service and agent code.
+ The manager carries its own vector store instance — its
+ ``__aenter__`` / ``__aexit__`` enter and release that
+ vector store, so the caller does not pass the vector
+ store separately. ``None`` disables knowledge base
+ endpoints entirely.
+ knowledge_parsers (`list[ParserBase] | dict[str, ParserBase] | \
+ None`, optional):
+ Parsers registered for knowledge base document uploads.
+ Pass a **list** to have the service route by each parser's
+ ``supported_media_types`` (later entries override earlier
+ ones for overlapping types, with a warning); pass a
+ **dict** ``media_type → parser`` for explicit routing
+ (one parser bound to multiple types, type aliases, ...).
+ Defaults to ``[TextParser()]`` when
+ ``knowledge_base_manager`` is set.
+ knowledge_chunker (`ChunkerBase | None`, optional):
+ The chunker shared across every knowledge base. Defaults
+ to :class:`~agentscope.rag.ApproxTokenChunker()` when
+ ``knowledge_base_manager`` is set.
+ blob_store (`BlobStoreBase | None`, optional):
+ Backend storing uploaded document bytes between the
+ upload endpoint and the indexing worker. Required when
+ ``knowledge_base_manager`` is set; defaults to
+ :class:`~agentscope.app.rag.blob_store.LocalBlobStore`
+ rooted at ``./blobs``. Its lifecycle (``__aenter__`` /
+ ``__aexit__``) is managed by the app lifespan.
+ enable_index_worker (`bool`, defaults to ``True``):
+ When ``True`` (embedded deployment) the API process starts
+ an :class:`~agentscope.app._service.IndexWorker` and an
+ :class:`~agentscope.app._service.IndexSweeper` in its
+ lifespan, and dispatches indexing tasks via an
+ in-process queue. When ``False`` (dedicated deployment)
+ the API process performs no indexing — a separate worker
+ process is expected to consume tasks from the message
+ bus. No effect when ``knowledge_base_manager`` is
+ ``None``.
extra_credentials (`list[Type[CredentialBase]] | None`, optional):
Additional :class:`~agentscope.credential.CredentialBase`
subclasses to register before the app starts. Equivalent to
@@ -142,10 +198,35 @@ def create_app(
app.state.storage = storage
app.state.message_bus = message_bus
app.state.workspace_manager = workspace_manager
+ app.state.knowledge_base_manager = knowledge_base_manager
app.state.extra_agent_middlewares = extra_agent_middlewares
app.state.extra_agent_tools = extra_agent_tools
app.state.custom_agent_cls = custom_agent_cls
+ # Parser / chunker / blob-store defaults only make sense when the
+ # KB feature is actually enabled. When ``knowledge_base_manager`` is
+ # ``None`` every KB endpoint is disabled, so leaving these as ``None``
+ # avoids unused imports being eagerly constructed at app startup.
+ if knowledge_base_manager is not None:
+ app.state.knowledge_parsers = (
+ knowledge_parsers
+ if knowledge_parsers is not None
+ else [TextParser()]
+ )
+ app.state.knowledge_chunker = knowledge_chunker or ApproxTokenChunker()
+ app.state.blob_store = (
+ blob_store
+ if blob_store is not None
+ else LocalBlobStore(root_dir="./blobs")
+ )
+ else:
+ app.state.knowledge_parsers = knowledge_parsers
+ app.state.knowledge_chunker = knowledge_chunker
+ app.state.blob_store = blob_store
+ app.state.enable_index_worker = (
+ enable_index_worker and knowledge_base_manager is not None
+ )
+
# Validate custom sub-agent templates for duplicate types and store in
# app.state
templates = custom_subagent_templates or []
@@ -166,6 +247,7 @@ def create_app(
agent_router,
chat_router,
credential_router,
+ knowledge_base_router,
schedule_router,
session_router,
workspace_router,
diff --git a/src/agentscope/app/_bus_ops.py b/src/agentscope/app/_bus_ops.py
index 73b4256fb..0128cbb33 100644
--- a/src/agentscope/app/_bus_ops.py
+++ b/src/agentscope/app/_bus_ops.py
@@ -14,6 +14,8 @@ other's internals.
- Append an event to the session replay log and fan it out live.
* - :func:`enqueue_run_trigger`
- Enqueue a typed run trigger and signal dispatchers.
+ * - :func:`enqueue_index_task`
+ - Enqueue a knowledge-document indexing task and signal consumers.
"""
from __future__ import annotations
@@ -120,3 +122,46 @@ async def enqueue_run_trigger(
},
)
await bus.publish(MessageBusKeys.wakeup_signal(), {})
+
+
+# ── enqueue_index_task ─────────────────────────────────────────────────
+
+
+async def enqueue_index_task(
+ bus: "MessageBus",
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+) -> None:
+ """Enqueue a knowledge-document indexing task and signal consumers.
+
+ Pushes a structured payload onto the durable index-task queue and
+ publishes a signal so any subscribed
+ :class:`~agentscope.app._service.IndexTaskConsumer` drains it within
+ one ``subscribe`` round-trip.
+
+ The push happens *before* the publish so a worker woken by the
+ signal is guaranteed to find the entry on its drain. Re-enqueuing
+ the same document is safe — the worker's lease CAS rejects
+ duplicates — so the queue may legitimately hold multiple entries
+ for the same document (one from upload, one from sweeper).
+
+ Args:
+ bus (`MessageBus`):
+ The application message bus.
+ user_id (`str`):
+ The owning user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document id to index.
+ """
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {
+ "user_id": user_id,
+ "knowledge_base_id": knowledge_base_id,
+ "document_id": document_id,
+ },
+ )
+ await bus.publish(MessageBusKeys.index_tasks_signal(), {})
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.py
index 6025c9b68..293871b24 100644
--- a/src/agentscope/app/_lifespan.py
+++ b/src/agentscope/app/_lifespan.py
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
"""The lifespan of the agent service."""
+import socket
+import uuid
from contextlib import AsyncExitStack, asynccontextmanager
from typing import TYPE_CHECKING, Any, AsyncIterator
@@ -10,7 +12,14 @@ from ._manager import (
SchedulerManager,
WakeupDispatcher,
)
-from ._service import ChatService, SessionService
+from ._service import (
+ ChatService,
+ IndexSweeper,
+ IndexTaskConsumer,
+ IndexWorker,
+ KnowledgeBaseService,
+ SessionService,
+)
if TYPE_CHECKING:
from fastapi import FastAPI
@@ -34,11 +43,20 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
storage = app.state.storage
message_bus = app.state.message_bus
workspace_manager = app.state.workspace_manager
+ knowledge_base_manager = app.state.knowledge_base_manager
+ blob_store = app.state.blob_store
+ enable_index_worker = app.state.enable_index_worker
async with AsyncExitStack() as stack:
await stack.enter_async_context(storage)
await stack.enter_async_context(message_bus)
await stack.enter_async_context(workspace_manager)
+ if knowledge_base_manager is not None:
+ # ``KnowledgeBaseManagerBase.__aenter__`` enters the bound
+ # vector store too, so a single context covers both.
+ await stack.enter_async_context(knowledge_base_manager)
+ if blob_store is not None:
+ await stack.enter_async_context(blob_store)
bg_manager = await stack.enter_async_context(
BackgroundTaskManager(message_bus=message_bus),
@@ -69,6 +87,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
scheduler_manager=scheduler,
background_task_manager=bg_manager,
message_bus=message_bus,
+ knowledge_base_manager=knowledge_base_manager,
extra_agent_middlewares=app.state.extra_agent_middlewares,
extra_agent_tools=app.state.extra_agent_tools,
custom_subagent_templates=app.state.custom_subagent_templates,
@@ -81,6 +100,64 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
message_bus=message_bus,
)
+ # ---------------- Knowledge-base wiring ----------------
+ knowledge_base_service = None
+ if knowledge_base_manager is not None:
+ # Indexing is uniformly driven by the message bus: the
+ # service publishes an index-task entry, and a consumer
+ # (in-process or in a dedicated worker process) drains it.
+ #
+ # * Embedded — ``enable_index_worker=True``: this lifespan
+ # additionally starts an :class:`IndexWorker` plus an
+ # :class:`IndexTaskConsumer` that subscribes to the same
+ # channel. The ``InMemoryMessageBus`` makes the round
+ # trip near-free; everything runs in one binary.
+ #
+ # * Dedicated — ``enable_index_worker=False``: this
+ # lifespan does NOT start a worker. One or more separate
+ # processes (``python -m agentscope.app.rag.index_worker``)
+ # run their own consumer + worker pair subscribed to the
+ # same channel.
+ #
+ # The sweeper STILL runs in the API process either way,
+ # because the API is the only resource guaranteed to be
+ # live whenever uploads happen — if the publish ever races
+ # a worker restart the durable queue catches the task, and
+ # if the queue write itself failed the sweeper eventually
+ # re-enqueues from storage.
+ if enable_index_worker:
+ node_id = f"{socket.gethostname()}:{uuid.uuid4().hex[:8]}"
+ worker = IndexWorker(
+ storage=storage,
+ blob_store=blob_store,
+ knowledge_base_manager=knowledge_base_manager,
+ parsers=app.state.knowledge_parsers,
+ chunker=app.state.knowledge_chunker,
+ node_id=node_id,
+ )
+ await stack.enter_async_context(
+ IndexTaskConsumer(
+ message_bus=message_bus,
+ worker=worker,
+ ),
+ )
+
+ sweeper = IndexSweeper(
+ storage=storage,
+ message_bus=message_bus,
+ )
+ await sweeper.start()
+ stack.push_async_callback(sweeper.stop)
+
+ knowledge_base_service = KnowledgeBaseService(
+ storage=storage,
+ knowledge_base_manager=knowledge_base_manager,
+ blob_store=blob_store,
+ message_bus=message_bus,
+ )
+
+ app.state.knowledge_base_service = knowledge_base_service
+
# Dispatchers need live references somewhere, or they would be
# garbage-collected; the AsyncExitStack holds those references
# for us, so we don't need local bindings or app.state slots.
diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.py
index 6511f3957..9f8ea4219 100644
--- a/src/agentscope/app/_router/__init__.py
+++ b/src/agentscope/app/_router/__init__.py
@@ -3,6 +3,7 @@
from ._agent import agent_router
from ._chat import chat_router
from ._credential import credential_router
+from ._knowledge_base import knowledge_base_router
from ._schedule import schedule_router
from ._session import session_router
from ._model import model_router
@@ -15,6 +16,7 @@ __all__ = [
"tts_model_router",
"chat_router",
"credential_router",
+ "knowledge_base_router",
"schedule_router",
"session_router",
"workspace_router",
diff --git a/src/agentscope/app/_router/_knowledge_base.py b/src/agentscope/app/_router/_knowledge_base.py
new file mode 100644
index 000000000..68b6dc8a3
--- /dev/null
+++ b/src/agentscope/app/_router/_knowledge_base.py
@@ -0,0 +1,574 @@
+# -*- coding: utf-8 -*-
+"""Knowledge base router — manage knowledge bases and their documents.
+
+A knowledge base is the user-facing concept; physically each one maps
+to a single vector store collection (in the MVP isolation strategy).
+The HTTP layer is intentionally thin — every endpoint translates the
+request into a single :class:`~agentscope.app._service.
+KnowledgeBaseService` call and returns the result.
+"""
+from fastapi import (
+ APIRouter,
+ Depends,
+ File,
+ Form,
+ Path,
+ Query,
+ UploadFile,
+ status,
+)
+
+from ..deps import (
+ get_current_user_id,
+ get_knowledge_base_manager,
+ get_knowledge_base_service,
+ get_knowledge_parsers,
+ get_storage,
+)
+from ._schema import (
+ CreateKnowledgeBaseRequest,
+ CreateKnowledgeBaseResponse,
+ KbEmbeddingProvider,
+ KbMiddlewareParametersSchemaResponse,
+ KnowledgeBaseView,
+ KnowledgeDocumentView,
+ ListKbEmbeddingModelsResponse,
+ ListKnowledgeBasesResponse,
+ ListKnowledgeDocumentsResponse,
+ ListKnowledgeDocumentStatusResponse,
+ ListSupportedContentTypesResponse,
+ SearchKnowledgeBaseRequest,
+ SearchKnowledgeBaseResponse,
+ UpdateKnowledgeBaseRequest,
+ UploadKnowledgeDocumentResponse,
+)
+from ...credential import CredentialFactory
+from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
+from ..storage import StorageBase
+from .._service import KnowledgeBaseService
+from ...middleware import RAGMiddleware
+from ...rag import ParserBase
+
+
+knowledge_base_router = APIRouter(
+ prefix="/knowledge_bases",
+ tags=["knowledge_bases"],
+ responses={404: {"description": "Not found"}},
+)
+
+
+@knowledge_base_router.get(
+ "/embedding_models",
+ response_model=ListKbEmbeddingModelsResponse,
+ summary="List embedding models compatible with the KB dimension policy",
+)
+async def list_kb_embedding_models(
+ user_id: str = Depends(get_current_user_id),
+ storage: "StorageBase" = Depends(get_storage),
+ manager: "KnowledgeBaseManagerBase" = Depends(
+ get_knowledge_base_manager,
+ ),
+) -> ListKbEmbeddingModelsResponse:
+ """List embedding models the user can pick at KB-creation time.
+
+ Walks the caller's credentials, looks up each provider's
+ embedding model class, gathers its model cards, and projects
+ each card through the manager's :class:`DimensionPolicy`.
+ Incompatible cards are dropped; matryoshka cards under a
+ ``FIXED`` / ``LOCKED_BY_EXISTING`` policy are narrowed to the
+ locked dimension. Providers that end up with zero compatible
+ models are omitted from the response entirely.
+
+ Args:
+ user_id (`str`):
+ Injected authenticated user ID.
+ storage (`StorageBase`):
+ Injected storage backend used to enumerate credentials.
+ manager (`KnowledgeBaseManagerBase`):
+ Injected knowledge base manager.
+
+ Returns:
+ `ListKbEmbeddingModelsResponse`:
+ One entry per credential with at least one compatible
+ embedding model, plus the policy used for filtering.
+ """
+ policy = await manager.get_dimension_policy()
+ credentials = await storage.list_credentials(user_id)
+
+ providers: list[KbEmbeddingProvider] = []
+ for credential in credentials:
+ credential_type = credential.data.get("type")
+ if not credential_type:
+ continue
+ credential_cls = CredentialFactory.get_credential_class(
+ credential_type,
+ )
+ if credential_cls is None:
+ continue
+ embedding_cls = credential_cls.get_embedding_model_class()
+ if embedding_cls is None:
+ continue
+
+ filtered = []
+ for card in embedding_cls.list_models():
+ projected = policy.filter_card(card)
+ if projected is not None:
+ filtered.append(projected)
+ if not filtered:
+ continue
+ providers.append(
+ KbEmbeddingProvider(credential=credential, models=filtered),
+ )
+
+ return ListKbEmbeddingModelsResponse(providers=providers, policy=policy)
+
+
+@knowledge_base_router.get(
+ "/middleware/parameters_schema",
+ response_model=KbMiddlewareParametersSchemaResponse,
+ summary="JSON Schema for the KB middleware's tunable parameters",
+)
+async def get_kb_middleware_parameters_schema(
+ _: str = Depends(get_current_user_id),
+) -> KbMiddlewareParametersSchemaResponse:
+ """Return the parameter schema for
+ :class:`agentscope.middleware.RAGMiddleware`.
+
+ The schema is shaped like every other ``parameter_schema`` served
+ by this service — title / description / default / enum / minimum
+ / maximum — so the front-end can render the session-level KB
+ attachment form with the same schema-driven component used for
+ model parameters.
+
+ Args:
+ _ (`str`):
+ Injected authenticated user ID; only used to gate the
+ endpoint behind authentication.
+
+ Returns:
+ `KbMiddlewareParametersSchemaResponse`:
+ The JSON Schema describing the middleware's
+ user-tunable parameters.
+ """
+ return KbMiddlewareParametersSchemaResponse(
+ parameter_schema=(RAGMiddleware.Parameters.model_json_schema()),
+ )
+
+
+@knowledge_base_router.get(
+ "/supported_content_types",
+ response_model=ListSupportedContentTypesResponse,
+ summary="List file types the configured parsers can ingest",
+)
+async def list_supported_content_types(
+ _: str = Depends(get_current_user_id),
+ parsers: list[ParserBase]
+ | dict[str, ParserBase] = Depends(
+ get_knowledge_parsers,
+ ),
+) -> ListSupportedContentTypesResponse:
+ """Advertise the union of media types and filename extensions every
+ registered parser accepts.
+
+ Used by the front-end to populate the document picker's ``accept``
+ attribute and to reject drag-dropped files whose extension lies
+ outside the supported set before the upload starts. Routing on
+ upload still goes through the media type — this endpoint is a
+ capability hint, not authoritative dispatch.
+
+ Args:
+ _ (`str`):
+ Injected authenticated user ID; only used to gate the
+ endpoint behind authentication.
+ parsers (`list[ParserBase] | dict[str, ParserBase]`):
+ Injected parser registry — the same value the index worker
+ uses to dispatch uploads.
+
+ Returns:
+ `ListSupportedContentTypesResponse`:
+ Deduplicated, sorted unions of ``media_types`` and
+ ``extensions``.
+ """
+ parser_iter = parsers.values() if isinstance(parsers, dict) else parsers
+ media_types: set[str] = set()
+ extensions: set[str] = set()
+ for parser in parser_iter:
+ media_types.update(parser.supported_media_types)
+ extensions.update(parser.supported_extensions())
+ return ListSupportedContentTypesResponse(
+ media_types=sorted(media_types),
+ extensions=sorted(extensions),
+ )
+
+
+# ----------------------------------------------------------------------
+# Knowledge base management
+# ----------------------------------------------------------------------
+
+
+@knowledge_base_router.post(
+ "/",
+ response_model=CreateKnowledgeBaseResponse,
+ status_code=status.HTTP_201_CREATED,
+ summary="Create a new knowledge base",
+)
+async def create_knowledge_base(
+ body: CreateKnowledgeBaseRequest,
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> CreateKnowledgeBaseResponse:
+ """Create a new knowledge base for the authenticated user.
+
+ Allocates a fresh vector store collection sized to the embedding
+ model's output dimension and persists the knowledge base record.
+
+ Args:
+ body (`CreateKnowledgeBaseRequest`):
+ Knowledge base name, description, and embedding model
+ configuration.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+
+ Returns:
+ `CreateKnowledgeBaseResponse`:
+ The server-assigned knowledge base identifier.
+ """
+ record = await service.create_knowledge_base(
+ user_id=user_id,
+ name=body.name,
+ description=body.description,
+ embedding_model_config=body.embedding_model_config,
+ )
+ return CreateKnowledgeBaseResponse(knowledge_base_id=record.id)
+
+
+@knowledge_base_router.get(
+ "/",
+ response_model=ListKnowledgeBasesResponse,
+ summary="List the caller's knowledge bases",
+)
+async def list_knowledge_bases(
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> ListKnowledgeBasesResponse:
+ """Return all knowledge bases owned by the authenticated user.
+
+ Args:
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+
+ Returns:
+ `ListKnowledgeBasesResponse`:
+ The user's knowledge bases.
+ """
+ records = await service.list_knowledge_bases(user_id)
+ views = [
+ KnowledgeBaseView(
+ id=record.id,
+ name=record.name,
+ description=record.description,
+ embedding_model_config=record.embedding_model_config,
+ created_at=record.created_at,
+ updated_at=record.updated_at,
+ )
+ for record in records
+ ]
+ return ListKnowledgeBasesResponse(knowledge_bases=views, total=len(views))
+
+
+@knowledge_base_router.patch(
+ "/{knowledge_base_id}",
+ response_model=KnowledgeBaseView,
+ summary="Update mutable fields on a knowledge base",
+)
+async def update_knowledge_base(
+ body: UpdateKnowledgeBaseRequest,
+ knowledge_base_id: str = Path(description="The knowledge base id."),
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> KnowledgeBaseView:
+ """Update mutable fields on a knowledge base.
+
+ Only ``name`` and ``description`` can be updated. The embedding
+ model configuration is pinned at creation time and cannot be
+ changed.
+
+ Args:
+ body (`UpdateKnowledgeBaseRequest`):
+ The fields to update; omitted fields stay unchanged.
+ knowledge_base_id (`str`):
+ The knowledge base to update.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+
+ Returns:
+ `KnowledgeBaseView`:
+ The knowledge base record after the update.
+ """
+ record = await service.update_knowledge_base(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ name=body.name,
+ description=body.description,
+ )
+ return KnowledgeBaseView(
+ id=record.id,
+ name=record.name,
+ description=record.description,
+ embedding_model_config=record.embedding_model_config,
+ created_at=record.created_at,
+ updated_at=record.updated_at,
+ )
+
+
+@knowledge_base_router.delete(
+ "/{knowledge_base_id}",
+ status_code=status.HTTP_204_NO_CONTENT,
+ summary="Delete a knowledge base",
+)
+async def delete_knowledge_base(
+ knowledge_base_id: str = Path(description="The knowledge base id."),
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> None:
+ """Permanently delete a knowledge base.
+
+ Drops the underlying vector store collection together with every
+ associated document and the knowledge base record itself.
+
+ Args:
+ knowledge_base_id (`str`):
+ The knowledge base to delete.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+ """
+ await service.delete_knowledge_base(user_id, knowledge_base_id)
+
+
+# ----------------------------------------------------------------------
+# Document management
+# ----------------------------------------------------------------------
+
+
+@knowledge_base_router.get(
+ "/{knowledge_base_id}/documents",
+ response_model=ListKnowledgeDocumentsResponse,
+ summary="List documents registered in a knowledge base",
+)
+async def list_knowledge_documents(
+ knowledge_base_id: str = Path(description="The knowledge base id."),
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> ListKnowledgeDocumentsResponse:
+ """List every document registered against a knowledge base.
+
+ Reads from the storage backend (service-mode source of truth), so
+ documents in any lifecycle state — including ``pending`` /
+ ``parsing`` / ``error`` — are returned alongside ``ready`` ones.
+
+ Args:
+ knowledge_base_id (`str`):
+ The target knowledge base id.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+
+ Returns:
+ `ListKnowledgeDocumentsResponse`:
+ One view per registered document.
+ """
+ records = await service.list_documents(user_id, knowledge_base_id)
+ views = [KnowledgeDocumentView.from_record(r) for r in records]
+ return ListKnowledgeDocumentsResponse(
+ documents=views,
+ total=len(views),
+ )
+
+
+@knowledge_base_router.get(
+ "/{knowledge_base_id}/documents/status",
+ response_model=ListKnowledgeDocumentStatusResponse,
+ summary="Batch-query indexing status of one or more documents",
+)
+async def list_knowledge_document_status(
+ knowledge_base_id: str = Path(description="The knowledge base id."),
+ ids: str = Query(
+ description=(
+ "Comma-separated list of document ids to query. "
+ "Missing ids are silently omitted from the response."
+ ),
+ ),
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> ListKnowledgeDocumentStatusResponse:
+ """Return the current lifecycle state of a batch of documents.
+
+ Designed for the front-end's status polling loop: the page sends
+ every in-flight document id at once so per-document round-trips
+ do not multiply with concurrency.
+
+ Args:
+ knowledge_base_id (`str`):
+ The target knowledge base id.
+ ids (`str`):
+ Comma-separated document ids.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+
+ Returns:
+ `ListKnowledgeDocumentStatusResponse`:
+ Views for the matched documents.
+ """
+ document_ids = [tok for tok in (s.strip() for s in ids.split(",")) if tok]
+ records = await service.get_document_status(
+ user_id,
+ knowledge_base_id,
+ document_ids,
+ )
+ return ListKnowledgeDocumentStatusResponse(
+ items=[KnowledgeDocumentView.from_record(r) for r in records],
+ )
+
+
+@knowledge_base_router.post(
+ "/{knowledge_base_id}/documents",
+ response_model=UploadKnowledgeDocumentResponse,
+ status_code=status.HTTP_201_CREATED,
+ summary="Upload a document into a knowledge base",
+)
+async def upload_knowledge_document(
+ knowledge_base_id: str = Path(description="The knowledge base id."),
+ file: UploadFile = File(
+ description="The document to index (PDF, TXT, Markdown, …).",
+ ),
+ content_type: str
+ | None = Form(
+ default=None,
+ description=(
+ "Override the IANA media type used to route the upload. "
+ "Defaults to the type guessed from the filename."
+ ),
+ ),
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> UploadKnowledgeDocumentResponse:
+ """Register an uploaded document and dispatch it for indexing.
+
+ The HTTP connection covers only the upload phase: the request body
+ is streamed into the blob store, a ``pending`` document record is
+ persisted, the indexing task is dispatched, and the response is
+ returned. Parsing / chunking / embedding happen asynchronously in
+ a worker; the client tracks progress via
+ :func:`list_knowledge_document_status`.
+
+ Args:
+ knowledge_base_id (`str`):
+ The knowledge base to receive the document.
+ file (`UploadFile`):
+ The uploaded file (multipart/form-data).
+ content_type (`str | None`, optional):
+ Override the IANA media type used to route the upload.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+
+ Returns:
+ `UploadKnowledgeDocumentResponse`:
+ The server-assigned document id, filename, and the
+ initial lifecycle state (always ``"pending"``).
+ """
+ record = await service.register_document(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ filename=file.filename or "uploaded_file",
+ stream=file.file,
+ size=file.size or 0,
+ content_type=content_type or file.content_type,
+ )
+ return UploadKnowledgeDocumentResponse(
+ document_id=record.id,
+ filename=record.data.filename,
+ status=record.data.status,
+ )
+
+
+@knowledge_base_router.delete(
+ "/{knowledge_base_id}/documents/{document_id}",
+ status_code=status.HTTP_204_NO_CONTENT,
+ summary="Delete a document from a knowledge base",
+)
+async def delete_knowledge_document(
+ knowledge_base_id: str = Path(description="The knowledge base id."),
+ document_id: str = Path(description="The document id."),
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> None:
+ """Remove a document and all its chunks from a knowledge base.
+
+ Args:
+ knowledge_base_id (`str`):
+ The knowledge base the document belongs to.
+ document_id (`str`):
+ The document to delete.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+ """
+ await service.delete_document(user_id, knowledge_base_id, document_id)
+
+
+# ----------------------------------------------------------------------
+# Search
+# ----------------------------------------------------------------------
+
+
+@knowledge_base_router.post(
+ "/{knowledge_base_id}/search",
+ response_model=SearchKnowledgeBaseResponse,
+ summary="Search a knowledge base by natural-language query",
+)
+async def search_knowledge_base(
+ body: SearchKnowledgeBaseRequest,
+ knowledge_base_id: str = Path(description="The knowledge base id."),
+ user_id: str = Depends(get_current_user_id),
+ service: "KnowledgeBaseService" = Depends(get_knowledge_base_service),
+) -> SearchKnowledgeBaseResponse:
+ """Run a similarity search over a knowledge base.
+
+ Embeds the query with the knowledge base's configured embedding
+ model and returns the top-K most similar chunks.
+
+ Args:
+ body (`SearchKnowledgeBaseRequest`):
+ The query text and ``top_k``.
+ knowledge_base_id (`str`):
+ The knowledge base to search.
+ user_id (`str`):
+ Injected authenticated user ID.
+ service (`KnowledgeBaseService`):
+ Injected knowledge base service.
+
+ Returns:
+ `SearchKnowledgeBaseResponse`:
+ Matched chunks ordered by descending similarity.
+ """
+ results = await service.search(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ query=body.query,
+ top_k=body.top_k,
+ )
+ return SearchKnowledgeBaseResponse(results=results, total=len(results))
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index e84deeaf9..8c25125a6 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -25,6 +25,23 @@ from ._credential import (
ListCredentialsResponse,
ListCredentialSchemasResponse,
)
+from ._knowledge_base import (
+ CreateKnowledgeBaseRequest,
+ CreateKnowledgeBaseResponse,
+ KbEmbeddingProvider,
+ KbMiddlewareParametersSchemaResponse,
+ KnowledgeBaseView,
+ KnowledgeDocumentView,
+ ListKbEmbeddingModelsResponse,
+ ListKnowledgeBasesResponse,
+ ListKnowledgeDocumentsResponse,
+ ListKnowledgeDocumentStatusResponse,
+ ListSupportedContentTypesResponse,
+ SearchKnowledgeBaseRequest,
+ SearchKnowledgeBaseResponse,
+ UpdateKnowledgeBaseRequest,
+ UploadKnowledgeDocumentResponse,
+)
from ._session import (
CreateSessionRequest,
CreateSessionResponse,
@@ -53,6 +70,22 @@ __all__ = [
"UpdateCredentialRequest",
"ListCredentialsResponse",
"ListCredentialSchemasResponse",
+ # Knowledge base
+ "CreateKnowledgeBaseRequest",
+ "CreateKnowledgeBaseResponse",
+ "KbEmbeddingProvider",
+ "KbMiddlewareParametersSchemaResponse",
+ "KnowledgeBaseView",
+ "KnowledgeDocumentView",
+ "ListKbEmbeddingModelsResponse",
+ "ListKnowledgeBasesResponse",
+ "ListKnowledgeDocumentsResponse",
+ "ListKnowledgeDocumentStatusResponse",
+ "ListSupportedContentTypesResponse",
+ "SearchKnowledgeBaseRequest",
+ "SearchKnowledgeBaseResponse",
+ "UpdateKnowledgeBaseRequest",
+ "UploadKnowledgeDocumentResponse",
# Model
"ListModelsRequest",
"ListModelsResponse",
diff --git a/src/agentscope/app/_router/_schema/_knowledge_base.py b/src/agentscope/app/_router/_schema/_knowledge_base.py
new file mode 100644
index 000000000..afd9dd786
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_knowledge_base.py
@@ -0,0 +1,292 @@
+# -*- coding: utf-8 -*-
+"""Request / response schemas for the knowledge base router."""
+from datetime import datetime
+
+from pydantic import BaseModel, Field
+
+from ...storage import (
+ CredentialRecord,
+ EmbeddingModelConfig,
+ KnowledgeDocumentRecord,
+ KnowledgeDocumentStatus,
+)
+from ....embedding import EmbeddingModelCard
+from ....rag import VectorSearchResult
+from ...rag.knowledge_base_manager._dimension_policy import DimensionPolicy
+
+
+class CreateKnowledgeBaseRequest(BaseModel):
+ """Request body for creating a new knowledge base."""
+
+ name: str = Field(description="Display name of the knowledge base.")
+ description: str = Field(
+ default="",
+ description="Free-form description shown in the UI.",
+ )
+ embedding_model_config: EmbeddingModelConfig = Field(
+ description=(
+ "Embedding model used both at indexing and at query time. "
+ "Cannot be changed after creation — switching would "
+ "invalidate every previously inserted vector."
+ ),
+ )
+
+
+class CreateKnowledgeBaseResponse(BaseModel):
+ """Response body after creating a knowledge base."""
+
+ knowledge_base_id: str = Field(
+ description="Server-assigned knowledge base identifier.",
+ )
+
+
+class UpdateKnowledgeBaseRequest(BaseModel):
+ """Request body for updating a knowledge base.
+
+ Only mutable fields can be set here. The embedding model
+ configuration is pinned at creation time and cannot be changed —
+ switching it would invalidate every previously inserted vector.
+ """
+
+ name: str | None = Field(
+ default=None,
+ description="New display name; omit to leave unchanged.",
+ )
+ description: str | None = Field(
+ default=None,
+ description="New free-form description; omit to leave unchanged.",
+ )
+
+
+class KnowledgeBaseView(BaseModel):
+ """A knowledge base record as exposed to API clients.
+
+ Mirrors :class:`KnowledgeBaseRecord` with the internal
+ ``user_id`` / ``collection_name`` fields stripped — clients have
+ no business introspecting either.
+ """
+
+ id: str = Field(description="The knowledge base identifier.")
+ name: str = Field(description="Display name of the knowledge base.")
+ description: str = Field(description="Free-form description.")
+ embedding_model_config: EmbeddingModelConfig = Field(
+ description="Embedding model configuration pinned at creation.",
+ )
+ created_at: datetime = Field(description="Creation timestamp.")
+ updated_at: datetime = Field(description="Last-update timestamp.")
+
+
+class ListKnowledgeBasesResponse(BaseModel):
+ """Response body for listing the caller's knowledge bases."""
+
+ knowledge_bases: list[KnowledgeBaseView] = Field(
+ description="All knowledge bases owned by the caller.",
+ )
+ total: int = Field(description="Total number of returned items.")
+
+
+class KnowledgeDocumentView(BaseModel):
+ """A document record as exposed to API clients.
+
+ Surfaces both the static fields the UI needs to render a row
+ (``filename`` / ``size``) and the live lifecycle fields the front
+ end polls (``status`` / ``error`` / ``chunk_count``). Internal
+ fields (``user_id`` / ``blob_uri`` / ``processing_node`` / lease)
+ are deliberately omitted — clients have no business introspecting
+ them.
+ """
+
+ id: str = Field(description="The document identifier.")
+ filename: str = Field(description="Original filename at upload time.")
+ size: int = Field(description="Document size in bytes.")
+ content_type: str | None = Field(
+ default=None,
+ description="IANA media type recorded at upload time, if any.",
+ )
+ status: KnowledgeDocumentStatus = Field(
+ description="Current lifecycle state of the document.",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Human-readable failure reason when ``status == 'error'``."
+ ),
+ )
+ chunk_count: int = Field(
+ default=0,
+ description="Number of chunks indexed so far.",
+ )
+ created_at: datetime = Field(description="Upload timestamp.")
+ updated_at: datetime = Field(
+ description="Last status transition timestamp.",
+ )
+
+ @classmethod
+ def from_record(
+ cls,
+ record: KnowledgeDocumentRecord,
+ ) -> "KnowledgeDocumentView":
+ """Project a storage record onto the API view.
+
+ Centralised so router code stays a one-liner and the field
+ mapping has exactly one source of truth.
+ """
+ return cls(
+ id=record.id,
+ filename=record.data.filename,
+ size=record.data.size,
+ content_type=record.data.content_type,
+ status=record.data.status,
+ error=record.data.error,
+ chunk_count=record.data.chunk_count,
+ created_at=record.created_at,
+ updated_at=record.updated_at,
+ )
+
+
+class ListKnowledgeDocumentsResponse(BaseModel):
+ """Response body for listing documents inside a knowledge base."""
+
+ documents: list[KnowledgeDocumentView] = Field(
+ description="One view per registered document.",
+ )
+ total: int = Field(description="Total number of returned items.")
+
+
+class ListKnowledgeDocumentStatusResponse(BaseModel):
+ """Response body for batch document-status polling."""
+
+ items: list[KnowledgeDocumentView] = Field(
+ description=(
+ "Subset of the requested documents that still exist. "
+ "Missing ids are silently omitted — clients may legitimately "
+ "ask about a document that was deleted between two polls."
+ ),
+ )
+
+
+class UploadKnowledgeDocumentResponse(BaseModel):
+ """Response body after uploading a document into a knowledge base."""
+
+ document_id: str = Field(
+ description="Server-assigned document identifier.",
+ )
+ filename: str = Field(
+ description="The original filename of the uploaded document.",
+ )
+ status: KnowledgeDocumentStatus = Field(
+ description=(
+ "Lifecycle state immediately after upload — always "
+ "``'pending'`` in the happy path; surfaced so the client "
+ "can seed its progress tracker without an extra round-trip."
+ ),
+ )
+
+
+class SearchKnowledgeBaseRequest(BaseModel):
+ """Request body for searching a knowledge base."""
+
+ query: str = Field(description="The natural-language search query.")
+ top_k: int = Field(
+ default=5,
+ ge=1,
+ le=50,
+ description="Maximum number of results to return.",
+ )
+
+
+class SearchKnowledgeBaseResponse(BaseModel):
+ """Response body for a knowledge base search."""
+
+ results: list[VectorSearchResult] = Field(
+ description="Matched chunks ordered by descending similarity score.",
+ )
+ total: int = Field(description="Total number of returned results.")
+
+
+class KbEmbeddingProvider(BaseModel):
+ """One credential and the embedding models it can serve.
+
+ The model cards have been projected through the manager's
+ dimension policy: incompatible models are removed and matryoshka
+ cards are narrowed to the locked dimension when applicable.
+ """
+
+ credential: CredentialRecord = Field(
+ description="The credential record exposing these models.",
+ )
+ models: list[EmbeddingModelCard] = Field(
+ description=(
+ "Embedding model cards available under this credential, "
+ "filtered to those compatible with the manager's "
+ "dimension policy."
+ ),
+ )
+
+
+class ListKbEmbeddingModelsResponse(BaseModel):
+ """Response body listing KB-compatible embedding models.
+
+ The list is pre-filtered server-side against the manager's
+ dimension policy. The policy itself is also returned so the
+ front-end can render an explanatory banner and lock the dimension
+ selector when applicable.
+ """
+
+ providers: list[KbEmbeddingProvider] = Field(
+ description=(
+ "One entry per credential that has at least one "
+ "compatible embedding model."
+ ),
+ )
+ policy: DimensionPolicy = Field(
+ description=(
+ "The dimension policy used to filter the cards; surfaced "
+ "verbatim so the UI can explain *why* models were filtered."
+ ),
+ )
+
+
+class KbMiddlewareParametersSchemaResponse(BaseModel):
+ """Response body exposing the KB middleware's parameters schema.
+
+ The schema is derived from
+ :class:`agentscope.middleware.RAGMiddleware.Parameters`
+ via ``model_json_schema()`` so the front-end can render the
+ session-level KB attachment form with the same schema-driven
+ component used for model parameters.
+ """
+
+ parameter_schema: dict = Field(
+ description=(
+ "JSON Schema produced by `RAGMiddleware.Parameters"
+ "model_json_schema()`. Shaped identically to the "
+ "`parameter_schema` field on `ModelCard`."
+ ),
+ )
+
+
+class ListSupportedContentTypesResponse(BaseModel):
+ """Response body advertising the parser-supported upload types.
+
+ Aggregated across every parser registered on the app — the union of
+ each parser's :attr:`supported_media_types` and
+ :meth:`supported_extensions`. The front-end uses this to populate
+ ``<input accept>`` and to reject unsupported drops on the client
+ before the file leaves the browser.
+ """
+
+ media_types: list[str] = Field(
+ description=(
+ "Union of IANA media types every registered parser claims "
+ "to handle. Deduplicated and sorted."
+ ),
+ )
+ extensions: list[str] = Field(
+ description=(
+ "Filename extensions (each starting with `.`) every "
+ "registered parser claims to handle. Deduplicated and "
+ "sorted. Derived from `mimetypes` by the base parser; "
+ "subclasses may override the default."
+ ),
+ )
diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.py
index 3b4865c5b..7146e0f7f 100644
--- a/src/agentscope/app/_router/_schema/_session.py
+++ b/src/agentscope/app/_router/_schema/_session.py
@@ -6,6 +6,7 @@ from ....permission import PermissionMode
from ...storage import (
AgentRecord,
ChatModelConfig,
+ SessionKnowledgeConfig,
TTSModelConfig,
SessionRecord,
TeamRecord,
@@ -78,6 +79,14 @@ class CreateSessionRequest(BaseModel):
default=None,
description="TTS model configuration. Can be set later via PATCH.",
)
+ knowledge_config: SessionKnowledgeConfig | None = Field(
+ default=None,
+ description=(
+ "Knowledge bases attached to this session plus the "
+ "`RAGMiddleware` parameters. Can be set later "
+ "via PATCH."
+ ),
+ )
class CreateSessionResponse(BaseModel):
@@ -112,6 +121,13 @@ class UpdateSessionRequest(BaseModel):
description="New TTS model configuration. "
"Pass null to clear; omit to leave unchanged.",
)
+ knowledge_config: SessionKnowledgeConfig | None = Field(
+ default=None,
+ description=(
+ "New knowledge base attachment + middleware parameters. "
+ "Pass null to clear; omit to leave unchanged."
+ ),
+ )
permission_mode: PermissionMode | None = Field(
default=None,
description="New permission mode for the session.",
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index f8d31e160..b9e60352a 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -29,6 +29,7 @@ from .._service import SessionService, SessionProjection, SubagentHitlProjector
from ..storage import (
AgentRecord,
ChatModelConfig,
+ SessionKnowledgeConfig,
TTSModelConfig,
SessionConfig,
SessionRecord,
@@ -120,6 +121,37 @@ async def _ensure_credential_exists(
)
+async def _ensure_knowledge_bases_exist(
+ storage: StorageBase,
+ user_id: str,
+ config: SessionKnowledgeConfig | None,
+) -> None:
+ """Validate every KB id in ``config`` belongs to the given user.
+
+ No-op when ``config`` is ``None`` or its ``knowledge_base_ids``
+ list is empty.
+
+ Args:
+ storage (`StorageBase`): Injected storage backend.
+ user_id (`str`): The authenticated user ID.
+ config (`SessionKnowledgeConfig | None`):
+ Knowledge config to validate. Pass ``None`` to skip.
+
+ Raises:
+ `HTTPException`: 404 if any KB id does not exist or is not
+ owned by the user.
+ """
+ if config is None or not config.knowledge_base_ids:
+ return
+ for kb_id in config.knowledge_base_ids:
+ kb = await storage.get_knowledge_base(user_id, kb_id)
+ if kb is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Knowledge base '{kb_id}' not found.",
+ )
+
+
@session_router.get(
"/",
response_model=ListSessionsResponse,
@@ -236,6 +268,11 @@ async def create_session(
body.fallback_chat_model_config,
)
await _ensure_credential_exists(storage, user_id, body.tts_model_config)
+ await _ensure_knowledge_bases_exist(
+ storage,
+ user_id,
+ body.knowledge_config,
+ )
session_record = await storage.upsert_session(
user_id=user_id,
@@ -245,6 +282,7 @@ async def create_session(
chat_model_config=body.chat_model_config,
fallback_chat_model_config=body.fallback_chat_model_config,
tts_model_config=body.tts_model_config,
+ knowledge_config=body.knowledge_config,
**({"name": body.name} if body.name is not None else {}),
),
)
@@ -333,6 +371,11 @@ async def update_session(
body.fallback_chat_model_config,
)
await _ensure_credential_exists(storage, user_id, body.tts_model_config)
+ await _ensure_knowledge_bases_exist(
+ storage,
+ user_id,
+ body.knowledge_config,
+ )
updated_state = existing.state
if body.permission_mode is not None:
diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.py
index 6b15f0cad..a6a02c61e 100644
--- a/src/agentscope/app/_service/__init__.py
+++ b/src/agentscope/app/_service/__init__.py
@@ -2,6 +2,10 @@
"""Service layer for the AgentScope app."""
from ._chat import ChatService
from ._embedding import get_embedding_model
+from ._index_sweeper import IndexSweeper
+from ._index_task_consumer import IndexTaskConsumer
+from ._index_worker import IndexWorker
+from ._knowledge_base import KnowledgeBaseService
from ._model import get_model
from ._tts_model import get_tts_model
from ._session import SessionService
@@ -11,6 +15,10 @@ from ._toolkit import get_toolkit
__all__ = [
"ChatService",
+ "IndexSweeper",
+ "IndexTaskConsumer",
+ "IndexWorker",
+ "KnowledgeBaseService",
"SessionService",
"SessionProjection",
"SubagentHitlProjector",
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index 67647e241..a6e9b03c7 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -15,6 +15,7 @@ from fastapi import HTTPException
from ..message_bus import MessageBus, MessageBusKeys
from .._bus_ops import publish_session_event
+from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
from ..storage import StorageBase, AgentRecord, SessionRecord
from .._manager import BackgroundTaskManager, SchedulerManager
from ..workspace_manager import WorkspaceManagerBase
@@ -23,7 +24,8 @@ from ..middleware import (
StateChangeMiddleware,
ToolOffloadMiddleware,
)
-from ...middleware import TTSMiddleware
+from ...middleware import TTSMiddleware, RAGMiddleware
+from ...rag import KnowledgeBase
from .._types import (
AgentMiddlewareFactory,
AgentToolFactory,
@@ -70,6 +72,7 @@ class ChatService:
scheduler_manager: SchedulerManager,
background_task_manager: BackgroundTaskManager,
message_bus: MessageBus,
+ knowledge_base_manager: KnowledgeBaseManagerBase | None = None,
extra_agent_middlewares: AgentMiddlewareFactory | None = None,
extra_agent_tools: AgentToolFactory | None = None,
custom_subagent_templates: dict[str, SubAgentTemplate] | None = None,
@@ -97,6 +100,15 @@ class ChatService:
distributed locking (via :meth:`session_run`), event
replay + live fan-out (via :meth:`session_publish_event`),
and inbox delivery (via :class:`InboxMiddleware`).
+ knowledge_base_manager (`KnowledgeBaseManagerBase | None`, \
+ optional):
+ The application's knowledge base manager. When
+ provided and the session config carries a
+ ``knowledge_config``, a
+ :class:`~agentscope.middleware.RAGMiddleware`
+ is attached to the agent at run time. ``None``
+ disables knowledge-base wiring even for sessions that
+ have one configured.
extra_agent_middlewares (`AgentMiddlewareFactory | None`, \
optional):
Async factory invoked at every chat turn to produce
@@ -125,6 +137,7 @@ class ChatService:
self._scheduler_manager = scheduler_manager
self._background_task_manager = background_task_manager
self._message_bus = message_bus
+ self._knowledge_base_manager = knowledge_base_manager
self._extra_agent_middlewares = extra_agent_middlewares
self._extra_agent_tools = extra_agent_tools
self._sub_agent_templates = custom_subagent_templates
@@ -251,24 +264,7 @@ class ChatService:
)
# ----------------------------------------------------------------
- # 2. Toolkit (workspace tools + planning + ToolStop + schedule +
- # team + extras + skills + mcps).
- # ----------------------------------------------------------------
- toolkit = await get_toolkit(
- storage=self._storage,
- workspace=workspace,
- scheduler_manager=self._scheduler_manager,
- background_task_manager=self._background_task_manager,
- message_bus=self._message_bus,
- user_id=user_id,
- agent_record=agent_record,
- session_record=session_record,
- extra_factory=self._extra_agent_tools,
- sub_agent_templates=self._sub_agent_templates,
- )
-
- # ----------------------------------------------------------------
- # 3. Middlewares — framework-supplied first, then caller extras.
+ # 2. Middlewares — framework-supplied first, then caller extras.
# Background-tool completions deliver their results via
# ``message_bus.inbox_push + enqueue_wakeup``, so the dispatcher
# (any process) wakes an idle session — no in-process retrigger
@@ -297,7 +293,7 @@ class ChatService:
)
# ----------------------------------------------------------------
- # 3b. TTS middleware — inject when the session has a TTS config.
+ # 2b. TTS middleware — inject when the session has a TTS config.
# ----------------------------------------------------------------
tts_cfg = session_record.config.tts_model_config
if tts_cfg is not None:
@@ -308,6 +304,67 @@ class ChatService:
)
middlewares.append(TTSMiddleware(tts_model))
+ # ----------------------------------------------------------------
+ # 2c. Knowledge-base middleware — inject when the session has KBs
+ # attached. Each KB resolves to its own :class:`KnowledgeBase` handle
+ # (own embedding model + vector store), so the middleware can
+ # retrieve across heterogeneous KBs in one fan-out.
+ # ----------------------------------------------------------------
+ kb_cfg = session_record.config.knowledge_config
+ if (
+ kb_cfg is not None
+ and kb_cfg.knowledge_base_ids
+ and self._knowledge_base_manager is not None
+ ):
+ knowledges: list[KnowledgeBase] = []
+ for kb_id in kb_cfg.knowledge_base_ids:
+ try:
+ knowledge = (
+ await self._knowledge_base_manager.get_knowledge(
+ user_id,
+ kb_id,
+ )
+ )
+ except Exception: # pylint: disable=broad-except
+ # A KB the session referenced was deleted (or its
+ # credential revoked) — log and skip so the chat
+ # turn can still run with the remaining KBs.
+ logger.exception(
+ "Skipping knowledge base %r for session %r: "
+ "failed to resolve runtime handle.",
+ kb_id,
+ session_id,
+ )
+ continue
+ knowledges.append(knowledge)
+ if knowledges:
+ middlewares.append(
+ RAGMiddleware(
+ knowledge_bases=knowledges,
+ parameters=RAGMiddleware.Parameters(
+ **(kb_cfg.parameters or {}),
+ ),
+ ),
+ )
+
+ # ----------------------------------------------------------------
+ # 3. Toolkit (workspace tools + planning + ToolStop + schedule +
+ # team + extras + skills + mcps).
+ # ----------------------------------------------------------------
+ toolkit = await get_toolkit(
+ storage=self._storage,
+ workspace=workspace,
+ scheduler_manager=self._scheduler_manager,
+ background_task_manager=self._background_task_manager,
+ message_bus=self._message_bus,
+ middlewares=middlewares,
+ user_id=user_id,
+ agent_record=agent_record,
+ session_record=session_record,
+ extra_factory=self._extra_agent_tools,
+ sub_agent_templates=self._sub_agent_templates,
+ )
+
# ----------------------------------------------------------------
# 4. Model + fallback (resolved from session's config).
# ----------------------------------------------------------------
diff --git a/src/agentscope/app/_service/_embedding.py b/src/agentscope/app/_service/_embedding.py
index 5fd2bc948..9554c2085 100644
--- a/src/agentscope/app/_service/_embedding.py
+++ b/src/agentscope/app/_service/_embedding.py
@@ -81,17 +81,18 @@ async def get_embedding_model(
context_size = card.context_size
break
- # 4. Build parameters.
+ # 4. Build parameters (provider-specific, no dimensions).
parameters = (
embedding_cls.Parameters(**config.parameters)
if config.parameters
else None
)
- # 5. Construct the model, passing context_size from the card.
+ # 5. Construct the model — dimensions is first-class, not in parameters.
kwargs: dict = {
"credential": credential,
"model": config.model,
+ "dimensions": config.dimensions,
"parameters": parameters,
}
if context_size is not None:
diff --git a/src/agentscope/app/_service/_index_sweeper.py b/src/agentscope/app/_service/_index_sweeper.py
new file mode 100644
index 000000000..51f14a20c
--- /dev/null
+++ b/src/agentscope/app/_service/_index_sweeper.py
@@ -0,0 +1,150 @@
+# -*- coding: utf-8 -*-
+"""Background sweep for stuck knowledge-document indexing jobs.
+
+The indexing pipeline relies on two storage-level signals to keep
+moving when something goes wrong:
+
+- a *lease* per in-flight document — its ``lease_expires_at`` is the
+ upper bound on how long a worker may sit on the document before
+ another worker is allowed to take over;
+- a *creation timestamp* on every ``pending`` record — used to catch
+ documents that were never picked up by a worker (e.g. process died
+ right after the upload endpoint persisted the record).
+
+The sweeper periodically scans storage for both classes of stuck
+records and re-enqueues them on the index-task channel. Re-enqueue is
+safe because the worker's CAS lease acquisition rejects duplicates,
+so multiple nodes running their own sweeper does not produce double
+processing.
+"""
+import asyncio
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING
+
+from ..._logging import logger
+from .._bus_ops import enqueue_index_task
+
+if TYPE_CHECKING:
+ from ..message_bus import MessageBus
+ from ..storage import StorageBase
+
+
+class IndexSweeper:
+ """Periodically re-enqueues documents stuck in indexing.
+
+ Lifecycle is wired into the app's lifespan: :meth:`start` schedules
+ the background task and runs an immediate sweep so that documents
+ left stuck by the previous process generation get picked up at
+ once; :meth:`stop` cancels the loop on shutdown.
+ """
+
+ def __init__(
+ self,
+ storage: "StorageBase",
+ message_bus: "MessageBus",
+ interval: timedelta = timedelta(seconds=60),
+ pending_grace: timedelta = timedelta(minutes=5),
+ ) -> None:
+ """Initialize the sweeper.
+
+ Args:
+ storage (`StorageBase`):
+ Used to find stuck records and as the contract holder
+ for the lease semantics.
+ message_bus (`MessageBus`):
+ The same bus the upload endpoint uses. Re-enqueuing
+ a document re-enters the worker pipeline, where the
+ CAS lease acquisition decides whether to actually
+ process or bail.
+ interval (`timedelta`, defaults to ``60s``):
+ How often the loop wakes up. Roughly one order of
+ magnitude shorter than the typical lease TTL — fast
+ enough to recover from crashes within a few minutes,
+ slow enough not to thrash storage.
+ pending_grace (`timedelta`, defaults to ``5min``):
+ A record may legitimately sit in ``pending`` while the
+ bus push is still queued; only after this grace period
+ do we treat the record as orphaned.
+ """
+ self._storage = storage
+ self._bus = message_bus
+ self._interval = interval
+ self._pending_grace = pending_grace
+ self._task: asyncio.Task[None] | None = None
+
+ async def start(self) -> None:
+ """Start the background sweep loop and run one immediate sweep."""
+ if self._task is not None:
+ return
+ # Catch up from any state the previous generation left behind.
+ await self._sweep_once()
+ self._task = asyncio.create_task(
+ self._loop(),
+ name="kb-index-sweeper",
+ )
+
+ async def stop(self) -> None:
+ """Cancel the sweep loop and wait for it to exit."""
+ if self._task is None:
+ return
+ self._task.cancel()
+ try:
+ await self._task
+ except asyncio.CancelledError:
+ pass
+ self._task = None
+
+ async def _loop(self) -> None:
+ """Run sweeps forever until cancelled."""
+ interval_seconds = self._interval.total_seconds()
+ while True:
+ try:
+ await asyncio.sleep(interval_seconds)
+ except asyncio.CancelledError:
+ return
+ try:
+ await self._sweep_once()
+ except asyncio.CancelledError:
+ return
+ except Exception: # noqa: BLE001 — keep the loop alive
+ logger.exception("Sweep iteration failed")
+
+ async def _sweep_once(self) -> None:
+ """Find and re-enqueue every stuck document.
+
+ De-duplication: a document showing up in both the
+ expired-lease and orphan-pending queries (a record that was
+ never picked up and whose lease pre-dates the grace period)
+ is enqueued only once per sweep, by record id.
+ """
+ now = datetime.now()
+ pending_threshold = now - self._pending_grace
+
+ seen: set[str] = set()
+ stuck = (
+ await self._storage.list_knowledge_documents_with_expired_lease(
+ now=now,
+ )
+ )
+ orphans = await self._storage.list_knowledge_documents_pending_since(
+ threshold=pending_threshold,
+ )
+ for record in (*stuck, *orphans):
+ if record.id in seen:
+ continue
+ seen.add(record.id)
+ try:
+ await enqueue_index_task(
+ self._bus,
+ user_id=record.user_id,
+ knowledge_base_id=record.knowledge_base_id,
+ document_id=record.id,
+ )
+ except Exception: # noqa: BLE001 — keep iterating
+ logger.exception(
+ "Failed to re-enqueue document %s",
+ record.id,
+ )
+
+ if seen:
+ logger.info("Re-enqueued %d stuck document(s)", len(seen))
diff --git a/src/agentscope/app/_service/_index_task_consumer.py b/src/agentscope/app/_service/_index_task_consumer.py
new file mode 100644
index 000000000..3b3aaba67
--- /dev/null
+++ b/src/agentscope/app/_service/_index_task_consumer.py
@@ -0,0 +1,216 @@
+# -*- coding: utf-8 -*-
+"""Single per-worker-process consumer of the shared index-task channel.
+
+One asyncio task per worker process. Subscribes to the shared
+:meth:`~agentscope.app.message_bus.MessageBusKeys.index_tasks_signal`
+channel and drains the durable
+:meth:`~agentscope.app.message_bus.MessageBusKeys.index_tasks_queue`
+on each signal. For each queued entry it invokes
+:meth:`IndexWorker.process` directly — the worker holds its own
+semaphore so we can fire-and-forget multiple ``process`` calls without
+overrunning resources.
+
+Mirrors :class:`~agentscope.app._manager.WakeupDispatcher`. The two
+patterns are deliberately identical: both subscribe to a signal,
+drain a queue, dispatch each entry, and run forever inside an
+``async with`` block. Keeping them shaped the same makes it cheap to
+reason about either one once you've read the other.
+
+The bus exposes only transport-level primitives — there is no
+``enqueue_index_task`` or ``dequeue_index_task`` method on it. The
+key constants live on :class:`~agentscope.app.message_bus.
+MessageBusKeys` (next to every other application-layer key) and the
+composition is inline here because the consumer is the only sink for
+the channel; introducing a separate ``IndexTaskBroker`` would be
+ceremony without gain.
+"""
+import asyncio
+from typing import TYPE_CHECKING, Any, Self
+
+from ..message_bus import MessageBusKeys
+from ..._logging import logger
+
+if TYPE_CHECKING:
+ from ..message_bus import MessageBus
+ from ._index_worker import IndexWorker
+
+
+class IndexTaskConsumer:
+ """Subscribe-then-drain consumer that feeds :class:`IndexWorker`.
+
+ Args:
+ message_bus (`MessageBus`):
+ Application message bus. The consumer only uses the two
+ transport-level primitives — ``subscribe`` (for the
+ signal channel) and ``queue_drain`` (for the durable
+ task queue).
+ worker (`IndexWorker`):
+ The worker that owns the parse → chunk → index pipeline.
+ ``process`` is invoked once per queue entry; the worker's
+ internal semaphore + lease CAS handle concurrency and
+ deduplication.
+ max_batch (`int`, defaults to ``32``):
+ Maximum entries drained per signal. Keeps a single
+ signal from monopolising the loop when the queue is
+ backed up; remaining entries are picked up on the next
+ signal or the next sweeper-driven eager drain.
+ """
+
+ def __init__(
+ self,
+ message_bus: "MessageBus",
+ worker: "IndexWorker",
+ max_batch: int = 32,
+ ) -> None:
+ self._bus = message_bus
+ self._worker = worker
+ self._max_batch = max_batch
+ self._task: asyncio.Task | None = None
+ # In-flight ``worker.process`` calls. Tracked so ``__aexit__``
+ # can cancel + drain them; otherwise the event-loop teardown
+ # would swallow exceptions raised inside the worker.
+ self._inflight: set[asyncio.Task[Any]] = set()
+
+ async def __aenter__(self) -> Self:
+ """Start the consumer loop and wait until its subscription
+ is live.
+
+ After the subscription is established, an initial drain runs
+ synchronously so tasks queued while every worker was down
+ get picked up immediately on startup, without waiting for
+ a fresh signal.
+ """
+ ready = asyncio.Event()
+ self._task = asyncio.create_task(
+ self._loop(ready),
+ name="index-task-consumer",
+ )
+ await ready.wait()
+ await self._drain_and_dispatch()
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: Any,
+ ) -> None:
+ """Cancel the consumer loop and drain any in-flight work.
+
+ Cancellation of the worker's ``process`` calls is a clean
+ shutdown signal — the worker holds the storage lease and
+ will let it expire so the sweeper re-dispatches the document
+ on the next loop tick.
+ """
+ if self._task is not None:
+ self._task.cancel()
+ try:
+ await self._task
+ except asyncio.CancelledError:
+ pass
+ self._task = None
+
+ for task in list(self._inflight):
+ task.cancel()
+ if self._inflight:
+ await asyncio.gather(*self._inflight, return_exceptions=True)
+ self._inflight.clear()
+
+ # ------------------------------------------------------------------
+ # Internals
+ # ------------------------------------------------------------------
+
+ async def _loop(self, ready: asyncio.Event) -> None:
+ """Long-lived loop: subscribe to the signal and drain on each
+ received signal.
+
+ Args:
+ ready (`asyncio.Event`):
+ Signalled after the underlying SUBSCRIBE completes.
+ :meth:`__aenter__` blocks on this so the producer
+ can publish a signal immediately after start-up
+ without racing.
+ """
+ try:
+ async for _signal in self._bus.subscribe(
+ MessageBusKeys.index_tasks_signal(),
+ on_ready=ready.set,
+ ):
+ await self._drain_and_dispatch()
+ except Exception: # pylint: disable=broad-except
+ logger.exception(
+ "IndexTaskConsumer loop crashed; subscription ended.",
+ )
+ finally:
+ # If ``subscribe`` raises before ``on_ready`` fires, the
+ # ``__aenter__`` coroutine would deadlock on ``ready.wait()``.
+ # Set the event unconditionally on the way out so startup
+ # cannot stall on a transient bus failure.
+ ready.set()
+
+ async def _drain_and_dispatch(self) -> None:
+ """Read up to a batch of task entries and dispatch each one."""
+ try:
+ entries = await self._bus.queue_drain(
+ MessageBusKeys.index_tasks_queue(),
+ max_count=self._max_batch,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.exception("IndexTaskConsumer: drain failed.")
+ return
+
+ for _entry_id, payload in entries:
+ try:
+ user_id = payload["user_id"]
+ knowledge_base_id = payload["knowledge_base_id"]
+ document_id = payload["document_id"]
+ except (KeyError, TypeError):
+ logger.warning(
+ "IndexTaskConsumer: skipping malformed entry %r",
+ payload,
+ )
+ continue
+
+ self._spawn(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ document_id=document_id,
+ )
+
+ def _spawn(
+ self,
+ *,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Run :meth:`IndexWorker.process` as a tracked background task.
+
+ We do not ``await`` ``worker.process`` inline — a slow parse
+ would block draining the next signal. The worker holds its
+ own concurrency semaphore, so spawning many tasks at once is
+ safe; they will queue at the semaphore.
+ """
+ task = asyncio.create_task(
+ self._worker.process(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ document_id=document_id,
+ ),
+ name=f"index-task:{knowledge_base_id}:{document_id}",
+ )
+ self._inflight.add(task)
+ task.add_done_callback(self._on_done)
+
+ def _on_done(self, task: asyncio.Task[Any]) -> None:
+ """Drop the task reference and log any uncaught exception."""
+ self._inflight.discard(task)
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ logger.exception(
+ "IndexTaskConsumer: worker.process(%s) raised",
+ task.get_name(),
+ exc_info=exc,
+ )
diff --git a/src/agentscope/app/_service/_index_worker.py b/src/agentscope/app/_service/_index_worker.py
new file mode 100644
index 000000000..3c2eae7d7
--- /dev/null
+++ b/src/agentscope/app/_service/_index_worker.py
@@ -0,0 +1,534 @@
+# -*- coding: utf-8 -*-
+"""Background indexing pipeline for one knowledge document.
+
+The :class:`IndexWorker` owns the post-upload half of the document
+lifecycle. Given a ``document_id`` it:
+
+1. acquires the processing lease via storage CAS (so only one worker
+ in the cluster handles the document at a time);
+2. reads the bytes back from the blob store (streamed);
+3. routes to a parser by IANA media type;
+4. chunks the resulting sections;
+5. embeds + writes to the vector store through
+ :class:`~agentscope.rag.KnowledgeBase`;
+6. transitions the status through ``parsing → chunking → indexing →
+ ready`` (or ``error``) on the way.
+
+The worker is intentionally embeddable: a single instance can live
+inside the API process (embedded deployment) or inside a dedicated
+worker process (dedicated deployment). Coordination across workers
+is done entirely through the storage lease — workers do not need to
+know about each other.
+"""
+import asyncio
+import contextlib
+import mimetypes
+from concurrent.futures import ProcessPoolExecutor
+from datetime import timedelta
+from typing import TYPE_CHECKING
+
+from ..._logging import logger
+
+if TYPE_CHECKING:
+ from ..rag.blob_store import BlobStoreBase
+ from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
+ from ..storage import StorageBase
+ from ...rag import ChunkerBase, ParserBase, Section
+
+# Read blob bytes in chunks bounded so the worker never holds the whole
+# file in memory at once even when the parser is byte-oriented.
+_READ_CHUNK = 1 << 20 # 1 MiB
+
+
+def _build_parser_registry(
+ parsers: "list[ParserBase] | dict[str, ParserBase]",
+) -> "dict[str, ParserBase]":
+ """Normalise the user-supplied parser registry.
+
+ Two input shapes are accepted:
+
+ - **List** — each parser's ``supported_media_types`` is expanded;
+ duplicate media types resolve to the **last** parser in the list
+ (so callers can layer custom parsers over the defaults), with a
+ warning logged for each override so silent shadowing is not
+ possible.
+ - **Dict** — the caller's mapping is used verbatim. This is the
+ escape hatch for callers who want full control over routing (one
+ parser bound to multiple types, type aliases, etc.); a warning is
+ logged when a parser is registered against a media type it does
+ not declare in ``supported_media_types``, since that almost
+ always indicates a typo.
+
+ Args:
+ parsers (`list[ParserBase] | dict[str, ParserBase]`):
+ The user-supplied parser registry.
+
+ Returns:
+ `dict[str, ParserBase]`:
+ The resolved ``media_type → parser`` routing table.
+ """
+ if isinstance(parsers, dict):
+ for media_type, parser in parsers.items():
+ declared = getattr(parser, "supported_media_types", ())
+ if declared and media_type not in declared:
+ logger.warning(
+ "Parser %s registered for media type %r but it only "
+ "declares %s — proceeding with the caller-supplied "
+ "mapping.",
+ type(parser).__name__,
+ media_type,
+ list(declared),
+ )
+ return dict(parsers)
+
+ registry: dict[str, "ParserBase"] = {}
+ for parser in parsers:
+ for media_type in parser.supported_media_types:
+ previous = registry.get(media_type)
+ if previous is not None and previous is not parser:
+ logger.warning(
+ "Parser %s overrides %s for media type %r — later "
+ "entries in `parsers` win. Pass a "
+ "`dict[str, ParserBase]` if you want explicit "
+ "routing.",
+ type(parser).__name__,
+ type(previous).__name__,
+ media_type,
+ )
+ registry[media_type] = parser
+ return registry
+
+
+class IndexWorker:
+ """Drive one document through parse → chunk → index.
+
+ Multiple invocations of :meth:`process` are run concurrently up to
+ a per-worker semaphore. The semaphore protects shared resources
+ that scale with the number of in-flight parses (memory for big
+ PDFs, embedding API rate budget), while the lease CAS in storage
+ protects against the *cross-worker* version of the same race.
+ """
+
+ def __init__(
+ self,
+ storage: "StorageBase",
+ blob_store: "BlobStoreBase",
+ knowledge_base_manager: "KnowledgeBaseManagerBase",
+ parsers: "list[ParserBase] | dict[str, ParserBase]",
+ chunker: "ChunkerBase",
+ node_id: str,
+ max_concurrency: int = 4,
+ lease_ttl: timedelta = timedelta(seconds=90),
+ parser_executor: ProcessPoolExecutor | None = None,
+ ) -> None:
+ """Initialize the worker.
+
+ Args:
+ storage (`StorageBase`):
+ Document records, lease, status.
+ blob_store (`BlobStoreBase`):
+ Source of the document bytes.
+ knowledge_base_manager (`KnowledgeBaseManagerBase`):
+ Resolves the :class:`KnowledgeBase` runtime for embedding
+ and vector store writes.
+ parsers (`list[ParserBase] | dict[str, ParserBase]`):
+ Parsers used to dispatch uploads by IANA media type.
+ Two input shapes are accepted:
+
+ - **List** — each parser's ``supported_media_types`` is
+ expanded into a routing table; later entries override
+ earlier ones for overlapping types, with a warning
+ logged at construction time.
+ - **Dict** — caller-supplied ``media_type → parser``
+ routing table used verbatim. ``supported_media_types``
+ is **not** consulted, but a warning is logged if a
+ parser is registered against a media type it does not
+ declare.
+
+ Same registry the upload service uses, passed in by DI.
+ chunker (`ChunkerBase`):
+ The shared chunker.
+ node_id (`str`):
+ Stable identifier for this worker process. Used as
+ ``processing_node`` on the lease so the sweeper can
+ tell whose work expired. Typically
+ ``f"{hostname}:{pid}:{uuid}"``.
+ max_concurrency (`int`, defaults to ``4``):
+ Maximum number of documents processed concurrently by
+ this worker. Higher values trade memory for
+ throughput; tune per embedding-API rate limits and
+ per-document parse cost.
+ lease_ttl (`timedelta`, defaults to ``90s``):
+ How long a single processing lease lives. The worker
+ renews periodically so long-running parses do not
+ trip the sweeper.
+ parser_executor (`ProcessPoolExecutor | None`, optional):
+ Process pool used to off-load CPU-intensive parses
+ (PDF, Office). ``None`` runs parses in the event-loop
+ thread, which is fine for plain text but unsafe for
+ third-party byte-oriented parsers. Injected so a
+ single pool can be shared across the app (built in
+ lifespan).
+ """
+ self._storage = storage
+ self._blob_store = blob_store
+ self._manager = knowledge_base_manager
+ self._parsers_by_media_type = _build_parser_registry(parsers)
+ self._chunker = chunker
+ self._node_id = node_id
+ self._lease_ttl = lease_ttl
+ self._sem = asyncio.Semaphore(max_concurrency)
+ self._parser_executor = parser_executor
+ # Renewal cadence: refresh while there is still half the lease
+ # left so a one-cycle missed renewal doesn't drop the lease.
+ self._renew_interval = max(lease_ttl / 2, timedelta(seconds=5))
+
+ async def process(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Run the full indexing pipeline for one document.
+
+ Steps:
+
+ 1. **Lease** — CAS-acquire the processing lease; bail if some
+ other worker already holds it (duplicate dispatch / sweep).
+ 2. **Throttle** — wait on the per-worker semaphore so the
+ number of in-flight parses stays bounded.
+ 3. **Pipeline** — parse → chunk → embed + write vector store,
+ updating status before each phase. A background heartbeat
+ keeps the lease alive while parsing runs.
+ 4. **Finalise** — on success mark ``ready`` with the final
+ chunk count; on failure mark ``error`` with a sanitised
+ message. The lease is released regardless.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document to process.
+ """
+ acquired = await self._storage.acquire_knowledge_document_lease(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ document_id=document_id,
+ processing_node=self._node_id,
+ lease_ttl=self._lease_ttl,
+ )
+ if not acquired:
+ logger.debug(
+ "Skipping %s — another worker holds the lease.",
+ document_id,
+ )
+ return
+
+ pipeline_task = asyncio.create_task(
+ self._guarded_pipeline(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ ),
+ name=f"pipeline:{document_id}",
+ )
+ heartbeat_task = asyncio.create_task(
+ self._heartbeat(user_id, knowledge_base_id, document_id),
+ name=f"lease-renew:{document_id}",
+ )
+ try:
+ # Race the pipeline against the heartbeat: if the heartbeat
+ # returns first, the lease was stolen mid-flight (e.g. the
+ # sweeper reaped this worker after a renewal gap) — we MUST
+ # stop the pipeline before it writes the vector store again,
+ # otherwise the worker that just took over and this one will
+ # both insert the same chunks.
+ await asyncio.wait(
+ {pipeline_task, heartbeat_task},
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+
+ if not pipeline_task.done():
+ # Heartbeat reached the end first; only `_heartbeat`'s
+ # lost-lease branch returns, so cancel the pipeline and
+ # surface it as a terminal error for this document.
+ pipeline_task.cancel()
+ with contextlib.suppress(
+ asyncio.CancelledError,
+ Exception,
+ ):
+ await pipeline_task
+ raise RuntimeError(
+ f"Lost lease on {document_id} during processing; "
+ "another worker has taken over.",
+ )
+
+ # Pipeline finished first; stop the heartbeat and re-raise
+ # whatever the pipeline raised (if anything).
+ heartbeat_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await heartbeat_task
+ await pipeline_task
+ except Exception as exc: # noqa: BLE001 — terminal error sink
+ await self._mark_error(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ exc,
+ )
+ finally:
+ # Release is CAS-guarded server-side on ``processing_node``
+ # (storage._base.release_knowledge_document_lease) — calling
+ # it after a stolen lease is a safe no-op.
+ await self._storage.release_knowledge_document_lease(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ document_id=document_id,
+ processing_node=self._node_id,
+ )
+
+ async def _guarded_pipeline(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Run the throttled pipeline inside the per-worker semaphore."""
+ async with self._sem:
+ await self._run_pipeline(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+
+ # ------------------------------------------------------------------
+ # Pipeline
+ # ------------------------------------------------------------------
+
+ async def _run_pipeline(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Walk the document through parse → chunk → index."""
+ record = await self._storage.get_knowledge_document(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+ if record is None:
+ logger.warning(
+ "Document %s vanished before processing.",
+ document_id,
+ )
+ return
+
+ data = record.data
+ media_type = (
+ data.content_type or mimetypes.guess_type(data.filename)[0]
+ )
+ if not media_type:
+ raise ValueError(
+ f"Cannot determine media type for {data.filename!r}.",
+ )
+ parser = self._parsers_by_media_type.get(media_type)
+ if parser is None:
+ raise ValueError(
+ f"No parser registered for media type {media_type!r}.",
+ )
+
+ # ---- parsing ----
+ await self._storage.update_knowledge_document_status(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ "parsing",
+ )
+ file_bytes = await self._read_blob(data.blob_uri)
+ sections = await self._parse(parser, file_bytes, data.filename)
+
+ # ---- chunking ----
+ await self._storage.update_knowledge_document_status(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ "chunking",
+ )
+ chunks = await self._chunker.chunk(sections)
+
+ # ---- indexing ----
+ await self._storage.update_knowledge_document_status(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ "indexing",
+ )
+ knowledge = await self._manager.get_knowledge(
+ user_id,
+ knowledge_base_id,
+ )
+ await knowledge.insert_document(
+ chunks=chunks,
+ document_id=document_id,
+ document_metadata={
+ "filename": data.filename,
+ "media_type": media_type,
+ "size_bytes": data.size,
+ },
+ )
+
+ # ---- ready ----
+ await self._storage.update_knowledge_document_status(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ "ready",
+ chunk_count=len(chunks),
+ )
+
+ async def _parse(
+ self,
+ parser: "ParserBase",
+ file_bytes: bytes,
+ filename: str,
+ ) -> "list[Section]":
+ """Run the parser, optionally on the process pool."""
+ if self._parser_executor is None:
+ return await parser.parse(file_bytes, filename)
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(
+ self._parser_executor,
+ _run_parser_sync,
+ parser,
+ file_bytes,
+ filename,
+ )
+
+ async def _read_blob(self, blob_uri: str) -> bytes:
+ """Stream the blob into memory in bounded chunks.
+
+ We buffer the whole file before handing it to the parser
+ because today's parser API is byte-oriented (``parse(file:
+ bytes, filename: str)``). The read loop still avoids large
+ single allocations and gives us a single place to upgrade to a
+ true streaming parser API later — only this method needs to
+ change.
+ """
+ buffer = bytearray()
+ async with self._blob_store.open(blob_uri) as fp:
+ while True:
+ chunk = await fp.read(_READ_CHUNK)
+ if not chunk:
+ break
+ buffer.extend(chunk)
+ return bytes(buffer)
+
+ # ------------------------------------------------------------------
+ # Lease heartbeat
+ # ------------------------------------------------------------------
+
+ async def _heartbeat(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Renew the lease in the background while processing runs.
+
+ Two exit paths:
+
+ - The surrounding pipeline finishes first and cancels this
+ task — silent return via :class:`asyncio.CancelledError`.
+ - The renewal fails (the sweeper reaped this worker and
+ another worker now holds the lease). The task **returns
+ normally** in this case; :meth:`process` is racing this task
+ against the pipeline and treats a normal return as the
+ "lost-lease" signal, cancelling the pipeline before it
+ double-writes the vector store.
+
+ Anything other than ``ok=False`` keeps the loop alive.
+ """
+ interval_seconds = self._renew_interval.total_seconds()
+ while True:
+ try:
+ await asyncio.sleep(interval_seconds)
+ except asyncio.CancelledError:
+ return
+ ok = await self._storage.renew_knowledge_document_lease(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ document_id=document_id,
+ processing_node=self._node_id,
+ lease_ttl=self._lease_ttl,
+ )
+ if not ok:
+ logger.warning(
+ "Lost lease on %s while processing.",
+ document_id,
+ )
+ return
+
+ # ------------------------------------------------------------------
+ # Error sink
+ # ------------------------------------------------------------------
+
+ async def _mark_error(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ exc: BaseException,
+ ) -> None:
+ """Persist a sanitised error and mark the document failed."""
+ logger.exception(
+ "Indexing failed for %s/%s",
+ knowledge_base_id,
+ document_id,
+ exc_info=exc,
+ )
+ message = _sanitise_error(exc)
+ try:
+ await self._storage.update_knowledge_document_status(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ "error",
+ error=message,
+ )
+ except Exception: # noqa: BLE001 — last-resort log
+ logger.exception(
+ "Failed to persist error status for %s",
+ document_id,
+ )
+
+
+# ----------------------------------------------------------------------
+# Module-level helpers (picklable for ProcessPoolExecutor)
+# ----------------------------------------------------------------------
+
+
+def _run_parser_sync(
+ parser: "ParserBase",
+ file_bytes: bytes,
+ filename: str,
+) -> "list[Section]":
+ """Run an async parser to completion inside a sync executor."""
+ return asyncio.run(parser.parse(file_bytes, filename))
+
+
+def _sanitise_error(exc: BaseException) -> str:
+ """Reduce an exception to a single user-facing line.
+
+ Only the exception class name + first line of its message are
+ kept — stack traces and filesystem paths stay inside the worker
+ log and out of the user-visible record.
+ """
+ raw = str(exc) or exc.__class__.__name__
+ first_line = raw.splitlines()[0].strip()
+ cls = exc.__class__.__name__
+ if not first_line:
+ return cls
+ return f"{cls}: {first_line[:240]}"
diff --git a/src/agentscope/app/_service/_knowledge_base.py b/src/agentscope/app/_service/_knowledge_base.py
new file mode 100644
index 000000000..7fb514e0c
--- /dev/null
+++ b/src/agentscope/app/_service/_knowledge_base.py
@@ -0,0 +1,515 @@
+# -*- coding: utf-8 -*-
+"""Knowledge base service: HTTP-side orchestration.
+
+The router stays thin and DTO-shaped; everything HTTP-side that needs
+to coordinate persistence, the blob store, the indexing pipeline,
+and the vector store goes through this service.
+
+The split with :class:`~agentscope.rag.KnowledgeBase`
+is deliberate. ``KnowledgeBase`` is a **library-mode** handle that only
+depends on the vector store; embedded users instantiate one and drive
+the parse → chunk → embed pipeline themselves. ``KnowledgeBaseService``
+is **service-mode** orchestration: it owns the document records
+(status / blob / lease) and is the single source of truth for "what
+documents exist in this KB" when the app is running over HTTP. The
+two views are intentionally not blended — mixing library-mode inserts
+with service-mode listing would leave records out of sync, and the
+project's stance is that a knowledge base is managed end-to-end in one
+mode.
+"""
+import uuid
+from typing import IO, TYPE_CHECKING
+
+from fastapi import HTTPException, status
+
+from ..rag.knowledge_base_manager import (
+ DimensionPolicyError,
+ KnowledgeBaseNotFoundError,
+)
+from ..storage import (
+ KnowledgeDocumentData,
+ KnowledgeDocumentRecord,
+)
+from ..._logging import logger
+from .._bus_ops import enqueue_index_task
+
+if TYPE_CHECKING:
+ from ..rag.blob_store import BlobStoreBase
+ from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
+ from ..message_bus import MessageBus
+ from ..storage import (
+ EmbeddingModelConfig,
+ KnowledgeBaseRecord,
+ StorageBase,
+ )
+ from ...rag import VectorSearchResult
+
+
+class KnowledgeBaseService:
+ """HTTP service for knowledge bases.
+
+ Owns the document lifecycle in service mode: register on upload,
+ enqueue an index task, query status during indexing, and clean up
+ record + blob + vector store on delete. All parsing / chunking /
+ embedding work happens inside the
+ :class:`~agentscope.app._service.IndexWorker`; the service only
+ hands off (via the message bus) and observes.
+ """
+
+ def __init__(
+ self,
+ storage: "StorageBase",
+ knowledge_base_manager: "KnowledgeBaseManagerBase",
+ blob_store: "BlobStoreBase",
+ message_bus: "MessageBus",
+ ) -> None:
+ """Initialize the service.
+
+ Args:
+ storage (`StorageBase`):
+ The application storage backend; documents are
+ persisted here, not inside the vector store.
+ knowledge_base_manager (`KnowledgeBaseManagerBase`):
+ Resolves the :class:`KnowledgeBase` runtime used to clear
+ vector store records on document deletion.
+ blob_store (`BlobStoreBase`):
+ Owns the bytes from upload until the worker is done.
+ The service writes on upload and deletes on document
+ removal.
+ message_bus (`MessageBus`):
+ Application message bus. The service publishes one
+ index-task entry per uploaded document via
+ :func:`~agentscope.app._bus_ops.enqueue_index_task`;
+ a co-located or out-of-process
+ :class:`IndexTaskConsumer` drains and processes them.
+ """
+ self._storage = storage
+ self._manager = knowledge_base_manager
+ self._blob_store = blob_store
+ self._bus = message_bus
+
+ # ------------------------------------------------------------------
+ # Knowledge base CRUD
+ # ------------------------------------------------------------------
+
+ async def create_knowledge_base(
+ self,
+ user_id: str,
+ name: str,
+ description: str,
+ embedding_model_config: "EmbeddingModelConfig",
+ ) -> "KnowledgeBaseRecord":
+ """Delegate creation to the manager, mapping policy errors.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ name (`str`):
+ Display name.
+ description (`str`):
+ Free-form description.
+ embedding_model_config (`EmbeddingModelConfig`):
+ Embedding model configuration; pinned to the record.
+
+ Returns:
+ `KnowledgeBaseRecord`:
+ The newly persisted record.
+
+ Raises:
+ `HTTPException`:
+ ``409`` when the requested embedding dimension
+ violates the manager's dimension policy.
+ """
+ try:
+ return await self._manager.create_knowledge_base(
+ user_id=user_id,
+ name=name,
+ description=description,
+ embedding_model_config=embedding_model_config,
+ )
+ except DimensionPolicyError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=str(exc),
+ ) from exc
+
+ async def list_knowledge_bases(
+ self,
+ user_id: str,
+ ) -> "list[KnowledgeBaseRecord]":
+ """List all knowledge base records owned by the given user.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+
+ Returns:
+ `list[KnowledgeBaseRecord]`:
+ All knowledge base records belonging to the user.
+ """
+ return await self._manager.list_knowledge_bases(user_id)
+
+ async def update_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ name: str | None = None,
+ description: str | None = None,
+ ) -> "KnowledgeBaseRecord":
+ """Update mutable fields on a knowledge base, raising 404 if absent.
+
+ Only ``name`` and ``description`` are mutable. The embedding
+ model configuration is pinned at creation time.
+ """
+ record = await self._manager.update_knowledge_base(
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ name=name,
+ description=description,
+ )
+ if record is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Knowledge base {knowledge_base_id!r} not found.",
+ )
+ return record
+
+ async def delete_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> None:
+ """Delete a knowledge base, raising 404 if absent.
+
+ Documents under the KB are cascade-deleted at the storage
+ layer; blob files referenced by those records are released
+ best-effort here so disk space is reclaimed even though the
+ manager + storage cascade would otherwise orphan them.
+ """
+ documents = await self._storage.list_knowledge_documents(
+ user_id,
+ knowledge_base_id,
+ )
+ for document in documents:
+ await self._delete_blob_quietly(document.data.blob_uri)
+
+ deleted = await self._manager.delete_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if not deleted:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Knowledge base {knowledge_base_id!r} not found.",
+ )
+
+ # ------------------------------------------------------------------
+ # Document management
+ # ------------------------------------------------------------------
+
+ async def register_document(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ filename: str,
+ stream: IO[bytes],
+ size: int,
+ content_type: str | None = None,
+ ) -> KnowledgeDocumentRecord:
+ """Persist an uploaded document and enqueue it for indexing.
+
+ Streams ``stream`` into the blob store (so the bytes never
+ live fully in memory), records a ``pending`` document, and
+ pushes an index-task entry onto the message bus. Returns
+ immediately — a worker (in-process or dedicated) takes over
+ from here and the client tracks progress via
+ :meth:`get_document_status`.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The target knowledge base id.
+ filename (`str`):
+ The original filename.
+ stream (`IO[bytes]`):
+ A synchronous binary stream — typically
+ ``UploadFile.file`` from FastAPI.
+ size (`int`):
+ Byte length declared by the uploader. Persisted on
+ the record for the UI; not authoritative.
+ content_type (`str | None`, optional):
+ IANA media type; ``None`` lets the worker fall back
+ to a filename guess at processing time.
+
+ Returns:
+ `KnowledgeDocumentRecord`:
+ The persisted record (``status='pending'``) with the
+ final ``blob_uri`` filled in.
+
+ Raises:
+ `HTTPException`:
+ ``404`` if the knowledge base does not exist.
+ """
+ # Authorise before touching the blob store: raising after a
+ # write would leave the blob orphaned.
+ await self._authorise_kb(user_id, knowledge_base_id)
+
+ document_id = uuid.uuid4().hex
+ blob_uri = await self._blob_store.write_stream(
+ key=f"kb/{knowledge_base_id}/{document_id}",
+ stream=stream,
+ )
+
+ record = KnowledgeDocumentRecord(
+ id=document_id,
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ data=KnowledgeDocumentData(
+ filename=filename,
+ size=size,
+ content_type=content_type,
+ blob_uri=blob_uri,
+ ),
+ )
+ try:
+ stored = await self._storage.upsert_knowledge_document(
+ user_id,
+ record,
+ )
+ except Exception:
+ # Storage write failed — drop the blob so the orphan
+ # sweeper doesn't later see a referenced-by-nobody file.
+ await self._delete_blob_quietly(blob_uri)
+ raise
+
+ await enqueue_index_task(
+ self._bus,
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ document_id=document_id,
+ )
+ return stored
+
+ async def list_documents(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> list[KnowledgeDocumentRecord]:
+ """List every document registered against a knowledge base.
+
+ Service-mode source of truth: reads from storage, NOT the
+ vector store. Documents in ``pending`` / ``parsing`` /
+ ``chunking`` / ``indexing`` / ``error`` show up here even
+ though they have no chunks in the vector store yet.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The target knowledge base id.
+
+ Returns:
+ `list[KnowledgeDocumentRecord]`:
+ Every document registered against the knowledge base,
+ in unspecified order.
+
+ Raises:
+ `HTTPException`:
+ ``404`` if the knowledge base does not exist.
+ """
+ await self._authorise_kb(user_id, knowledge_base_id)
+ return await self._storage.list_knowledge_documents(
+ user_id,
+ knowledge_base_id,
+ )
+
+ async def get_document_status(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_ids: list[str],
+ ) -> list[KnowledgeDocumentRecord]:
+ """Batch-fetch documents for status polling.
+
+ The endpoint backing this method accepts a comma-separated list
+ of ids so the front-end can ask "what's the state of these N
+ in-flight uploads" in a single round-trip. Records that do
+ not exist or do not belong to the user are silently skipped —
+ the front-end may legitimately ask about a document that was
+ deleted between two polls.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The target knowledge base id.
+ document_ids (`list[str]`):
+ Document ids to look up.
+
+ Returns:
+ `list[KnowledgeDocumentRecord]`:
+ One record per matched id; missing ids omitted.
+
+ Raises:
+ `HTTPException`:
+ ``404`` if the knowledge base does not exist.
+ """
+ await self._authorise_kb(user_id, knowledge_base_id)
+ records: list[KnowledgeDocumentRecord] = []
+ for document_id in document_ids:
+ record = await self._storage.get_knowledge_document(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+ if record is not None:
+ records.append(record)
+ return records
+
+ async def delete_document(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Remove a document end-to-end: vector store, record, blob.
+
+ Order is chosen so that a crash mid-way always leaves a
+ recoverable state:
+
+ 1. Vector store delete (idempotent — re-deleting an already
+ empty document_id is harmless).
+ 2. Storage record delete.
+ 3. Blob delete (idempotent).
+
+ A failure at step 1 surfaces as an exception to the caller and
+ the record + blob are left untouched, so a retry sees the same
+ state. Failures at steps 2/3 leave a small amount of orphan
+ data but the user-visible deletion has already succeeded from
+ the vector store's point of view.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The target knowledge base id.
+ document_id (`str`):
+ The document to delete.
+
+ Raises:
+ `HTTPException`:
+ ``404`` if the knowledge base does not exist.
+ """
+ record = await self._storage.get_knowledge_document(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+ if record is None:
+ # 404 if the KB does not exist, otherwise treat the
+ # missing document as already-deleted (idempotent).
+ await self._authorise_kb(user_id, knowledge_base_id)
+ return
+
+ knowledge = await self._resolve_knowledge(user_id, knowledge_base_id)
+ await knowledge.delete_document(document_id)
+ await self._storage.delete_knowledge_document(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+ await self._delete_blob_quietly(record.data.blob_uri)
+
+ # ------------------------------------------------------------------
+ # Search
+ # ------------------------------------------------------------------
+
+ async def search(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ query: str,
+ top_k: int = 5,
+ ) -> "list[VectorSearchResult]":
+ """Search a knowledge base by text query.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The knowledge base to search.
+ query (`str`):
+ The natural-language query.
+ top_k (`int`, defaults to ``5``):
+ Maximum number of results.
+
+ Returns:
+ `list[VectorSearchResult]`:
+ The top hits ordered by descending similarity score.
+
+ Raises:
+ `HTTPException`:
+ ``404`` if the knowledge base does not exist.
+ """
+ knowledge = await self._resolve_knowledge(user_id, knowledge_base_id)
+ return await knowledge.search(queries=[query], top_k=top_k)
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ async def _authorise_kb(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> "KnowledgeBaseRecord":
+ """Look the KB record up so we can 404 cleanly.
+
+ The check is intentionally separate from :meth:`_resolve_knowledge`
+ because document-level endpoints (list / delete) need to refuse
+ unknown KBs without paying the embedding-model construction cost
+ that :meth:`_resolve_knowledge` triggers.
+ """
+ record = await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if record is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Knowledge base {knowledge_base_id!r} not found.",
+ )
+ return record
+
+ async def _resolve_knowledge(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> "object":
+ """Resolve a :class:`KnowledgeBase` and translate not-found to 404."""
+ try:
+ return await self._manager.get_knowledge(
+ user_id,
+ knowledge_base_id,
+ )
+ except KnowledgeBaseNotFoundError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=str(exc),
+ ) from exc
+
+ async def _delete_blob_quietly(self, blob_uri: str) -> None:
+ """Best-effort blob delete — swallow backend errors.
+
+ Treated as cleanup: if the blob store is unavailable the
+ record/vector-store state is still consistent and a future
+ sweep can reclaim the disk space. Surface only via logs.
+ """
+ try:
+ await self._blob_store.delete(blob_uri)
+ except Exception: # noqa: BLE001 — cleanup only
+ logger.exception(
+ "Failed to delete blob %s",
+ blob_uri,
+ )
diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.py
index a9bdfdfd4..fa86e68f8 100644
--- a/src/agentscope/app/_service/_toolkit.py
+++ b/src/agentscope/app/_service/_toolkit.py
@@ -13,6 +13,7 @@ from ..message_bus import MessageBus
from .._tool import AgentCreate, TeamCreate, TeamDelete, TeamSay
from .._types import AgentToolFactory, SubAgentTemplate
from ..storage import AgentRecord, SessionRecord, StorageBase
+from ...middleware import MiddlewareBase
from ...tool import (
TaskCreate,
TaskGet,
@@ -31,6 +32,7 @@ async def get_toolkit(
scheduler_manager: SchedulerManager,
background_task_manager: BackgroundTaskManager,
message_bus: MessageBus,
+ middlewares: list[MiddlewareBase],
user_id: str,
agent_record: AgentRecord,
session_record: SessionRecord,
@@ -79,6 +81,9 @@ async def get_toolkit(
Application message bus; passed to team tools so they can
push HintBlocks + wakeups when delivering inter-session
messages.
+ middlewares (`list[MiddlewareBase]`):
+ The agent middlewares that may provide tools to the agent via the
+ `list_tools` interface.
user_id (`str`):
Caller user id.
agent_record (`AgentRecord`):
@@ -175,6 +180,10 @@ time or interval"
session_record.id,
)
+ # Tools from middleware
+ for mw in middlewares:
+ tools.extend(await mw.list_tools())
+
return Toolkit(
tools=tools,
skills_or_loaders=await workspace.list_skills(),
diff --git a/src/agentscope/app/_tools/__init__.py b/src/agentscope/app/_tools/__init__.py
deleted file mode 100644
index 6ad921716..000000000
--- a/src/agentscope/app/_tools/__init__.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# -*- coding: utf-8 -*-
-"""Framework-builtin tools wired into team-participating agents.
-
-These tools differ from the workspace-provided builtins (Bash, Read,
-Task series, …) in two ways:
-
-1. **Construction depends on app-level resources** — they bind a
- :class:`StorageBase` + :class:`MessageBus` reference plus the
- request-scoped ``user_id`` / ``session_id`` / ``agent_id`` at agent
- assembly time, and call storage / bus directly in their
- ``__call__`` (no intermediate service layer).
-2. **Visibility depends only on the agent's source field** —
- ``source='user'`` agents always see the full leader-side toolset
- (``TeamCreate / AgentCreate / TeamSay / TeamDelete``) regardless of
- whether they currently lead a team. Each tool checks the storage
- state at ``__call__`` time and fails clearly if its precondition
- is not met. ``source='team'`` workers only see ``TeamSay``.
-
- The benefit is that a single chat run can ``TeamCreate`` and then
- ``AgentCreate`` immediately afterward — there is no toolkit
- refresh point because the toolkit never changed; only the
- underlying storage state did, which the next tool reads fresh.
-
-Selection of the right subset by ``agent.source`` happens inline in
-:func:`get_toolkit`; there is no separate "team tool factory" helper.
-"""
-from ._agent_create import AgentCreate, DEFAULT_SUB_AGENT_TEMPLATE
-from ._team_create import TeamCreate
-from ._team_delete import TeamDelete
-from ._team_say import TeamSay
-
-__all__ = [
- "AgentCreate",
- "DEFAULT_SUB_AGENT_TEMPLATE",
- "TeamCreate",
- "TeamDelete",
- "TeamSay",
-]
diff --git a/src/agentscope/app/_tools/_agent_create.py b/src/agentscope/app/_tools/_agent_create.py
deleted file mode 100644
index 381d393b8..000000000
--- a/src/agentscope/app/_tools/_agent_create.py
+++ /dev/null
@@ -1,527 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The AgentCreate tool — spawns a worker into the current team."""
-from __future__ import annotations
-
-import copy
-import json
-from typing import TYPE_CHECKING
-
-from pydantic import Field
-
-from ._team_tool_base import _TeamToolBase
-from .._types import SubAgentTemplate
-from ..storage import AgentData, AgentRecord, SessionConfig
-from ...message import HintBlock, TextBlock, ToolResultState
-from ...permission import PermissionContext
-from ...state import AgentState
-from ...tool import ToolChunk, ParamsBase
-
-if TYPE_CHECKING:
- from ..message_bus import MessageBus
- from ..storage import StorageBase
-
-
-_DEFAULT_SYSTEM_PROMPT_TEMPLATE = (
- "You are {member_name}, a member of team '{team_name}' led by "
- "{leader_name}.\n\n"
- "Team purpose: {team_description}\n\n"
- "Your role: {member_description}\n\n"
- "You communicate with the team leader and other members "
- "through the TeamSay tool. "
- "Speak on the team only when you have something "
- "external to share — your private reasoning stays private."
-)
-
-DEFAULT_SUB_AGENT_TEMPLATE = SubAgentTemplate(
- type="default",
- description="Default worker agent with standard configuration.",
- system_prompt_template=_DEFAULT_SYSTEM_PROMPT_TEMPLATE,
- override_leader_mode=False,
- extend_leader_permission_rules=True,
- extend_leader_working_directories=True,
-)
-# The built-in default sub-agent template.
-#
-# Used when no custom templates are registered, or when the leader
-# agent creates a member without specifying a ``subagent_type`` (or
-# explicitly specifies ``subagent_type="default"``). Developers can
-# override this by registering their own template with
-# ``type="default"`` via :func:`~agentscope.app.create_app`.
-#
-# The default template fully follows the leader: the worker inherits
-# the leader's permission mode, working directories, and rules —
-# matching the intuition that a generic worker should behave like the
-# leader unless the developer registers a more opinionated template.
-
-
-def _merge_leader_permissions(
- template: SubAgentTemplate,
- leader_context: PermissionContext,
-) -> PermissionContext:
- """Build the worker's permission context from the template, layered
- with the leader's runtime state according to the template's three
- inherit-from-leader flags.
-
- - ``override_leader_mode``: if True, the template's
- :attr:`PermissionContext.mode` wins; otherwise the worker
- inherits the leader's mode.
- - ``extend_leader_permission_rules``: if True, the leader's
- allow/deny/ask rules are appended after the template's rules for
- each tool, so the worker doesn't re-prompt for permissions the
- user has already granted in the leader session. The template's
- rules appear first in each list, so the engine — which returns
- on the first matching rule per stage — evaluates the template's
- intent before the leader's.
- - ``extend_leader_working_directories``: if True, the leader's
- working directories are merged in; on key (path) collisions the
- template's entry wins.
-
- The template fields are deep-copied so the returned context is
- independent of both the template and the leader state.
- """
- merged = template.permission_context.model_copy(deep=True)
-
- if not template.override_leader_mode:
- merged.mode = leader_context.mode
-
- if template.extend_leader_working_directories:
- for path, wd in leader_context.working_directories.items():
- merged.working_directories.setdefault(
- path,
- wd.model_copy(deep=True),
- )
-
- if template.extend_leader_permission_rules:
- for attr in ("allow_rules", "deny_rules", "ask_rules"):
- merged_rules: dict = getattr(merged, attr)
- for tool_name, rules in getattr(leader_context, attr).items():
- merged_rules.setdefault(tool_name, []).extend(
- r.model_copy(deep=True) for r in rules
- )
-
- return merged
-
-
-class _AgentCreateParams(ParamsBase):
- """Parameters for :class:`AgentCreate`."""
-
- name: str = Field(
- description=(
- 'Short identifier for the new member, e.g. ``"researcher"`` '
- 'or ``"coder-1"``. Other members address it via '
- "``TeamSay(to=<this name>)``, so it MUST be unique within "
- "the team."
- ),
- )
- description: str = Field(
- description=(
- "One-sentence summary of the member's role — e.g. "
- '``"Researches background information on the target topic"``. '
- "Becomes part of the member's system prompt so it understands "
- "its place in the team."
- ),
- )
- prompt: str = Field(
- description=(
- "The first task delivered to the member as a user message. "
- "The member begins executing immediately upon creation, so "
- "make this concrete and self-contained — do not just say "
- '``"wait for instructions"`` (use TeamSay later instead). '
- "Include any context, constraints, deliverables, and "
- "deadlines the member needs."
- ),
- )
-
-
-class AgentCreate(_TeamToolBase):
- """Spawn a new worker member into the team you lead."""
-
- name: str = "AgentCreate"
- is_state_injected: bool = True
-
- description: str = """Add a new member to the team you lead.
-
-## When to Use This Tool
-After ``TeamCreate``, call this for each member you want on the team. \
-Each call:
-- Creates a worker agent dedicated to this team.
-- Delivers ``prompt`` as the worker's first user message — **the worker \
-starts executing it immediately**. (So DONT use ``TeamSay`` right after \
-creating one agent).
-
-## When NOT to Use This Tool
-- You're not currently leading a team. Call ``TeamCreate`` first.
-- The new member would duplicate an existing member's role; reuse the \
-existing member via ``TeamSay`` instead.
-
-## Effects
-- Use the ``name`` you chose as ``to=<name>`` in ``TeamSay`` to direct \
-messages to this member specifically. Names must be unique within the \
-team (including against the leader's name); duplicates are rejected.
-- Members spawned this way live only as long as the team — they are \
-deleted when ``TeamDelete`` is called.
-
-## Important
-- You are responsible for organising the team, assigning tasks, collecting \
-every member's report, and producing the final answer — all members report \
-directly to you. Therefore, **DO NOT** encourage members to communicate with \
-each other, and **AVOID** creating "integrator"-style members; both make the \
-overall communication topology unnecessarily complex.
-"""
-
- input_schema: dict = _AgentCreateParams.model_json_schema()
-
- def __init__(
- self,
- storage: "StorageBase",
- message_bus: "MessageBus",
- user_id: str,
- session_id: str,
- agent_id: str,
- sub_agent_templates: dict[str, SubAgentTemplate] | None = None,
- ) -> None:
- """Bind request-scoped identifiers plus sub-agent templates.
-
- Extends :meth:`_TeamToolBase.__init__` with an optional
- template registry. The built-in ``"default"`` template is
- always present as a fallback; developers can override it by
- registering their own template with ``type="default"``.
-
- When more than one template type is available (i.e. custom
- templates were registered), the tool's ``input_schema`` is
- dynamically extended with a ``subagent_type`` enum field so
- the leader agent can choose which type to create.
-
- Args:
- storage (`StorageBase`):
- Application storage backend.
- message_bus (`MessageBus`):
- Application message bus for inter-session delivery.
- user_id (`str`):
- The owner user id of the calling agent.
- session_id (`str`):
- The current session id of the calling agent.
- agent_id (`str`):
- The id of the agent invoking the tool.
- sub_agent_templates (`dict[str, SubAgentTemplate] | None`, \
-optional):
- Template registry keyed by template type. The
- built-in ``"default"`` template is injected
- automatically if not already present.
- """
- super().__init__(storage, message_bus, user_id, session_id, agent_id)
-
- self._sub_agent_templates: dict[str, SubAgentTemplate] = dict(
- sub_agent_templates or {},
- )
- if "default" not in self._sub_agent_templates:
- self._sub_agent_templates["default"] = DEFAULT_SUB_AGENT_TEMPLATE
-
- # Only expose subagent_type when the developer registered
- # custom templates — a single "default" type is redundant in
- # the schema and would confuse the LLM.
- has_custom_templates = set(self._sub_agent_templates) != {"default"}
- if has_custom_templates:
- schema = copy.deepcopy(
- _AgentCreateParams.model_json_schema(),
- )
- type_descriptions = "\n".join(
- f"- ``{t.type!r}`` — {t.description}"
- for t in self._sub_agent_templates.values()
- )
- schema["properties"]["subagent_type"] = {
- "type": "string",
- "enum": list(self._sub_agent_templates),
- "description": (
- "The type of sub-agent template to use. "
- "Available types:\n\n"
- f"{type_descriptions}\n\n"
- "Each type has pre-configured system prompt, "
- "permissions, and task context."
- ),
- }
- self.input_schema = schema
-
- async def __call__(
- self,
- name: str,
- description: str,
- prompt: str,
- subagent_type: str = "default",
- _agent_state: AgentState | None = None,
- ) -> ToolChunk:
- """Spawn the worker agent + session directly via storage.
-
- Reads the current session + team records from storage to
- enforce two preconditions: the calling session must be in a
- team, and it must be that team's leader.
-
- The worker's configuration (system prompt, context/react
- config, permission context, task context) is determined by
- the :class:`SubAgentTemplate` matching ``subagent_type``. The
- leader's user-confirmed permission rules and working
- directories are merged into the template's permission context
- so the worker does not re-prompt for permissions the user has
- already granted.
-
- Args:
- name (`str`):
- Short identifier for the worker, unique within the
- team. Used as the ``to`` target in ``TeamSay``.
- description (`str`):
- One-sentence summary of the worker's role.
- prompt (`str`):
- First task delivered as a user message to the worker.
- subagent_type (`str`, defaults to ``"default"``):
- Template type to use. Must match a registered
- :class:`SubAgentTemplate.type`.
- _agent_state (`AgentState | None`, optional):
- Live leader state injected by the toolkit.
-
- Returns:
- `ToolChunk`:
- A success message containing the new member id, or an
- error chunk on failure.
- """
- try:
- session = await self._storage.get_session(
- self._user_id,
- self._agent_id,
- self._session_id,
- )
- if session is None or session.team_id is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "AgentCreate: this session is not in "
- "any team — call TeamCreate first."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
- team = await self._storage.get_team(
- self._user_id,
- session.team_id,
- )
- if team is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "AgentCreate: team "
- f"{session.team_id} no longer exists."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
- if team.session_id != self._session_id:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "AgentCreate: only the team leader "
- "can add members; this session is a "
- "worker."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- # Look up leader session for chat-model inheritance + name.
- leader_session = await self._storage.get_session(
- self._user_id,
- "", # agent_id unused at storage level
- team.session_id,
- )
- if leader_session is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"AgentCreate: leader session "
- f"{team.session_id} for team {team.id} is "
- f"missing — team is in an inconsistent "
- f"state."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- # Resolve the template.
- template = self._sub_agent_templates.get(subagent_type)
- if template is None:
- available = list(self._sub_agent_templates)
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"AgentCreate: unknown subagent_type "
- f"{subagent_type!r}; expected one of "
- f"{available}."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- # Enforce team-scoped name uniqueness. TeamSay routes by
- # ``name`` (not agent_id), so duplicates would be ambiguous
- # and unaddressable. The leader's name participates too —
- # workers must not collide with it.
- leader_agent_record = await self._storage.get_agent(
- self._user_id,
- leader_session.agent_id,
- )
- existing_names: set[str] = set()
- if leader_agent_record is not None:
- existing_names.add(leader_agent_record.data.name)
- for member_id in team.data.member_ids:
- member_record = await self._storage.get_agent(
- self._user_id,
- member_id,
- )
- if member_record is not None:
- existing_names.add(member_record.data.name)
- if name in existing_names:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"AgentCreate: a team member named "
- f"{name!r} already exists. Member names "
- f"must be unique within the team "
- f"(including the leader's name); pick "
- f"another."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- # Resolve leader name early — needed both for the system
- # prompt template and for the initial team-message hint.
- leader_name = (
- leader_agent_record.data.name
- if leader_agent_record is not None
- else leader_session.agent_id
- )
-
- # 1. Build worker AgentRecord (source="team" so it's hidden
- # from the global agent list).
- system_prompt = template.system_prompt_template.format(
- team_name=team.data.name,
- team_description=team.data.description,
- member_name=name,
- member_description=description,
- leader_name=leader_name,
- )
- worker_agent = AgentRecord(
- user_id=self._user_id,
- source="team",
- data=AgentData(
- name=name,
- system_prompt=system_prompt,
- context_config=template.context_config.model_copy(
- deep=True,
- ),
- react_config=template.react_config.model_copy(
- deep=True,
- ),
- ),
- )
- await self._storage.upsert_agent(self._user_id, worker_agent)
-
- # 2. Build worker SessionRecord, inheriting leader's model
- # config. The template's permission context is the base;
- # on top of it we merge the leader's mode and/or rules
- # and/or working directories according to the template's
- # inherit-from-leader flags. See
- # :func:`_merge_leader_permissions` for the policy.
- leader_permission_context = (
- _agent_state.permission_context
- if _agent_state is not None
- else leader_session.state.permission_context
- )
- worker_permission_context = _merge_leader_permissions(
- template,
- leader_permission_context,
- )
- worker_state = AgentState(
- permission_context=worker_permission_context,
- tasks_context=template.tasks_context.model_copy(
- deep=True,
- ),
- )
- worker_session = await self._storage.upsert_session(
- user_id=self._user_id,
- agent_id=worker_agent.id,
- config=SessionConfig(
- workspace_id=leader_session.config.workspace_id,
- name=f"team:{team.id}/{name}",
- chat_model_config=(
- leader_session.config.chat_model_config
- ),
- fallback_chat_model_config=(
- leader_session.config.fallback_chat_model_config
- ),
- ),
- state=worker_state,
- )
- await self._storage.set_session_team_id(
- self._user_id,
- worker_session.id,
- team.id,
- )
-
- # 3. Append worker to team.member_ids.
- team.data.member_ids = [
- *team.data.member_ids,
- worker_agent.id,
- ]
- await self._storage.upsert_team(self._user_id, team)
-
- # 4. Deliver the initial task to the worker's inbox + wakeup.
- hint = HintBlock(
- hint=(
- f'<team-message from="{leader_name}">\n'
- f"{prompt}\n"
- f"</team-message>"
- ),
- source=json.dumps(
- {
- "label": "team_message",
- "sublabel": leader_name,
- },
- ensure_ascii=False,
- ),
- )
- await self._message_bus.inbox_push(
- worker_session.id,
- hint.model_dump(mode="json"),
- )
- await self._message_bus.enqueue_wakeup(
- user_id=self._user_id,
- session_id=worker_session.id,
- agent_id=worker_agent.id,
- )
-
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"Member {name!r} added to team "
- f"{team.data.name!r}."
- ),
- ),
- ],
- )
- except Exception as e: # pylint: disable=broad-except
- return ToolChunk(
- content=[TextBlock(text=f"AgentCreate failed: {e}")],
- state=ToolResultState.ERROR,
- )
diff --git a/src/agentscope/app/_tools/_team_create.py b/src/agentscope/app/_tools/_team_create.py
deleted file mode 100644
index d2c2c4782..000000000
--- a/src/agentscope/app/_tools/_team_create.py
+++ /dev/null
@@ -1,145 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The TeamCreate tool — establishes a new team led by the current session."""
-from pydantic import Field
-
-from ._team_tool_base import _TeamToolBase
-from ..storage import TeamData, TeamRecord
-from ...message import TextBlock, ToolResultState
-from ...tool import ToolChunk, ParamsBase
-
-
-class _TeamCreateParams(ParamsBase):
- """Parameters for :class:`TeamCreate`."""
-
- name: str = Field(
- description=(
- "Display name of the team. Used by the user to identify the "
- "team and shown in the team UI."
- ),
- )
- description: str = Field(
- description=(
- "What the team is for — its overall goal or shared context. "
- "This becomes the team's charter and is wired into every "
- "member's system prompt so all members share the same "
- "high-level understanding of why the team exists."
- ),
- )
-
-
-class TeamCreate(_TeamToolBase):
- """Create a new team and become its leader."""
-
- name: str = "TeamCreate"
-
- description: str = """Create a new team led by your current session and \
-return its team id.
-
-## When to Use This Tool
-Use this tool when the task you've been given is best decomposed into \
-parallel sub-tasks executed by multiple specialised agents (members) \
-under your coordination. After creating the team, use ``AgentCreate`` to \
-spawn each member with its own role, prompt, and permission mode. NOTE: \
-the ``prompt`` you pass to ``AgentCreate`` is delivered to that member \
-automatically, so do **NOT** call ``TeamSay`` right after ``AgentCreate`` — \
-just wait for the members to report back.
-
-## When NOT to Use This Tool
-- The task is small enough to handle yourself.
-- You already lead a team in this session — a session can only lead \
-one team at a time.
-"""
-
- input_schema: dict = _TeamCreateParams.model_json_schema()
-
- async def __call__(
- self,
- name: str,
- description: str,
- ) -> ToolChunk:
- """Create the team directly via storage.
-
- Reads the current session record from storage to enforce the
- precondition: a session can only lead one team at a time.
- This makes the tool safe to attach unconditionally to
- ``source='user'`` agents — calling it when the session
- already leads a team returns a clear error rather than
- silently corrupting state.
-
- Args:
- name (`str`):
- Display name of the team.
- description (`str`):
- Description / charter of the team.
-
- Returns:
- `ToolChunk`:
- A success message containing the team id, or an error
- chunk if a precondition fails or creation failed.
- """
- try:
- session = await self._storage.get_session(
- self._user_id,
- self._agent_id,
- self._session_id,
- )
- if session is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "TeamCreate: session "
- f"{self._session_id} not found."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
- if session.team_id is not None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "TeamCreate: this session is already "
- f"part of team {session.team_id}. A "
- "session can only lead one team at a "
- "time — dissolve the current one with "
- "TeamDelete first."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- team = TeamRecord(
- user_id=self._user_id,
- session_id=self._session_id,
- data=TeamData(
- name=name,
- description=description,
- member_ids=[],
- ),
- )
- await self._storage.upsert_team(self._user_id, team)
- await self._storage.set_session_team_id(
- self._user_id,
- self._session_id,
- team.id,
- )
-
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"Team {team.id} ({team.data.name}) created. "
- f"You are the leader. Use AgentCreate to add "
- f"members, then TeamSay to coordinate them."
- ),
- ),
- ],
- )
- except Exception as e: # pylint: disable=broad-except
- return ToolChunk(
- content=[TextBlock(text=f"TeamCreate failed: {e}")],
- state=ToolResultState.ERROR,
- )
diff --git a/src/agentscope/app/_tools/_team_delete.py b/src/agentscope/app/_tools/_team_delete.py
deleted file mode 100644
index ea34bfe3c..000000000
--- a/src/agentscope/app/_tools/_team_delete.py
+++ /dev/null
@@ -1,130 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The TeamDelete tool — dissolves the team led by the current session."""
-from ._team_tool_base import _TeamToolBase
-from ...message import TextBlock, ToolResultState
-from ...tool import ToolChunk, ParamsBase
-
-
-class _TeamDeleteParams(ParamsBase):
- """Parameters for :class:`TeamDelete` — none."""
-
-
-class TeamDelete(_TeamToolBase):
- """Dissolve the team you currently lead and clean up all members."""
-
- name: str = "TeamDelete"
-
- description: str = """Dissolve the team you currently lead.
-
-## When to Use This Tool
-- The team has finished its work and you want to clean up.
-- The team is unrecoverably stuck and you want to start over.
-- You have collected the deliverables you need from each member.
-
-## When NOT to Use This Tool
-- Members are still producing useful output and you may want their \
-follow-up; dissolving deletes them and they cannot be revived.
-- You want to remove only one specific member — there is no "remove \
-single member" tool in v1, only whole-team dissolution.
-
-## Effects
-- Every member agent + its session is deleted.
-- The team record is deleted.
-- Your own session continues to exist but is no longer associated with \
-any team — the team-related tools become unavailable on subsequent \
-reasoning steps.
-
-This is irreversible.
-"""
-
- input_schema: dict = _TeamDeleteParams.model_json_schema()
-
- async def __call__(self) -> ToolChunk:
- """Dissolve the bound session's team via :class:`SessionService`.
-
- Reads the current session + team records from storage to
- enforce: caller must be in a team AND must be its leader.
- Then delegates the actual cancel + delete + bus-purge cascade
- to :meth:`SessionService.delete_team`, which routes every
- member through the shared session-level primitive — so worker
- chat runs are cancelled cross-process and their bus state is
- cleaned up the same way ``DELETE /agents`` would.
-
- Returns:
- `ToolChunk`:
- A confirmation message, or an error chunk if a
- precondition fails.
- """
- try:
- session = await self._storage.get_session(
- self._user_id,
- self._agent_id,
- self._session_id,
- )
- if session is None or session.team_id is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "TeamDelete: this session is not in "
- "any team."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
- team = await self._storage.get_team(
- self._user_id,
- session.team_id,
- )
- if team is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "TeamDelete: team "
- f"{session.team_id} no longer exists."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
- if team.session_id != self._session_id:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "TeamDelete: only the team leader "
- "can dissolve the team; this session "
- "is a worker."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- # Local import to avoid a circular dependency between
- # ``_tools`` and ``_service`` at module load.
- from .._service import SessionService # noqa: PLC0415
-
- session_service = SessionService(
- storage=self._storage,
- message_bus=self._message_bus,
- )
- await session_service.delete_team(self._user_id, team.id)
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"Team {team.id} dissolved. All members "
- f"deleted; your session is no longer "
- f"leading any team."
- ),
- ),
- ],
- )
- except Exception as e: # pylint: disable=broad-except
- return ToolChunk(
- content=[TextBlock(text=f"TeamDelete failed: {e}")],
- state=ToolResultState.ERROR,
- )
diff --git a/src/agentscope/app/_tools/_team_say.py b/src/agentscope/app/_tools/_team_say.py
deleted file mode 100644
index 87af8cf4d..000000000
--- a/src/agentscope/app/_tools/_team_say.py
+++ /dev/null
@@ -1,329 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The TeamSay tool — sends a message to one or all team members."""
-from typing import Any
-
-from pydantic import Field
-
-from ._team_tool_base import _TeamToolBase
-from ...message import HintBlock, TextBlock, ToolResultState
-from ...tool import ToolChunk, ParamsBase
-
-
-class _TeamSayParams(ParamsBase):
- """Parameters for :class:`TeamSay`."""
-
- content: str = Field(
- description=(
- "The message text. Plain natural-language; the recipient "
- "sees it as a user message in its context."
- ),
- )
- to: str | None = Field(
- default=None,
- description=(
- "Recipient member name. Pass ``null`` (the default) to "
- "broadcast to every other member of the team. To address "
- "a specific peer use that member's name."
- ),
- )
-
-
-_LEADER_DESCRIPTION = """Send a message to a specific team member or \
-broadcast to all members.
-
-## When to Use This Tool
-- Pass **new** requirements or context from the user to a specific member.
-- Broadcast an update or coordination message to all members.
-- Ask a member a follow-up question when you need clarification.
-
-## When NOT to Use This Tool
-- DO NOT repeatedly call this to check on a member's progress — members \
-will automatically notify you via ``TeamSay`` when they finish their task. \
-Wait for their message instead of polling.
-- DO NOT call this right after creating a member by ``AgentCreate``, the \
-member will receive its initial task from the ``prompt`` of the \
-``AgentCreate`` call and report back when done — just wait for their message. \
-- The session is not in a team yet (call ``TeamCreate`` first).
-- You want to talk to yourself — use your own reasoning.
-
-## Important
-- Each member starts working immediately when created via AgentCreate. \
-When a member finishes its task, it will call ``TeamSay`` to report results \
-back to you. You do NOT need to prompt them — just wait for their reply.
-- **DO NOT** reply to a member's report message unless you have further \
-questions or requirements. ``TeamSay`` is for coordination, not chit-chat — \
-your top priority is to complete the overall task.
-"""
-
-_WORKER_DESCRIPTION = """Send a message to the team leader or broadcast to \
-all team members.
-
-## When to Use This Tool
-- **IMPORTANT**: When you finish your assigned task, you MUST call this \
-tool to report your results back to the leader. The leader is waiting \
-for your report — do not end your turn without sending it.
-- Share intermediate findings or ask the leader for clarification.
-- Broadcast information that other members might need.
-
-## When NOT to Use This Tool
-- You want to talk to yourself — use your own reasoning.
-- The message is a transient internal thought with no value to others.
-"""
-
-
-class TeamSay(_TeamToolBase):
- """Send a message to a teammate (or broadcast to all teammates).
-
- Resolves the team membership at ``__call__`` time from storage,
- so a member added moments earlier in the same chat run is
- addressable immediately.
-
- The ``description`` shown to the agent differs by role: leaders
- are reminded not to poll members, workers are reminded to report
- results when done. The role is passed at construction time via
- the ``role`` parameter.
- """
-
- name: str = "TeamSay"
- description: str
-
- is_concurrency_safe: bool = True
- is_read_only: bool = True
-
- input_schema: dict = _TeamSayParams.model_json_schema()
-
- def __init__(
- self,
- *args: Any,
- role: str = "leader",
- **kwargs: Any,
- ) -> None:
- """Initialise with role-specific description.
-
- Args:
- role (`str`, defaults to ``"leader"``):
- Either ``"leader"`` or ``"worker"``. Determines which
- description the agent sees for this tool.
- *args:
- Forwarded to :class:`_TeamToolBase.__init__`.
- **kwargs:
- Forwarded to :class:`_TeamToolBase.__init__`.
- """
- super().__init__(*args, **kwargs)
- self.description = (
- _LEADER_DESCRIPTION if role == "leader" else _WORKER_DESCRIPTION
- )
-
- async def __call__(
- self,
- content: str,
- to: str | None = None,
- ) -> ToolChunk:
- """Deliver the message directly via storage + message bus.
-
- Reads the current session record from storage to resolve the
- team_id (the agent's team membership may have changed since
- agent assembly), builds the team's (agent_id, session_id)
- directory, and pushes a HintBlock + wakeup to each recipient.
-
- Args:
- content (`str`):
- Message body.
- to (`str | None`, defaults to ``None``):
- Specific member agent id to target, or ``None`` for
- broadcast.
-
- Returns:
- `ToolChunk`:
- A confirmation containing the recipient count, or an
- error chunk on failure.
- """
- try:
- session = await self._storage.get_session(
- self._user_id,
- self._agent_id,
- self._session_id,
- )
- if session is None or session.team_id is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "TeamSay: this session is not in any "
- "team — call TeamCreate first if you "
- "want to start one."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- team = await self._storage.get_team(
- self._user_id,
- session.team_id,
- )
- if team is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"TeamSay: team {session.team_id} no longer "
- f"exists."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- leader_session = await self._storage.get_session(
- self._user_id,
- "",
- team.session_id,
- )
- if leader_session is None:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"TeamSay: leader session "
- f"{team.session_id} missing for team "
- f"{team.id}."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- # Build a (name -> (session_id, agent_id)) directory in one
- # pass over the team. Routing is by **name** rather than
- # agent_id so workers can address the leader (they receive
- # the leader's name in the <team-message from="..."> hint
- # but never see the leader's agent_id). Uniqueness of names
- # within the team is enforced at AgentCreate time.
- leader_agent = await self._storage.get_agent(
- self._user_id,
- leader_session.agent_id,
- )
- leader_name = (
- leader_agent.data.name
- if leader_agent is not None
- else leader_session.agent_id
- )
- directory: dict[str, tuple[str, str]] = {
- leader_name: (leader_session.id, leader_session.agent_id),
- }
- for worker_agent_id in team.data.member_ids:
- worker_agent = await self._storage.get_agent(
- self._user_id,
- worker_agent_id,
- )
- if worker_agent is None:
- continue
- sessions = await self._storage.list_sessions(
- self._user_id,
- worker_agent_id,
- )
- if sessions:
- directory[worker_agent.data.name] = (
- sessions[0].id,
- worker_agent_id,
- )
-
- own_session_ids = {sid for sid, _aid in directory.values()}
- if self._session_id not in own_session_ids:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"TeamSay: this session "
- f"({self._session_id}) is not part of "
- f"team {team.id}."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
-
- if to is None:
- recipients: list[tuple[str, str]] = [
- (sid, aid)
- for sid, aid in directory.values()
- if sid != self._session_id
- ]
- else:
- resolved = directory.get(to)
- if resolved is None:
- known = sorted(directory.keys())
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"TeamSay: no team member is named "
- f"{to!r}. Known members: {known}."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
- target_session_id, target_agent_id = resolved
- if target_session_id == self._session_id:
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- "TeamSay: cannot send a message to "
- "yourself; talk to yourself in your "
- "own reasoning instead."
- ),
- ),
- ],
- state=ToolResultState.ERROR,
- )
- recipients = [(target_session_id, target_agent_id)]
-
- # Resolve sender display name once.
- sender_agent = await self._storage.get_agent(
- self._user_id,
- self._agent_id,
- )
- sender_name = (
- sender_agent.data.name
- if sender_agent is not None
- else self._agent_id
- )
-
- hint = HintBlock(
- hint=(
- f'<team-message from="{sender_name}">\n'
- f"{content}\n"
- f"</team-message>"
- ),
- source=sender_name,
- )
- payload = hint.model_dump(mode="json")
-
- for sid, aid in recipients:
- await self._message_bus.inbox_push(sid, payload)
- await self._message_bus.enqueue_wakeup(
- user_id=self._user_id,
- session_id=sid,
- agent_id=aid,
- )
-
- count = len(recipients)
- target = "broadcast" if to is None else f"member {to!r}"
- return ToolChunk(
- content=[
- TextBlock(
- text=(
- f"Delivered to {count} recipient(s) "
- f"({target})."
- ),
- ),
- ],
- )
- except Exception as e: # pylint: disable=broad-except
- return ToolChunk(
- content=[TextBlock(text=f"TeamSay failed: {e}")],
- state=ToolResultState.ERROR,
- )
diff --git a/src/agentscope/app/_tools/_team_tool_base.py b/src/agentscope/app/_tools/_team_tool_base.py
deleted file mode 100644
index 734e74e5f..000000000
--- a/src/agentscope/app/_tools/_team_tool_base.py
+++ /dev/null
@@ -1,99 +0,0 @@
-# -*- coding: utf-8 -*-
-"""Base class shared by the team tools."""
-from typing import Any, TYPE_CHECKING
-
-from ...permission import (
- PermissionBehavior,
- PermissionContext,
- PermissionDecision,
-)
-from ...tool import ToolBase
-
-if TYPE_CHECKING:
- from ..message_bus import MessageBus
- from ..storage import StorageBase
-
-
-class _TeamToolBase(ToolBase):
- """Shared base for the team tools.
-
- All team tools are constructed at agent assembly time (in
- :func:`get_toolkit`) with the request-scoped ``user_id``,
- ``session_id``, and ``agent_id`` plus ``storage`` + ``message_bus``
- references. Each tool's ``__call__`` does its work directly via
- those two dependencies — there is no intermediate service layer.
-
- Permissions: all team tools allow themselves unconditionally — the
- agent's authority to call them is already gated by the
- role/source-aware logic inside :func:`get_toolkit` that decides
- which team tools to attach in the first place.
- """
-
- name: str
- description: str
- input_schema: dict[str, Any]
- is_concurrency_safe: bool = False
- is_read_only: bool = True
- is_state_injected: bool = False
- is_external_tool: bool = False
- is_mcp: bool = False
- mcp_name: str | None = None
-
- def __init__(
- self,
- storage: "StorageBase",
- message_bus: "MessageBus",
- user_id: str,
- session_id: str,
- agent_id: str,
- ) -> None:
- """Bind request-scoped identifiers and shared dependencies.
-
- Args:
- storage (`StorageBase`):
- Application storage. Each tool reads the current
- session / team records at ``__call__`` time to do
- runtime precondition checks (am I in a team? am I the
- leader?) — this is what lets all four team tools be
- attached unconditionally to ``source='user'`` agents
- without depending on a stale snapshot of ``team_id``
- taken at agent assembly time.
- message_bus (`MessageBus`):
- Application message bus. Tools that deliver
- inter-session messages (``AgentCreate``, ``TeamSay``)
- push HintBlocks + wakeups through it.
- user_id (`str`):
- The owner user id of the calling agent.
- session_id (`str`):
- The current session id of the calling agent.
- agent_id (`str`):
- The id of the agent invoking the tool.
- """
- self._storage = storage
- self._message_bus = message_bus
- self._user_id = user_id
- self._session_id = session_id
- self._agent_id = agent_id
-
- async def check_permissions(
- self,
- tool_input: dict[str, Any],
- context: PermissionContext,
- ) -> PermissionDecision:
- """Always allow — gating is done by tool-attachment logic.
-
- Args:
- tool_input (`dict[str, Any]`):
- The arguments the agent passed; ignored here.
- context (`PermissionContext`):
- The active permission context; ignored here.
-
- Returns:
- `PermissionDecision`:
- An ``ALLOW`` decision with a brief explanation.
- """
- return PermissionDecision(
- behavior=PermissionBehavior.ALLOW,
- message=f"{self.name} is always allowed when attached to the "
- f"agent.",
- )
diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.py
index ed2a2dd97..80b27279f 100644
--- a/src/agentscope/app/deps.py
+++ b/src/agentscope/app/deps.py
@@ -8,10 +8,13 @@ from ._manager import (
ChatRunRegistry,
SchedulerManager,
)
-from ._service import ChatService, SessionService
+from ._service import ChatService, KnowledgeBaseService, SessionService
from ._types import AgentMiddlewareFactory, AgentToolFactory
from .message_bus import MessageBus
+from .rag.blob_store import BlobStoreBase
+from .rag.knowledge_base_manager import KnowledgeBaseManagerBase
from .storage import StorageBase
+from ..rag import ParserBase
async def get_current_user_id(
@@ -167,3 +170,124 @@ async def get_extra_agent_tools(
:func:`~agentscope.app.create_app`, or ``None`` if not configured.
"""
return request.app.state.extra_agent_tools
+
+
+async def get_knowledge_base_service(
+ request: Request,
+) -> KnowledgeBaseService:
+ """Return the application-wide knowledge base service.
+
+ Args:
+ request (`Request`):
+ The incoming FastAPI request.
+
+ Returns:
+ `KnowledgeBaseService`:
+ The service stored in ``app.state``.
+
+ Raises:
+ `HTTPException`:
+ ``503`` when the app was created without a
+ ``knowledge_base_manager`` and therefore exposes no
+ knowledge base endpoints.
+ """
+ service = getattr(request.app.state, "knowledge_base_service", None)
+ if service is None:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "Knowledge base feature is disabled — pass a "
+ "knowledge_base_manager to create_app() to enable it."
+ ),
+ )
+ return service
+
+
+async def get_knowledge_base_manager(
+ request: Request,
+) -> KnowledgeBaseManagerBase:
+ """Return the application-wide knowledge base manager.
+
+ Args:
+ request (`Request`):
+ The incoming FastAPI request.
+
+ Returns:
+ `KnowledgeBaseManagerBase`:
+ The manager stored in ``app.state``.
+
+ Raises:
+ `HTTPException`:
+ ``503`` when the app was created without a
+ ``knowledge_base_manager``.
+ """
+ manager = getattr(request.app.state, "knowledge_base_manager", None)
+ if manager is None:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "Knowledge base feature is disabled — pass a "
+ "knowledge_base_manager to create_app() to enable it."
+ ),
+ )
+ return manager
+
+
+async def get_blob_store(request: Request) -> BlobStoreBase:
+ """Return the application-wide blob store.
+
+ Args:
+ request (`Request`):
+ The incoming FastAPI request.
+
+ Returns:
+ `BlobStoreBase`:
+ The blob store instance stored in ``app.state``.
+
+ Raises:
+ `HTTPException`:
+ ``503`` when no blob store is configured (e.g. the KB
+ feature was disabled at app-creation time).
+ """
+ blob_store = getattr(request.app.state, "blob_store", None)
+ if blob_store is None:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "Blob store is not configured — pass a "
+ "knowledge_base_manager (and optionally a blob_store) "
+ "to create_app() to enable knowledge base features."
+ ),
+ )
+ return blob_store
+
+
+async def get_knowledge_parsers(
+ request: Request,
+) -> list[ParserBase] | dict[str, ParserBase]:
+ """Return the parser registry configured on the app.
+
+ Args:
+ request (`Request`):
+ The incoming FastAPI request.
+
+ Returns:
+ `list[ParserBase] | dict[str, ParserBase]`:
+ The parser registry stored in ``app.state.knowledge_parsers``
+ — the same value the index worker uses to dispatch uploads.
+
+ Raises:
+ `HTTPException`:
+ ``503`` when the KB feature is disabled (no parsers
+ configured).
+ """
+ parsers = getattr(request.app.state, "knowledge_parsers", None)
+ if not parsers:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "Knowledge base feature is disabled — pass a "
+ "knowledge_base_manager to create_app() to enable it."
+ ),
+ )
+ return parsers
diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.py
index 9057769ef..2d4e1773c 100644
--- a/src/agentscope/app/message_bus/_keys.py
+++ b/src/agentscope/app/message_bus/_keys.py
@@ -191,3 +191,38 @@ class MessageBusKeys:
def bg_tasks(cls, session_id: str) -> str:
"""Per-session background task registry key."""
return cls._BG_TASKS.format(sid=session_id)
+
+ # ------------------------------------------------------------------
+ # Knowledge-base indexing pipeline
+ # ------------------------------------------------------------------
+
+ _INDEX_TASKS_QUEUE = "agentscope:index:tasks"
+ _INDEX_TASKS_SIGNAL = "agentscope:index:tasks:wake"
+
+ @classmethod
+ def index_tasks_queue(cls) -> str:
+ """Shared, durable index-task queue.
+
+ The producer-side
+ :class:`~agentscope.app._service.KnowledgeBaseService`
+ ``queue_push``\\ es here through
+ :func:`~agentscope.app._bus_ops.enqueue_index_task`; the
+ consumer-side
+ :class:`~agentscope.app._service.IndexTaskConsumer`
+ ``queue_drain``\\ s it on each signal — plus once eagerly on
+ consumer start-up so tasks queued while every worker was down
+ are picked up immediately.
+ """
+ return cls._INDEX_TASKS_QUEUE
+
+ @classmethod
+ def index_tasks_signal(cls) -> str:
+ """Shared pub/sub channel that nudges every running index-task
+ consumer to drain the queue.
+
+ Payload is opaque — only its arrival matters. Redis pub/sub is
+ fire-and-forget, so a published signal does not guarantee
+ delivery; the durable queue keeps work safe in case every
+ subscriber happens to be offline.
+ """
+ return cls._INDEX_TASKS_SIGNAL
diff --git a/src/agentscope/app/rag/__init__.py b/src/agentscope/app/rag/__init__.py
new file mode 100644
index 000000000..3fe4fbc43
--- /dev/null
+++ b/src/agentscope/app/rag/__init__.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+"""Service-layer RAG building blocks.
+
+This subpackage groups every RAG-specific service-layer concept under
+one roof so the user-facing import surface stays compact:
+
+- :mod:`.blob_store` — backends storing uploaded document bytes;
+- :mod:`.knowledge_base_manager` — knowledge base lifecycle and the
+ runtime :class:`~agentscope.rag.KnowledgeBase` handle shared between
+ HTTP and agents;
+- :mod:`.index_worker` — out-of-process indexing worker entry point.
+
+Commonly used symbols are re-exported here so the typical user import
+collapses to a single line::
+
+ from agentscope.app.rag import (
+ LocalBlobStore,
+ S3BlobStore,
+ CollectionPerKbManager,
+ run_worker,
+ )
+
+For type-level imports or rare subclasses, use the submodules directly.
+"""
+from typing import TYPE_CHECKING
+
+from .blob_store import (
+ AsyncReadable,
+ BlobStoreBase,
+ LocalBlobStore,
+ S3BlobStore,
+)
+from .knowledge_base_manager import (
+ CollectionPerKbManager,
+ DimensionPolicy,
+ DimensionPolicyError,
+ DimensionPolicyKind,
+ KnowledgeBaseError,
+ KnowledgeBaseManagerBase,
+ KnowledgeBaseNotFoundError,
+)
+
+if TYPE_CHECKING:
+ # Re-exported lazily at runtime via ``__getattr__`` to break a
+ # package-load import cycle; declared here so static analysers
+ # (pylint, mypy, IDEs) still see the symbol on the package.
+ from .index_worker import run_worker # noqa: F401
+
+
+def __getattr__(name: str) -> object:
+ """Lazy-load attributes that would cause an import cycle.
+
+ ``run_worker`` is lazy-imported because :mod:`.index_worker` pulls
+ in :mod:`agentscope.app._service`, which itself imports
+ :mod:`agentscope.app.rag` for the middleware — a direct re-export
+ would create an import cycle at package load. Users who actually
+ want the worker (``from agentscope.app.rag import run_worker``)
+ pay the import cost on first access.
+
+ Args:
+ name (`str`):
+ The attribute name requested by the importer.
+
+ Returns:
+ `object`:
+ The resolved attribute value.
+
+ Raises:
+ `AttributeError`:
+ When ``name`` is not exposed by this package.
+ """
+ if name == "run_worker":
+ from .index_worker import run_worker as _run_worker
+
+ return _run_worker
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
+__all__ = [
+ "AsyncReadable",
+ "BlobStoreBase",
+ "CollectionPerKbManager",
+ "DimensionPolicy",
+ "DimensionPolicyError",
+ "DimensionPolicyKind",
+ "KnowledgeBaseError",
+ "KnowledgeBaseManagerBase",
+ "KnowledgeBaseNotFoundError",
+ "LocalBlobStore",
+ "S3BlobStore",
+ "run_worker",
+]
diff --git a/src/agentscope/app/rag/blob_store/__init__.py b/src/agentscope/app/rag/blob_store/__init__.py
new file mode 100644
index 000000000..c2e543da0
--- /dev/null
+++ b/src/agentscope/app/rag/blob_store/__init__.py
@@ -0,0 +1,12 @@
+# -*- coding: utf-8 -*-
+"""Blob storage backends for document uploads."""
+from ._base import AsyncReadable, BlobStoreBase
+from ._local import LocalBlobStore
+from ._s3 import S3BlobStore
+
+__all__ = [
+ "AsyncReadable",
+ "BlobStoreBase",
+ "LocalBlobStore",
+ "S3BlobStore",
+]
diff --git a/src/agentscope/app/rag/blob_store/_base.py b/src/agentscope/app/rag/blob_store/_base.py
new file mode 100644
index 000000000..a7c4bed68
--- /dev/null
+++ b/src/agentscope/app/rag/blob_store/_base.py
@@ -0,0 +1,158 @@
+# -*- coding: utf-8 -*-
+"""Abstract base class for blob storage backends.
+
+A :class:`BlobStoreBase` is the byte-level home of files uploaded into
+the application — knowledge base documents in v1, potentially other
+binary payloads later. It is created once at app startup and shared
+across requests, mirroring the lifecycle of
+:class:`~agentscope.app.storage.StorageBase` and
+:class:`~agentscope.rag.VectorStoreBase`.
+
+The abstraction owes its existence to a single hard requirement: bytes
+must never sit in memory for the duration of indexing. The upload
+endpoint streams the request body into ``write_stream``; the indexing
+worker streams the bytes back out via ``open``. Implementations decide
+where those bytes physically live (local disk, S3-compatible object
+store, etc.) — neither caller cares.
+"""
+from abc import ABC, abstractmethod
+from contextlib import AbstractAsyncContextManager
+from typing import IO, Any, Protocol, Self
+
+
+class AsyncReadable(Protocol):
+ """Minimal async-read protocol returned by :meth:`BlobStoreBase.open`.
+
+ Backed by ``aiofiles`` handles for the local store and by streaming
+ response bodies for object-storage backends. The narrow interface
+ keeps the worker's blob-reading code identical across backends
+ even though no single concrete type implements both shapes.
+ """
+
+ async def read(self, n: int = -1) -> bytes:
+ """Read up to ``n`` bytes (``-1`` reads to EOF).
+
+ Args:
+ n (`int`, defaults to ``-1``):
+ The maximum number of bytes to read; ``-1`` drains the
+ stream.
+
+ Returns:
+ `bytes`:
+ The bytes read; an empty ``bytes`` at EOF.
+ """
+
+
+class BlobStoreBase(ABC):
+ """Abstract base class for blob storage backends.
+
+ Lifecycle is managed via the async context manager protocol so the
+ app lifespan can open / close connection pools or filesystem
+ handles uniformly.
+ """
+
+ # ------------------------------------------------------------------
+ # Lifecycle
+ # ------------------------------------------------------------------
+
+ async def __aenter__(self) -> Self:
+ """Enter the async context — open connections / create dirs.
+
+ The default implementation is a no-op. Subclasses that need
+ explicit setup should override this.
+
+ Returns:
+ `BlobStoreBase`:
+ ``self``.
+ """
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: Any,
+ ) -> None:
+ """Exit the async context — close connections if needed."""
+
+ # ------------------------------------------------------------------
+ # Byte operations
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def write_stream(self, key: str, stream: IO[bytes]) -> str:
+ """Stream-write a blob and return its URI.
+
+ Implementations MUST copy the bytes in chunks (typically ~1 MB)
+ and MUST NOT call ``stream.read()`` without a size argument —
+ the whole point of the abstraction is that the byte payload
+ never lives in memory all at once.
+
+ Args:
+ key (`str`):
+ Backend-relative key, e.g. ``"kb/{kb_id}/{doc_id}"``.
+ The caller picks the key layout; the backend turns it
+ into a backend-native location (filesystem path,
+ ``s3://`` object name, ...).
+ stream (`IO[bytes]`):
+ A readable binary stream. Synchronous read API
+ (``read(n)``) — ``UploadFile.file`` from FastAPI fits
+ directly, and other binary streams are wrapped via the
+ same protocol.
+
+ Returns:
+ `str`:
+ A scheme-qualified URI (e.g. ``"local://kb/.../uuid"``,
+ ``"s3://bucket/kb/.../uuid"``) that round-trips back
+ through :meth:`open` / :meth:`delete` / :meth:`exists`.
+ """
+
+ @abstractmethod
+ async def open(
+ self,
+ uri: str,
+ ) -> AbstractAsyncContextManager[AsyncReadable]:
+ """Stream-read a blob by URI.
+
+ Returns an async context manager whose ``__aenter__`` yields a
+ stream with an awaitable ``read(n)`` method. Implementations
+ decide whether the stream is backed by an ``aiofiles`` handle,
+ a streaming response body, or any other async source —
+ callers MUST treat it as forward-only and chunked.
+
+ Args:
+ uri (`str`):
+ A URI produced by :meth:`write_stream`.
+
+ Returns:
+ `AbstractAsyncContextManager[AsyncReadable]`:
+ The byte stream, wrapped so the backend can release
+ handles deterministically on context exit.
+ """
+
+ @abstractmethod
+ async def delete(self, uri: str) -> None:
+ """Delete the blob at ``uri`` if it exists.
+
+ MUST be idempotent — a no-op when the blob is already gone.
+ The caller (document deletion path) treats blob deletion as
+ best-effort cleanup; partial failures are recoverable by
+ re-running the sweep.
+
+ Args:
+ uri (`str`):
+ A URI produced by :meth:`write_stream`.
+ """
+
+ @abstractmethod
+ async def exists(self, uri: str) -> bool:
+ """Return whether the blob at ``uri`` is present.
+
+ Args:
+ uri (`str`):
+ A URI produced by :meth:`write_stream`.
+
+ Returns:
+ `bool`:
+ ``True`` if the blob is currently retrievable.
+ """
diff --git a/src/agentscope/app/rag/blob_store/_local.py b/src/agentscope/app/rag/blob_store/_local.py
new file mode 100644
index 000000000..10ddd2826
--- /dev/null
+++ b/src/agentscope/app/rag/blob_store/_local.py
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-
+"""Local filesystem implementation of :class:`BlobStoreBase`.
+
+The backend reserves a single root directory and treats keys as
+relative paths beneath it. URIs are formatted as ``local://{key}`` —
+the scheme acts as a discriminator so a mixed-deployment app can route
+``local://`` and ``s3://`` URIs to different backends without
+re-parsing the rest of the string.
+"""
+import os
+import shutil
+from contextlib import asynccontextmanager
+from pathlib import Path
+from typing import IO, AsyncIterator
+
+import aiofiles
+import aiofiles.os
+import aiofiles.ospath
+
+from ._base import AsyncReadable, BlobStoreBase
+
+
+_SCHEME = "local://"
+_CHUNK_SIZE = 1 << 20 # 1 MiB — keep peak memory bounded, match S3 part size.
+
+
+class LocalBlobStore(BlobStoreBase):
+ """Store blobs as files beneath a configurable root directory.
+
+ Intended for single-node deployments and development. The lifecycle
+ of a blob is bound to the document that owns it, not to the request
+ that uploaded it — this is what distinguishes the store from
+ FastAPI's per-request ``SpooledTemporaryFile`` and is the reason
+ the abstraction exists at all.
+ """
+
+ def __init__(self, root_dir: str | os.PathLike) -> None:
+ """Initialize the local backend.
+
+ Args:
+ root_dir (`str | PathLike`):
+ Directory that holds all blobs for this app. Created
+ on :meth:`__aenter__` if it does not exist.
+ """
+ self._root = Path(root_dir).resolve()
+
+ async def __aenter__(self) -> "LocalBlobStore":
+ """Ensure the root directory exists."""
+ await aiofiles.os.makedirs(self._root, exist_ok=True)
+ return self
+
+ def _path_for(self, key: str) -> Path:
+ """Resolve a backend-relative key to an absolute filesystem path.
+
+ Rejects keys that try to escape :attr:`_root` via ``..`` or
+ absolute paths. Callers pick keys server-side so this is
+ defensive rather than a primary trust boundary, but we still
+ refuse to write outside the root.
+
+ Args:
+ key (`str`):
+ Backend-relative key.
+
+ Returns:
+ `Path`:
+ The absolute filesystem path within :attr:`_root`.
+ """
+ if not key or key.startswith("/") or ".." in Path(key).parts:
+ raise ValueError(f"Invalid blob key: {key!r}")
+ path = (self._root / key).resolve()
+ if self._root not in path.parents and path != self._root:
+ raise ValueError(f"Blob key {key!r} escapes the root directory.")
+ return path
+
+ def _key_from_uri(self, uri: str) -> str:
+ """Extract the backend-relative key from a ``local://`` URI."""
+ if not uri.startswith(_SCHEME):
+ raise ValueError(f"Not a local blob URI: {uri!r}")
+ return uri[len(_SCHEME) :]
+
+ async def write_stream(self, key: str, stream: IO[bytes]) -> str:
+ """Copy ``stream`` into the blob at ``key`` in 1 MiB chunks.
+
+ Creates intermediate directories as needed. Existing blobs at
+ the same key are overwritten — keys are generated server-side
+ from document ids, so collisions only happen on intentional
+ re-uploads.
+
+ Args:
+ key (`str`):
+ Backend-relative key.
+ stream (`IO[bytes]`):
+ Synchronous binary source.
+
+ Returns:
+ `str`:
+ The ``local://{key}`` URI.
+ """
+ path = self._path_for(key)
+ await aiofiles.os.makedirs(path.parent, exist_ok=True)
+ async with aiofiles.open(path, "wb") as out:
+ while True:
+ chunk = stream.read(_CHUNK_SIZE)
+ if not chunk:
+ break
+ await out.write(chunk)
+ return f"{_SCHEME}{key}"
+
+ @asynccontextmanager
+ async def open( # type: ignore[override]
+ self,
+ uri: str,
+ ) -> AsyncIterator[AsyncReadable]:
+ """Open the blob at ``uri`` for streaming reads."""
+ path = self._path_for(self._key_from_uri(uri))
+ async with aiofiles.open(path, "rb") as fp:
+ yield fp
+
+ async def delete(self, uri: str) -> None:
+ """Remove the blob at ``uri`` if present (idempotent)."""
+ path = self._path_for(self._key_from_uri(uri))
+ try:
+ await aiofiles.os.remove(path)
+ except FileNotFoundError:
+ return
+ # Best-effort cleanup of empty parent directories up to the root.
+ parent = path.parent
+ while parent != self._root and parent.is_relative_to(self._root):
+ try:
+ await aiofiles.os.rmdir(parent)
+ except OSError:
+ break
+ parent = parent.parent
+
+ async def exists(self, uri: str) -> bool:
+ """Return whether the blob at ``uri`` is present."""
+ path = self._path_for(self._key_from_uri(uri))
+ return await aiofiles.ospath.isfile(path)
+
+ # Synchronous helper used by tests / cleanup scripts; not part of
+ # the public abstraction.
+ def _wipe(self) -> None:
+ """Delete the entire root directory. Test-only."""
+ if self._root.exists():
+ shutil.rmtree(self._root)
diff --git a/src/agentscope/app/rag/blob_store/_s3.py b/src/agentscope/app/rag/blob_store/_s3.py
new file mode 100644
index 000000000..0c21a7141
--- /dev/null
+++ b/src/agentscope/app/rag/blob_store/_s3.py
@@ -0,0 +1,276 @@
+# -*- coding: utf-8 -*-
+"""S3-compatible implementation of :class:`BlobStoreBase`.
+
+Works against any service that implements the S3 wire protocol —
+AWS S3, MinIO, Cloudflare R2, Aliyun OSS (S3-compatible), Tencent yun COS, etc.
+The discriminator is ``endpoint_url``: ``None`` means real AWS S3
+(``aioboto3`` resolves the regional endpoint); any other value points
+at the compatible service's S3 endpoint.
+
+URIs are formatted as ``s3://{bucket}/{key}``. The bucket is baked
+into the URI (rather than carried out-of-band) so a single deployment
+can read blobs that were written under a different bucket — for
+example, after a bucket migration — without breaking existing
+document records.
+
+The implementation is intentionally minimal: this is a byte store,
+not a multipart upload optimiser. Production-scale uploads (>5 GiB)
+would need the multipart API explicitly, but our documents are
+bounded by ``UPLOAD_MAX_BYTES`` well below that ceiling, so a single
+``upload_fileobj`` call (which uses multipart internally when the
+body is large enough) is sufficient.
+"""
+from contextlib import asynccontextmanager
+from typing import IO, Any, AsyncIterator
+
+from ._base import AsyncReadable, BlobStoreBase
+
+
+_SCHEME = "s3://"
+
+
+class _StreamingBody:
+ """Adapter that exposes :class:`AsyncReadable` over an aioboto3 body.
+
+ ``aioboto3`` returns ``aiohttp``-backed streaming bodies that
+ already expose ``read(n)`` — but ``n=-1`` is "read until EOF"
+ which our ``IndexWorker._read_blob`` does not want; it asks for
+ a bounded chunk every iteration. We wrap the body in a thin
+ object so the adapter contract is explicit and so the underlying
+ body type can change without the worker noticing.
+ """
+
+ def __init__(self, body: Any) -> None:
+ """Initialize the body."""
+ self._body = body
+
+ async def read(self, n: int = -1) -> bytes:
+ """Read up to *n* bytes; ``-1`` reads to EOF."""
+ if n == -1:
+ return await self._body.read()
+ # aiohttp's StreamReader.read(n) returns up to n bytes; if
+ # the server-side stream is bursty, we may get a short read,
+ # which is exactly the contract we want for chunked indexing.
+ return await self._body.read(n)
+
+
+class S3BlobStore(BlobStoreBase):
+ """Store blobs in an S3-compatible bucket."""
+
+ def __init__(
+ self,
+ bucket: str,
+ *,
+ region_name: str | None = None,
+ endpoint_url: str | None = None,
+ aws_access_key_id: str | None = None,
+ aws_secret_access_key: str | None = None,
+ session_token: str | None = None,
+ use_ssl: bool = True,
+ config: Any = None,
+ ) -> None:
+ """Initialize an S3-compatible bucket.
+
+ Args:
+ bucket (`str`):
+ Bucket name. The bucket MUST exist; this store will not
+ create it. Production deployments commonly provision the
+ bucket out-of-band via Terraform / CloudFormation so the
+ app's IAM role does not need ``s3:CreateBucket``.
+ region_name (`str | None`, optional):
+ AWS region for AWS S3. Required for AWS, ignored for
+ MinIO / R2 / other services that locate the bucket via
+ ``endpoint_url``.
+ endpoint_url (`str | None`, optional):
+ Full URL of the S3-compatible service. ``None`` selects
+ real AWS S3. Examples: ``http://minio:9000``,
+ ``https://<account>.r2.cloudflarestorage.com``,
+ ``https://oss-cn-hangzhou.aliyuncs.com``.
+ aws_access_key_id (`str | None`, optional):
+ Static credential. Prefer leaving this ``None`` and letting
+ the IAM role / environment chain resolve credentials when
+ running on AWS infrastructure.
+ aws_secret_access_key (`str | None`, optional):
+ Paired with ``aws_access_key_id``.
+ session_token (`str | None`, optional):
+ For STS-issued temporary credentials.
+ use_ssl (`bool`, defaults to ``True``):
+ Force HTTPS. Production deployments must keep this on;
+ local MinIO with self-signed certs is the only place
+ ``False`` is reasonable.
+ config (`Any | None`, optional):
+ ``aiobotocore.config.AioConfig`` instance for users who
+ need to tune timeouts, retry mode, signature version
+ (e.g. ``s3v4`` for Aliyun OSS), or addressing style.
+ Path-style addressing is needed for MinIO; pass
+ ``AioConfig(s3={"addressing_style": "path"})``.
+ """
+ try:
+ import aioboto3
+ except ImportError as e:
+ raise ImportError(
+ "S3BlobStore requires the optional dependency ``aioboto3``. "
+ "Install it with ``uv pip install aioboto3`` or with the "
+ "``[s3]`` extra.",
+ ) from e
+
+ self._bucket = bucket
+ self._region_name = region_name
+ self._endpoint_url = endpoint_url
+ self._aws_access_key_id = aws_access_key_id
+ self._aws_secret_access_key = aws_secret_access_key
+ self._session_token = session_token
+ self._use_ssl = use_ssl
+ self._config = config
+
+ # Session is cheap; the actual transport is the ``client``
+ # context manager opened per call. We deliberately do NOT
+ # cache a long-lived client across the lifespan: aiobotocore
+ # clients hold an aiohttp connection pool tied to a loop, and
+ # the per-call cost is negligible compared to the network
+ # round-trip.
+ self._session: (
+ aioboto3.Session | None
+ ) = None # type: ignore[name-defined]
+
+ async def __aenter__(self) -> "S3BlobStore":
+ try:
+ import aioboto3
+ except ImportError as e:
+ raise ImportError(
+ "S3BlobStore requires the optional dependency ``aioboto3``. "
+ "Install it with ``uv pip install aioboto3`` or with the "
+ "``[s3]`` extra.",
+ ) from e
+
+ self._session = aioboto3.Session()
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: Any,
+ ) -> None:
+ self._session = None
+
+ def _client(self) -> Any:
+ """Open a fresh S3 client context manager for one call."""
+ if self._session is None:
+ raise RuntimeError(
+ "S3BlobStore is not entered; use it inside "
+ "``async with`` before calling blob methods.",
+ )
+ return self._session.client(
+ "s3",
+ region_name=self._region_name,
+ endpoint_url=self._endpoint_url,
+ aws_access_key_id=self._aws_access_key_id,
+ aws_secret_access_key=self._aws_secret_access_key,
+ aws_session_token=self._session_token,
+ use_ssl=self._use_ssl,
+ config=self._config,
+ )
+
+ @staticmethod
+ def _parse_uri(uri: str) -> tuple[str, str]:
+ """Split an ``s3://{bucket}/{key}`` URI into ``(bucket, key)``."""
+ if not uri.startswith(_SCHEME):
+ raise ValueError(f"Not an S3 blob URI: {uri!r}")
+ rest = uri[len(_SCHEME) :]
+ bucket, _, key = rest.partition("/")
+ if not bucket or not key:
+ raise ValueError(f"Malformed S3 blob URI: {uri!r}")
+ return bucket, key
+
+ @classmethod
+ def _key_from_uri(cls, uri: str, expected_bucket: str) -> str:
+ """Return the object key, asserting the bucket matches.
+
+ Used by mutating operations (``delete``, ``exists``) where
+ crossing into another bucket would be a bug — the configured
+ bucket is the only place the store owns objects.
+ """
+ bucket, key = cls._parse_uri(uri)
+ if bucket != expected_bucket:
+ raise ValueError(
+ f"Bucket {bucket!r} in URI {uri!r} does not match "
+ f"configured bucket {expected_bucket!r}.",
+ )
+ return key
+
+ async def write_stream(self, key: str, stream: IO[bytes]) -> str:
+ """Stream-write a blob and return its ``s3://{bucket}/{key}`` URI.
+
+ Uses ``upload_fileobj`` so aioboto3 picks multipart upload
+ automatically for bodies above the multipart threshold
+ (8 MiB by default in botocore). For smaller bodies it
+ promotes to a single ``PutObject`` call.
+ """
+ async with self._client() as s3:
+ await s3.upload_fileobj(stream, self._bucket, key)
+ return f"{_SCHEME}{self._bucket}/{key}"
+
+ @asynccontextmanager
+ async def open( # type: ignore[override]
+ self,
+ uri: str,
+ ) -> AsyncIterator[AsyncReadable]:
+ """Stream-read a blob by URI.
+
+ Yields an :class:`AsyncReadable` backed by the response
+ ``Body``. The S3 GET response is held open for the duration
+ of the ``async with`` block — exit promptly so the connection
+ returns to the pool.
+
+ The bucket is read from the URI rather than the configured
+ bucket so post-migration deployments can still resolve
+ document records that were written under the previous bucket.
+ The IAM role must grant ``s3:GetObject`` on the legacy bucket
+ for this to actually succeed at the wire level.
+ """
+ bucket, key = self._parse_uri(uri)
+ async with self._client() as s3:
+ response = await s3.get_object(Bucket=bucket, Key=key)
+ body = response["Body"]
+ try:
+ yield _StreamingBody(body)
+ finally:
+ # aiobotocore's body has a ``close`` coroutine; call
+ # it explicitly so the connection is released rather
+ # than waiting for GC.
+ close = getattr(body, "close", None)
+ if close is not None:
+ result = close()
+ if hasattr(result, "__await__"):
+ await result
+
+ async def delete(self, uri: str) -> None:
+ """Delete the object at ``uri``. Idempotent."""
+ key = self._key_from_uri(uri, self._bucket)
+ async with self._client() as s3:
+ # S3 ``DeleteObject`` is idempotent on a missing key —
+ # no special handling needed for the "already gone" case.
+ await s3.delete_object(Bucket=self._bucket, Key=key)
+
+ async def exists(self, uri: str) -> bool:
+ """Return whether the object at ``uri`` is present."""
+ key = self._key_from_uri(uri, self._bucket)
+ async with self._client() as s3:
+ try:
+ await s3.head_object(Bucket=self._bucket, Key=key)
+ return True
+ except Exception as exc: # noqa: BLE001
+ # botocore's ClientError has ``response["Error"]["Code"]``
+ # of "404" or "NoSuchKey" for missing objects; we
+ # treat anything that isn't a successful HEAD as
+ # "missing" rather than re-raising, matching the
+ # local backend's permissive contract. A genuinely
+ # broken backend (auth failure, network) will surface
+ # on the next read/write.
+ code = (
+ getattr(exc, "response", {}).get("Error", {}).get("Code")
+ )
+ if code in {"404", "NoSuchKey", "NotFound"}:
+ return False
+ raise
diff --git a/src/agentscope/app/rag/index_worker/__init__.py b/src/agentscope/app/rag/index_worker/__init__.py
new file mode 100644
index 000000000..bb4612b35
--- /dev/null
+++ b/src/agentscope/app/rag/index_worker/__init__.py
@@ -0,0 +1,198 @@
+# -*- coding: utf-8 -*-
+"""Out-of-process index worker entry point.
+
+A worker process owns:
+
+- a :class:`~agentscope.app._service.IndexWorker` instance, which
+ runs the parse → chunk → embed pipeline for one document at a time;
+- an :class:`~agentscope.app._service.IndexTaskConsumer`, which
+ subscribes to the shared task channel on the message bus and
+ feeds the worker.
+
+It does NOT own the sweeper — the API process keeps running the
+sweeper so that documents stuck in ``pending`` (because the API
+crashed between the storage write and the dispatcher publish) still
+recover, even if every worker process happens to be offline at the
+moment the publish was attempted.
+
+This module is a library: a deployment wires its concrete backends
+through :func:`run_worker` from whatever bootstrap script it uses
+(systemd unit, Kubernetes Deployment + container entrypoint,
+docker-compose ``command``, ...). The shape mirrors
+:func:`agentscope.app.create_app` — pass already-constructed
+backend instances, the worker manages their lifecycle through an
+:class:`AsyncExitStack`.
+
+Example::
+
+ import asyncio
+ import socket
+ import uuid
+
+ from agentscope.app.rag.blob_store import S3BlobStore
+ from agentscope.app.rag.knowledge_base_manager import (
+ DefaultKnowledgeBaseManager,
+ )
+ from agentscope.app.message_bus import RedisMessageBus
+ from agentscope.app.storage import RedisStorage
+ from agentscope.app.rag.index_worker import run_worker
+ from agentscope.rag import ApproxTokenChunker, TextParser, ...
+
+ async def main() -> None:
+ storage = RedisStorage(url=os.environ["REDIS_URL"])
+ message_bus = RedisMessageBus(url=os.environ["REDIS_URL"])
+ blob_store = S3BlobStore(
+ bucket=os.environ["S3_BUCKET"],
+ endpoint_url=os.environ.get("S3_ENDPOINT"),
+ )
+ kb_manager = DefaultKnowledgeBaseManager(...)
+ parsers = [TextParser()]
+ chunker = ApproxTokenChunker()
+ await run_worker(
+ storage=storage,
+ message_bus=message_bus,
+ blob_store=blob_store,
+ knowledge_base_manager=kb_manager,
+ parsers=parsers,
+ chunker=chunker,
+ )
+
+ if __name__ == "__main__":
+ asyncio.run(main())
+"""
+import asyncio
+import signal
+import socket
+import uuid
+from concurrent.futures import ProcessPoolExecutor
+from contextlib import AsyncExitStack
+from typing import TYPE_CHECKING
+
+from ..._service import IndexTaskConsumer, IndexWorker
+from ...._logging import logger
+
+if TYPE_CHECKING:
+ from ..blob_store import BlobStoreBase
+ from ..knowledge_base_manager import KnowledgeBaseManagerBase
+ from ...message_bus import MessageBus
+ from ...storage import StorageBase
+ from ....rag import ChunkerBase, ParserBase
+
+
+async def run_worker(
+ *,
+ storage: "StorageBase",
+ message_bus: "MessageBus",
+ blob_store: "BlobStoreBase",
+ knowledge_base_manager: "KnowledgeBaseManagerBase",
+ parsers: "list[ParserBase] | dict[str, ParserBase]",
+ chunker: "ChunkerBase",
+ node_id: str | None = None,
+ worker_max_concurrency: int = 4,
+ consumer_max_batch: int = 32,
+ parser_executor: ProcessPoolExecutor | None = None,
+) -> None:
+ """Run the out-of-process index worker until cancelled.
+
+ Manages the lifecycle of every passed-in backend through a single
+ :class:`AsyncExitStack`. The function returns when SIGINT or
+ SIGTERM is delivered (deployment-controlled shutdown).
+
+ Args:
+ storage (`StorageBase`):
+ Persistent storage backend. Lifecycle managed here.
+ message_bus (`MessageBus`):
+ Live message bus subscribed to for index-task signals.
+ Lifecycle managed here.
+ blob_store (`BlobStoreBase`):
+ Backend the worker reads document bytes from. Lifecycle
+ managed here.
+ knowledge_base_manager (`KnowledgeBaseManagerBase`):
+ Resolves :class:`KnowledgeBase` runtimes for embedding +
+ vector store writes. Lifecycle managed here.
+ parsers (`list[ParserBase] | dict[str, ParserBase]`):
+ Parsers used to dispatch uploads by IANA media type.
+ Pass the same registry both to ``create_app`` and to the
+ worker — list mode expands each parser's
+ ``supported_media_types`` (later entries override earlier
+ ones, with a warning); dict mode is used verbatim for
+ explicit routing.
+ chunker (`ChunkerBase`):
+ Shared chunker.
+ node_id (`str | None`, optional):
+ Stable identifier for this worker process used on the
+ storage lease. Defaults to
+ ``"{hostname}:{uuid-prefix}"`` — good enough for
+ distinguishing two workers running on the same host;
+ override when your orchestrator has a more meaningful
+ id (Kubernetes pod name, ECS task id, ...).
+ worker_max_concurrency (`int`, defaults to ``4``):
+ Maximum number of documents the worker processes
+ concurrently. See
+ :class:`~agentscope.app._service.IndexWorker`.
+ consumer_max_batch (`int`, defaults to ``32``):
+ Maximum entries the consumer drains per signal. See
+ :class:`~agentscope.app._service.IndexTaskConsumer`.
+ parser_executor (`ProcessPoolExecutor | None`, optional):
+ Process pool for CPU-bound parses. ``None`` runs parses
+ inline (fine for text-only deployments).
+ """
+ resolved_node_id = (
+ node_id or f"{socket.gethostname()}:{uuid.uuid4().hex[:8]}"
+ )
+
+ async with AsyncExitStack() as stack:
+ await stack.enter_async_context(storage)
+ await stack.enter_async_context(message_bus)
+ await stack.enter_async_context(blob_store)
+ await stack.enter_async_context(knowledge_base_manager)
+
+ worker = IndexWorker(
+ storage=storage,
+ blob_store=blob_store,
+ knowledge_base_manager=knowledge_base_manager,
+ parsers=parsers,
+ chunker=chunker,
+ node_id=resolved_node_id,
+ max_concurrency=worker_max_concurrency,
+ parser_executor=parser_executor,
+ )
+ await stack.enter_async_context(
+ IndexTaskConsumer(
+ message_bus=message_bus,
+ worker=worker,
+ max_batch=consumer_max_batch,
+ ),
+ )
+
+ logger.info(
+ "Index worker %s ready (max_concurrency=%d, max_batch=%d)",
+ resolved_node_id,
+ worker_max_concurrency,
+ consumer_max_batch,
+ )
+
+ # Block until a signal arrives. We install handlers on the
+ # running loop rather than using ``signal.signal`` so the
+ # interaction with asyncio is well-defined (the default
+ # handler would raise KeyboardInterrupt at an arbitrary
+ # await point, which is awkward to clean up).
+ loop = asyncio.get_running_loop()
+ stop = loop.create_future()
+
+ def _request_stop() -> None:
+ if not stop.done():
+ stop.set_result(None)
+
+ for sig in (signal.SIGINT, signal.SIGTERM):
+ try:
+ loop.add_signal_handler(sig, _request_stop)
+ except NotImplementedError:
+ # Windows event loop does not implement add_signal_handler;
+ # tests and Linux/macOS deployments are unaffected.
+ pass
+
+ try:
+ await stop
+ finally:
+ logger.info("Index worker %s shutting down", resolved_node_id)
diff --git a/src/agentscope/app/rag/index_worker/__main__.py b/src/agentscope/app/rag/index_worker/__main__.py
new file mode 100644
index 000000000..805391222
--- /dev/null
+++ b/src/agentscope/app/rag/index_worker/__main__.py
@@ -0,0 +1,108 @@
+# -*- coding: utf-8 -*-
+"""Entry point for ``python -m agentscope.app.rag.index_worker``.
+
+Resolves a deployment-supplied bootstrap callable from the
+``AGENTSCOPE_WORKER_BOOTSTRAP`` environment variable, calls it to
+obtain the concrete backends, and hands them to :func:`run_worker`.
+
+The deployment owns the bootstrap because backend selection is a
+deployment concern — there is no one-size-fits-all storage,
+message bus, or blob store. The bootstrap must be importable, must
+take no arguments, and must return a dict whose keys match
+:func:`run_worker`'s keyword arguments.
+
+Example bootstrap (``mydeploy/worker_bootstrap.py``)::
+
+ import os
+
+ from agentscope.app.rag.blob_store import S3BlobStore
+ from agentscope.app.rag.knowledge_base_manager import (
+ DefaultKnowledgeBaseManager,
+ )
+ from agentscope.app.message_bus import RedisMessageBus
+ from agentscope.app.storage import RedisStorage
+ from agentscope.rag import ApproxTokenChunker, TextParser
+
+ def bootstrap() -> dict:
+ return {
+ "storage": RedisStorage(url=os.environ["REDIS_URL"]),
+ "message_bus": RedisMessageBus(url=os.environ["REDIS_URL"]),
+ "blob_store": S3BlobStore(
+ bucket=os.environ["S3_BUCKET"],
+ endpoint_url=os.environ.get("S3_ENDPOINT"),
+ ),
+ "knowledge_base_manager": DefaultKnowledgeBaseManager(...),
+ "parsers": [TextParser()],
+ "chunker": ApproxTokenChunker(),
+ }
+
+And launch::
+
+ AGENTSCOPE_WORKER_BOOTSTRAP=mydeploy.worker_bootstrap:bootstrap \\
+ python -m agentscope.app.rag.index_worker
+"""
+import asyncio
+import importlib
+import logging
+import os
+import sys
+from typing import Any, Callable
+
+from . import run_worker
+
+
+def _resolve(dotted: str) -> Callable[[], dict[str, Any]]:
+ """Import ``module:attribute`` and return the attribute.
+
+ Args:
+ dotted (`str`):
+ A ``module:attribute`` reference; must contain a colon.
+
+ Returns:
+ `Callable[[], dict[str, Any]]`:
+ The resolved attribute — expected to be a zero-arg
+ callable that returns the kwargs dict for
+ :func:`run_worker`.
+
+ Raises:
+ `ValueError`:
+ When ``dotted`` does not contain a colon.
+ """
+ if ":" not in dotted:
+ raise ValueError(
+ f"AGENTSCOPE_WORKER_BOOTSTRAP must be in 'module:attr' "
+ f"form, got {dotted!r}.",
+ )
+ module_name, _, attr = dotted.partition(":")
+ module = importlib.import_module(module_name)
+ return getattr(module, attr)
+
+
+def main() -> None:
+ """Resolve the bootstrap callable from the environment and run the worker.
+
+ Reads ``AGENTSCOPE_WORKER_BOOTSTRAP`` (``module:attr`` form),
+ imports the target, calls it for the kwargs dict, and forwards
+ them to :func:`run_worker`. Exits with code ``2`` when the
+ environment variable is missing — the deployment must supply it
+ because backend selection is a deployment concern.
+ """
+ logging.basicConfig(
+ level=os.environ.get("LOG_LEVEL", "INFO"),
+ format="%(asctime)s %(levelname)s %(name)s %(message)s",
+ )
+ bootstrap_path = os.environ.get("AGENTSCOPE_WORKER_BOOTSTRAP")
+ if not bootstrap_path:
+ sys.stderr.write(
+ "AGENTSCOPE_WORKER_BOOTSTRAP is required — set it to "
+ "'package.module:callable' that returns a kwargs dict for "
+ "run_worker.\n",
+ )
+ sys.exit(2)
+ factory = _resolve(bootstrap_path)
+ kwargs = factory()
+ asyncio.run(run_worker(**kwargs))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agentscope/app/rag/knowledge_base_manager/__init__.py b/src/agentscope/app/rag/knowledge_base_manager/__init__.py
new file mode 100644
index 000000000..3ed9f775d
--- /dev/null
+++ b/src/agentscope/app/rag/knowledge_base_manager/__init__.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+"""Knowledge base manager classes.
+
+The manager owns the lifecycle of knowledge bases:
+
+- creation / deletion / listing of :class:`KnowledgeBaseRecord` rows,
+- allocation / drop of the matching vector store storage,
+- construction of :class:`~agentscope.rag.KnowledgeBase` runtime handles
+ used by both the HTTP service and the agent runtime.
+
+The MVP ships a single isolation strategy
+(:class:`CollectionPerKbManager`); future strategies will live
+alongside it.
+"""
+
+from ._base import KnowledgeBaseManagerBase
+from ._collection_per_kb import CollectionPerKbManager
+from ._dimension_policy import DimensionPolicy, DimensionPolicyKind
+from ._errors import (
+ DimensionPolicyError,
+ KnowledgeBaseError,
+ KnowledgeBaseNotFoundError,
+)
+
+__all__ = [
+ "CollectionPerKbManager",
+ "DimensionPolicy",
+ "DimensionPolicyError",
+ "DimensionPolicyKind",
+ "KnowledgeBaseError",
+ "KnowledgeBaseManagerBase",
+ "KnowledgeBaseNotFoundError",
+]
diff --git a/src/agentscope/app/rag/knowledge_base_manager/_base.py b/src/agentscope/app/rag/knowledge_base_manager/_base.py
new file mode 100644
index 000000000..d3557a248
--- /dev/null
+++ b/src/agentscope/app/rag/knowledge_base_manager/_base.py
@@ -0,0 +1,302 @@
+# -*- coding: utf-8 -*-
+"""Abstract knowledge base manager.
+
+The manager is the **lifecycle owner** of knowledge bases:
+
+- it creates / lists / deletes :class:`KnowledgeBaseRecord` rows in
+ storage,
+- it allocates / drops the matching vector store collections,
+- it resolves an embedding model from the record's credential and
+ hands a ready-to-use :class:`KnowledgeBase` runtime back to callers.
+
+Different subclasses encode different *isolation strategies*: one
+collection per knowledge base, a single shared collection scoped by
+metadata, native VDB namespaces, etc. All of them share the same
+:class:`KnowledgeBaseManagerBase` interface so the rest of the
+application can stay strategy-agnostic.
+
+The manager is created once at application startup and stored on
+``app.state.knowledge_base_manager``. See
+:func:`~agentscope.app.create_app` for the wiring.
+"""
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Self
+
+from ._dimension_policy import DimensionPolicy
+
+if TYPE_CHECKING:
+ from types import TracebackType
+
+ from ...storage import (
+ EmbeddingModelConfig,
+ KnowledgeBaseRecord,
+ StorageBase,
+ )
+ from ....rag import KnowledgeBase, VectorStoreBase
+
+
+class KnowledgeBaseManagerBase(ABC):
+ """Abstract base for knowledge base managers.
+
+ Subclasses implement a specific isolation strategy by overriding
+ :meth:`create_knowledge_base`, :meth:`delete_knowledge_base`, and
+ :meth:`get_knowledge`. The bookkeeping methods
+ (:meth:`get_knowledge_base`, :meth:`list_knowledge_bases`) have
+ default implementations that delegate to the bound storage.
+ """
+
+ def __init__(
+ self,
+ storage: "StorageBase",
+ vector_store: "VectorStoreBase",
+ ) -> None:
+ """Initialize the manager.
+
+ Args:
+ storage (`StorageBase`):
+ The application-wide storage backend used to persist
+ :class:`KnowledgeBaseRecord` rows and resolve
+ credentials.
+ vector_store (`VectorStoreBase`):
+ The application-wide vector store instance shared by
+ every knowledge base allocated by this manager.
+ """
+ self._storage = storage
+ self._vector_store = vector_store
+
+ # ------------------------------------------------------------------
+ # Lifecycle hooks
+ # ------------------------------------------------------------------
+
+ async def __aenter__(self) -> Self:
+ """Enter the manager's lifetime.
+
+ Enters the bound vector store's async context so a single
+ ``create_app`` parameter (the manager) covers the vector store's
+ lifecycle too. Subclasses that override this MUST call
+ ``await super().__aenter__()`` first to keep the vector store
+ ready before subclass-specific setup runs.
+ """
+ await self._vector_store.__aenter__()
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: "TracebackType | None",
+ ) -> None:
+ """Exit the manager's lifetime, releasing the vector store.
+
+ Args:
+ exc_type (`type[BaseException] | None`):
+ The exception type raised inside the with-block, if any.
+ exc (`BaseException | None`):
+ The exception instance raised inside the with-block,
+ if any.
+ tb (`TracebackType | None`):
+ The traceback for the raised exception, if any.
+ """
+ await self._vector_store.__aexit__(exc_type, exc, tb)
+
+ # ------------------------------------------------------------------
+ # Capability discovery
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def get_dimension_policy(self) -> DimensionPolicy:
+ """Return the embedding-dimension policy this manager enforces.
+
+ Surfaced over HTTP so the front-end can soft-filter
+ incompatible models / dimensions before submission and show a
+ helpful banner.
+
+ Returns:
+ `DimensionPolicy`:
+ The current dimension policy.
+ """
+
+ # ------------------------------------------------------------------
+ # CRUD
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def create_knowledge_base(
+ self,
+ user_id: str,
+ name: str,
+ description: str,
+ embedding_model_config: "EmbeddingModelConfig",
+ ) -> "KnowledgeBaseRecord":
+ """Create a new knowledge base for the given user.
+
+ Implementations must:
+
+ 1. validate ``embedding_model_config.dimensions`` against
+ :meth:`get_dimension_policy`;
+ 2. allocate the vector store collection (or namespace) the
+ strategy uses;
+ 3. persist a :class:`KnowledgeBaseRecord` and return it.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ name (`str`):
+ Display name.
+ description (`str`):
+ Free-form description.
+ embedding_model_config (`EmbeddingModelConfig`):
+ Embedding model configuration; pinned to the record.
+
+ Returns:
+ `KnowledgeBaseRecord`:
+ The newly persisted record.
+
+ Raises:
+ `DimensionPolicyError`:
+ If the requested dimension violates the manager's
+ dimension policy.
+ """
+
+ async def get_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> "KnowledgeBaseRecord | None":
+ """Fetch a knowledge base record by id (delegates to storage).
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The knowledge base id.
+
+ Returns:
+ `KnowledgeBaseRecord | None`:
+ The record, or ``None`` if not found / not owned by
+ the user.
+ """
+ return await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+
+ async def list_knowledge_bases(
+ self,
+ user_id: str,
+ ) -> "list[KnowledgeBaseRecord]":
+ """List all knowledge base records owned by the given user.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+
+ Returns:
+ `list[KnowledgeBaseRecord]`:
+ All knowledge base records belonging to the user.
+ """
+ return await self._storage.list_knowledge_bases(user_id)
+
+ async def update_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ name: str | None = None,
+ description: str | None = None,
+ ) -> "KnowledgeBaseRecord | None":
+ """Update mutable fields on an existing knowledge base record.
+
+ Only ``name`` and ``description`` are mutable. The embedding
+ model configuration and the underlying collection are pinned
+ for the lifetime of the record because changing either would
+ invalidate every previously inserted vector.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The knowledge base id.
+ name (`str | None`, optional):
+ New display name; ``None`` leaves the name unchanged.
+ description (`str | None`, optional):
+ New description; ``None`` leaves the description
+ unchanged.
+
+ Returns:
+ `KnowledgeBaseRecord | None`:
+ The updated record, or ``None`` if the record was not
+ found / not owned by the user.
+ """
+ record = await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if record is None:
+ return None
+ if name is not None:
+ record.name = name
+ if description is not None:
+ record.description = description
+ return await self._storage.upsert_knowledge_base(user_id, record)
+
+ @abstractmethod
+ async def delete_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> bool:
+ """Delete a knowledge base record and its underlying storage.
+
+ Implementations must:
+
+ 1. authorise the call by looking the record up first;
+ 2. drop the vector store collection (or scope) the strategy
+ uses;
+ 3. remove the :class:`KnowledgeBaseRecord` from storage.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The id of the knowledge base to delete.
+
+ Returns:
+ `bool`:
+ ``True`` if the record existed and was deleted,
+ ``False`` if it was not found.
+ """
+
+ # ------------------------------------------------------------------
+ # KnowledgeBase runtime
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def get_knowledge(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> "KnowledgeBase":
+ """Resolve a runtime :class:`KnowledgeBase` handle for one KB.
+
+ Implementations are responsible for:
+
+ - looking the record up in storage (authorisation);
+ - resolving the embedding model from the record's credential;
+ - constructing the :class:`KnowledgeBase` with the strategy's
+ collection name and metadata filter.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The knowledge base id.
+
+ Returns:
+ `KnowledgeBase`:
+ A runtime handle bound to this knowledge base.
+
+ Raises:
+ `KnowledgeBaseNotFoundError`:
+ If the record does not exist or does not belong to
+ the authenticated user.
+ """
diff --git a/src/agentscope/app/rag/knowledge_base_manager/_collection_per_kb.py b/src/agentscope/app/rag/knowledge_base_manager/_collection_per_kb.py
new file mode 100644
index 000000000..042d8077e
--- /dev/null
+++ b/src/agentscope/app/rag/knowledge_base_manager/_collection_per_kb.py
@@ -0,0 +1,188 @@
+# -*- coding: utf-8 -*-
+"""Collection-per-knowledge-base isolation strategy.
+
+The simplest correct implementation: every knowledge base gets its own
+vector store collection sized to the chosen embedding model. No
+cross-KB co-location, no namespace gymnastics — collection names are
+the isolation key.
+
+Because each knowledge base owns its collection outright, the
+dimension policy reported by this manager is always
+:attr:`DimensionPolicyKind.ANY`: the user is free to pick any
+dimension supported by their embedding model.
+
+The collection name is generated as ``kb_<uuid_hex>`` (no user id is
+encoded, since storage does the user-scoped authorisation).
+"""
+from typing import TYPE_CHECKING
+
+from ._base import KnowledgeBaseManagerBase
+from ._dimension_policy import DimensionPolicy, DimensionPolicyKind
+from ._errors import KnowledgeBaseNotFoundError
+from ...._logging import logger
+from ....rag import KnowledgeBase
+from ..._service._embedding import get_embedding_model
+from ...storage import KnowledgeBaseRecord
+
+if TYPE_CHECKING:
+ from ...storage import EmbeddingModelConfig
+
+
+class CollectionPerKbManager(KnowledgeBaseManagerBase):
+ """One-collection-per-KB knowledge base manager.
+
+ Each knowledge base maps to one collection in the bound
+ :class:`~agentscope.rag.VectorStoreBase`. The collection is
+ created at :meth:`create_knowledge_base` time and dropped at
+ :meth:`delete_knowledge_base` time.
+ """
+
+ async def get_dimension_policy(self) -> DimensionPolicy:
+ """Return :attr:`DimensionPolicyKind.ANY` — every KB picks freely.
+
+ Returns:
+ `DimensionPolicy`:
+ The dimension policy ``(ANY, None)``.
+ """
+ return DimensionPolicy(
+ kind=DimensionPolicyKind.ANY,
+ dimension=None,
+ )
+
+ async def create_knowledge_base(
+ self,
+ user_id: str,
+ name: str,
+ description: str,
+ embedding_model_config: "EmbeddingModelConfig",
+ ) -> KnowledgeBaseRecord:
+ """Allocate a new collection and persist the knowledge base record.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ name (`str`):
+ Display name.
+ description (`str`):
+ Free-form description.
+ embedding_model_config (`EmbeddingModelConfig`):
+ Embedding model configuration; pinned to the record.
+
+ Returns:
+ `KnowledgeBaseRecord`:
+ The newly persisted record.
+ """
+ record = KnowledgeBaseRecord(
+ user_id=user_id,
+ name=name,
+ description=description,
+ embedding_model_config=embedding_model_config,
+ collection_name="",
+ )
+ record.collection_name = f"kb_{record.id}"
+
+ await self._vector_store.create_collection(
+ name=record.collection_name,
+ dimensions=embedding_model_config.dimensions,
+ )
+ try:
+ return await self._storage.upsert_knowledge_base(user_id, record)
+ except Exception:
+ # Compensating delete must not shadow the original exception:
+ # if the delete itself raises, the caller would be misdirected
+ # to investigate the wrong error and the orphan collection
+ # would leave no trace.
+ try:
+ await self._vector_store.delete_collection(
+ record.collection_name,
+ )
+ except Exception: # noqa: BLE001 — best-effort cleanup
+ logger.exception(
+ "Failed to drop orphan collection %r after "
+ "upsert_knowledge_base failed; collection leaked.",
+ record.collection_name,
+ )
+ raise
+
+ async def delete_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> bool:
+ """Drop the underlying collection and remove the record.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The id of the knowledge base to delete.
+
+ Returns:
+ `bool`:
+ ``True`` if the record existed and was deleted,
+ ``False`` if it was not found.
+ """
+ record = await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if record is None:
+ return False
+
+ if await self._vector_store.has_collection(record.collection_name):
+ await self._vector_store.delete_collection(record.collection_name)
+ return await self._storage.delete_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+
+ async def get_knowledge(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> KnowledgeBase:
+ """Resolve a :class:`KnowledgeBase` runtime for one knowledge base.
+
+ Looks the record up in storage (raising
+ :class:`KnowledgeBaseNotFoundError` for unknown / un-owned
+ ids), constructs the embedding model from the pinned
+ credential, and returns a ready-to-use handle bound to the
+ record's collection.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The knowledge base id.
+
+ Returns:
+ `KnowledgeBase`:
+ A runtime handle bound to this knowledge base.
+
+ Raises:
+ `KnowledgeBaseNotFoundError`:
+ If the record does not exist or does not belong to
+ the authenticated user.
+ """
+ record = await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if record is None:
+ raise KnowledgeBaseNotFoundError(
+ f"Knowledge base {knowledge_base_id!r} not found.",
+ )
+
+ embedding_model = await get_embedding_model(
+ user_id=user_id,
+ config=record.embedding_model_config,
+ storage=self._storage,
+ )
+ return KnowledgeBase(
+ name=record.name,
+ description=record.description,
+ embedding_model=embedding_model,
+ vector_store=self._vector_store,
+ collection=record.collection_name,
+ metadata_filter=None,
+ )
diff --git a/src/agentscope/app/rag/knowledge_base_manager/_dimension_policy.py b/src/agentscope/app/rag/knowledge_base_manager/_dimension_policy.py
new file mode 100644
index 000000000..d83c6fe0f
--- /dev/null
+++ b/src/agentscope/app/rag/knowledge_base_manager/_dimension_policy.py
@@ -0,0 +1,154 @@
+# -*- coding: utf-8 -*-
+"""Dimension policy advertised by a knowledge base manager.
+
+The policy tells the front-end which embedding-model dimensions are
+acceptable when creating a new knowledge base. It is the *capability*
+side of the contract; the server still hard-validates every create
+call against the same rules.
+
+Three kinds are modelled:
+
+- ``ANY`` — any positive dimension is acceptable. The user picks
+ freely from the list of supported dimensions on the chosen
+ embedding model card. This is the case for one-collection-per-KB
+ isolation strategies.
+- ``FIXED`` — the dimension is fixed by the server (e.g. a single
+ shared collection sized to a specific dimension). The front-end
+ hides incompatible models / dimensions.
+- ``LOCKED_BY_EXISTING`` — semantically identical to ``FIXED`` from
+ the front-end's perspective, but communicates *why* the dimension
+ is fixed: a previously created knowledge base in the same shared
+ collection has pinned it.
+"""
+from enum import Enum
+from typing import TYPE_CHECKING
+
+from pydantic import BaseModel, Field, model_validator
+
+if TYPE_CHECKING:
+ from ....embedding import EmbeddingModelCard
+
+
+class DimensionPolicyKind(str, Enum):
+ """The kind of dimension policy the manager publishes."""
+
+ ANY = "any"
+ """Any positive dimension is acceptable.
+
+ Used by isolation strategies that allocate a fresh collection per
+ knowledge base (each one sized to its own embedding model)."""
+
+ FIXED = "fixed"
+ """A specific dimension is required by the manager configuration.
+
+ Used by isolation strategies that share a single collection across
+ knowledge bases — every record must agree on the dimension."""
+
+ LOCKED_BY_EXISTING = "locked_by_existing"
+ """A specific dimension was locked in by a previously created
+ knowledge base.
+
+ Identical to ``FIXED`` for clients; the distinction lets the UI
+ show *why* the dimension is fixed (e.g. "the first KB pinned the
+ dimension to 768 — switch isolation strategy to use 1536").
+ """
+
+
+class DimensionPolicy(BaseModel):
+ """The dimension policy a manager exposes to the front-end."""
+
+ kind: DimensionPolicyKind = Field(
+ description="What constraint applies to the chosen dimension.",
+ )
+ """The kind of constraint."""
+
+ dimension: int | None = Field(
+ default=None,
+ description=(
+ "The required dimension when ``kind`` is ``FIXED`` or "
+ "``LOCKED_BY_EXISTING``. Always ``None`` for ``ANY``."
+ ),
+ )
+ """The required dimension, or ``None`` when any dimension is fine."""
+
+ @model_validator(mode="after")
+ def _enforce_kind_dimension_invariant(self) -> "DimensionPolicy":
+ """Reject states like ``ANY + dimension=768`` or ``FIXED + None``.
+
+ Without this guard, downstream code silently produces wrong
+ results (``ANY`` ignores a stray dimension) or crashes
+ (``FIXED`` with ``None`` makes ``filter_card`` raise
+ ``TypeError`` on ``target not in card.supported_dimensions``).
+ """
+ if self.kind is DimensionPolicyKind.ANY:
+ if self.dimension is not None:
+ raise ValueError(
+ "DimensionPolicy: kind=ANY requires dimension=None, "
+ f"got dimension={self.dimension!r}.",
+ )
+ else:
+ if self.dimension is None or self.dimension <= 0:
+ raise ValueError(
+ f"DimensionPolicy: kind={self.kind.value} requires a "
+ f"positive dimension, got dimension={self.dimension!r}.",
+ )
+ return self
+
+ def accepts(self, dimensions: int) -> bool:
+ """Check whether a candidate dimension satisfies this policy.
+
+ Args:
+ dimensions (`int`):
+ The candidate output dimension.
+
+ Returns:
+ `bool`:
+ ``True`` if the dimension is acceptable.
+ """
+ if self.kind is DimensionPolicyKind.ANY:
+ return dimensions > 0
+ return dimensions == self.dimension
+
+ def filter_card(
+ self,
+ card: "EmbeddingModelCard",
+ ) -> "EmbeddingModelCard | None":
+ """Project an embedding model card through this policy.
+
+ Used by the knowledge base router to pre-filter the embedding
+ model catalogue exposed at KB-creation time:
+
+ - ``ANY`` returns the card unchanged.
+ - ``FIXED`` / ``LOCKED_BY_EXISTING``:
+
+ - fixed-dim cards (``supported_dimensions is None``) are
+ kept iff their default ``dimensions`` matches the locked
+ value;
+ - matryoshka cards are kept iff the locked dimension is in
+ ``supported_dimensions``, and a copy is returned with
+ ``supported_dimensions`` narrowed to the locked value and
+ ``dimensions`` set accordingly. This guarantees the
+ front-end cannot pick an incompatible dimension.
+
+ Args:
+ card (`EmbeddingModelCard`):
+ The candidate embedding model card.
+
+ Returns:
+ `EmbeddingModelCard | None`:
+ The (possibly narrowed) card, or ``None`` if the card
+ cannot satisfy this policy.
+ """
+ if self.kind is DimensionPolicyKind.ANY:
+ return card
+ target = self.dimension
+ if card.supported_dimensions is None:
+ return card if card.dimensions == target else None
+ if target not in card.supported_dimensions:
+ return None
+ return card.model_copy(
+ update={
+ "dimensions": target,
+ "supported_dimensions": [target],
+ },
+ )
diff --git a/src/agentscope/app/rag/knowledge_base_manager/_errors.py b/src/agentscope/app/rag/knowledge_base_manager/_errors.py
new file mode 100644
index 000000000..529f51ffd
--- /dev/null
+++ b/src/agentscope/app/rag/knowledge_base_manager/_errors.py
@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+"""Knowledge base manager exception hierarchy.
+
+The router maps each exception to an HTTP status code in
+:mod:`agentscope.app._router._knowledge_base`:
+
+- :class:`KnowledgeBaseNotFoundError` → ``404``
+- :class:`DimensionPolicyError` → ``409``
+
+Keeping the mapping inside the router (and not raising
+``HTTPException`` from the manager) lets the same manager be reused by
+non-HTTP entry points (e.g. CLI tools, the agent middleware) without
+pulling in FastAPI.
+"""
+
+
+class KnowledgeBaseError(Exception):
+ """Base class for knowledge base manager errors."""
+
+
+class KnowledgeBaseNotFoundError(KnowledgeBaseError):
+ """Raised when a knowledge base record cannot be located.
+
+ The record is missing entirely, or it exists but does not belong
+ to the authenticated user. The two are reported identically to
+ avoid leaking existence of other users' knowledge bases.
+ """
+
+
+class DimensionPolicyError(KnowledgeBaseError):
+ """Raised when a create-time embedding model violates the manager's
+ dimension policy.
+
+ Carries both the offending dimension and the manager's policy so
+ the router can surface a precise error message without having to
+ re-derive either side.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ requested_dimension: int,
+ policy_dimension: int | None,
+ ) -> None:
+ """Initialize the error.
+
+ Args:
+ message (`str`):
+ Human-readable error message.
+ requested_dimension (`int`):
+ The dimension the caller asked for.
+ policy_dimension (`int | None`):
+ The dimension the policy enforces, or ``None`` if the
+ policy admits any dimension.
+ """
+ super().__init__(message)
+ self.requested_dimension = requested_dimension
+ self.policy_dimension = policy_dimension
diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.py
index 4baf8f70f..0c0f4ab14 100644
--- a/src/agentscope/app/storage/__init__.py
+++ b/src/agentscope/app/storage/__init__.py
@@ -7,10 +7,15 @@ from ._model import (
AgentData,
AgentRecord,
CredentialRecord,
+ KnowledgeBaseRecord,
+ KnowledgeDocumentData,
+ KnowledgeDocumentRecord,
+ KnowledgeDocumentStatus,
ScheduleData,
ScheduleRecord,
ScheduleSource,
SessionConfig,
+ SessionKnowledgeConfig,
SessionRecord,
SessionSource,
ChatModelConfig,
@@ -28,7 +33,12 @@ __all__ = [
"AgentData",
"AgentRecord",
"CredentialRecord",
+ "KnowledgeBaseRecord",
+ "KnowledgeDocumentData",
+ "KnowledgeDocumentRecord",
+ "KnowledgeDocumentStatus",
"SessionConfig",
+ "SessionKnowledgeConfig",
"SessionRecord",
"SessionSource",
"ChatModelConfig",
diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.py
index 6f446b7f1..7731bf7ba 100644
--- a/src/agentscope/app/storage/_base.py
+++ b/src/agentscope/app/storage/_base.py
@@ -2,12 +2,16 @@
# pylint: disable=too-many-public-methods
"""The storage base class."""
from abc import ABC, abstractmethod
+from datetime import datetime, timedelta
from typing import Any, Self
from ._model import (
AgentRecord,
CredentialRecord,
+ KnowledgeBaseRecord,
+ KnowledgeDocumentRecord,
+ KnowledgeDocumentStatus,
ScheduleRecord,
SessionRecord,
SessionConfig,
@@ -525,3 +529,380 @@ class StorageBase(ABC):
``True`` if the team record existed and was deleted,
``False`` if not found.
"""
+
+ # ------------------------------------------------------------------
+ # Knowledge base persistence
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def upsert_knowledge_base(
+ self,
+ user_id: str,
+ record: KnowledgeBaseRecord,
+ ) -> KnowledgeBaseRecord:
+ """Create or update a knowledge base record.
+
+ The caller is responsible for constructing the full
+ :class:`KnowledgeBaseRecord` (including ``id`` and
+ ``collection_name``). If a record with the same id already
+ exists it is overwritten and ``updated_at`` refreshed.
+
+ Args:
+ user_id (`str`):
+ The owner user id. Must match ``record.user_id``.
+ record (`KnowledgeBaseRecord`):
+ The fully-populated record to persist.
+
+ Returns:
+ `KnowledgeBaseRecord`:
+ The stored record (with ``updated_at`` refreshed).
+ """
+
+ @abstractmethod
+ async def get_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> KnowledgeBaseRecord | None:
+ """Fetch a single knowledge base record by id.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The knowledge base id.
+
+ Returns:
+ `KnowledgeBaseRecord | None`:
+ The record, or ``None`` if not found or not owned by
+ the given user.
+ """
+
+ @abstractmethod
+ async def list_knowledge_bases(
+ self,
+ user_id: str,
+ ) -> list[KnowledgeBaseRecord]:
+ """List all knowledge base records owned by the given user.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+
+ Returns:
+ `list[KnowledgeBaseRecord]`:
+ All knowledge base records belonging to the user.
+ """
+
+ @abstractmethod
+ async def delete_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> bool:
+ """Delete a knowledge base record and remove it from the user index.
+
+ Note: this only removes the metadata record; deletion of the
+ underlying vector store collection is the caller's
+ responsibility (typically the knowledge base manager).
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The id of the record to delete.
+
+ Returns:
+ `bool`:
+ ``True`` if the record existed and was deleted,
+ ``False`` if not found.
+ """
+
+ # ------------------------------------------------------------------
+ # Knowledge document persistence
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def upsert_knowledge_document(
+ self,
+ user_id: str,
+ record: KnowledgeDocumentRecord,
+ ) -> KnowledgeDocumentRecord:
+ """Create or update a knowledge document record.
+
+ Used by the upload endpoint to register a freshly arrived
+ document (``status='pending'``) and by other code paths that
+ need to overwrite the full record. Phase transitions during
+ indexing should go through :meth:`update_knowledge_document_status`
+ instead, which is cheaper and atomic w.r.t. the lease fields.
+
+ Args:
+ user_id (`str`):
+ The owner user id. Must match ``record.user_id``.
+ record (`KnowledgeDocumentRecord`):
+ The fully-populated record to persist.
+
+ Returns:
+ `KnowledgeDocumentRecord`:
+ The stored record (with ``updated_at`` refreshed).
+ """
+
+ @abstractmethod
+ async def get_knowledge_document(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> KnowledgeDocumentRecord | None:
+ """Fetch a single knowledge document record by id.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document id.
+
+ Returns:
+ `KnowledgeDocumentRecord | None`:
+ The record, or ``None`` if not found.
+ """
+
+ @abstractmethod
+ async def list_knowledge_documents(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> list[KnowledgeDocumentRecord]:
+ """List all documents in a knowledge base.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+
+ Returns:
+ `list[KnowledgeDocumentRecord]`:
+ All document records belonging to the knowledge base,
+ in arbitrary order.
+ """
+
+ @abstractmethod
+ async def delete_knowledge_document(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> bool:
+ """Delete a knowledge document record.
+
+ Only removes the metadata record; cleanup of the underlying
+ blob and vector store records is the caller's responsibility.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The id of the record to delete.
+
+ Returns:
+ `bool`:
+ ``True`` if the record existed and was deleted,
+ ``False`` if not found.
+ """
+
+ @abstractmethod
+ async def update_knowledge_document_status(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ status: KnowledgeDocumentStatus,
+ error: str | None = None,
+ chunk_count: int | None = None,
+ ) -> None:
+ """Update only the status-related fields of a document record.
+
+ Used by the indexing worker as it walks the lifecycle
+ transitions (``parsing`` → ``chunking`` → ``indexing`` →
+ ``ready`` / ``error``). Cheaper than a full upsert and avoids
+ races with concurrent lease writes by touching only the status
+ / error / chunk_count fields.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document being updated.
+ status (`KnowledgeDocumentStatus`):
+ The new lifecycle state.
+ error (`str | None`, optional):
+ Failure reason, set when ``status == 'error'``.
+ Ignored otherwise. ``None`` leaves the existing
+ value unchanged.
+ chunk_count (`int | None`, optional):
+ The final chunk count, set when ``status == 'ready'``.
+ ``None`` leaves the existing value unchanged.
+ """
+
+ @abstractmethod
+ async def acquire_knowledge_document_lease(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ processing_node: str,
+ lease_ttl: timedelta,
+ now: datetime | None = None,
+ ) -> bool:
+ """Compare-and-swap acquisition of the document processing lease.
+
+ Succeeds only if no other worker currently holds a live lease —
+ i.e. ``processing_node`` is unset or ``lease_expires_at`` is in
+ the past relative to ``now``. On success the record's
+ ``processing_node`` and ``data.lease_expires_at`` fields are
+ updated. The CAS is what makes the sweeper safe to run on
+ multiple nodes at once: even if two sweepers redispatch the
+ same document, only one worker can acquire its lease.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document whose lease is being acquired.
+ processing_node (`str`):
+ Stable identifier of the calling worker (e.g.
+ ``hostname:pid:uuid``). Persisted as
+ ``processing_node`` on success.
+ lease_ttl (`timedelta`):
+ How long the lease should live from ``now``.
+ now (`datetime | None`, optional):
+ Reference time for the comparison. Defaults to
+ ``datetime.now()``. Injectable for testing.
+
+ Returns:
+ `bool`:
+ ``True`` when the lease was acquired by this caller,
+ ``False`` when another worker already holds it.
+ """
+
+ @abstractmethod
+ async def renew_knowledge_document_lease(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ processing_node: str,
+ lease_ttl: timedelta,
+ now: datetime | None = None,
+ ) -> bool:
+ """Extend an existing lease this worker already holds.
+
+ Required for long-running parses that exceed ``lease_ttl`` —
+ the worker calls this periodically so the sweeper does not
+ mistake it for a crash. Updates ``lease_expires_at`` to
+ ``now + lease_ttl`` only when ``processing_node`` matches the
+ caller; otherwise returns ``False`` so the worker can abandon
+ cleanly (its lease was stolen).
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document being renewed.
+ processing_node (`str`):
+ The caller's processing node id; must match the
+ record's current ``processing_node`` for renewal to
+ succeed.
+ lease_ttl (`timedelta`):
+ The new lease duration relative to ``now``.
+ now (`datetime | None`, optional):
+ Reference time. Defaults to ``datetime.now()``.
+
+ Returns:
+ `bool`:
+ ``True`` when the renewal succeeded, ``False`` when
+ the lease no longer belongs to the caller.
+ """
+
+ @abstractmethod
+ async def release_knowledge_document_lease(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ processing_node: str,
+ ) -> None:
+ """Release the processing lease this worker holds.
+
+ Clears ``processing_node`` and ``data.lease_expires_at`` only
+ if the current holder matches ``processing_node`` — a stolen
+ lease (e.g. after sweep) is left untouched. Idempotent: a
+ no-op when the document is missing or already free.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document whose lease is being released.
+ processing_node (`str`):
+ The caller's processing node id; must match the
+ record's current holder.
+ """
+
+ @abstractmethod
+ async def list_knowledge_documents_with_expired_lease(
+ self,
+ now: datetime | None = None,
+ ) -> list[KnowledgeDocumentRecord]:
+ """Return non-terminal documents whose lease has expired.
+
+ Scans every user / knowledge base — used by the sweeper, not
+ by user-facing endpoints. A document is "expired" when
+ ``data.status`` is not terminal (``ready`` / ``error``),
+ ``processing_node`` is set, and ``data.lease_expires_at`` is
+ in the past. Implementations are free to skip records that
+ match no work and return an unspecified order.
+
+ Args:
+ now (`datetime | None`, optional):
+ Reference time. Defaults to ``datetime.now()``.
+
+ Returns:
+ `list[KnowledgeDocumentRecord]`:
+ Documents to redispatch.
+ """
+
+ @abstractmethod
+ async def list_knowledge_documents_pending_since(
+ self,
+ threshold: datetime,
+ ) -> list[KnowledgeDocumentRecord]:
+ """Return documents stuck in ``pending`` older than ``threshold``.
+
+ Catches the corner case where the upload endpoint persisted a
+ record but the dispatcher (or the process holding it) died
+ before any worker picked the document up — a crashed lease
+ sweep would miss it because no lease was ever written.
+
+ Args:
+ threshold (`datetime`):
+ Cut-off creation time; only ``pending`` records
+ ``created_at < threshold`` are returned.
+
+ Returns:
+ `list[KnowledgeDocumentRecord]`:
+ Orphan ``pending`` documents to redispatch.
+ """
diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.py
index b68673f6d..3cbc86a2d 100644
--- a/src/agentscope/app/storage/_model/__init__.py
+++ b/src/agentscope/app/storage/_model/__init__.py
@@ -3,10 +3,17 @@
from ._agent import AgentRecord, AgentData
from ._credential import CredentialRecord
+from ._knowledge_base import KnowledgeBaseRecord
+from ._knowledge_document import (
+ KnowledgeDocumentData,
+ KnowledgeDocumentRecord,
+ KnowledgeDocumentStatus,
+)
from ._schedule import ScheduleData, ScheduleRecord, ScheduleSource
from ._session import (
SessionRecord,
SessionConfig,
+ SessionKnowledgeConfig,
ChatModelConfig,
TTSModelConfig,
EmbeddingModelConfig,
@@ -19,10 +26,15 @@ __all__ = [
"AgentData",
"AgentRecord",
"CredentialRecord",
+ "KnowledgeBaseRecord",
+ "KnowledgeDocumentData",
+ "KnowledgeDocumentRecord",
+ "KnowledgeDocumentStatus",
"ScheduleData",
"ScheduleRecord",
"ScheduleSource",
"SessionConfig",
+ "SessionKnowledgeConfig",
"SessionRecord",
"SessionSource",
"ChatModelConfig",
diff --git a/src/agentscope/app/storage/_model/_knowledge_base.py b/src/agentscope/app/storage/_model/_knowledge_base.py
new file mode 100644
index 000000000..cdeba3fba
--- /dev/null
+++ b/src/agentscope/app/storage/_model/_knowledge_base.py
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+"""The knowledge base record."""
+from pydantic import Field
+
+from ._base import _RecordBase
+from ._session import EmbeddingModelConfig
+
+
+class KnowledgeBaseRecord(_RecordBase):
+ """A persisted knowledge base record.
+
+ Stores per-user metadata for a knowledge base; the actual chunks
+ and vectors live in the configured ``VectorStoreBase`` backend.
+ Each record is the canonical authorisation gate: HTTP handlers and
+ middleware look the record up by ``(user_id, id)`` before talking
+ to the vector store.
+ """
+
+ user_id: str = Field(description="The owner user id.")
+ """The user id that owns this knowledge base."""
+
+ name: str = Field(description="Display name of the knowledge base.")
+ """Display name shown in the UI."""
+
+ description: str = Field(
+ default="",
+ description="Free-form description of the knowledge base purpose.",
+ )
+ """Free-form description shown in the UI."""
+
+ embedding_model_config: EmbeddingModelConfig = Field(
+ description=(
+ "Embedding model configuration pinned at creation time. "
+ "Cannot change for the lifetime of the record because the "
+ "underlying collection is sized to its dimension."
+ ),
+ )
+ """Embedding model configuration pinned at creation time."""
+
+ collection_name: str = Field(
+ description=(
+ "The vector store collection that physically backs this "
+ "knowledge base. Generated server-side; opaque to clients."
+ ),
+ )
+ """The vector store collection name (e.g. ``kb_<uuid_hex>``)."""
diff --git a/src/agentscope/app/storage/_model/_knowledge_document.py b/src/agentscope/app/storage/_model/_knowledge_document.py
new file mode 100644
index 000000000..f3c7b9fb1
--- /dev/null
+++ b/src/agentscope/app/storage/_model/_knowledge_document.py
@@ -0,0 +1,139 @@
+# -*- coding: utf-8 -*-
+"""The knowledge document record.
+
+A :class:`KnowledgeDocumentRecord` is the canonical source of truth
+for one uploaded file inside a knowledge base. It owns the document's
+**lifecycle** (status, error, lease) and **byte handle** (``blob_uri``)
+before any chunks reach the vector store, which is exactly the state
+the vector store cannot represent on its own (no chunks means no
+``document_id`` to aggregate from).
+
+Top-level fields are the relational keys (``user_id`` /
+``knowledge_base_id`` / ``processing_node``) that the storage backend
+indexes on; everything else lives inside ``data`` per the project
+record convention.
+"""
+from datetime import datetime
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from ._base import _RecordBase
+
+
+KnowledgeDocumentStatus = Literal[
+ "pending",
+ "parsing",
+ "chunking",
+ "indexing",
+ "ready",
+ "error",
+]
+# The six lifecycle states of a knowledge document.
+#
+# ``pending`` — bytes are in the blob store, waiting for a worker to
+# pick the document up. ``parsing`` / ``chunking`` / ``indexing`` are
+# worker-owned transitions; ``ready`` and ``error`` are terminal.
+
+
+class KnowledgeDocumentData(BaseModel):
+ """The mutable payload of a knowledge document record."""
+
+ filename: str = Field(
+ description="Original filename supplied by the uploader.",
+ )
+ """The original filename — used both for citation and as the
+ ``source`` field on every chunk produced from this document."""
+
+ size: int = Field(
+ ge=0,
+ description="Document size in bytes as observed at upload time.",
+ )
+ """Byte length recorded at upload time. Used by quota checks and
+ the UI; not authoritative for parsing (the worker reopens the
+ blob)."""
+
+ content_type: str | None = Field(
+ default=None,
+ description="IANA media type used to route the upload to a parser.",
+ )
+ """IANA media type. ``None`` lets the worker fall back to
+ ``mimetypes.guess_type(filename)``."""
+
+ blob_uri: str = Field(
+ description=(
+ "URI returned by the blob store after the upload was "
+ "streamed in (e.g. ``local://kb/.../uuid``)."
+ ),
+ )
+ """Scheme-qualified URI handed back by
+ :class:`~agentscope.app.rag.blob_store.BlobStoreBase`. The worker
+ streams bytes back through the same blob store."""
+
+ status: KnowledgeDocumentStatus = Field(
+ default="pending",
+ description="Current lifecycle state.",
+ )
+ """Current lifecycle state. Read by the polling endpoint, written
+ by the worker as it transitions phases."""
+
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Human-readable failure reason when ``status == 'error'``. "
+ "MUST NOT include stack traces or filesystem paths — it is "
+ "rendered verbatim in the UI."
+ ),
+ )
+ """Human-readable failure reason. Surfaced directly to the user;
+ keep it short and free of sensitive content."""
+
+ chunk_count: int = Field(
+ default=0,
+ ge=0,
+ description="Number of chunks successfully indexed.",
+ )
+ """The final chunk count, written by the worker when the document
+ reaches ``ready``."""
+
+ lease_expires_at: datetime | None = Field(
+ default=None,
+ description=(
+ "Wall-clock deadline for the worker that currently holds "
+ "this document. ``None`` if no worker is processing it."
+ ),
+ )
+ """Lease deadline. Together with ``processing_node`` lets the
+ sweeper detect crashed workers and reassign their documents."""
+
+
+class KnowledgeDocumentRecord(_RecordBase):
+ """A persisted knowledge document record.
+
+ Top-level fields are relational keys the storage backend needs to
+ index on directly (per-user listing, per-KB listing, per-node lease
+ sweeps); the mutable payload lives in :attr:`data`.
+ """
+
+ user_id: str = Field(description="The owner user id.")
+ """The user id that owns the parent knowledge base."""
+
+ knowledge_base_id: str = Field(
+ description="The id of the knowledge base this document belongs to.",
+ )
+ """The knowledge base the document is being indexed into."""
+
+ processing_node: str | None = Field(
+ default=None,
+ description=(
+ "Identifier of the worker process that currently holds the "
+ "lease on this document. ``None`` if no worker is "
+ "processing it."
+ ),
+ )
+ """The current lease holder. Promoted to the top level so the
+ storage backend can look up "documents owned by node X" or
+ "documents with no owner" without deserialising every payload."""
+
+ data: KnowledgeDocumentData
+ """The mutable document payload."""
diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.py
index a43c0a181..bf83b9991 100644
--- a/src/agentscope/app/storage/_model/_session.py
+++ b/src/agentscope/app/storage/_model/_session.py
@@ -66,8 +66,48 @@ class EmbeddingModelConfig(BaseModel):
model: str
"""The embedding model name (e.g. ``"text-embedding-3-small"``)."""
- parameters: dict
- """The embedding model parameters (e.g. ``{"dimensions": 1024}``)."""
+ dimensions: int = Field(..., gt=0)
+ """The output embedding vector dimensions.
+
+ Required and first-class — chosen at config-creation time and
+ pinned to the resulting :class:`KnowledgeBaseRecord` so subsequent
+ indexing / retrieval calls are dim-deterministic without any
+ fallback lookup.
+ """
+
+ parameters: dict = Field(default_factory=dict)
+ """The provider-specific non-dimensional parameters.
+
+ Does **not** carry ``dimensions`` — that field is promoted to a
+ top-level attribute above.
+ """
+
+
+class SessionKnowledgeConfig(BaseModel):
+ """Session-level knowledge base attachment.
+
+ Persists which knowledge bases the agent should retrieve from for
+ this session and how the
+ :class:`~agentscope.middleware.RAGMiddleware` should be
+ configured. ``parameters`` carries the user-tunable middleware
+ fields verbatim (mirrors :attr:`ChatModelConfig.parameters`); the
+ accepted keys and value types are described by
+ :meth:`RAGMiddleware.Config.model_json_schema`.
+ """
+
+ knowledge_base_ids: list[str] = Field(default_factory=list)
+ """Ids of the knowledge bases attached to this session.
+
+ Empty list means no knowledge base is wired and the middleware is
+ not installed.
+ """
+
+ parameters: dict = Field(default_factory=dict)
+ """Middleware parameters keyed by ``RAGMiddleware``'s
+ :class:`Config` model fields (``mode``, ``top_k``,
+ ``score_threshold``, ``emit_hint_event``, ``persist_hint``,
+ ``hint_template``).
+ """
class SessionConfig(BaseModel):
@@ -92,6 +132,11 @@ class SessionConfig(BaseModel):
tts_model_config: TTSModelConfig | None = None
"""The TTS model config. None means TTS is not enabled."""
+ knowledge_config: SessionKnowledgeConfig | None = None
+ """Knowledge bases attached to this session and the corresponding
+ :class:`~agentscope.middleware.RAGMiddleware` parameters.
+ ``None`` means no knowledge base is wired."""
+
class SessionRecord(_RecordBase):
"""The session record."""
diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.py
index c45e4f924..57a31e308 100644
--- a/src/agentscope/app/storage/_redis_storage.py
+++ b/src/agentscope/app/storage/_redis_storage.py
@@ -2,7 +2,7 @@
# pylint: disable=too-many-public-methods
"""The Redis storage implementation."""
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any, TYPE_CHECKING, Self
from pydantic import BaseModel
@@ -11,6 +11,9 @@ from ._base import StorageBase
from ._model import (
AgentRecord,
CredentialRecord,
+ KnowledgeBaseRecord,
+ KnowledgeDocumentRecord,
+ KnowledgeDocumentStatus,
ScheduleRecord,
SessionRecord,
SessionConfig,
@@ -29,6 +32,17 @@ else:
Redis = Any
+def _watch_error() -> type[BaseException]:
+ """Return the ``WatchError`` class from ``redis.exceptions``.
+
+ Lazy-imported so ``redis`` stays an optional dependency at module
+ load time — same trick the storage class uses in ``__aenter__``.
+ """
+ from redis.exceptions import WatchError
+
+ return WatchError
+
+
class RedisStorage(StorageBase):
"""The Redis storage implementation."""
@@ -74,6 +88,25 @@ class RedisStorage(StorageBase):
team: str = "agentscope:user:{user_id}:team:{team_id}"
team_index: str = "agentscope:user:{user_id}:teams"
+ knowledge_base: str = (
+ "agentscope:user:{user_id}:knowledge_base:{knowledge_base_id}"
+ )
+ knowledge_base_index: str = "agentscope:user:{user_id}:knowledge_bases"
+
+ # Knowledge document keys
+ knowledge_document: str = (
+ "agentscope:user:{user_id}"
+ ":knowledge_base:{knowledge_base_id}"
+ ":document:{document_id}"
+ )
+ knowledge_document_index: str = (
+ "agentscope:user:{user_id}"
+ ":knowledge_base:{knowledge_base_id}:documents"
+ )
+ # Global index of every document key as ``user_id:kb_id:doc_id``;
+ # used by the lease sweeper, never by per-user listing.
+ knowledge_document_global_index: str = "agentscope:knowledge_documents"
+
def __init__(
self,
host: str = "localhost",
@@ -1145,3 +1178,555 @@ class RedisStorage(StorageBase):
index_key = self._key(self.key_config.team_index, user_id=user_id)
await self._client.srem(index_key, team_id)
return bool(existed)
+
+ # ------------------------------------------------------------------
+ # Knowledge base persistence
+ # ------------------------------------------------------------------
+
+ async def upsert_knowledge_base(
+ self,
+ user_id: str,
+ record: KnowledgeBaseRecord,
+ ) -> KnowledgeBaseRecord:
+ """Persist a knowledge base record and register it in the user index.
+
+ If a record with the same ``id`` already exists it is overwritten
+ and ``updated_at`` is refreshed; ``created_at`` is preserved.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ record (`KnowledgeBaseRecord`):
+ The fully-populated record to store.
+
+ Returns:
+ `KnowledgeBaseRecord`:
+ The stored record (with ``updated_at`` refreshed).
+ """
+ if record.user_id != user_id:
+ raise ValueError(
+ "record.user_id does not match the given user_id.",
+ )
+
+ key = self._key(
+ self.key_config.knowledge_base,
+ user_id=user_id,
+ knowledge_base_id=record.id,
+ )
+ existing_raw = await self._client.get(key)
+ if existing_raw:
+ existing = KnowledgeBaseRecord.model_validate_json(existing_raw)
+ record.created_at = existing.created_at
+ record.updated_at = datetime.now()
+
+ index_key = self._key(
+ self.key_config.knowledge_base_index,
+ user_id=user_id,
+ )
+ await self._set_with_ttl(key, record.model_dump_json())
+ await self._client.sadd(index_key, record.id)
+ return record
+
+ async def get_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> KnowledgeBaseRecord | None:
+ """Fetch a single knowledge base record by id.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The knowledge base id.
+
+ Returns:
+ `KnowledgeBaseRecord | None`:
+ The record, or ``None`` if not found.
+ """
+ key = self._key(
+ self.key_config.knowledge_base,
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ )
+ raw = await self._client.get(key)
+ return KnowledgeBaseRecord.model_validate_json(raw) if raw else None
+
+ async def list_knowledge_bases(
+ self,
+ user_id: str,
+ ) -> list[KnowledgeBaseRecord]:
+ """List all knowledge base records belonging to the given user.
+
+ Reads the per-user knowledge base index Set to obtain all ids,
+ then fetches each record individually. Records whose keys have
+ expired or been deleted externally are silently skipped.
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+
+ Returns:
+ `list[KnowledgeBaseRecord]`:
+ All knowledge base records for the user.
+ """
+ index_key = self._key(
+ self.key_config.knowledge_base_index,
+ user_id=user_id,
+ )
+ ids = await self._client.smembers(index_key)
+ records: list[KnowledgeBaseRecord] = []
+ for kb_id in ids:
+ raw = await self._client.get(
+ self._key(
+ self.key_config.knowledge_base,
+ user_id=user_id,
+ knowledge_base_id=kb_id,
+ ),
+ )
+ if raw:
+ records.append(
+ KnowledgeBaseRecord.model_validate_json(raw),
+ )
+ return records
+
+ async def delete_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> bool:
+ """Delete a knowledge base record and remove it from the index.
+
+ Cascades the per-knowledge-base document index: every
+ :class:`KnowledgeDocumentRecord` indexed under the KB is
+ removed from storage so no orphan documents survive the KB
+ deletion. Cleanup of the underlying vector store collection
+ and blob payloads remains the caller's responsibility (the
+ manager + the blob store, respectively).
+
+ Args:
+ user_id (`str`):
+ The owner user id.
+ knowledge_base_id (`str`):
+ The id of the record to delete.
+
+ Returns:
+ `bool`:
+ ``True`` if the record existed and was deleted,
+ ``False`` if not found.
+ """
+ # Cascade: drop every document record so the sweeper does not
+ # later try to redispatch leases for a KB that no longer exists.
+ documents = await self.list_knowledge_documents(
+ user_id,
+ knowledge_base_id,
+ )
+ for document in documents:
+ await self.delete_knowledge_document(
+ user_id,
+ knowledge_base_id,
+ document.id,
+ )
+
+ key = self._key(
+ self.key_config.knowledge_base,
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ )
+ index_key = self._key(
+ self.key_config.knowledge_base_index,
+ user_id=user_id,
+ )
+ deleted = await self._client.delete(key)
+ await self._client.srem(index_key, knowledge_base_id)
+ return deleted > 0
+
+ # ------------------------------------------------------------------
+ # Knowledge document persistence
+ # ------------------------------------------------------------------
+
+ def _document_key(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> str:
+ """Format the Redis key for one document record."""
+ return self._key(
+ self.key_config.knowledge_document,
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ document_id=document_id,
+ )
+
+ def _document_index_key(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> str:
+ """Format the per-KB document index Set key."""
+ return self._key(
+ self.key_config.knowledge_document_index,
+ user_id=user_id,
+ knowledge_base_id=knowledge_base_id,
+ )
+
+ def _document_global_token(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> str:
+ """Encode (user_id, kb_id, doc_id) for the global sweeper index."""
+ return f"{user_id}:{knowledge_base_id}:{document_id}"
+
+ async def upsert_knowledge_document(
+ self,
+ user_id: str,
+ record: KnowledgeDocumentRecord,
+ ) -> KnowledgeDocumentRecord:
+ """Persist a document record and update its indexes.
+
+ If a record with the same ``id`` already exists it is
+ overwritten and ``updated_at`` refreshed; ``created_at`` is
+ preserved.
+
+ Args:
+ user_id (`str`):
+ The owner user id. Must match ``record.user_id``.
+ record (`KnowledgeDocumentRecord`):
+ The fully-populated record to persist.
+
+ Returns:
+ `KnowledgeDocumentRecord`:
+ The stored record (with ``updated_at`` refreshed).
+ """
+ if record.user_id != user_id:
+ raise ValueError(
+ "record.user_id does not match the given user_id.",
+ )
+
+ key = self._document_key(
+ user_id,
+ record.knowledge_base_id,
+ record.id,
+ )
+ existing_raw = await self._client.get(key)
+ if existing_raw:
+ existing = KnowledgeDocumentRecord.model_validate_json(
+ existing_raw,
+ )
+ record.created_at = existing.created_at
+ record.updated_at = datetime.now()
+
+ await self._set_with_ttl(key, record.model_dump_json())
+ await self._client.sadd(
+ self._document_index_key(user_id, record.knowledge_base_id),
+ record.id,
+ )
+ await self._client.sadd(
+ self.key_config.knowledge_document_global_index,
+ self._document_global_token(
+ user_id,
+ record.knowledge_base_id,
+ record.id,
+ ),
+ )
+ return record
+
+ async def get_knowledge_document(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> KnowledgeDocumentRecord | None:
+ """Fetch a single knowledge document record by id."""
+ raw = await self._client.get(
+ self._document_key(user_id, knowledge_base_id, document_id),
+ )
+ return (
+ KnowledgeDocumentRecord.model_validate_json(raw) if raw else None
+ )
+
+ async def list_knowledge_documents(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> list[KnowledgeDocumentRecord]:
+ """List all documents in a knowledge base.
+
+ Reads the per-KB document index Set and fetches each record.
+ Records whose keys have expired or been deleted externally are
+ silently skipped.
+ """
+ ids = await self._client.smembers(
+ self._document_index_key(user_id, knowledge_base_id),
+ )
+ records: list[KnowledgeDocumentRecord] = []
+ for document_id in ids:
+ raw = await self._client.get(
+ self._document_key(user_id, knowledge_base_id, document_id),
+ )
+ if raw:
+ records.append(
+ KnowledgeDocumentRecord.model_validate_json(raw),
+ )
+ return records
+
+ async def delete_knowledge_document(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> bool:
+ """Delete a document record and remove it from the indexes."""
+ key = self._document_key(user_id, knowledge_base_id, document_id)
+ deleted = await self._client.delete(key)
+ await self._client.srem(
+ self._document_index_key(user_id, knowledge_base_id),
+ document_id,
+ )
+ await self._client.srem(
+ self.key_config.knowledge_document_global_index,
+ self._document_global_token(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ ),
+ )
+ return deleted > 0
+
+ async def update_knowledge_document_status(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ status: KnowledgeDocumentStatus,
+ error: str | None = None,
+ chunk_count: int | None = None,
+ ) -> None:
+ """Update only the status-related fields of a document record.
+
+ Reads the record, mutates the status fields in memory, and
+ writes it back. Not atomic across multiple writers — relies
+ on the indexing worker holding the lease, which serialises
+ status transitions for a single document.
+ """
+ key = self._document_key(user_id, knowledge_base_id, document_id)
+ raw = await self._client.get(key)
+ if not raw:
+ return
+ record = KnowledgeDocumentRecord.model_validate_json(raw)
+ record.data.status = status
+ if error is not None:
+ record.data.error = error
+ if chunk_count is not None:
+ record.data.chunk_count = chunk_count
+ record.updated_at = datetime.now()
+ await self._set_with_ttl(key, record.model_dump_json())
+
+ async def acquire_knowledge_document_lease(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ processing_node: str,
+ lease_ttl: timedelta,
+ now: datetime | None = None,
+ ) -> bool:
+ """Compare-and-swap acquisition of the processing lease.
+
+ Implementation is a read-modify-write under a per-document
+ ``WATCH`` so two workers racing on the same document cannot
+ both win. Redis ``WATCH`` aborts the transaction if the key
+ changes between WATCH and EXEC; we retry a few times on
+ ``WatchError`` and otherwise give up (treating the contention
+ as "someone else already holds the lease").
+ """
+ now = now or datetime.now()
+ new_deadline = now + lease_ttl
+
+ async with self._client.pipeline(transaction=True) as pipe:
+ for _ in range(3):
+ try:
+ key = self._document_key(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+ await pipe.watch(key)
+ raw = await pipe.get(key)
+ if not raw:
+ await pipe.unwatch()
+ return False
+ record = KnowledgeDocumentRecord.model_validate_json(raw)
+ holder = record.processing_node
+ deadline = record.data.lease_expires_at
+ if (
+ holder is not None
+ and deadline is not None
+ and deadline > now
+ ):
+ await pipe.unwatch()
+ return False
+ record.processing_node = processing_node
+ record.data.lease_expires_at = new_deadline
+ record.updated_at = now
+ pipe.multi()
+ pipe.set(key, record.model_dump_json())
+ if self.key_ttl is not None:
+ pipe.expire(key, self.key_ttl)
+ await pipe.execute()
+ return True
+ except _watch_error():
+ # Another writer touched the key between WATCH and
+ # EXEC; loop and re-read.
+ continue
+ return False
+
+ async def renew_knowledge_document_lease(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ processing_node: str,
+ lease_ttl: timedelta,
+ now: datetime | None = None,
+ ) -> bool:
+ """Extend the lease this worker already holds."""
+ now = now or datetime.now()
+ new_deadline = now + lease_ttl
+
+ async with self._client.pipeline(transaction=True) as pipe:
+ for _ in range(3):
+ try:
+ key = self._document_key(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+ await pipe.watch(key)
+ raw = await pipe.get(key)
+ if not raw:
+ await pipe.unwatch()
+ return False
+ record = KnowledgeDocumentRecord.model_validate_json(raw)
+ if record.processing_node != processing_node:
+ await pipe.unwatch()
+ return False
+ record.data.lease_expires_at = new_deadline
+ record.updated_at = now
+ pipe.multi()
+ pipe.set(key, record.model_dump_json())
+ if self.key_ttl is not None:
+ pipe.expire(key, self.key_ttl)
+ await pipe.execute()
+ return True
+ except _watch_error():
+ continue
+ return False
+
+ async def release_knowledge_document_lease(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ processing_node: str,
+ ) -> None:
+ """Release the lease only if this worker still owns it."""
+ async with self._client.pipeline(transaction=True) as pipe:
+ for _ in range(3):
+ try:
+ key = self._document_key(
+ user_id,
+ knowledge_base_id,
+ document_id,
+ )
+ await pipe.watch(key)
+ raw = await pipe.get(key)
+ if not raw:
+ await pipe.unwatch()
+ return
+ record = KnowledgeDocumentRecord.model_validate_json(raw)
+ if record.processing_node != processing_node:
+ await pipe.unwatch()
+ return
+ record.processing_node = None
+ record.data.lease_expires_at = None
+ record.updated_at = datetime.now()
+ pipe.multi()
+ pipe.set(key, record.model_dump_json())
+ if self.key_ttl is not None:
+ pipe.expire(key, self.key_ttl)
+ await pipe.execute()
+ return
+ except _watch_error():
+ continue
+
+ async def list_knowledge_documents_with_expired_lease(
+ self,
+ now: datetime | None = None,
+ ) -> list[KnowledgeDocumentRecord]:
+ """Return non-terminal documents whose lease has expired.
+
+ Reads the global document index and filters in-memory — there
+ is no Redis-side filter primitive that knows about our nested
+ ``data.lease_expires_at`` field. For production deployments
+ with very large document counts a secondary index would pay
+ off, but for the v1 workload the global scan is acceptable
+ because the sweep runs on a slow cadence (minutes) and only
+ cares about the small subset of non-terminal documents.
+ """
+ now = now or datetime.now()
+ terminal = {"ready", "error"}
+ tokens = await self._client.smembers(
+ self.key_config.knowledge_document_global_index,
+ )
+ records: list[KnowledgeDocumentRecord] = []
+ for token in tokens:
+ try:
+ user_id, kb_id, document_id = token.split(":", 2)
+ except ValueError:
+ continue
+ raw = await self._client.get(
+ self._document_key(user_id, kb_id, document_id),
+ )
+ if not raw:
+ continue
+ record = KnowledgeDocumentRecord.model_validate_json(raw)
+ if record.data.status in terminal:
+ continue
+ if record.processing_node is None:
+ continue
+ if (
+ record.data.lease_expires_at is not None
+ and record.data.lease_expires_at < now
+ ):
+ records.append(record)
+ return records
+
+ async def list_knowledge_documents_pending_since(
+ self,
+ threshold: datetime,
+ ) -> list[KnowledgeDocumentRecord]:
+ """Return documents stuck in ``pending`` since before ``threshold``."""
+ tokens = await self._client.smembers(
+ self.key_config.knowledge_document_global_index,
+ )
+ records: list[KnowledgeDocumentRecord] = []
+ for token in tokens:
+ try:
+ user_id, kb_id, document_id = token.split(":", 2)
+ except ValueError:
+ continue
+ raw = await self._client.get(
+ self._document_key(user_id, kb_id, document_id),
+ )
+ if not raw:
+ continue
+ record = KnowledgeDocumentRecord.model_validate_json(raw)
+ if record.data.status != "pending":
+ continue
+ if record.created_at < threshold:
+ records.append(record)
+ return records
diff --git a/src/agentscope/embedding/_dashscope/_model.py b/src/agentscope/embedding/_dashscope/_model.py
index cd31edeca..81f1b0892 100644
--- a/src/agentscope/embedding/_dashscope/_model.py
+++ b/src/agentscope/embedding/_dashscope/_model.py
@@ -3,10 +3,15 @@
Handles both text-only and multimodal models under a single class.
Text models (``text-embedding-v3``, ``text-embedding-v4``) accept
-``list[str]``. Multimodal models (``qwen*-vl-embedding``,
+``list[str | TextBlock]``. Multimodal models (``qwen*-vl-embedding``,
``multimodal-embedding-*``, ``tongyi-embedding-vision-*``)
additionally accept :class:`~agentscope.message.DataBlock`.
The model name determines which DashScope API endpoint is used.
+
+Text payloads may be passed either as bare ``str`` or as
+:class:`~agentscope.message.TextBlock` — the latter is unpacked to its
+``.text`` field on entry so the rest of the pipeline only deals with
+``str`` and ``DataBlock``.
"""
from __future__ import annotations
@@ -21,7 +26,7 @@ from .._embedding_usage import EmbeddingUsage
from .._embedding_base import EmbeddingModelBase
from ..._logging import logger
from ...credential import CredentialBase
-from ...message import DataBlock, Base64Source, URLSource
+from ...message import DataBlock, Base64Source, TextBlock, URLSource
#: Model name prefixes that route to the multimodal API.
_MULTIMODAL_PREFIXES = (
@@ -83,7 +88,7 @@ _DEFAULT_LIMITS = _MultimodalLimits(
)
-class DashScopeEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
+class DashScopeEmbeddingModel(EmbeddingModelBase[str | TextBlock | DataBlock]):
"""Unified DashScope embedding model.
Routes to the text or multimodal DashScope API based on the model
@@ -105,6 +110,7 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
self,
credential: CredentialBase,
model: str,
+ dimensions: int | None,
parameters: "DashScopeEmbeddingModel.Parameters | None" = None,
embedding_cache: EmbeddingCacheBase | None = None,
context_size: int = 8192,
@@ -121,10 +127,16 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
The embedding model name (e.g.
``"text-embedding-v4"`` or
``"qwen3-vl-embedding"``).
+ dimensions (`int | None`):
+ The output embedding vector dimensions. Required at
+ the contract level — see :class:`EmbeddingModelBase`
+ for the rationale. ``None`` is accepted only for
+ backward compatibility with legacy configs that
+ persisted ``dimensions`` inside ``parameters``.
parameters (`DashScopeEmbeddingModel.Parameters | None`, \
defaults to ``None``):
- User-configurable parameters (currently only
- ``dimensions``).
+ Provider-specific non-dimensional parameters. Currently
+ empty for DashScope.
embedding_cache (`EmbeddingCacheBase | None`, defaults to \
``None``):
Optional embedding cache.
@@ -140,6 +152,7 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
super().__init__(
credential=credential,
model=model,
+ dimensions=dimensions,
parameters=parameters,
context_size=context_size,
batch_size=self._TEXT_BATCH_SIZE,
@@ -169,7 +182,7 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
async def __call__(
self,
- inputs: list[str | DataBlock],
+ inputs: list[str | TextBlock | DataBlock],
**kwargs: Any,
) -> EmbeddingResponse:
"""Embed inputs with batching and retry.
@@ -180,26 +193,34 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
total elements, images, and videos per request.
Args:
- inputs (`list[str | DataBlock]`):
- The input data to embed.
+ inputs (`list[str | TextBlock | DataBlock]`):
+ The input data to embed. ``TextBlock`` items are
+ unpacked to their ``.text`` field on entry, so the
+ remainder of the pipeline only sees ``str`` and
+ ``DataBlock``.
**kwargs:
Forwarded to the DashScope API.
Returns:
`EmbeddingResponse`: Merged response for all inputs.
"""
+ normalized: list[str | DataBlock] = [
+ item.text if isinstance(item, TextBlock) else item
+ for item in inputs
+ ]
+
if not self._is_multimodal:
# Text mode — use base class batching.
- return await super().__call__(inputs, **kwargs)
+ return await super().__call__(normalized, **kwargs)
# Multimodal mode — content-aware batching.
- batches = self._split_multimodal_batches(inputs)
+ batches = self._split_multimodal_batches(normalized)
if len(batches) > 1:
logger.info(
"Embedding %d multimodal inputs in %d batches for "
"model %s (limits: elements=%d, images=%d, videos=%d).",
- len(inputs),
+ len(normalized),
len(batches),
self.model,
self._limits.max_elements,
diff --git a/src/agentscope/embedding/_dashscope/_models/multimodal-embedding-v1.yaml b/src/agentscope/embedding/_dashscope/_models/multimodal-embedding-v1.yaml
index b6fe26e47..58cefd68e 100644
--- a/src/agentscope/embedding/_dashscope/_models/multimodal-embedding-v1.yaml
+++ b/src/agentscope/embedding/_dashscope/_models/multimodal-embedding-v1.yaml
@@ -13,7 +13,4 @@ output_types:
context_size: 512
-parameter_overrides:
- dimensions:
- hidden: true
- default: 1024
+dimensions: 1024
diff --git a/src/agentscope/embedding/_dashscope/_models/qwen2.5-vl-embedding.yaml b/src/agentscope/embedding/_dashscope/_models/qwen2.5-vl-embedding.yaml
index 7d6c88de8..b5ebec7a0 100644
--- a/src/agentscope/embedding/_dashscope/_models/qwen2.5-vl-embedding.yaml
+++ b/src/agentscope/embedding/_dashscope/_models/qwen2.5-vl-embedding.yaml
@@ -16,7 +16,5 @@ output_types:
context_size: 32000
-parameter_overrides:
- dimensions:
- default: 1024
- enum: [2048, 1024, 768, 512]
+dimensions: 1024
+supported_dimensions: [2048, 1024, 768, 512]
diff --git a/src/agentscope/embedding/_dashscope/_models/qwen3-vl-embedding.yaml b/src/agentscope/embedding/_dashscope/_models/qwen3-vl-embedding.yaml
index a2ed76053..900c6fb9e 100644
--- a/src/agentscope/embedding/_dashscope/_models/qwen3-vl-embedding.yaml
+++ b/src/agentscope/embedding/_dashscope/_models/qwen3-vl-embedding.yaml
@@ -16,7 +16,5 @@ output_types:
context_size: 32000
-parameter_overrides:
- dimensions:
- default: 2560
- enum: [2560, 2048, 1536, 1024, 768, 512, 256]
+dimensions: 2560
+supported_dimensions: [2560, 2048, 1536, 1024, 768, 512, 256]
diff --git a/src/agentscope/embedding/_dashscope/_models/text-embedding-v3.yaml b/src/agentscope/embedding/_dashscope/_models/text-embedding-v3.yaml
index cc40c19c9..c344d32d6 100644
--- a/src/agentscope/embedding/_dashscope/_models/text-embedding-v3.yaml
+++ b/src/agentscope/embedding/_dashscope/_models/text-embedding-v3.yaml
@@ -10,7 +10,5 @@ output_types:
context_size: 8192
-parameter_overrides:
- dimensions:
- default: 1024
- enum: [1024, 768, 512, 256, 128, 64]
+dimensions: 1024
+supported_dimensions: [1024, 768, 512, 256, 128, 64]
diff --git a/src/agentscope/embedding/_dashscope/_models/text-embedding-v4.yaml b/src/agentscope/embedding/_dashscope/_models/text-embedding-v4.yaml
index f941108f9..11a8fff50 100644
--- a/src/agentscope/embedding/_dashscope/_models/text-embedding-v4.yaml
+++ b/src/agentscope/embedding/_dashscope/_models/text-embedding-v4.yaml
@@ -10,7 +10,5 @@ output_types:
context_size: 8192
-parameter_overrides:
- dimensions:
- default: 1024
- enum: [2048, 1536, 1024, 768, 512, 256, 128, 64]
+dimensions: 1024
+supported_dimensions: [2048, 1536, 1024, 768, 512, 256, 128, 64]
diff --git a/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-flash.yaml b/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-flash.yaml
index 0884e5f56..ec2065556 100644
--- a/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-flash.yaml
+++ b/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-flash.yaml
@@ -17,7 +17,5 @@ output_types:
context_size: 1024
-parameter_overrides:
- dimensions:
- default: 768
- enum: [768, 512, 256, 128, 64]
+dimensions: 768
+supported_dimensions: [768, 512, 256, 128, 64]
diff --git a/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-plus.yaml b/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-plus.yaml
index 06388a073..9fe2ecaea 100644
--- a/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-plus.yaml
+++ b/src/agentscope/embedding/_dashscope/_models/tongyi-embedding-vision-plus.yaml
@@ -17,7 +17,5 @@ output_types:
context_size: 1024
-parameter_overrides:
- dimensions:
- default: 1152
- enum: [1152, 1024, 512, 256, 128, 64]
+dimensions: 1152
+supported_dimensions: [1152, 1024, 512, 256, 128, 64]
diff --git a/src/agentscope/embedding/_embedding_base.py b/src/agentscope/embedding/_embedding_base.py
index 747861e51..966d4819d 100644
--- a/src/agentscope/embedding/_embedding_base.py
+++ b/src/agentscope/embedding/_embedding_base.py
@@ -8,24 +8,27 @@ from abc import abstractmethod
from pathlib import Path
from typing import Any, Generic, TypeVar, Type, Union
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict
from ._embedding_model_card import EmbeddingModelCard
from ._embedding_response import EmbeddingResponse
from ._embedding_usage import EmbeddingUsage
from .._logging import logger
from ..credential import CredentialBase
-from ..message import DataBlock
+from ..message import DataBlock, TextBlock
#: Type variable for embedding input elements.
#:
-#: - Text-only models bind this to ``str``.
-#: - Multimodal models bind this to ``str | DataBlock``.
+#: Bound to the union of all element shapes the framework supports;
+#: each concrete subclass narrows it to its accepted input via
+#: ``class Foo(EmbeddingModelBase[str | TextBlock]): ...`` so callers
+#: get accurate IDE completion and type-checking on ``__call__``.
#:
-#: The IDE resolves the concrete type from each subclass's
-#: ``class Foo(EmbeddingModelBase[str]): ...`` declaration, so
-#: callers get accurate completion and type-checking.
-InputT = TypeVar("InputT", str, Union[str, DataBlock])
+#: ``__call__`` accepts ``TextBlock`` and unpacks it to ``.text``
+#: before invoking :meth:`_call_api`; therefore ``_call_api``'s input
+#: type is intentionally decoupled from :data:`InputT` (it is typed
+#: ``list[Any]`` on the base and narrowed by each subclass).
+InputT = TypeVar("InputT", bound=Union[str, TextBlock, DataBlock])
class EmbeddingModelBase(Generic[InputT]):
@@ -33,8 +36,8 @@ class EmbeddingModelBase(Generic[InputT]):
Generic over :data:`InputT` so that text-only subclasses
(``EmbeddingModelBase[str]``) and multimodal subclasses
- (``EmbeddingModelBase[str | DataBlock]``) expose the correct
- ``inputs`` type to the IDE.
+ (``EmbeddingModelBase[str | TextBlock | DataBlock]``) expose the
+ correct ``inputs`` type to the IDE.
Follows the same pattern as :class:`~agentscope.model.ChatModelBase`:
@@ -49,19 +52,22 @@ class EmbeddingModelBase(Generic[InputT]):
"""
class Parameters(BaseModel):
- """Base parameters for embedding models.
-
- Contains ``dimensions`` — the single parameter that every
- embedding model needs. Subclasses may extend this class to
- add provider-specific parameters.
+ """Provider-specific tunables for embedding models.
+
+ Intentionally empty in the base — ``dimensions`` is a contract
+ property of an embedding model (its output vector size), not a
+ tunable knob, so it lives directly on the instance via the
+ required :paramref:`__init__.dimensions` argument. Subclasses
+ extend this class to expose **non-dimensional** knobs (e.g.
+ Gemini's ``task_type``, Dashscope's ``text_type``).
+
+ ``extra="allow"`` is set so old persisted configs (where
+ ``dimensions`` lived in ``parameters``) keep deserialising
+ without raising; :meth:`EmbeddingModelBase.__init__` extracts
+ it back out for backward compatibility.
"""
- dimensions: int = Field(
- default=512,
- title="Dimensions",
- description="The output embedding vector dimensions.",
- gt=0,
- )
+ model_config = ConfigDict(extra="allow")
credential: CredentialBase
"""The API credential."""
@@ -70,9 +76,11 @@ class EmbeddingModelBase(Generic[InputT]):
"""The embedding model name."""
dimensions: int
- """The dimensions of the embedding vector.
+ """The output embedding vector dimensions.
- Shortcut for ``self.parameters.dimensions``, set during ``__init__``.
+ Set directly from the :paramref:`__init__.dimensions` argument —
+ a required, first-class field rather than something derived from
+ :attr:`parameters`.
"""
context_size: int
@@ -87,10 +95,17 @@ class EmbeddingModelBase(Generic[InputT]):
retry_delay: float
"""Seconds to sleep between retry attempts."""
+ supports_multimodal: bool = False
+ """Whether this model instance accepts :class:`DataBlock` inputs in
+ addition to text. Text-only models keep the default ``False``;
+ multimodal subclasses must set it to ``True`` (per instance when
+ routing depends on the model name)."""
+
def __init__(
self,
credential: CredentialBase,
model: str,
+ dimensions: int | None,
parameters: BaseModel | None,
context_size: int,
batch_size: int,
@@ -104,9 +119,18 @@ class EmbeddingModelBase(Generic[InputT]):
The API credential used for authentication.
model (`str`):
The name of the embedding model.
+ dimensions (`int | None`):
+ The output embedding vector dimensions for this
+ instance. Required and first-class — see the class
+ docstring for the rationale of keeping ``dimensions``
+ outside :class:`Parameters`. For backward compatibility
+ with older configs that stored ``dimensions`` inside
+ :class:`Parameters`, ``None`` is accepted at the
+ signature level and is back-filled from
+ ``parameters.dimensions`` when present.
parameters (`BaseModel | None`):
- Provider-specific parameters (including ``dimensions``).
- When ``None``, the default ``Parameters()`` is used.
+ Provider-specific non-dimensional parameters. When
+ ``None``, the default ``Parameters()`` is used.
context_size (`int`):
Maximum input length (in tokens) per single input item.
batch_size (`int`):
@@ -121,10 +145,37 @@ class EmbeddingModelBase(Generic[InputT]):
retry_delay (`float`):
Seconds to sleep between retry attempts.
"""
+ resolved_parameters = parameters or self.Parameters()
+ # Backward-compat: older session/KB configs persisted
+ # ``dimensions`` inside ``parameters``. Promote it to the
+ # constructor argument when the caller did not pass one
+ # explicitly, then strip it from the parameters object so it
+ # never reaches provider-specific request payloads.
+ param_dump = resolved_parameters.model_dump()
+ legacy_dimensions = param_dump.pop("dimensions", None)
+ if dimensions is None:
+ if legacy_dimensions is None:
+ raise ValueError(
+ "dimensions is required: pass it explicitly to "
+ "EmbeddingModelBase.__init__ or include it in the "
+ "legacy `parameters` mapping.",
+ )
+ dimensions = int(legacy_dimensions)
+ resolved_parameters = type(resolved_parameters)(**param_dump)
+ elif legacy_dimensions is not None:
+ # Both routes set it — explicit constructor wins, strip the
+ # legacy mirror so it can't drift.
+ resolved_parameters = type(resolved_parameters)(**param_dump)
+
+ if dimensions <= 0:
+ raise ValueError(
+ f"dimensions must be a positive integer, got {dimensions}.",
+ )
+
self.credential = credential
self.model = model
- self.parameters = parameters or self.Parameters()
- self.dimensions = self.parameters.dimensions
+ self.dimensions = dimensions
+ self.parameters = resolved_parameters
self.context_size = context_size
self.batch_size = batch_size
self.max_retries = max_retries
@@ -161,7 +212,11 @@ class EmbeddingModelBase(Generic[InputT]):
inputs (`list[InputT]`):
The input data to embed. For text-only models this is
``list[str]``; for multimodal models it is
- ``list[str | DataBlock]``.
+ ``list[str | TextBlock | DataBlock]``. Any
+ :class:`TextBlock` items are transparently unpacked to
+ their ``.text`` field on entry, so subclasses' batching
+ and ``_call_api`` only have to handle ``str`` (and
+ ``DataBlock`` for multimodal variants).
**kwargs:
Additional keyword arguments forwarded to
:meth:`_call_api`.
@@ -176,17 +231,22 @@ class EmbeddingModelBase(Generic[InputT]):
usage=EmbeddingUsage(tokens=0, time=0),
)
+ normalized: list[Any] = [
+ item.text if isinstance(item, TextBlock) else item
+ for item in inputs
+ ]
+
# Split into batches.
batches = [
- inputs[i : i + self.batch_size]
- for i in range(0, len(inputs), self.batch_size)
+ normalized[i : i + self.batch_size]
+ for i in range(0, len(normalized), self.batch_size)
]
if len(batches) > 1:
logger.info(
"Embedding %d inputs in %d batches (batch_size=%d) "
"for model %s.",
- len(inputs),
+ len(normalized),
len(batches),
self.batch_size,
self.model,
@@ -246,14 +306,18 @@ class EmbeddingModelBase(Generic[InputT]):
async def _call_with_retry(
self,
- inputs: list[InputT],
+ inputs: list[Any],
**kwargs: Any,
) -> EmbeddingResponse:
"""Call :meth:`_call_api` with retry logic for a single batch.
Args:
- inputs (`list[InputT]`):
- A single batch of inputs (size ≤ ``batch_size``).
+ inputs (`list[Any]`):
+ A single batch of inputs (size ≤ ``batch_size``), already
+ normalised by :meth:`__call__` (any :class:`TextBlock`
+ items unpacked to their ``.text``). Typed as
+ ``list[Any]`` because the concrete element shape depends
+ on the subclass — see :meth:`_call_api`.
**kwargs:
Forwarded to :meth:`_call_api`.
"""
@@ -299,7 +363,7 @@ class EmbeddingModelBase(Generic[InputT]):
@abstractmethod
async def _call_api(
self,
- inputs: list[InputT],
+ inputs: list[Any],
**kwargs: Any,
) -> EmbeddingResponse:
"""Call the underlying embedding API for a **single batch**.
@@ -308,8 +372,19 @@ class EmbeddingModelBase(Generic[InputT]):
concurrency, and retry logic are handled by :meth:`__call__`
— this method only needs to handle one API call.
+ .. note::
+ The parameter is typed ``list[Any]`` rather than
+ ``list[InputT]`` because :meth:`__call__` unpacks
+ :class:`TextBlock` items to their ``.text`` field *before*
+ dispatching to this method. The element shape this method
+ actually receives is therefore subclass-specific
+ (:data:`InputT` minus :class:`TextBlock`). Subclasses
+ should override with their concrete narrower type, e.g.
+ ``list[str]`` for text-only models or
+ ``list[str | DataBlock]`` for multimodal ones.
+
Args:
- inputs (`list[InputT]`):
+ inputs (`list[Any]`):
A batch of inputs (guaranteed ``len(inputs) <=
self.batch_size``).
**kwargs:
diff --git a/src/agentscope/embedding/_embedding_model_card.py b/src/agentscope/embedding/_embedding_model_card.py
index 7e307bee9..04de52d0d 100644
--- a/src/agentscope/embedding/_embedding_model_card.py
+++ b/src/agentscope/embedding/_embedding_model_card.py
@@ -50,6 +50,34 @@ class EmbeddingModelCard(BaseModel):
)
"""Output types. ``application/x-embedding`` for vector output."""
+ dimensions: int = Field(
+ ...,
+ description="Default output vector dimensions for this model.",
+ gt=0,
+ )
+ """The default output dimensions for this model.
+
+ First-class top-level field — kept outside of
+ :attr:`parameter_schema` so that callers can rely on a strongly
+ typed ``int`` rather than the soft ``parameter_schema['properties']
+ ['dimensions']['default']`` lookup.
+ """
+
+ supported_dimensions: list[int] | None = Field(
+ default=None,
+ description=(
+ "If set, the only dimensions this model can produce. "
+ "``None`` means dimensions are fixed at "
+ ":attr:`dimensions` and cannot be overridden."
+ ),
+ )
+ """Optional set of allowed output dimensions.
+
+ Set for Matryoshka-style models (e.g. OpenAI's
+ ``text-embedding-3-*``) that can be truncated to a smaller size.
+ ``None`` indicates a fixed-dimension model.
+ """
+
context_size: int | None = Field(
default=None,
description="Maximum input length (in tokens) per request.",
@@ -98,6 +126,12 @@ class EmbeddingModelCard(BaseModel):
with open(yaml_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
+ if "dimensions" not in config:
+ raise ValueError(
+ f"Embedding model card {yaml_path!r} is missing the "
+ f"required top-level 'dimensions' field.",
+ )
+
# Build parameter schema from the Parameters class
base_schema = parameter_class.model_json_schema()
properties = copy.deepcopy(base_schema.get("properties", {}))
@@ -137,6 +171,8 @@ class EmbeddingModelCard(BaseModel):
"output_types",
["application/x-embedding"],
),
+ dimensions=config["dimensions"],
+ supported_dimensions=config.get("supported_dimensions"),
context_size=config.get("context_size"),
parameter_schema=final_schema,
parameter_overrides=overrides,
diff --git a/src/agentscope/embedding/_gemini/_model.py b/src/agentscope/embedding/_gemini/_model.py
index 7827dc32a..89cb8a47d 100644
--- a/src/agentscope/embedding/_gemini/_model.py
+++ b/src/agentscope/embedding/_gemini/_model.py
@@ -2,10 +2,15 @@
"""The Google Gemini embedding model.
Handles both text-only and multimodal models under a single class.
-``gemini-embedding-001`` accepts ``list[str]`` only.
+``gemini-embedding-001`` accepts ``list[str | TextBlock]``.
``gemini-embedding-2`` additionally accepts
:class:`~agentscope.message.DataBlock` (images, video, audio, PDF).
The model name determines the API call style.
+
+Text payloads may be passed either as bare ``str`` or as
+:class:`~agentscope.message.TextBlock` — the latter is unpacked to its
+``.text`` field on entry so the rest of the pipeline only deals with
+``str`` and ``DataBlock``.
"""
from __future__ import annotations
@@ -20,7 +25,7 @@ from .._embedding_usage import EmbeddingUsage
from .._embedding_base import EmbeddingModelBase
from ..._logging import logger
from ...credential import CredentialBase
-from ...message import DataBlock
+from ...message import DataBlock, TextBlock
#: Model name prefixes that use the multimodal API path.
_MULTIMODAL_PREFIXES = ("gemini-embedding-2",)
@@ -59,7 +64,7 @@ _MODEL_LIMITS: dict[str, _MultimodalLimits] = {
_DEFAULT_LIMITS = _MultimodalLimits()
-class GeminiEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
+class GeminiEmbeddingModel(EmbeddingModelBase[str | TextBlock | DataBlock]):
"""Unified Google Gemini embedding model.
Routes to the text-only or multimodal Gemini API based on the
@@ -89,6 +94,7 @@ class GeminiEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
self,
credential: CredentialBase,
model: str,
+ dimensions: int | None,
parameters: "GeminiEmbeddingModel.Parameters | None" = None,
embedding_cache: EmbeddingCacheBase | None = None,
context_size: int = 8192,
@@ -105,10 +111,16 @@ class GeminiEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
The embedding model name (e.g.
``"gemini-embedding-001"`` or
``"gemini-embedding-2"``).
+ dimensions (`int | None`):
+ The output embedding vector dimensions. Required at
+ the contract level — see :class:`EmbeddingModelBase`
+ for the rationale. ``None`` is accepted only for
+ backward compatibility with legacy configs that
+ persisted ``dimensions`` inside ``parameters``.
parameters (`GeminiEmbeddingModel.Parameters | None`, \
defaults to ``None``):
- User-configurable parameters (currently only
- ``dimensions``).
+ Provider-specific non-dimensional parameters. Currently
+ empty for Gemini.
embedding_cache (`EmbeddingCacheBase | None`, defaults to \
``None``):
Optional embedding cache.
@@ -127,12 +139,14 @@ class GeminiEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
super().__init__(
credential=credential,
model=model,
+ dimensions=dimensions,
parameters=parameters,
context_size=context_size,
batch_size=self._TEXT_BATCH_SIZE,
max_retries=max_retries,
retry_delay=retry_delay,
)
+ self.supports_multimodal = self._is_multimodal
self.client: genai.Client = genai.Client(
api_key=credential.api_key.get_secret_value(),
@@ -148,7 +162,7 @@ class GeminiEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
async def __call__(
self,
- inputs: list[str | DataBlock],
+ inputs: list[str | TextBlock | DataBlock],
**kwargs: Any,
) -> EmbeddingResponse:
"""Embed inputs with batching and retry.
@@ -158,24 +172,32 @@ class GeminiEmbeddingModel(EmbeddingModelBase[str | DataBlock]):
limits on images, videos, audios, and PDFs.
Args:
- inputs (`list[str | DataBlock]`):
- The input data to embed.
+ inputs (`list[str | TextBlock | DataBlock]`):
+ The input data to embed. ``TextBlock`` items are
+ unpacked to their ``.text`` field on entry, so the
+ remainder of the pipeline only sees ``str`` and
+ ``DataBlock``.
**kwargs:
Forwarded to the Gemini API config.
Returns:
`EmbeddingResponse`: Merged response for all inputs.
"""
+ normalized: list[str | DataBlock] = [
+ item.text if isinstance(item, TextBlock) else item
+ for item in inputs
+ ]
+
if not self._is_multimodal:
- return await super().__call__(inputs, **kwargs)
+ return await super().__call__(normalized, **kwargs)
- batches = self._split_multimodal_batches(inputs)
+ batches = self._split_multimodal_batches(normalized)
if len(batches) > 1:
logger.info(
"Embedding %d multimodal inputs in %d batches "
"for model %s.",
- len(inputs),
+ len(normalized),
len(batches),
self.model,
)
diff --git a/src/agentscope/embedding/_gemini/_models/gemini-embedding-001.yaml b/src/agentscope/embedding/_gemini/_models/gemini-embedding-001.yaml
index 40c44e35f..402ca4616 100644
--- a/src/agentscope/embedding/_gemini/_models/gemini-embedding-001.yaml
+++ b/src/agentscope/embedding/_gemini/_models/gemini-embedding-001.yaml
@@ -10,7 +10,5 @@ output_types:
context_size: 2048
-parameter_overrides:
- dimensions:
- default: 3072
- enum: [3072, 1536, 768, 512, 256, 128]
+dimensions: 3072
+supported_dimensions: [3072, 1536, 768, 512, 256, 128]
diff --git a/src/agentscope/embedding/_gemini/_models/gemini-embedding-2.yaml b/src/agentscope/embedding/_gemini/_models/gemini-embedding-2.yaml
index 47d874e29..17aa3cc7c 100644
--- a/src/agentscope/embedding/_gemini/_models/gemini-embedding-2.yaml
+++ b/src/agentscope/embedding/_gemini/_models/gemini-embedding-2.yaml
@@ -16,7 +16,5 @@ output_types:
context_size: 8192
-parameter_overrides:
- dimensions:
- default: 3072
- enum: [3072, 1536, 768]
+dimensions: 3072
+supported_dimensions: [3072, 1536, 768]
diff --git a/src/agentscope/embedding/_ollama/_model.py b/src/agentscope/embedding/_ollama/_model.py
index 5fce28803..9210ac22c 100644
--- a/src/agentscope/embedding/_ollama/_model.py
+++ b/src/agentscope/embedding/_ollama/_model.py
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
"""The Ollama embedding model."""
-from __future__ import annotations
from datetime import datetime
from typing import Any
@@ -10,14 +9,18 @@ from .._embedding_usage import EmbeddingUsage
from .._cache_base import EmbeddingCacheBase
from .._embedding_base import EmbeddingModelBase
from ...credential import CredentialBase
+from ...message import TextBlock
-class OllamaEmbeddingModel(EmbeddingModelBase[str]):
+class OllamaEmbeddingModel(EmbeddingModelBase[str | TextBlock]):
"""Ollama text embedding model.
Wraps locally-hosted embedding models served by Ollama (e.g.
``nomic-embed-text``, ``mxbai-embed-large``). Inherits batching
- and retry logic from :class:`EmbeddingModelBase`.
+ and retry logic from :class:`EmbeddingModelBase`. ``TextBlock``
+ items in the input list are unpacked to their ``.text`` field by
+ the base class before ``_call_api`` runs, so this subclass only
+ has to handle plain ``str``.
"""
_TEXT_BATCH_SIZE: int = 512
@@ -26,6 +29,7 @@ class OllamaEmbeddingModel(EmbeddingModelBase[str]):
self,
credential: CredentialBase,
model: str,
+ dimensions: int | None,
parameters: "OllamaEmbeddingModel.Parameters | None" = None,
embedding_cache: EmbeddingCacheBase | None = None,
context_size: int = 8192,
@@ -41,10 +45,16 @@ class OllamaEmbeddingModel(EmbeddingModelBase[str]):
model (`str`):
The embedding model name (e.g.
``"nomic-embed-text"``).
+ dimensions (`int | None`):
+ The output embedding vector dimensions. Required at
+ the contract level — see :class:`EmbeddingModelBase`
+ for the rationale. ``None`` is accepted only for
+ backward compatibility with legacy configs that
+ persisted ``dimensions`` inside ``parameters``.
parameters (`OllamaEmbeddingModel.Parameters | None`, \
defaults to ``None``):
- User-configurable parameters (currently only
- ``dimensions``).
+ Provider-specific non-dimensional parameters. Currently
+ empty for Ollama.
embedding_cache (`EmbeddingCacheBase | None`, defaults to \
``None``):
Optional embedding cache.
@@ -58,6 +68,7 @@ class OllamaEmbeddingModel(EmbeddingModelBase[str]):
super().__init__(
credential=credential,
model=model,
+ dimensions=dimensions,
parameters=parameters,
context_size=context_size,
batch_size=self._TEXT_BATCH_SIZE,
diff --git a/src/agentscope/embedding/_openai/_model.py b/src/agentscope/embedding/_openai/_model.py
index defe23e0e..ee3901996 100644
--- a/src/agentscope/embedding/_openai/_model.py
+++ b/src/agentscope/embedding/_openai/_model.py
@@ -10,14 +10,18 @@ from .._embedding_usage import EmbeddingUsage
from .._cache_base import EmbeddingCacheBase
from .._embedding_base import EmbeddingModelBase
from ...credential import CredentialBase
+from ...message import TextBlock
-class OpenAIEmbeddingModel(EmbeddingModelBase[str]):
+class OpenAIEmbeddingModel(EmbeddingModelBase[str | TextBlock]):
"""OpenAI text embedding model.
Supports ``text-embedding-3-small``, ``text-embedding-3-large``,
and other OpenAI-compatible embedding models. Inherits batching
- and retry logic from :class:`EmbeddingModelBase`.
+ and retry logic from :class:`EmbeddingModelBase`. ``TextBlock``
+ items in the input list are unpacked to their ``.text`` field by
+ the base class before ``_call_api`` runs, so this subclass only
+ has to handle plain ``str``.
"""
#: OpenAI does not document an explicit per-request item limit;
@@ -29,6 +33,7 @@ class OpenAIEmbeddingModel(EmbeddingModelBase[str]):
self,
credential: CredentialBase,
model: str,
+ dimensions: int | None,
parameters: "OpenAIEmbeddingModel.Parameters | None" = None,
pass_dimensions: bool = True,
embedding_cache: EmbeddingCacheBase | None = None,
@@ -46,10 +51,16 @@ class OpenAIEmbeddingModel(EmbeddingModelBase[str]):
model (`str`):
The embedding model name (e.g.
``"text-embedding-3-small"``).
+ dimensions (`int | None`):
+ The output embedding vector dimensions. Required at
+ the contract level — see :class:`EmbeddingModelBase`
+ for the rationale. ``None`` is accepted only for
+ backward compatibility with legacy configs that
+ persisted ``dimensions`` inside ``parameters``.
parameters (`OpenAIEmbeddingModel.Parameters | None`, \
defaults to ``None``):
- User-configurable parameters (currently only
- ``dimensions``).
+ Provider-specific non-dimensional parameters. Currently
+ empty for OpenAI.
pass_dimensions (`bool`, defaults to `True`):
Whether to pass the ``dimensions`` parameter to the API.
Some OpenAI-compatible providers do not support it.
@@ -68,6 +79,7 @@ class OpenAIEmbeddingModel(EmbeddingModelBase[str]):
super().__init__(
credential=credential,
model=model,
+ dimensions=dimensions,
parameters=parameters,
context_size=context_size,
batch_size=self._TEXT_BATCH_SIZE,
diff --git a/src/agentscope/embedding/_openai/_models/text-embedding-3-large.yaml b/src/agentscope/embedding/_openai/_models/text-embedding-3-large.yaml
index 448e019e6..6ddfc9eee 100644
--- a/src/agentscope/embedding/_openai/_models/text-embedding-3-large.yaml
+++ b/src/agentscope/embedding/_openai/_models/text-embedding-3-large.yaml
@@ -10,7 +10,5 @@ output_types:
context_size: 8191
-parameter_overrides:
- dimensions:
- default: 3072
- enum: [3072, 1536, 1024, 768, 512, 256]
+dimensions: 3072
+supported_dimensions: [3072, 1536, 1024, 768, 512, 256]
diff --git a/src/agentscope/embedding/_openai/_models/text-embedding-3-small.yaml b/src/agentscope/embedding/_openai/_models/text-embedding-3-small.yaml
index 7f9a307e5..b74c2811c 100644
--- a/src/agentscope/embedding/_openai/_models/text-embedding-3-small.yaml
+++ b/src/agentscope/embedding/_openai/_models/text-embedding-3-small.yaml
@@ -10,7 +10,5 @@ output_types:
context_size: 8191
-parameter_overrides:
- dimensions:
- default: 1536
- enum: [1536, 1024, 768, 512, 256]
+dimensions: 1536
+supported_dimensions: [1536, 1024, 768, 512, 256]
diff --git a/src/agentscope/middleware/__init__.py b/src/agentscope/middleware/__init__.py
index f3c51e568..57edf90eb 100644
--- a/src/agentscope/middleware/__init__.py
+++ b/src/agentscope/middleware/__init__.py
@@ -2,14 +2,16 @@
"""Middleware system for AgentScope agents."""
from ._base import MiddlewareBase
+from ._rag import RAGMiddleware
from ._budget import ReplyBudgetControlMiddleware
from ._longterm_memory import Mem0Middleware
from ._tracing import TracingMiddleware
from ._tts_middleware import TTSMiddleware
__all__ = [
- "Mem0Middleware",
"MiddlewareBase",
+ "Mem0Middleware",
+ "RAGMiddleware",
"TracingMiddleware",
"ReplyBudgetControlMiddleware",
"TTSMiddleware",
diff --git a/src/agentscope/middleware/_rag.py b/src/agentscope/middleware/_rag.py
new file mode 100644
index 000000000..735c481d7
--- /dev/null
+++ b/src/agentscope/middleware/_rag.py
@@ -0,0 +1,765 @@
+# -*- coding: utf-8 -*-
+"""RAG middleware that brings knowledge-base search into the agent loop.
+
+The :class:`RAGMiddleware` wraps one or more
+:class:`~agentscope.rag.KnowledgeBase` runtime handles — each carrying
+its own embedding model, vector store, and (optional) metadata filter —
+so a single agent can search across knowledge bases that were created
+with *different* embedding models.
+
+Two modes are supported, selected via :class:`SearchConfig.mode`:
+
+- ``"agentic"`` — exposes a single ``search_knowledge`` tool via
+ :meth:`RAGMiddleware.list_tools`. The agent decides when (and which
+ knowledge bases) to query. Nothing is injected automatically.
+- ``"static"`` — on the first reasoning step of each reply
+ (``agent.state.cur_iter == 0``) the middleware searches with the
+ fresh user turn as the query and injects the merged results into
+ ``agent.state.context`` as a :class:`~agentscope.message.HintBlock`.
+ Optionally surfaces a
+ :class:`~agentscope.event.HintBlockEvent` so the front-end can
+ display the matched snippets.
+
+User-tunable parameters are declared on :class:`SearchConfig`; the
+JSON Schema served to the front-end is derived from it via
+``model_json_schema()``.
+
+Document indexing (parsing, chunking, embedding, insertion) is *not*
+this middleware's job — it belongs to the caller (or, in the hosted
+service, to the knowledge-base manager) that constructs the
+:class:`KnowledgeBase` instances passed in.
+"""
+import asyncio
+import json
+from copy import deepcopy
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncGenerator,
+ Callable,
+ Literal,
+ Sequence,
+)
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+from pydantic.json_schema import SkipJsonSchema
+
+from ._base import MiddlewareBase
+from .._logging import logger
+from ..event import HintBlockEvent
+from ..message import (
+ DataBlock,
+ HintBlock,
+ Msg,
+ TextBlock,
+ ToolResultState,
+)
+from ..permission import PermissionBehavior, PermissionDecision
+from ..tool import ParamsBase, ToolBase, ToolChunk
+
+if TYPE_CHECKING:
+ from ..agent import Agent
+ from ..rag import KnowledgeBase, VectorSearchResult
+
+
+_DEFAULT_HINT_TEMPLATE = (
+ "<system-reminder>The following content is retrieved from the "
+ "knowledge base(s) and may be helpful for the current "
+ "request:\n<content>{context}</content></system-reminder>"
+)
+# Wrapper around the formatted search results. Must contain a single
+# ``{context}`` placeholder — :func:`_wrap_hint` splits on it.
+
+_HINT_SOURCE = json.dumps({"label": "KnowledgeBase", "sublabel": ""})
+# The ``source`` value stamped on injected hint blocks. Encoded as a
+# JSON string so the front-end can parse a structured label out of it
+# while the field stays a plain ``str`` everywhere else.
+
+
+class _SearchParams(ParamsBase):
+ """The parameters accepted by ``_SearchKnowledgeTool``."""
+
+ query: str = Field(
+ description=(
+ "The query string to search the knowledge base(s) with. "
+ "Must be concise, explicit, and self-contained: AVOID "
+ "ambiguous references like `he`/`she`/`it`, "
+ "`today`/`yesterday`/`tomorrow`, `here`/`there`, etc. — "
+ "the search is purely semantic and has no conversational "
+ "context. Phrase the query as a complete statement of "
+ "what you want to find."
+ ),
+ )
+
+ knowledge_bases: list[str] | None = Field(
+ default=None,
+ description=(
+ "Optional subset of knowledge bases to query, by name. "
+ "When omitted (or `null`) every equipped knowledge base "
+ "is searched. Names must exactly match those listed in "
+ "the tool description."
+ ),
+ )
+
+
+class _SearchKnowledgeTool(ToolBase):
+ """The agentic-mode search tool exposed by :class:`RAGMiddleware`.
+
+ A single tool fans out across every bound knowledge base; the
+ agent may also pass ``knowledge_bases`` to restrict the search to
+ a subset by name.
+ """
+
+ name: str = "search_knowledge"
+ """The tool name presented to the agent."""
+
+ is_read_only: bool = True
+ is_concurrency_safe: bool = True
+ is_external_tool: bool = False
+ is_state_injected: bool = False
+ is_mcp: bool = False
+
+ def __init__(
+ self,
+ knowledge_bases: list["KnowledgeBase"],
+ top_k: int,
+ score_threshold: float | None,
+ ) -> None:
+ """Initialize the search tool.
+
+ Args:
+ knowledge_bases (`list[KnowledgeBase]`):
+ The knowledge bases the agent may query.
+ top_k (`int`):
+ Maximum number of chunks returned per call, after
+ merging across knowledge bases.
+ score_threshold (`float | None`):
+ Minimum similarity score; forwarded unchanged to each
+ :meth:`KnowledgeBase.search` call.
+ """
+ # ``ToolBase`` expects a list of *tool* middlewares; this tool
+ # has none of its own (the owning ``RAGMiddleware`` is an
+ # *agent* middleware, not a tool one).
+ super().__init__()
+ self._knowledge_bases = knowledge_bases
+ self._top_k = top_k
+ self._score_threshold = score_threshold
+ self.description = self._build_description()
+ self.input_schema = self._build_input_schema()
+
+ def _build_description(self) -> str:
+ """Build the tool description from the currently equipped
+ knowledge bases so the agent has enough context to decide which
+ ones to query."""
+ lines = [
+ "Search the agent's equipped knowledge bases by semantic "
+ "similarity and return the most relevant chunks.",
+ "",
+ "## When to Use",
+ "- The user's question may be answered by content stored "
+ "in one of the listed knowledge bases (see *Equipped "
+ "Knowledge Bases* below).",
+ "- You need supporting facts, definitions, or documents "
+ "that are unlikely to be in your parametric knowledge.",
+ "",
+ "## Guidance",
+ "- Knowledge base names and descriptions are "
+ "user-supplied and may be terse, vague, or unrelated to "
+ "the actual contents. When in doubt, try the search — a "
+ "single call is cheap and an empty result is informative.",
+ "- Phrase `query` as a self-contained statement of what "
+ "you want to find. Avoid pronouns or relative time "
+ "references — the search is purely semantic and has no "
+ "conversational context.",
+ "- Set `knowledge_bases` only when the question clearly "
+ "matches one or two specific bases; otherwise leave it "
+ "unset to search them all.",
+ "",
+ "## Equipped Knowledge Bases",
+ ]
+ if self._knowledge_bases:
+ lines.append(
+ f"The agent is currently equipped with "
+ f"{len(self._knowledge_bases)} knowledge base(s):",
+ )
+ lines.extend(
+ f"- **{kb.name}**: {kb.description}"
+ for kb in self._knowledge_bases
+ )
+ else:
+ lines.append(
+ "No knowledge bases are currently equipped. **Do "
+ "not call this tool** — it will return nothing.",
+ )
+ return "\n".join(lines)
+
+ def _build_input_schema(self) -> dict:
+ """Build the JSON Schema, with ``knowledge_bases.items.enum``
+ narrowed to the currently equipped knowledge-base names so
+ the LLM cannot invent unknown names."""
+ schema: dict[str, Any] = _SearchParams.model_json_schema()
+ if self._knowledge_bases:
+ names = [kb.name for kb in self._knowledge_bases]
+ kb_schema = schema["properties"]["knowledge_bases"]
+ # Pydantic emits ``Optional[list[str]]`` as
+ # ``anyOf: [{type: array, items: ...}, {type: null}]``; we
+ # narrow the array branch's items. Fall back to a direct
+ # ``items`` field for the non-optional shape.
+ if "items" in kb_schema:
+ kb_schema["items"]["enum"] = names
+ else:
+ for variant in kb_schema.get("anyOf", []):
+ if variant.get("type") == "array" and "items" in variant:
+ variant["items"]["enum"] = names
+ break
+ return schema
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: Any,
+ ) -> Any:
+ """Allow the engine to handle this read-only search.
+
+ Args:
+ tool_input (`dict[str, Any]`):
+ The tool input data.
+ context (`PermissionContext`):
+ The permission context.
+
+ Returns:
+ `PermissionDecision`:
+ An allow decision — knowledge-base search is read-only.
+ """
+ del tool_input, context
+ return PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ message="Knowledge-base search is read-only.",
+ )
+
+ async def call( # type: ignore[override]
+ self,
+ query: str,
+ knowledge_bases: list[str] | None = None,
+ ) -> ToolChunk:
+ """Search the selected knowledge bases and return the results
+ as content blocks.
+
+ Args:
+ query (`str`):
+ The natural-language search query.
+ knowledge_bases (`list[str] | None`, optional):
+ Optional subset of knowledge bases to query, by name.
+ ``None`` searches every equipped knowledge base.
+
+ Returns:
+ `ToolChunk`:
+ The formatted search results, or a notice when
+ nothing relevant is found.
+ """
+ if knowledge_bases is None:
+ targets = list(self._knowledge_bases)
+ else:
+ wanted = set(knowledge_bases)
+ targets = [kb for kb in self._knowledge_bases if kb.name in wanted]
+
+ if not targets:
+ return ToolChunk(
+ content=[TextBlock(text="No relevant content found.")],
+ state=ToolResultState.SUCCESS,
+ is_last=True,
+ )
+
+ try:
+ results = await _search_across(
+ targets,
+ [query],
+ top_k=self._top_k,
+ score_threshold=self._score_threshold,
+ )
+ except Exception as e: # pylint: disable=broad-except
+ logger.exception("search_knowledge failed.")
+ return ToolChunk(
+ content=[TextBlock(text=f"Search failed: {e}")],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+
+ blocks = _format_results(results)
+ if not blocks:
+ return ToolChunk(
+ content=[TextBlock(text="No relevant content found.")],
+ state=ToolResultState.SUCCESS,
+ is_last=True,
+ )
+ return ToolChunk(
+ content=blocks,
+ state=ToolResultState.SUCCESS,
+ is_last=True,
+ )
+
+
+# ---------------------------------------------------------------------
+# Shared helpers — used by both the tool (agentic mode) and the
+# middleware's static-mode injection path.
+# ---------------------------------------------------------------------
+
+
+async def _search_across(
+ knowledge_bases: Sequence["KnowledgeBase"],
+ queries: Sequence[str | TextBlock | DataBlock],
+ top_k: int,
+ score_threshold: float | None,
+) -> list["VectorSearchResult"]:
+ """Search every knowledge base concurrently and merge the results.
+
+ Each knowledge base handles its own filtering — it silently drops
+ :class:`DataBlock` inputs when its embedding model is not
+ multimodal — so callers can pass the same query list to every
+ knowledge base without per-KB pre-filtering. Per-KB hits are
+ flattened, sorted by descending score, and truncated to ``top_k``.
+
+ .. note::
+ Scores from knowledge bases with different embedding models
+ are not strictly comparable; this merge sorts by raw score.
+ For mixed-embedding deployments where that matters, switch to
+ a rank-based fusion (e.g. RRF) — each per-KB
+ :meth:`KnowledgeBase.search` already returns ordered results.
+
+ Args:
+ knowledge_bases (`list[KnowledgeBase]`):
+ The knowledge bases to query.
+ queries (`list[str | TextBlock | DataBlock]`):
+ The query inputs.
+ top_k (`int`):
+ Maximum number of results after merging.
+ score_threshold (`float | None`):
+ Forwarded to each :meth:`KnowledgeBase.search` call.
+
+ Returns:
+ `list[VectorSearchResult]`:
+ At most ``top_k`` hits across all knowledge bases.
+ """
+ if not queries or not knowledge_bases:
+ return []
+
+ queries_list = list(queries)
+ per_kb = await asyncio.gather(
+ *(
+ kb.search(
+ queries=queries_list,
+ top_k=top_k,
+ score_threshold=score_threshold,
+ )
+ for kb in knowledge_bases
+ ),
+ )
+
+ merged = [r for sub in per_kb for r in sub]
+ merged.sort(key=lambda r: r.score, reverse=True)
+ return merged[:top_k]
+
+
+def _format_results(
+ results: list["VectorSearchResult"],
+) -> list[TextBlock | DataBlock]:
+ """Render search results as a numbered, cited list of blocks.
+
+ Every result becomes ``[N] (source: ...)`` followed by its chunk
+ content (text inlined, multimodal blocks kept as standalone
+ :class:`DataBlock` entries). Adjacent text fragments are merged
+ into a single :class:`TextBlock` so downstream consumers see one
+ contiguous text block instead of many small ones.
+
+ Args:
+ results (`list[VectorSearchResult]`):
+ The search results to format.
+
+ Returns:
+ `list[TextBlock | DataBlock]`:
+ The formatted blocks; empty list when ``results`` is
+ empty.
+ """
+ entries: list[TextBlock | DataBlock] = []
+ last = len(results)
+ for index, result in enumerate(results, start=1):
+ prefix = f"[{index}] (source: {result.chunk.source})\n"
+ block = deepcopy(result.chunk.content)
+ if isinstance(block, TextBlock):
+ block.text = prefix + block.text
+ entries.append(block)
+ else:
+ entries.append(TextBlock(text=prefix))
+ entries.append(block)
+ if index != last:
+ entries.append(TextBlock(text="\n\n"))
+
+ # Coalesce adjacent TextBlocks into one to keep the consumer-facing
+ # block list tight. We build fresh TextBlocks rather than mutating
+ # the deep copied ones to avoid aliasing the originals.
+ merged: list[TextBlock | DataBlock] = []
+ for entry in entries:
+ if (
+ isinstance(entry, TextBlock)
+ and merged
+ and isinstance(merged[-1], TextBlock)
+ ):
+ merged[-1] = TextBlock(text=merged[-1].text + entry.text)
+ else:
+ merged.append(entry)
+ return merged
+
+
+def _wrap_hint(
+ template: str,
+ blocks: list[TextBlock | DataBlock],
+) -> str | list[TextBlock | DataBlock]:
+ """Substitute ``{context}`` in ``template`` with the rendered blocks.
+
+ When every block is a :class:`TextBlock` the result is a single
+ ``str`` (cheap, no block overhead). When the blocks include
+ multimodal :class:`DataBlock` content the template is split on
+ ``{context}`` and the surrounding text is prepended / appended as
+ :class:`TextBlock` items, producing a ``list[TextBlock |
+ DataBlock]`` that preserves the binary payloads end-to-end.
+
+ Args:
+ template (`str`):
+ Wrapper template with a single ``{context}`` placeholder.
+ blocks (`list[TextBlock | DataBlock]`):
+ The formatted search blocks to wrap.
+
+ Returns:
+ `str | list[TextBlock | DataBlock]`:
+ A plain string for text-only payloads, or a list of blocks
+ when binary payloads are involved.
+ """
+ if all(isinstance(b, TextBlock) for b in blocks):
+ joined = "\n".join(b.text for b in blocks) # type: ignore[union-attr]
+ return template.format(context=joined)
+
+ prefix, _, end = template.partition("{context}")
+ wrapped: list[TextBlock | DataBlock] = list(blocks)
+ if prefix:
+ if isinstance(wrapped[0], TextBlock):
+ wrapped[0] = TextBlock(text=prefix + wrapped[0].text)
+ else:
+ wrapped.insert(0, TextBlock(text=prefix))
+ if end:
+ if isinstance(wrapped[-1], TextBlock):
+ wrapped[-1] = TextBlock(text=wrapped[-1].text + end)
+ else:
+ wrapped.append(TextBlock(text=end))
+ return wrapped
+
+
+class RAGMiddleware(MiddlewareBase):
+ """Middleware that integrates knowledge-base search into the agent.
+
+ Constructed from a list of :class:`~agentscope.rag.KnowledgeBase`
+ handles — each carrying its own embedding model, vector store, and
+ metadata filter. The middleware does not own these resources; it
+ only orchestrates search against them.
+
+ .. code-block:: python
+
+ # Automatic injection (static mode)
+ middleware = RAGMiddleware(
+ knowledge_bases=[kb1, kb2],
+ search_config=SearchConfig(mode="static"),
+ )
+
+ # Agent-driven search (agentic mode, the default)
+ middleware = RAGMiddleware(knowledge_bases=[kb1, kb2])
+
+ agent = Agent(..., middlewares=[middleware], ...)
+ """
+
+ class Parameters(BaseModel):
+ """User-tunable knowledge-base search parameters of
+ :class:`RAGMiddleware`.
+
+ The fields here are exactly the keys the hosted service persists
+ into ``SessionKnowledgeConfig.parameters`` and the keys
+ :class:`RAGMiddleware` accepts as ``search_config``. Every field
+ is annotated with a ``title`` and ``description`` so the front-end
+ can render them as labels and tooltips via
+ ``model_json_schema()``.
+ """
+
+ model_config = ConfigDict(frozen=True)
+
+ mode: Literal["static", "agentic"] = Field(
+ default="agentic",
+ title="Mode",
+ description=(
+ "Retrieval is either agentic, letting the Agent decide when "
+ "to retrieve, or static, triggering on every user input."
+ ),
+ )
+
+ top_k: int = Field(
+ default=5,
+ ge=1,
+ le=50,
+ title="Top K",
+ description=(
+ "Maximum number of chunks returned per search, across all "
+ "configured knowledge bases."
+ ),
+ )
+
+ score_threshold: float | None = Field(
+ default=None,
+ title="Score Threshold",
+ description=(
+ "Minimum similarity score for a hit to be kept. Leave "
+ "empty to disable filtering."
+ ),
+ )
+
+ emit_hint_event: bool = Field(
+ default=True,
+ title="Show matched chunks in chat",
+ description=(
+ "Emit a `HintBlockEvent` in static mode so the front-end "
+ "can display the matched snippets to the user."
+ ),
+ )
+
+ persist_hint: bool = Field(
+ default=False,
+ title="Persist Hint",
+ description=(
+ "In `static` mode, keep the injected hint block in the "
+ "agent context instead of removing it right after the "
+ "model call."
+ ),
+ )
+
+ hint_template: SkipJsonSchema[str] = Field(
+ default=_DEFAULT_HINT_TEMPLATE,
+ title="Hint template",
+ description=(
+ "Template wrapping the formatted search results in static "
+ "mode, with a `{context}` placeholder."
+ ),
+ )
+
+ # ``hint_template`` is intentionally hidden from the JSON Schema
+ # exposed to the dock UI: the wrapper text is part of the
+ # middleware's prompt contract and exposing it through the dock
+ # invites session-by-session prompt drift. It is still accepted
+ # for programmatic use.
+
+ @field_validator("hint_template")
+ @classmethod
+ def _validate_hint_template(cls, value: str) -> str:
+ """Reject templates with anything other than exactly one
+ ``{context}`` placeholder — :func:`_wrap_hint` substitutes on
+ the first occurrence, so zero placeholders silently drop the
+ matched content and multiple placeholders duplicate it."""
+ count = value.count("{context}")
+ if count != 1:
+ raise ValueError(
+ "hint_template must contain exactly one '{context}' "
+ f"placeholder; found {count}.",
+ )
+ return value
+
+ def __init__(
+ self,
+ knowledge_bases: list["KnowledgeBase"],
+ parameters: "RAGMiddleware.Parameters | None" = None,
+ ) -> None:
+ """Initialize the RAG middleware.
+
+ Args:
+ knowledge_bases (`list[KnowledgeBase]`):
+ The knowledge bases this agent searches.
+ parameters (`RAGMiddleware.Parameters | None`, optional):
+ Search-time knobs (mode, top_k, score threshold, hint
+ behaviour). ``None`` uses the defaults of
+ :class:`SearchConfig`.
+ """
+ self._knowledge_bases = knowledge_bases
+ self._parameters = parameters or RAGMiddleware.Parameters()
+ # Static-mode reply scratchpad: populated by ``on_reply`` and
+ # consumed by ``on_reasoning`` so the auto-search can use the
+ # original reply inputs (which are no longer in
+ # ``agent.state.context`` by the time ``on_reasoning`` runs in
+ # a tool-call loop). Cleared in ``on_reply``'s finally.
+ self._cached_inputs: list[TextBlock | DataBlock] | None = None
+
+ # ------------------------------------------------------------------
+ # Agentic mode — expose the search tool
+ # ------------------------------------------------------------------
+
+ async def list_tools(self) -> list[ToolBase]:
+ """Expose the search tool in ``"agentic"`` mode.
+
+ Returns:
+ `list[ToolBase]`:
+ A single ``search_knowledge`` tool in ``"agentic"``
+ mode; an empty list in ``"static"`` mode.
+ """
+ if self._parameters.mode == "agentic":
+ return [
+ _SearchKnowledgeTool(
+ self._knowledge_bases,
+ top_k=self._parameters.top_k,
+ score_threshold=self._parameters.score_threshold,
+ ),
+ ]
+ return []
+
+ # ------------------------------------------------------------------
+ # Static mode — capture inputs in on_reply, search in on_reasoning
+ # ------------------------------------------------------------------
+
+ async def on_reply(
+ self,
+ agent: "Agent",
+ input_kwargs: dict,
+ next_handler: Callable[..., AsyncGenerator],
+ ) -> AsyncGenerator:
+ """Cache reply inputs for the static-mode search.
+
+ ``on_reasoning`` runs *after* the agent has potentially
+ consumed the inputs and started its own reply, so it cannot
+ recover them from ``agent.state.context`` reliably. This
+ method captures them on entry and clears the cache when the
+ reply finishes.
+
+ Args:
+ agent (`Agent`):
+ The executing agent. Unused, but part of the
+ middleware contract.
+ input_kwargs (`dict`):
+ Reply input kwargs (``inputs``, plus any extras);
+ forwarded unchanged.
+ next_handler (`Callable[..., AsyncGenerator]`):
+ The downstream middleware or core reply logic.
+
+ Yields:
+ `Any`:
+ Whatever ``next_handler`` yields.
+ """
+ inputs = input_kwargs.get("inputs")
+
+ msgs: list[Msg] | None = None
+ if isinstance(inputs, Msg):
+ msgs = [inputs]
+ elif isinstance(inputs, list) and all(
+ isinstance(m, Msg) for m in inputs
+ ):
+ msgs = inputs
+
+ if msgs:
+ # Deepcopy because we are about to mutate the first text block of
+ # each message to prepend the speaker name — never touch the
+ # caller's message objects.
+ msgs = deepcopy(msgs)
+ blocks: list[TextBlock | DataBlock] = []
+ for msg in msgs:
+ if not msg.content:
+ continue
+ speaker = f"{msg.name}: "
+ if isinstance(msg.content[0], TextBlock):
+ msg.content[0].text = speaker + msg.content[0].text
+ else:
+ blocks.append(TextBlock(text=speaker))
+ blocks.extend(msg.content)
+
+ self._cached_inputs = blocks
+
+ try:
+ async for evt in next_handler(**input_kwargs):
+ yield evt
+ finally:
+ self._cached_inputs = None
+
+ async def on_reasoning(
+ self,
+ agent: "Agent",
+ input_kwargs: dict,
+ next_handler: Callable[..., AsyncGenerator],
+ ) -> AsyncGenerator:
+ """Inject a one-shot RAG hint on the first reasoning step.
+
+ Only active in ``"static"`` mode and only when
+ ``agent.state.cur_iter == 0`` — i.e. the first reasoning cycle
+ of a reply. Subsequent reasoning iterations (tool-call
+ rounds) skip the search so the agent does not re-embed and
+ re-inject for every iteration.
+
+ When ``persist_hint`` is ``False`` (the default) the injected
+ block is removed from the context right after the reasoning
+ step it participated in — keyed on the block's id so other
+ middlewares can append their own blocks to the same carrier
+ message without interfering.
+
+ Args:
+ agent (`Agent`):
+ The executing agent whose ``state.context`` receives
+ the hint.
+ input_kwargs (`dict`):
+ Reasoning input kwargs; forwarded unchanged.
+ next_handler (`Callable[..., AsyncGenerator]`):
+ The downstream middleware or core reasoning logic.
+
+ Yields:
+ `Any`:
+ An optional :class:`HintBlockEvent` followed by events
+ from downstream.
+ """
+ hint: HintBlock | None = None
+
+ if (
+ self._parameters.mode == "static"
+ and agent.state.cur_iter == 0
+ and self._cached_inputs
+ ):
+ try:
+ results = await _search_across(
+ self._knowledge_bases,
+ self._cached_inputs,
+ top_k=self._parameters.top_k,
+ score_threshold=self._parameters.score_threshold,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.exception(
+ "Knowledge-base search failed; proceeding without "
+ "matched context.",
+ )
+ results = []
+
+ blocks = _format_results(results)
+ if blocks:
+ hint = HintBlock(
+ hint=_wrap_hint(self._parameters.hint_template, blocks),
+ source=_HINT_SOURCE,
+ )
+ agent.state.append_context(agent.name, [hint])
+ if self._parameters.emit_hint_event:
+ yield HintBlockEvent(
+ reply_id=agent.state.reply_id,
+ block_id=hint.id,
+ source=hint.source,
+ hint=hint.hint,
+ )
+
+ try:
+ async for evt in next_handler(**input_kwargs):
+ yield evt
+ finally:
+ if hint is not None and not self._parameters.persist_hint:
+ # Remove the injected block from whichever message
+ # ``append_context`` placed it on. Reverse-scan
+ # because that carrier is always the latest message
+ # with our ``reply_id``.
+ for msg in reversed(agent.state.context):
+ if msg.id != agent.state.reply_id:
+ continue
+ msg.content = [b for b in msg.content if b.id != hint.id]
+ break
diff --git a/src/agentscope/rag/__init__.py b/src/agentscope/rag/__init__.py
new file mode 100644
index 000000000..46fe9b4c0
--- /dev/null
+++ b/src/agentscope/rag/__init__.py
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+"""The retrieval-augmented generation (RAG) module in AgentScope."""
+
+from ._chunker import ApproxTokenChunker, ChunkerBase
+from ._document import (
+ Section,
+ Chunk,
+)
+from ._parser import ImageParser, ParserBase, PDFParser, PPTParser, TextParser
+from ._vdb import (
+ DocumentSummary,
+ VectorStoreBase,
+ VectorRecord,
+ VectorSearchResult,
+ QdrantStore,
+)
+from ._knowledge import KnowledgeBase
+
+__all__ = [
+ "ApproxTokenChunker",
+ "ChunkerBase",
+ "Chunk",
+ "DocumentSummary",
+ "ImageParser",
+ "ParserBase",
+ "PDFParser",
+ "PPTParser",
+ "TextParser",
+ "Section",
+ "VectorStoreBase",
+ "VectorRecord",
+ "VectorSearchResult",
+ "QdrantStore",
+ "KnowledgeBase",
+]
diff --git a/src/agentscope/rag/_chunker/__init__.py b/src/agentscope/rag/_chunker/__init__.py
new file mode 100644
index 000000000..e8c271987
--- /dev/null
+++ b/src/agentscope/rag/_chunker/__init__.py
@@ -0,0 +1,10 @@
+# -*- coding: utf-8 -*-
+"""Chunker implementations for the RAG indexing pipeline."""
+
+from ._approx_token_chunker import ApproxTokenChunker
+from ._base import ChunkerBase
+
+__all__ = [
+ "ApproxTokenChunker",
+ "ChunkerBase",
+]
diff --git a/src/agentscope/rag/_chunker/_approx_token_chunker.py b/src/agentscope/rag/_chunker/_approx_token_chunker.py
new file mode 100644
index 000000000..fe26674d4
--- /dev/null
+++ b/src/agentscope/rag/_chunker/_approx_token_chunker.py
@@ -0,0 +1,172 @@
+# -*- coding: utf-8 -*-
+"""A chunker that splits text by an approximate token count.
+
+The token count is approximated as ``len(text.encode("utf-8")) // 4``,
+which avoids a hard dependency on any tokenizer library while staying
+within the right order of magnitude for most LLM tokenizers.
+"""
+from bisect import bisect_right
+from itertools import accumulate
+
+from ._base import ChunkerBase
+from .._document import Chunk, Section
+from ...message import TextBlock, DataBlock
+
+
+class ApproxTokenChunker(ChunkerBase):
+ """A chunker based on an approximate token counting strategy.
+
+ Text sections are sliced into pieces of at most ``chunk_size``
+ approximate tokens, with ``overlap`` approximate tokens shared
+ between two consecutive pieces. The token count of a string is
+ approximated as ``len(text.encode("utf-8")) // 4``, so no
+ tokenizer dependency is required.
+
+ Sections carrying a :class:`~agentscope.message.DataBlock`
+ (images, video, etc.) are passed through unchanged as a single
+ chunk.
+
+ .. note:: Chunks never span across two input Sections, as
+ required by :class:`ChunkerBase`.
+ """
+
+ def __init__(self, chunk_size: int = 512, overlap: int = 50) -> None:
+ """Initialize the approx token chunker.
+
+ Args:
+ chunk_size (`int`, defaults to `512`):
+ The maximum number of approximate tokens per chunk.
+ Must be a positive integer.
+ overlap (`int`, defaults to `50`):
+ The number of approximate tokens shared between two
+ consecutive chunks. Must be non-negative and smaller
+ than ``chunk_size``.
+
+ Raises:
+ `ValueError`:
+ If ``chunk_size`` is not positive, or ``overlap`` is
+ negative or not smaller than ``chunk_size``.
+ """
+ if chunk_size <= 0:
+ raise ValueError(
+ f"chunk_size must be positive, got {chunk_size}.",
+ )
+ if overlap < 0 or overlap >= chunk_size:
+ raise ValueError(
+ "overlap must satisfy 0 <= overlap < chunk_size, "
+ f"got overlap={overlap}, chunk_size={chunk_size}.",
+ )
+
+ self.chunk_size = chunk_size
+ self.overlap = overlap
+
+ async def chunk(self, sections: list[Section]) -> list[Chunk]:
+ """Chunk the input sections into smaller chunks based on an approx
+ token counting strategy.
+
+ Args:
+ sections (`list[Section]`):
+ A list of sections to chunk.
+
+ Returns:
+ `list[Chunk]`:
+ A list of chunks, with ``chunk_index`` numbered
+ ``0..N-1`` and ``total_chunks`` set to ``N`` on every
+ chunk.
+ """
+ chunks: list[Chunk] = []
+ for section in sections:
+ contents: list[TextBlock | DataBlock]
+ if isinstance(section.content, TextBlock):
+ contents = [
+ TextBlock(text=piece)
+ for piece in self._split_text(section.content.text)
+ ]
+ else:
+ # DataBlock pass-through: never slice multimodal data
+ contents = [section.content]
+
+ chunks.extend(
+ Chunk(
+ content=content,
+ source=section.source,
+ chunk_index=0, # renumbered below
+ total_chunks=0, # renumbered below
+ metadata=dict(section.metadata),
+ )
+ for content in contents
+ )
+
+ for index, chunk in enumerate(chunks):
+ chunk.chunk_index = index
+ chunk.total_chunks = len(chunks)
+
+ return chunks
+
+ def _split_text(self, text: str) -> list[str]:
+ """Split text into pieces of at most ``chunk_size`` approx tokens.
+
+ Consecutive pieces share approximately ``overlap`` tokens.
+
+ Args:
+ text (`str`):
+ The text to split.
+
+ Returns:
+ `list[str]`:
+ The text pieces, in document order.
+ """
+ if self._approx_count_tokens(text) <= self.chunk_size:
+ return [text]
+
+ # Cumulative UTF-8 byte length after each character, so that
+ # the byte length of text[i:j] == byte_offsets[j] - byte_offsets[i]
+ byte_offsets = [0, *accumulate(len(c.encode("utf-8")) for c in text)]
+
+ chunk_bytes = self.chunk_size * 4
+ overlap_bytes = self.overlap * 4
+
+ pieces: list[str] = []
+ start = 0
+ while start < len(text):
+ # The largest end such that the slice fits the byte budget
+ end = (
+ bisect_right(
+ byte_offsets,
+ byte_offsets[start] + chunk_bytes,
+ )
+ - 1
+ )
+ # Always make progress, even for characters whose UTF-8
+ # encoding exceeds the budget on their own
+ end = max(end, start + 1)
+ pieces.append(text[start:end])
+
+ if end >= len(text):
+ break
+
+ # Step back by the overlap budget, ensuring forward progress
+ next_start = (
+ bisect_right(
+ byte_offsets,
+ byte_offsets[end] - overlap_bytes,
+ )
+ - 1
+ )
+ start = max(next_start, start + 1)
+
+ return pieces
+
+ @staticmethod
+ def _approx_count_tokens(text: str) -> int:
+ """The approx count of tokens.
+
+ Args:
+ text (`str`):
+ The text to be counted.
+
+ Returns:
+ `int`:
+ The approx count of tokens.
+ """
+ return len(text.encode("utf-8")) // 4
diff --git a/src/agentscope/rag/_chunker/_base.py b/src/agentscope/rag/_chunker/_base.py
new file mode 100644
index 000000000..a766d20ac
--- /dev/null
+++ b/src/agentscope/rag/_chunker/_base.py
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+"""Abstract base class for chunkers.
+
+A :class:`ChunkerBase` subclass takes the :class:`Section` list
+produced by a :class:`~agentscope.rag.ParserBase` and splits the
+content into final :class:`Chunk` objects suitable for embedding and
+storage in a vector database.
+
+Chunkers are **format-agnostic** — they operate on the unified
+``TextBlock | DataBlock`` content carried in each Section. Long
+:class:`TextBlock` content is sliced according to a chunking strategy
+(by character count, by tokens, by semantic boundaries, etc.); short
+text and :class:`DataBlock` content are passed through unchanged.
+
+Chunkers **never combine content across Section boundaries**. This
+guarantee preserves the structural metadata attached by the Parser
+(page numbers, slide indices, embedded-image isolation, etc.).
+"""
+from abc import ABC, abstractmethod
+
+from .._document import Chunk, Section
+
+
+class ChunkerBase(ABC):
+ """Abstract base class for chunkers.
+
+ Subclasses implement a specific chunking strategy (by character
+ count, by token count, by semantic boundary, etc.). The
+ chunker is configured once at construction time and reused
+ across many ``chunk()`` calls within the same knowledge base.
+
+ Subclasses must guarantee:
+
+ - **No cross-Section merging**: every output :class:`Chunk` is
+ derived from exactly one input :class:`Section`.
+ - **DataBlock pass-through**: a Section whose content is a
+ :class:`~agentscope.message.DataBlock` becomes a single Chunk
+ with the same content; multimodal data is never sliced.
+ - **Continuous indexing**: ``chunk_index`` runs from ``0`` to
+ ``total_chunks - 1`` across the entire output list, even
+ when the input contains many Sections.
+ - **Consistent total_chunks**: every output Chunk carries the
+ same ``total_chunks`` value (the length of the output list).
+ - **Metadata inheritance**: each output Chunk's ``source`` and
+ ``metadata`` are copied from its parent Section.
+ """
+
+ @abstractmethod
+ async def chunk(self, sections: list[Section]) -> list[Chunk]:
+ """Split a list of Sections into Chunks.
+
+ Args:
+ sections (`list[Section]`):
+ The Sections produced by a :class:`ParserBase`, in
+ document order.
+
+ Returns:
+ `list[Chunk]`:
+ The final chunks, in document order, with
+ ``chunk_index`` numbered ``0..N-1`` and
+ ``total_chunks`` set to ``N`` on every chunk.
+ """
diff --git a/src/agentscope/rag/_document.py b/src/agentscope/rag/_document.py
new file mode 100644
index 000000000..b6fce8b75
--- /dev/null
+++ b/src/agentscope/rag/_document.py
@@ -0,0 +1,102 @@
+# -*- coding: utf-8 -*-
+"""Data structures used in the RAG indexing pipeline.
+
+The indexing pipeline has two stages, each producing its own
+structured output:
+
+1. :class:`Section` — produced by a :class:`ParserBase` from a raw
+ file. Each ``Section`` represents one "natural boundary" of the
+ source (a PDF page, a PPTX slide, an embedded image, a Markdown
+ heading section, etc.). A ``Chunker`` never combines content
+ across two ``Section`` instances, so ``Section`` is also a hard
+ boundary that prevents leakage of format-specific structure into
+ downstream chunks.
+
+2. :class:`Chunk` — produced by a :class:`ChunkerBase` from one or
+ more ``Section`` instances. Each ``Chunk`` is the final unit
+ that gets embedded and inserted into the vector store.
+
+Neither structure is persisted on its own — they are transient
+in-memory carriers between pipeline stages. Persistence happens at
+the :class:`~agentscope.rag.VectorRecord` and
+``KnowledgeDocumentRecord`` layers.
+"""
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from ..message import TextBlock, DataBlock
+
+
+class Section(BaseModel):
+ """A single natural section produced by a :class:`ParserBase`.
+
+ A ``Section`` represents one logical region of the source file.
+ The :class:`ChunkerBase` guarantees that no resulting
+ :class:`Chunk` ever spans content from two different sections.
+
+ The granularity of a ``Section`` is format-specific:
+
+ - **PDF**: one section per page (plus separate sections for
+ embedded images).
+ - **PPTX**: one section per slide.
+ - **Markdown**: one section per top-level heading, or the entire
+ file if unstructured.
+ - **TXT / image / video**: one section for the whole file.
+ """
+
+ content: TextBlock | DataBlock
+ """The section content. Text sections use :class:`TextBlock`;
+ multimodal sections (images, video, etc.) use :class:`DataBlock`."""
+
+ source: str
+ """The source filename (e.g. ``"report.pdf"``). Carried through
+ to every downstream :class:`Chunk` and into the vector store
+ metadata for citation / display."""
+
+ metadata: dict[str, Any] = Field(default_factory=dict)
+ """Format-specific metadata written by the parser. Examples:
+
+ - PDFParser: ``{"page": 3}``
+ - PPTXParser: ``{"slide": 2}``
+ - ExcelParser: ``{"sheet": "Q3 Sales"}``
+
+ These keys are not part of any retrieval / pipeline contract —
+ they are passed through verbatim to the vector store metadata for
+ later citation. Each Chunk inherits this dict from its parent
+ Section.
+ """
+
+
+class Chunk(BaseModel):
+ """A final indexable chunk produced by a :class:`ChunkerBase`.
+
+ Each ``Chunk`` corresponds to one record in the vector store.
+ The required structural fields (``source``, ``chunk_index``,
+ ``total_chunks``) enable downstream features such as "expand
+ context around a hit" during retrieval.
+ """
+
+ content: TextBlock | DataBlock
+ """The chunk content (sliced from a text :class:`Section`, or a
+ multimodal :class:`DataBlock` passed through unchanged)."""
+
+ source: str
+ """The source filename — inherited from the parent
+ :class:`Section`. Used for display / citation."""
+
+ chunk_index: int
+ """The 0-based index of this chunk **within the document**.
+ Sequential across all sections of the same source file. Used to
+ locate neighbouring chunks for "context expansion" at query time.
+ """
+
+ total_chunks: int
+ """The total number of chunks produced from the same source file.
+ Together with :attr:`chunk_index` lets callers know whether a hit
+ is near the start / end of the document, and bounds the
+ expansion range."""
+
+ metadata: dict[str, Any] = Field(default_factory=dict)
+ """Format-specific metadata inherited from the parent
+ :class:`Section`. See :attr:`Section.metadata`."""
diff --git a/src/agentscope/rag/_knowledge.py b/src/agentscope/rag/_knowledge.py
new file mode 100644
index 000000000..cc87c0877
--- /dev/null
+++ b/src/agentscope/rag/_knowledge.py
@@ -0,0 +1,384 @@
+# -*- coding: utf-8 -*-
+"""Runtime handle for a single knowledge base.
+
+A :class:`KnowledgeBase` instance is the **single algorithmic source of
+truth** for talking to one knowledge base: it pairs an embedding model
+with a vector-store collection (optionally scoped by a payload
+``metadata_filter``) and exposes the four operations a caller ever
+needs — :meth:`search`, :meth:`insert_document`,
+:meth:`delete_document`, :meth:`list_documents`.
+
+The handle is *narrow on purpose* — it carries the resolved runtime
+state (embedding model + vector store + scope) and delegates every
+operation to the bound :class:`VectorStoreBase`. Document parsing,
+chunking, credential resolution, dimension policy validation, and
+persistence of knowledge-base records all belong one layer up
+(service-side :class:`KnowledgeBaseManagerBase` for hosted
+deployments; the caller directly otherwise).
+
+The backing collection is created on first use — each operation
+transparently calls :meth:`ensure_collection`, which is itself
+idempotent and memoised after the first success, so the only cost is
+one extra round-trip on the very first call against a fresh
+deployment.
+
+``metadata_filter`` is the defense-in-depth scoping mechanism for
+co-locating multiple logical knowledge bases inside the same physical
+collection — typically multi-tenant deployments where every record
+carries a ``{"tenant_id": "..."}`` payload. It is set once at
+construction time and **always** applied: search/list never escape
+it, and insert forces it onto every chunk's metadata so a malicious or
+buggy parser cannot rebind a record into another scope.
+"""
+
+import asyncio
+
+from ._document import Chunk
+from ._vdb import VectorRecord, VectorSearchResult, VectorStoreBase
+from .._utils._common import _generate_id
+from ..embedding import EmbeddingModelBase
+from ..message import DataBlock, TextBlock
+from ._vdb import DocumentSummary
+
+
+class KnowledgeBase:
+ """Runtime handle for one knowledge base.
+
+ Binds an embedding model and a vector-store collection together so
+ callers can retrieve / insert / delete / list documents without
+ repeating the wiring. Cheap to construct (no I/O); the collection
+ itself is created lazily on the first operation, so a fresh
+ deployment "just works" without an explicit setup step.
+
+ .. code-block:: python
+
+ kb = KnowledgeBase(
+ name="company-handbook",
+ description="Internal HR and onboarding documents.",
+ embedding_model=embedding_model,
+ vector_store=vector_store,
+ collection="handbook",
+ )
+ await kb.insert_document(chunks)
+ results = await kb.search(["What is the PTO policy?"])
+ """
+
+ name: str
+ """Agent-oriented knowledge base name — used by tool descriptions
+ and frontend rendering."""
+
+ description: str
+ """Agent-oriented knowledge base description — what this knowledge
+ base contains and when to retrieve from it."""
+
+ def __init__(
+ self,
+ name: str,
+ description: str,
+ embedding_model: EmbeddingModelBase,
+ vector_store: VectorStoreBase,
+ collection: str,
+ metadata_filter: dict | None = None,
+ ) -> None:
+ """Initialize the runtime handle.
+
+ Args:
+ name (`str`):
+ Agent-oriented knowledge base name. Surfaced to the
+ LLM (via tool descriptions) and to the front-end.
+ description (`str`):
+ Agent-oriented description. Should answer "what is in
+ this knowledge base and when should I search it?" — the
+ LLM uses it to decide whether to call the search tool
+ in agentic mode.
+ embedding_model (`EmbeddingModelBase`):
+ The embedding model used to embed both queries and
+ inserted chunks. Must be the same model used at
+ indexing time and at retrieval time, otherwise vectors
+ will not be comparable.
+ vector_store (`VectorStoreBase`):
+ The shared vector-store connection. The store must
+ already be entered (its own ``__aenter__`` already
+ called) before any operation on this handle runs.
+ collection (`str`):
+ The physical collection backing this knowledge base.
+ Created lazily on the first operation; see
+ :meth:`ensure_collection`.
+ metadata_filter (`dict | None`, optional):
+ Defense-in-depth payload filter. When set:
+
+ - :meth:`search` and :meth:`list_documents` restrict
+ results to records whose payload matches every
+ ``key == value`` pair;
+ - :meth:`insert_document` forces these keys onto every
+ inserted chunk's metadata, overriding caller-supplied
+ values, so records cannot leak into another scope.
+
+ ``None`` disables filtering — the default for
+ deployments where every knowledge base owns its
+ collection outright.
+ """
+ self.name = name
+ self.description = description
+ self._embedding_model = embedding_model
+ self._vector_store = vector_store
+ self._collection = collection
+ self._metadata_filter = metadata_filter
+ # Memoise the "collection exists" check after the first
+ # successful ensure_collection so subsequent operations avoid
+ # the extra round-trip.
+ self._collection_ready = False
+
+ # ------------------------------------------------------------------
+ # Read-only accessors
+ # ------------------------------------------------------------------
+
+ @property
+ def embedding_model(self) -> EmbeddingModelBase:
+ """The bound embedding model."""
+ return self._embedding_model
+
+ @property
+ def vector_store(self) -> VectorStoreBase:
+ """The bound vector store."""
+ return self._vector_store
+
+ @property
+ def collection(self) -> str:
+ """The physical collection backing this knowledge base."""
+ return self._collection
+
+ @property
+ def metadata_filter(self) -> dict | None:
+ """The defense-in-depth payload filter, or ``None``."""
+ return self._metadata_filter
+
+ # ------------------------------------------------------------------
+ # Lifecycle
+ # ------------------------------------------------------------------
+
+ async def ensure_collection(self) -> None:
+ """Idempotently create the backing collection if missing.
+
+ Called transparently at the top of every public operation —
+ callers should not need to invoke it themselves. Memoised on
+ the instance after the first success, so subsequent calls are
+ a single ``if`` check.
+
+ Looks up the collection via
+ :meth:`VectorStoreBase.has_collection` and creates it with the
+ embedding model's :attr:`~EmbeddingModelBase.dimensions` when
+ absent.
+
+ Raises whatever the backend raises if the collection exists at
+ an incompatible dimension (the backend is the authority on
+ that; we do not double-check here).
+ """
+ if self._collection_ready:
+ return
+ if not await self._vector_store.has_collection(self._collection):
+ await self._vector_store.create_collection(
+ self._collection,
+ dimensions=self._embedding_model.dimensions,
+ )
+ self._collection_ready = True
+
+ # ------------------------------------------------------------------
+ # Search
+ # ------------------------------------------------------------------
+
+ async def search(
+ self,
+ queries: list[str | TextBlock | DataBlock],
+ top_k: int = 5,
+ score_threshold: float | None = None,
+ ) -> list[VectorSearchResult]:
+ """Search the knowledge base with one or more queries.
+
+ All queries are embedded in a single batch, then searched
+ concurrently against the bound collection (with
+ :attr:`metadata_filter` applied). Hits are deduplicated by
+ ``(document_id, chunk_index)`` keeping the best score,
+ optionally filtered by ``score_threshold``, sorted by
+ descending score, and truncated to ``top_k``.
+
+ Args:
+ queries (`list[str | TextBlock | DataBlock]`):
+ Query inputs. Text may be either bare ``str`` or
+ :class:`TextBlock`; :class:`DataBlock` items are
+ **silently dropped** when the bound embedding model
+ does not declare ``supports_multimodal`` — text-only
+ models would otherwise reject them. Callers can
+ therefore pass a mixed list without per-KB filtering.
+ top_k (`int`, defaults to ``5``):
+ Maximum number of results returned across all queries
+ (after dedup).
+ score_threshold (`float | None`, optional):
+ Minimum similarity score for a hit to be retained.
+ Only meaningful for similarity metrics where higher is
+ better (cosine / dot-product). ``None`` disables
+ filtering.
+
+ Returns:
+ `list[VectorSearchResult]`:
+ At most ``top_k`` deduplicated hits ordered by
+ descending similarity score. Empty when there are no
+ queries the bound embedding model can consume.
+ """
+ if not queries:
+ return []
+
+ if not self._embedding_model.supports_multimodal:
+ queries = [q for q in queries if not isinstance(q, DataBlock)]
+ if not queries:
+ return []
+
+ await self.ensure_collection()
+ response = await self._embedding_model(queries)
+
+ results_per_query = await asyncio.gather(
+ *(
+ self._vector_store.search(
+ collection=self._collection,
+ query_vector=vector,
+ top_k=top_k,
+ metadata_filter=self._metadata_filter,
+ )
+ for vector in response.embeddings
+ ),
+ )
+
+ best: dict[tuple[str, int], VectorSearchResult] = {}
+ for results in results_per_query:
+ for result in results:
+ if (
+ score_threshold is not None
+ and result.score < score_threshold
+ ):
+ continue
+ # ``(document_id, chunk_index)`` is the stable identity
+ # of a chunk: it survives reindex (block UUIDs do not)
+ # and uniquely names "this slice of that document"
+ # regardless of which query surfaced it.
+ key = (result.document_id, result.chunk.chunk_index)
+ if key not in best or result.score > best[key].score:
+ best[key] = result
+
+ merged = sorted(
+ best.values(),
+ key=lambda result: result.score,
+ reverse=True,
+ )
+ return merged[:top_k]
+
+ # ------------------------------------------------------------------
+ # Document management
+ # ------------------------------------------------------------------
+
+ async def insert_document(
+ self,
+ chunks: list[Chunk],
+ document_id: str | None = None,
+ document_metadata: dict | None = None,
+ ) -> str:
+ """Embed and insert a list of chunks as a single source document.
+
+ All chunks share the resolved ``document_id``;
+ :meth:`delete_document` later removes them as a unit. Each
+ chunk's metadata is merged in this precedence (highest wins):
+
+ 1. :attr:`metadata_filter` keys — defense-in-depth scoping, so
+ a chunk can never be inserted with a payload that escapes
+ the filter (any escape would silently disappear at retrieve
+ time anyway, but failing closed at insert is clearer).
+ 2. The chunk's pre-existing ``metadata`` — parser-supplied.
+ 3. ``document_metadata`` — document-level fields propagated
+ down (filename, media type, upload time, ...).
+
+ Args:
+ chunks (`list[Chunk]`):
+ The pre-chunked document content (already produced by
+ a parser + chunker pipeline). An empty list is a
+ no-op.
+ document_id (`str | None`, optional):
+ The document identifier. When ``None`` a fresh UUID
+ hex is generated and returned so the caller can record
+ it for future :meth:`delete_document` calls.
+ document_metadata (`dict | None`, optional):
+ Document-level metadata (filename, media type, size,
+ upload time, ...). Merged into each chunk's
+ ``metadata``.
+
+ Returns:
+ `str`:
+ The (possibly generated) document id.
+
+ Raises:
+ `RuntimeError`:
+ If the embedding model returns a number of vectors
+ that does not match the number of chunks.
+ """
+ if not chunks:
+ return document_id or _generate_id()
+ document_id = document_id or _generate_id()
+
+ await self.ensure_collection()
+
+ # Precedence: metadata_filter wins (security boundary), then
+ # chunk metadata, then document_metadata. See docstring.
+ for chunk in chunks:
+ chunk.metadata = {
+ **(document_metadata or {}),
+ **chunk.metadata,
+ **(self._metadata_filter or {}),
+ }
+
+ response = await self._embedding_model(
+ [chunk.content for chunk in chunks],
+ )
+
+ if len(response.embeddings) != len(chunks):
+ raise RuntimeError(
+ f"Embedding model returned {len(response.embeddings)} "
+ f"vectors for {len(chunks)} chunks.",
+ )
+
+ records = [
+ VectorRecord(
+ vector=vector,
+ document_id=document_id,
+ chunk=chunk,
+ )
+ for vector, chunk in zip(response.embeddings, chunks)
+ ]
+ await self._vector_store.insert(self._collection, records)
+ return document_id
+
+ async def delete_document(self, document_id: str) -> None:
+ """Remove every record for one source document.
+
+ Args:
+ document_id (`str`):
+ The source document id whose records should be removed.
+ """
+ await self.ensure_collection()
+ await self._vector_store.delete(
+ self._collection,
+ document_id,
+ )
+
+ async def list_documents(self) -> list["DocumentSummary"]:
+ """List all distinct source documents in this knowledge base.
+
+ Filtered by :attr:`metadata_filter` when set, so callers only
+ ever see documents within their own scope.
+
+ Returns:
+ `list[DocumentSummary]`:
+ One summary per indexed document, in unspecified order.
+ """
+ await self.ensure_collection()
+ return await self._vector_store.list_documents(
+ self._collection,
+ metadata_filter=self._metadata_filter,
+ )
diff --git a/src/agentscope/rag/_parser/__init__.py b/src/agentscope/rag/_parser/__init__.py
new file mode 100644
index 000000000..2011e71d1
--- /dev/null
+++ b/src/agentscope/rag/_parser/__init__.py
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+"""File parser implementations for the RAG indexing pipeline."""
+
+from ._base import ParserBase
+from ._image import ImageParser
+from ._pdf import PDFParser
+from ._ppt import PPTParser
+from ._text import TextParser
+
+__all__ = [
+ "ParserBase",
+ "PDFParser",
+ "PPTParser",
+ "ImageParser",
+ "TextParser",
+]
diff --git a/src/agentscope/rag/_parser/_base.py b/src/agentscope/rag/_parser/_base.py
new file mode 100644
index 000000000..b98055800
--- /dev/null
+++ b/src/agentscope/rag/_parser/_base.py
@@ -0,0 +1,116 @@
+# -*- coding: utf-8 -*-
+"""Abstract base class for file parsers.
+
+A :class:`ParserBase` subclass handles **one file format**. Its job
+is to read a file's raw bytes and produce a list of
+:class:`~agentscope.rag.Section` objects, each representing a natural
+boundary of the source (e.g. one PDF page, one PPTX slide, one
+embedded image).
+
+Parsers **do not chunk text**. Long text is left intact inside the
+Section; splitting happens later in a
+:class:`~agentscope.rag.ChunkerBase`. Parsers also do not need to
+worry about output size — only about preserving the structural
+boundaries that downstream consumers must not cross.
+"""
+import mimetypes
+from abc import ABC, abstractmethod
+
+from .._document import Section
+
+
+class ParserBase(ABC):
+ """Abstract base class for file-format parsers.
+
+ Each subclass handles a single file format (or a related family,
+ e.g. all plain-text MIME types). Subclasses are typically
+ instantiated once and reused across many ``parse()`` calls.
+
+ Subclasses should be stateless or thread-safe — a single
+ instance may be invoked concurrently from multiple agent runs.
+
+ Subclasses must declare :attr:`supported_media_types` so that the
+ KnowledgeBaseManager can route uploaded files to the right parser
+ based on standard IANA media types (RFC 6838).
+ """
+
+ supported_media_types: list[str]
+ """Standard IANA media types (RFC 6838) this parser handles,
+ e.g. ``["application/pdf"]`` or
+ ``["text/plain", "text/markdown"]``. Used by the
+ KnowledgeBaseManager to select a parser for an uploaded file."""
+
+ @classmethod
+ def supported_extensions(cls) -> list[str]:
+ """Filename extensions (including the leading ``.``) this parser
+ can produce uploads for.
+
+ The base implementation derives extensions from
+ :attr:`supported_media_types` via
+ :func:`mimetypes.guess_all_extensions` — good enough for clean
+ IANA types like ``application/pdf``. Subclasses **should
+ override** this when the default reverse-lookup is noisy
+ (``text/plain`` resolves to ``.bat`` / ``.c`` / ``.pl`` and a
+ dozen other developer extensions no KB user wants in the file
+ picker) or when a media type has no registered extension at all
+ (``application/x-yaml`` returns the empty list).
+
+ The result is consumed by the front-end's ``<input accept>`` and
+ by the client-side filename guard; it is **not** consulted for
+ media-type routing — that always goes through
+ :attr:`supported_media_types`.
+
+ Returns:
+ `list[str]`:
+ Deduplicated, sorted extensions (each starting with
+ ``.``). May be empty when no media type resolves.
+ """
+ out: set[str] = set()
+ for media_type in cls.supported_media_types:
+ out.update(mimetypes.guess_all_extensions(media_type))
+ return sorted(out)
+
+ @abstractmethod
+ async def parse(
+ self,
+ file: bytes | str,
+ filename: str,
+ ) -> list[Section]:
+ """Parse a file into a list of :class:`Section` objects.
+
+ The ``file`` argument is a union covering the three call sites
+ a parser sees in practice:
+
+ - ``bytes`` — the raw payload, as handed in by HTTP uploads
+ and blob-store reads.
+ - ``str`` for binary parsers (PDF, PPT, image, …) — a
+ **filesystem path** to the file to read. The parser opens
+ the path itself; callers do not need to read the bytes first.
+ - ``str`` for :class:`TextParser` — disambiguated at runtime:
+ if the string names an existing file on disk it is treated
+ as a path and the file is decoded with the configured
+ encoding; otherwise it is treated as pre-decoded text.
+
+ Args:
+ file (`bytes | str`):
+ The file content or a path to it (see above).
+ filename (`str`):
+ The original filename (e.g. ``"report.pdf"``). Used
+ for error messages and copied into each Section's
+ :attr:`Section.source` field for downstream display
+ / citation.
+
+ Returns:
+ `list[Section]`:
+ One Section per natural boundary in the source file.
+ For unstructured formats (plain text, image, video),
+ a single Section may cover the whole file. Sections
+ are returned in document order.
+
+ Raises:
+ `TypeError`: If the subclass does not accept the supplied
+ ``file`` form.
+ `FileNotFoundError`: If a binary parser is handed a
+ ``str`` that does not name an existing file.
+ `ValueError`: If the file cannot be parsed.
+ """
diff --git a/src/agentscope/rag/_parser/_image.py b/src/agentscope/rag/_parser/_image.py
new file mode 100644
index 000000000..f64d441ec
--- /dev/null
+++ b/src/agentscope/rag/_parser/_image.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+"""Image file parser.
+
+A single :class:`Section` carrying the raw image bytes as a
+base64-encoded :class:`DataBlock`. No OCR, no captioning — the
+section is the image, ready to flow through to a multimodal
+embedding model unchanged.
+"""
+import base64
+
+from ...message import Base64Source, DataBlock
+from .._document import Section
+from ._base import ParserBase
+from ._utils import _guess_image_media_type
+
+
+class ImageParser(ParserBase):
+ """Parser for image files.
+
+ Wraps the entire file as a single :class:`Section` holding a
+ :class:`DataBlock` with the image's base64-encoded bytes. This is
+ the input shape a multimodal embedding model expects; the
+ surrounding pipeline (chunker, vector store) treats the section
+ opaquely.
+
+ The IANA media type is sniffed from the bytes' magic number so
+ callers do not need to pass it explicitly.
+ """
+
+ supported_media_types: list[str] = [
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/bmp",
+ "image/webp",
+ ]
+
+ @classmethod
+ def supported_extensions(cls) -> list[str]:
+ """Return the canonical image extensions."""
+ return [
+ ".bmp",
+ ".gif",
+ ".jpeg",
+ ".jpg",
+ ".png",
+ ".webp",
+ ]
+
+ async def parse(
+ self,
+ file: bytes | str,
+ filename: str,
+ ) -> list[Section]:
+ """Wrap the image bytes in a single :class:`Section`.
+
+ Args:
+ file (`bytes | str`):
+ Either the raw image bytes, or a filesystem path to
+ the image file.
+ filename (`str`):
+ The source filename, copied into
+ :attr:`Section.source`.
+
+ Returns:
+ `list[Section]`:
+ A one-element list whose section's ``content`` is a
+ :class:`DataBlock` with the base64-encoded image data.
+
+ Raises:
+ `FileNotFoundError`: If ``file`` is a ``str`` pointing to
+ a path that does not exist.
+ """
+ if isinstance(file, str):
+ with open(file, "rb") as fp:
+ file = fp.read()
+
+ media_type = _guess_image_media_type(file)
+ data = base64.b64encode(file).decode("utf-8")
+ return [
+ Section(
+ content=DataBlock(
+ source=Base64Source(
+ media_type=media_type,
+ data=data,
+ ),
+ name=filename,
+ ),
+ source=filename,
+ metadata={"media_type": media_type},
+ ),
+ ]
diff --git a/src/agentscope/rag/_parser/_pdf.py b/src/agentscope/rag/_parser/_pdf.py
new file mode 100644
index 000000000..0a7d240c4
--- /dev/null
+++ b/src/agentscope/rag/_parser/_pdf.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+"""PDF file parser.
+
+One :class:`Section` per page so a downstream
+:class:`~agentscope.rag.ChunkerBase` never combines text across page
+boundaries. Each section's :attr:`Section.metadata` carries the
+page number (starting at 1) for later citation.
+"""
+import io
+
+from ...message import TextBlock
+from .._document import Section
+from ._base import ParserBase
+
+
+class PDFParser(ParserBase):
+ """Parser for PDF files.
+
+ Returns one :class:`Section` per page. Empty / image-only pages
+ still produce a Section (with empty text) so the page → section
+ correspondence stays exact — downstream chunkers naturally drop
+ empty content.
+
+ Requires :mod:`pypdf`; install with ``pip install pypdf`` (or via
+ the ``agentscope[rag]`` extra).
+ """
+
+ supported_media_types: list[str] = ["application/pdf"]
+
+ @classmethod
+ def supported_extensions(cls) -> list[str]:
+ """Return the canonical ``.pdf`` extension."""
+ return [".pdf"]
+
+ async def parse(
+ self,
+ file: bytes | str,
+ filename: str,
+ ) -> list[Section]:
+ """Read the PDF bytes and return one Section per page.
+
+ Args:
+ file (`bytes | str`):
+ Either the raw PDF bytes, or a filesystem path to
+ the PDF file.
+ filename (`str`):
+ The source filename, copied verbatim into each
+ Section's :attr:`Section.source` field.
+
+ Returns:
+ `list[Section]`:
+ One Section per page, in document order. Each
+ section's metadata holds ``{"page": <starting at 1>}``.
+
+ Raises:
+ `FileNotFoundError`: If ``file`` is a ``str`` pointing to
+ a path that does not exist.
+ `ImportError`: If :mod:`pypdf` is not installed.
+ `ValueError`: If the bytes cannot be parsed as PDF.
+ """
+ if isinstance(file, str):
+ with open(file, "rb") as fp:
+ file = fp.read()
+
+ try:
+ from pypdf import PdfReader
+ from pypdf.errors import PdfReadError
+ except ImportError as e:
+ raise ImportError(
+ "Please install pypdf to use the PDF parser. "
+ "You can install it by `pip install pypdf` (or "
+ "`pip install agentscope[rag]`).",
+ ) from e
+
+ try:
+ reader = PdfReader(io.BytesIO(file))
+ except PdfReadError as e:
+ raise ValueError(
+ f"Failed to parse {filename!r} as PDF: {e}",
+ ) from e
+
+ sections: list[Section] = []
+ for page_idx, page in enumerate(reader.pages, start=1):
+ text = page.extract_text() or ""
+ sections.append(
+ Section(
+ content=TextBlock(text=text),
+ source=filename,
+ metadata={"page": page_idx},
+ ),
+ )
+ return sections
diff --git a/src/agentscope/rag/_parser/_ppt.py b/src/agentscope/rag/_parser/_ppt.py
new file mode 100644
index 000000000..52bc2b481
--- /dev/null
+++ b/src/agentscope/rag/_parser/_ppt.py
@@ -0,0 +1,341 @@
+# -*- coding: utf-8 -*-
+"""PowerPoint (.pptx) file parser.
+
+Walks the deck slide-by-slide and emits one :class:`Section` per
+contiguous content block — adjacent text runs (and, by default,
+tables) are merged into a single text section; embedded images are
+emitted as their own :class:`DataBlock` sections. Each section's
+metadata carries the slide index (starting at 1) for later citation.
+
+Mirrors the knob set of the v1 ``PowerPointReader``:
+``include_image``, ``separate_table``, ``table_format``,
+``slide_prefix``, ``slide_suffix``. Chunking is **not** done here —
+long text stays intact inside a section and is split downstream by a
+:class:`~agentscope.rag.ChunkerBase`.
+"""
+import base64
+import io
+from typing import Any, Literal
+
+from ..._logging import logger
+from ...message import Base64Source, DataBlock, TextBlock
+from .._document import Section
+from ._base import ParserBase
+from ._utils import (
+ _guess_image_media_type,
+ _table_to_json,
+ _table_to_markdown,
+)
+
+
+def _extract_table_rows(table: Any) -> list[list[str]]:
+ """Read a python-pptx table into a 2-D ``list[list[str]]``.
+
+ Args:
+ table (`Any`):
+ The python-pptx ``Table`` object.
+
+ Returns:
+ `list[list[str]]`:
+ One inner list per row; per-cell line breaks are
+ normalised to ``\\n``.
+ """
+ rows: list[list[str]] = []
+ for row in table.rows:
+ cells: list[str] = []
+ for cell in row.cells:
+ text = cell.text.strip()
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
+ cells.append(text)
+ rows.append(cells)
+ return rows
+
+
+def _extract_image_bytes(shape: Any) -> bytes | None:
+ """Return the embedded image bytes for a picture shape, or ``None``.
+
+ Args:
+ shape (`Any`):
+ A python-pptx shape. Non-picture shapes return ``None``.
+
+ Returns:
+ `bytes | None`:
+ The raw image bytes, or ``None`` when ``shape`` is not a
+ picture / the bytes are unreadable.
+ """
+ try:
+ from pptx.enum.shapes import MSO_SHAPE_TYPE
+
+ picture_type = MSO_SHAPE_TYPE.PICTURE
+ except ImportError:
+ # MSO_SHAPE_TYPE.PICTURE numeric value used as the fallback
+ # so the parser still works against pptx builds where the
+ # enum import path has moved.
+ picture_type = 13
+
+ if shape.shape_type != picture_type:
+ return None
+ try:
+ return shape.image.blob
+ except Exception as e: # pylint: disable=broad-except
+ logger.warning("Failed to extract image from PPT shape: %s", e)
+ return None
+
+
+class PPTParser(ParserBase):
+ """Parser for PowerPoint ``.pptx`` files.
+
+ Slide order is preserved. Within a slide, shapes are visited in
+ document order and grouped into a minimum number of sections:
+
+ - **Text** shapes and **table** shapes contribute to one running
+ text section. When ``separate_table=True`` a table closes the
+ running section and starts a new one of its own.
+ - **Picture** shapes emit a standalone :class:`Section` whose
+ ``content`` is a :class:`DataBlock` holding the base64-encoded
+ image bytes.
+
+ ``slide_prefix`` / ``slide_suffix`` are wrapped around each
+ slide's text content (the prefix is prepended to the slide's
+ first text section, the suffix is appended to its last text
+ section). Use ``None`` on either to disable wrapping.
+ """
+
+ supported_media_types: list[str] = [
+ "application/vnd.openxmlformats-officedocument.presentationml"
+ ".presentation",
+ ]
+
+ @classmethod
+ def supported_extensions(cls) -> list[str]:
+ """Return ``[".pptx"]`` — the only format ``python-pptx``
+ reads."""
+ return [".pptx"]
+
+ def __init__(
+ self,
+ include_image: bool = True,
+ separate_table: bool = False,
+ table_format: Literal["markdown", "json"] = "markdown",
+ slide_prefix: str | None = "<slide index={index}>",
+ slide_suffix: str | None = "</slide>",
+ ) -> None:
+ """Initialize the PowerPoint parser.
+
+ Args:
+ include_image (`bool`, defaults to ``True``):
+ When ``True``, picture shapes are emitted as
+ :class:`DataBlock` sections. Set to ``False`` to keep
+ a text-only index.
+ separate_table (`bool`, defaults to ``False``):
+ When ``True``, each table becomes its own text
+ section, never merged with surrounding text.
+ table_format (`Literal["markdown", "json"]`, defaults to
+ ``"markdown"``):
+ How to render tables. ``"markdown"`` uses pipe-table
+ syntax; ``"json"`` emits a JSON array prefixed with a
+ ``<system-info>`` marker — choose JSON when cells
+ contain newlines that would corrupt Markdown layout.
+ slide_prefix (`str | None`, defaults to
+ ``"<slide index={index}>"``):
+ Prepended to the first text section of each slide.
+ Supports the ``{index}`` placeholder (starting at 1). Use
+ ``None`` to disable.
+ slide_suffix (`str | None`, defaults to ``"</slide>"``):
+ Appended to the last text section of each slide. Use
+ ``None`` to disable.
+
+ Raises:
+ `ValueError`: If ``table_format`` is not one of
+ ``"markdown"`` / ``"json"``.
+ """
+ if table_format not in ("markdown", "json"):
+ raise ValueError(
+ "The table_format must be one of 'markdown' or 'json', "
+ f"got {table_format!r}.",
+ )
+ self.include_image = include_image
+ self.separate_table = separate_table
+ self.table_format = table_format
+ self.slide_prefix = slide_prefix
+ self.slide_suffix = slide_suffix
+
+ async def parse(
+ self,
+ file: bytes | str,
+ filename: str,
+ ) -> list[Section]:
+ """Parse a PPTX file into a list of :class:`Section` objects.
+
+ Args:
+ file (`bytes | str`):
+ Either the raw PPTX bytes, or a filesystem path to
+ the PPTX file.
+ filename (`str`):
+ The source filename, copied into each Section's
+ :attr:`Section.source`.
+
+ Returns:
+ `list[Section]`:
+ Sections in deck order. Text sections carry
+ ``{"slide": <starting at 1>}``; image sections add
+ ``{"media_type": "image/..."}``.
+
+ Raises:
+ `FileNotFoundError`: If ``file`` is a ``str`` pointing to
+ a path that does not exist.
+ `ImportError`: If :mod:`python-pptx` is not installed.
+ `ValueError`: If the bytes cannot be parsed.
+ """
+ if isinstance(file, str):
+ with open(file, "rb") as fp:
+ file = fp.read()
+
+ try:
+ from pptx import Presentation
+ except ImportError as e:
+ raise ImportError(
+ "Please install python-pptx to use the PowerPoint "
+ "parser. You can install it by "
+ "`pip install python-pptx` (or "
+ "`pip install agentscope[rag]`).",
+ ) from e
+
+ try:
+ prs = Presentation(io.BytesIO(file))
+ except Exception as e: # pylint: disable=broad-except
+ raise ValueError(
+ f"Failed to parse {filename!r} as PPTX: {e}",
+ ) from e
+
+ sections: list[Section] = []
+ for slide_idx, slide in enumerate(prs.slides):
+ sections.extend(
+ self._parse_slide(slide, slide_idx, filename),
+ )
+ return sections
+
+ # ------------------------------------------------------------------
+ # Slide-level parsing
+ # ------------------------------------------------------------------
+
+ def _parse_slide(
+ self,
+ slide: Any,
+ slide_idx: int,
+ filename: str,
+ ) -> list[Section]:
+ """Walk one slide and return its ordered sections."""
+ slide_no = slide_idx + 1
+ prefix = (
+ self.slide_prefix.format(index=slide_no)
+ if self.slide_prefix is not None
+ else ""
+ )
+
+ slide_sections: list[Section] = []
+ # ``text_buffer`` accumulates the running text section; it is
+ # flushed whenever an image arrives, the slide ends, or
+ # ``separate_table`` forces a break around a table shape.
+ text_buffer: list[str] = []
+
+ def flush_text() -> None:
+ if not text_buffer:
+ return
+ slide_sections.append(
+ Section(
+ content=TextBlock(text="\n".join(text_buffer)),
+ source=filename,
+ metadata={"slide": slide_no},
+ ),
+ )
+ text_buffer.clear()
+
+ # Slide prefix lives at the very top of the first text section.
+ if prefix:
+ text_buffer.append(prefix)
+
+ for shape in slide.shapes:
+ # 1. Pictures — flush running text, emit a DataBlock section.
+ if self.include_image:
+ image_bytes = _extract_image_bytes(shape)
+ if image_bytes is not None:
+ flush_text()
+ media_type = _guess_image_media_type(image_bytes)
+ data = base64.b64encode(image_bytes).decode("utf-8")
+ slide_sections.append(
+ Section(
+ content=DataBlock(
+ source=Base64Source(
+ media_type=media_type,
+ data=data,
+ ),
+ name=filename,
+ ),
+ source=filename,
+ metadata={
+ "slide": slide_no,
+ "media_type": media_type,
+ },
+ ),
+ )
+ continue
+
+ # 2. Tables — render to text; optionally flush around them.
+ if getattr(shape, "has_table", False):
+ try:
+ rows = _extract_table_rows(shape.table)
+ except Exception as e: # pylint: disable=broad-except
+ logger.warning(
+ "Failed to extract table from slide %d: %s",
+ slide_no,
+ e,
+ )
+ continue
+ rendered = (
+ _table_to_markdown(rows)
+ if self.table_format == "markdown"
+ else _table_to_json(rows)
+ )
+ if not rendered:
+ continue
+ if self.separate_table:
+ flush_text()
+ slide_sections.append(
+ Section(
+ content=TextBlock(text=rendered),
+ source=filename,
+ metadata={"slide": slide_no},
+ ),
+ )
+ else:
+ text_buffer.append(rendered)
+ continue
+
+ # 3. Text frames.
+ if getattr(shape, "has_text_frame", False):
+ try:
+ parts = [
+ para.text.strip()
+ for para in shape.text_frame.paragraphs
+ if para.text.strip()
+ ]
+ except Exception as e: # pylint: disable=broad-except
+ logger.warning(
+ "Failed to extract text from shape in slide %d: %s",
+ slide_no,
+ e,
+ )
+ continue
+ if parts:
+ text_buffer.append("\n".join(parts))
+
+ # Suffix goes onto the last text section of this slide. If the
+ # slide ends on an image (text_buffer empty, no prior text
+ # section in this slide), create a small text-only carrier so
+ # the suffix is preserved.
+ if self.slide_suffix is not None:
+ text_buffer.append(self.slide_suffix)
+
+ flush_text()
+ return slide_sections
diff --git a/src/agentscope/rag/_parser/_text.py b/src/agentscope/rag/_parser/_text.py
new file mode 100644
index 000000000..6fd41161a
--- /dev/null
+++ b/src/agentscope/rag/_parser/_text.py
@@ -0,0 +1,125 @@
+# -*- coding: utf-8 -*-
+"""Plain-text file parser."""
+import os
+
+from ...message import TextBlock
+from .._document import Section
+from ._base import ParserBase
+
+
+class TextParser(ParserBase):
+ """Parser for plain-text file formats.
+
+ Reads the entire file as UTF-8 text and returns a single
+ :class:`Section`. No internal boundaries are inferred — the file
+ is treated as one unstructured blob, leaving all splitting to a
+ downstream :class:`~agentscope.rag.ChunkerBase`.
+
+ Supports a fixed set of standard text-based IANA media types
+ (``text/plain``, ``text/markdown``, ``text/csv``, …). Use
+ ``TextParser.supported_media_types`` to enumerate them.
+ """
+
+ supported_media_types: list[str] = [
+ "text/plain",
+ "text/markdown",
+ "text/csv",
+ "text/html",
+ "text/x-rst",
+ "application/json",
+ "application/xml",
+ "application/x-yaml",
+ ]
+ """Standard IANA media types this parser handles."""
+
+ @classmethod
+ def supported_extensions(cls) -> list[str]:
+ """Return the human-friendly text extensions.
+
+ Override the base reverse-lookup because
+ :func:`mimetypes.guess_all_extensions` returns a long tail of
+ developer-tool extensions for ``text/plain`` (``.bat`` /
+ ``.c`` / ``.pl`` / ``.ksh`` / …) that have no place in a KB
+ file picker, and returns the empty list for
+ ``application/x-yaml``.
+ """
+ return [
+ ".csv",
+ ".htm",
+ ".html",
+ ".json",
+ ".markdown",
+ ".md",
+ ".rst",
+ ".txt",
+ ".xml",
+ ".yaml",
+ ".yml",
+ ]
+
+ def __init__(self, encoding: str = "utf-8") -> None:
+ """Initialize the text parser.
+
+ Args:
+ encoding (`str`, defaults to ``"utf-8"``):
+ The text encoding used to decode the file bytes.
+ """
+ self.encoding = encoding
+
+ async def parse(
+ self,
+ file: bytes | str,
+ filename: str,
+ ) -> list[Section]:
+ """Read the file as text and return a single :class:`Section`.
+
+ Args:
+ file (`bytes | str`):
+ The file content. ``bytes`` is decoded with the
+ configured encoding. ``str`` is disambiguated at
+ runtime: if it names an existing file on disk the
+ file is read and decoded; otherwise it is used
+ verbatim as pre-decoded text — letting local-mode
+ callers skip the encode → decode round trip.
+ filename (`str`):
+ The source filename, copied verbatim into
+ :attr:`Section.source`.
+
+ Returns:
+ `list[Section]`:
+ Always a one-element list containing the entire file
+ contents.
+
+ Raises:
+ `ValueError`: If the bytes cannot be decoded with the
+ configured encoding.
+ """
+ if isinstance(file, str):
+ if os.path.isfile(file):
+ with open(file, "rb") as fp:
+ raw = fp.read()
+ try:
+ text = raw.decode(self.encoding)
+ except UnicodeDecodeError as e:
+ raise ValueError(
+ f"Failed to decode {filename!r} as "
+ f"{self.encoding!r}: {e}",
+ ) from e
+ else:
+ text = file
+ else:
+ try:
+ text = file.decode(self.encoding)
+ except UnicodeDecodeError as e:
+ raise ValueError(
+ f"Failed to decode {filename!r} as "
+ f"{self.encoding!r}: {e}",
+ ) from e
+
+ return [
+ Section(
+ content=TextBlock(text=text),
+ source=filename,
+ metadata={},
+ ),
+ ]
diff --git a/src/agentscope/rag/_parser/_utils.py b/src/agentscope/rag/_parser/_utils.py
new file mode 100644
index 000000000..bff8f45f1
--- /dev/null
+++ b/src/agentscope/rag/_parser/_utils.py
@@ -0,0 +1,99 @@
+# -*- coding: utf-8 -*-
+"""Shared helpers for binary parsers.
+
+Three small utilities used by :class:`PDFParser`, :class:`ImageParser`,
+and :class:`PPTParser`:
+
+- :func:`_guess_image_media_type` — sniff the IANA media type from raw
+ image bytes by looking at the magic number. Used to populate the
+ ``media_type`` field of :class:`Base64Source` for embedded images.
+- :func:`_table_to_markdown` — render a 2-D ``list[list[str]]`` as a
+ Markdown pipe-table; the default rendering for table content.
+- :func:`_table_to_json` — render the same shape as a JSON array
+ prefixed with a one-line ``<system-info>`` marker; used when the
+ caller picks ``table_format="json"`` to avoid Markdown's
+ multi-line-cell ambiguity.
+"""
+import json
+
+
+def _guess_image_media_type(data: bytes) -> str:
+ """Sniff the IANA media type of an image from its magic number.
+
+ Args:
+ data (`bytes`):
+ The raw image bytes.
+
+ Returns:
+ `str`:
+ The IANA media type (e.g. ``"image/png"``). Falls back to
+ ``"image/jpeg"`` when no signature matches — JPEG is the
+ most permissive default and matches what every consumer can
+ decode.
+ """
+ signatures = {
+ b"\x89PNG\r\n\x1a\n": "image/png",
+ b"\xff\xd8": "image/jpeg",
+ b"GIF87a": "image/gif",
+ b"GIF89a": "image/gif",
+ b"BM": "image/bmp",
+ }
+ for signature, media_type in signatures.items():
+ if data.startswith(signature):
+ return media_type
+ # WebP: ``RIFF`` at offset 0 + ``WEBP`` at offset 8.
+ if len(data) > 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "image/webp"
+ return "image/jpeg"
+
+
+def _table_to_markdown(table_data: list[list[str]]) -> str:
+ """Render a 2-D table as a Markdown pipe-table.
+
+ Args:
+ table_data (`list[list[str]]`):
+ The table data; ``table_data[0]`` is the header row.
+
+ Returns:
+ `str`:
+ The Markdown rendering, or the empty string when
+ ``table_data`` is empty / column-less.
+ """
+ if not table_data:
+ return ""
+
+ num_cols = len(table_data[0])
+ if num_cols == 0:
+ return ""
+
+ lines = [
+ "| " + " | ".join(table_data[0]) + " |",
+ "| " + " | ".join(["---"] * num_cols) + " |",
+ ]
+ for row in table_data[1:]:
+ # Pad short rows so column counts match the header.
+ padded = list(row) + [""] * max(0, num_cols - len(row))
+ lines.append("| " + " | ".join(padded[:num_cols]) + " |")
+ return "\n".join(lines) + "\n"
+
+
+def _table_to_json(table_data: list[list[str]]) -> str:
+ """Render a 2-D table as JSON prefixed by a one-line marker.
+
+ The ``<system-info>`` marker lets the LLM (and any
+ structure-aware downstream renderer) tell at a glance that this
+ block is tabular data, not free text — which is otherwise
+ indistinguishable from a raw JSON dump in the middle of a chunk.
+
+ Args:
+ table_data (`list[list[str]]`):
+ The table data.
+
+ Returns:
+ `str`:
+ ``"<system-info>...</system-info>\\n<json>"``.
+ """
+ return (
+ "<system-info>A table loaded as a JSON array:</system-info>\n"
+ + json.dumps(table_data, ensure_ascii=False)
+ )
diff --git a/src/agentscope/rag/_vdb/__init__.py b/src/agentscope/rag/_vdb/__init__.py
new file mode 100644
index 000000000..95cde6164
--- /dev/null
+++ b/src/agentscope/rag/_vdb/__init__.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+"""The vector store classes in AgentScope."""
+
+from ._vector_store import (
+ DocumentSummary,
+ VectorRecord,
+ VectorSearchResult,
+ VectorStoreBase,
+)
+from ._qdrant import QdrantStore
+
+__all__ = [
+ "DocumentSummary",
+ "VectorStoreBase",
+ "VectorRecord",
+ "VectorSearchResult",
+ "QdrantStore",
+]
diff --git a/src/agentscope/rag/_vdb/_qdrant.py b/src/agentscope/rag/_vdb/_qdrant.py
new file mode 100644
index 000000000..3fc44b082
--- /dev/null
+++ b/src/agentscope/rag/_vdb/_qdrant.py
@@ -0,0 +1,392 @@
+# -*- coding: utf-8 -*-
+"""Qdrant implementation of the vector store backend.
+
+Built on the official ``qdrant-client`` SDK using its fully
+asynchronous client (:class:`~qdrant_client.AsyncQdrantClient`), so all
+operations are non-blocking and safe to call from the application's
+event loop.
+
+The same class supports all Qdrant deployment modes through the
+constructor arguments:
+
+- ``location=":memory:"`` — in-process, ephemeral (ideal for tests)
+- ``path="/path/to/db"`` — in-process, persisted to local disk
+- ``url="http://localhost:6333"`` — remote Qdrant server / cloud
+"""
+import uuid
+from typing import TYPE_CHECKING, Any, Literal
+
+from ._vector_store import (
+ DocumentSummary,
+ VectorRecord,
+ VectorSearchResult,
+ VectorStoreBase,
+)
+from .._document import Chunk
+
+if TYPE_CHECKING:
+ from qdrant_client import AsyncQdrantClient
+
+
+class QdrantStore(VectorStoreBase):
+ """Vector store backend backed by `Qdrant <https://qdrant.tech>`_.
+
+ Each knowledge base maps to one Qdrant collection. Every point
+ payload stores the owning ``document_id`` plus the serialized
+ :class:`~agentscope.rag.Chunk`, which is reconstructed on
+ retrieval.
+
+ .. note:: The ``qdrant-client`` package is required. Install it
+ with ``pip install qdrant-client``.
+
+ .. code-block:: python
+
+ # In-memory (tests / prototyping)
+ store = QdrantStore(location=":memory:")
+
+ # Remote server
+ store = QdrantStore(
+ url="http://localhost:6333",
+ api_key="...",
+ )
+
+ async with store:
+ await store.create_collection("kb-1", dimensions=768)
+
+ """
+
+ def __init__(
+ self,
+ location: str | None = None,
+ url: str | None = None,
+ path: str | None = None,
+ api_key: str | None = None,
+ distance: Literal["Cosine", "Dot", "Euclid", "Manhattan"] = "Cosine",
+ client_kwargs: dict[str, Any] | None = None,
+ ) -> None:
+ """Initialize the Qdrant vector store.
+
+ Args:
+ location (`str | None`, optional):
+ Pass ``":memory:"`` for an ephemeral in-process
+ instance. Mutually exclusive with ``url`` and ``path``.
+ url (`str | None`, optional):
+ The URL of a remote Qdrant server, e.g.
+ ``"http://localhost:6333"``.
+ path (`str | None`, optional):
+ A local directory for an in-process, on-disk instance.
+ api_key (`str | None`, optional):
+ The API key for Qdrant Cloud or a secured server.
+ distance (`Literal["Cosine", "Dot", "Euclid", "Manhattan"]`, \
+ defaults to ``"Cosine"``):
+ The distance metric used when creating collections.
+ client_kwargs (`dict[str, Any] | None`, optional):
+ Extra keyword arguments forwarded to
+ :class:`~qdrant_client.AsyncQdrantClient`.
+ """
+ self._location = location
+ self._url = url
+ self._path = path
+ self._api_key = api_key
+ self._distance = distance
+ self._client_kwargs = client_kwargs or {}
+ self._client: "AsyncQdrantClient | None" = None
+
+ def get_client(self) -> "AsyncQdrantClient":
+ """Lazily create and cache the async Qdrant client.
+
+ Returns:
+ `AsyncQdrantClient`:
+ The shared async client instance.
+ """
+ if self._client is None:
+ from qdrant_client import AsyncQdrantClient
+
+ self._client = AsyncQdrantClient(
+ location=self._location,
+ url=self._url,
+ path=self._path,
+ api_key=self._api_key,
+ **self._client_kwargs,
+ )
+ return self._client
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: Any,
+ ) -> None:
+ """Exit the async context — close the underlying client."""
+ if self._client is not None:
+ await self._client.close()
+ self._client = None
+
+ # ------------------------------------------------------------------
+ # Collection management
+ # ------------------------------------------------------------------
+
+ async def create_collection(
+ self,
+ name: str,
+ dimensions: int,
+ ) -> None:
+ """Create a new Qdrant collection.
+
+ No-op if the collection already exists.
+
+ Args:
+ name (`str`):
+ The collection name. Typically, the knowledge base ID.
+ dimensions (`int`):
+ The fixed vector dimensionality for this collection.
+ """
+ from qdrant_client import models
+
+ client = self.get_client()
+ if await client.collection_exists(name):
+ return
+ await client.create_collection(
+ collection_name=name,
+ vectors_config=models.VectorParams(
+ size=dimensions,
+ distance=models.Distance(self._distance),
+ ),
+ )
+
+ async def delete_collection(self, name: str) -> None:
+ """Delete a collection and all its data.
+
+ Args:
+ name (`str`):
+ The collection name to delete.
+ """
+ await self.get_client().delete_collection(name)
+
+ async def has_collection(self, name: str) -> bool:
+ """Check whether a collection exists.
+
+ Args:
+ name (`str`):
+ The collection name to check.
+
+ Returns:
+ `bool`: ``True`` if the collection exists.
+ """
+ return await self.get_client().collection_exists(name)
+
+ # ------------------------------------------------------------------
+ # Data operations
+ # ------------------------------------------------------------------
+
+ async def insert(
+ self,
+ collection: str,
+ records: list[VectorRecord],
+ ) -> None:
+ """Insert records into a collection.
+
+ Each point payload stores the :attr:`VectorRecord.document_id`
+ under the ``document_id`` key and the serialized
+ :class:`Chunk` under the ``chunk`` key, so that :meth:`delete`
+ can remove all records of one document.
+
+ Args:
+ collection (`str`):
+ The target collection name.
+ records (`list[VectorRecord]`):
+ The records to insert (each carrying a
+ :class:`Chunk` and its embedding vector).
+ """
+
+ from qdrant_client import models
+
+ if not records:
+ return
+ await self.get_client().upsert(
+ collection_name=collection,
+ points=[
+ models.PointStruct(
+ id=str(uuid.uuid4()),
+ vector=record.vector,
+ payload={
+ "document_id": record.document_id,
+ "chunk": record.chunk.model_dump(mode="json"),
+ },
+ )
+ for record in records
+ ],
+ )
+
+ async def delete(
+ self,
+ collection: str,
+ document_id: str,
+ ) -> None:
+ """Delete all records belonging to one source document.
+
+ Matches the ``document_id`` payload key written by
+ :meth:`insert` from :attr:`VectorRecord.document_id`.
+
+ Args:
+ collection (`str`):
+ The target collection name.
+ document_id (`str`):
+ The source document ID whose records should be
+ removed.
+ """
+ from qdrant_client import models
+
+ await self.get_client().delete(
+ collection_name=collection,
+ points_selector=models.FilterSelector(
+ filter=models.Filter(
+ must=[
+ models.FieldCondition(
+ key="document_id",
+ match=models.MatchValue(value=document_id),
+ ),
+ ],
+ ),
+ ),
+ )
+
+ # ------------------------------------------------------------------
+ # Search
+ # ------------------------------------------------------------------
+
+ async def search(
+ self,
+ collection: str,
+ query_vector: list[float],
+ top_k: int = 5,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[VectorSearchResult]:
+ """Find the most similar records to a query vector.
+
+ Args:
+ collection (`str`):
+ The collection to search.
+ query_vector (`list[float]`):
+ The query embedding vector.
+ top_k (`int`, defaults to ``5``):
+ Maximum number of results to return.
+ metadata_filter (`dict[str, Any] | None`, optional):
+ If provided, restrict the search to records whose
+ ``chunk.metadata`` matches every ``key == value`` pair
+ in this dict (translated into a Qdrant ``must`` payload
+ filter against ``chunk.metadata.<key>``).
+
+ Returns:
+ `list[VectorSearchResult]`:
+ Results ordered by descending similarity score.
+ """
+ response = await self.get_client().query_points(
+ collection_name=collection,
+ query=query_vector,
+ limit=top_k,
+ with_payload=True,
+ query_filter=self._build_metadata_filter(metadata_filter),
+ )
+ return [
+ VectorSearchResult(
+ score=point.score,
+ document_id=point.payload["document_id"],
+ chunk=Chunk.model_validate(point.payload["chunk"]),
+ )
+ for point in response.points
+ ]
+
+ # ------------------------------------------------------------------
+ # Document listing
+ # ------------------------------------------------------------------
+
+ async def list_documents(
+ self,
+ collection: str,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[DocumentSummary]:
+ """List all distinct source documents indexed in a collection.
+
+ Scrolls the collection in payload-only mode (vectors disabled)
+ and aggregates by ``document_id``. The first chunk encountered
+ for each document supplies the ``source`` filename and the
+ document-level ``metadata``.
+
+ Args:
+ collection (`str`):
+ The target collection name.
+ metadata_filter (`dict[str, Any] | None`, optional):
+ If provided, restrict aggregation to records whose
+ ``chunk.metadata`` matches every ``key == value`` pair.
+
+ Returns:
+ `list[DocumentSummary]`:
+ One summary per distinct ``document_id``.
+ """
+ client = self.get_client()
+ query_filter = self._build_metadata_filter(metadata_filter)
+ summaries: dict[str, DocumentSummary] = {}
+ offset: Any = None
+
+ while True:
+ points, next_offset = await client.scroll(
+ collection_name=collection,
+ scroll_filter=query_filter,
+ limit=256,
+ offset=offset,
+ with_payload=True,
+ with_vectors=False,
+ )
+ for point in points:
+ doc_id = point.payload["document_id"]
+ summary = summaries.get(doc_id)
+ if summary is None:
+ chunk_payload = point.payload["chunk"]
+ summaries[doc_id] = DocumentSummary(
+ document_id=doc_id,
+ source=chunk_payload.get("source", ""),
+ chunk_count=1,
+ metadata=dict(chunk_payload.get("metadata", {})),
+ )
+ else:
+ summary.chunk_count += 1
+ if next_offset is None:
+ break
+ offset = next_offset
+
+ return list(summaries.values())
+
+ @staticmethod
+ def _build_metadata_filter(
+ metadata_filter: dict[str, Any] | None,
+ ) -> Any:
+ """Translate a flat ``{key: value}`` filter into a Qdrant filter.
+
+ Each ``key`` is matched against the corresponding nested path
+ ``chunk.metadata.<key>`` written by :meth:`insert`. Returns
+ ``None`` when ``metadata_filter`` is empty so that callers
+ skip the filter argument entirely.
+
+ Args:
+ metadata_filter (`dict[str, Any] | None`):
+ The flat filter, or ``None`` for no filter.
+
+ Returns:
+ `qdrant_client.models.Filter | None`:
+ A Qdrant ``Filter`` object, or ``None``.
+ """
+ if not metadata_filter:
+ return None
+
+ from qdrant_client import models
+
+ return models.Filter(
+ must=[
+ models.FieldCondition(
+ key=f"chunk.metadata.{key}",
+ match=models.MatchValue(value=value),
+ )
+ for key, value in metadata_filter.items()
+ ],
+ )
diff --git a/src/agentscope/rag/_vdb/_vector_store.py b/src/agentscope/rag/_vdb/_vector_store.py
new file mode 100644
index 000000000..e491c701a
--- /dev/null
+++ b/src/agentscope/rag/_vdb/_vector_store.py
@@ -0,0 +1,291 @@
+# -*- coding: utf-8 -*-
+"""Abstract base class for vector store backends.
+
+A :class:`VectorStoreBase` instance is the single connection point to
+one vector database deployment. It is created once at application
+startup, passed into ``create_app(vector_store=...)``, and shared
+across all requests for the lifetime of the process — similar to
+:class:`~agentscope.app.storage.StorageBase` and
+:class:`~agentscope.app.message_bus.MessageBus`.
+
+Each **knowledge base** maps to one **collection** inside the vector
+store. Collections are isolated: different knowledge bases never
+share a collection, so retrieval is always scoped to a single
+collection without cross-collection filtering.
+
+Lifecycle is managed via the async context manager protocol
+(``__aenter__`` / ``__aexit__``), which the app lifespan calls
+automatically.
+"""
+from abc import ABC, abstractmethod
+from typing import Any, Self
+
+from pydantic import BaseModel, Field
+
+from .._document import Chunk
+
+
+class VectorRecord(BaseModel):
+ """A single record to insert into a vector store collection.
+
+ Pairs a :class:`Chunk` (the business payload — content, source,
+ structural metadata) with its dense embedding vector. ``Chunk``
+ is intentionally not extended with an ``embedding`` field so its
+ semantics stay stable across the indexing pipeline; instead the
+ vector lives in this wrapper whose only purpose is "I am about
+ to be inserted into a vector database."
+ """
+
+ vector: list[float]
+ """The dense embedding vector for :attr:`chunk`."""
+
+ document_id: str
+ """The ID of the source document this record belongs to.
+ Assigned by the knowledge base layer when the document is
+ registered. Backends must persist it at insertion time so that
+ :meth:`VectorStoreBase.delete` can remove all records of one
+ document as a unit."""
+
+ chunk: Chunk
+ """The business payload — content, source, structural metadata."""
+
+
+class VectorSearchResult(BaseModel):
+ """A single result returned by a similarity search.
+
+ Pairs the matched :class:`Chunk` with its similarity score.
+ ``Chunk`` is intentionally not extended with a ``score`` field so
+ its semantics stay stable; instead the score lives in this
+ wrapper whose only purpose is "I am a query hit."
+ """
+
+ score: float
+ """Similarity score. Higher = more similar for cosine /
+ dot-product; lower = more similar for L2 distance."""
+
+ document_id: str
+ """The ID of the source document the matched chunk belongs to —
+ the same value carried by :attr:`VectorRecord.document_id` at
+ insertion time. Lets callers cite, group, or delete the source
+ document of a hit."""
+
+ chunk: Chunk
+ """The matched business payload."""
+
+
+class DocumentSummary(BaseModel):
+ """A lightweight description of one source document inside a collection.
+
+ Aggregated by :meth:`VectorStoreBase.list_documents` from the
+ records of each ``document_id`` — the vector store is the single
+ source of truth for "what documents exist in a knowledge base".
+ """
+
+ document_id: str
+ """The source document identifier — the same value carried by
+ :attr:`VectorRecord.document_id` at insertion time."""
+
+ source: str
+ """The original filename, taken from the first chunk encountered.
+ All chunks of the same document share the same filename so any
+ chunk yields the same value."""
+
+ chunk_count: int
+ """The total number of chunks indexed for this document."""
+
+ metadata: dict[str, Any] = Field(default_factory=dict)
+ """Document-level metadata propagated from the parser / uploader
+ (media type, size, upload time, ...). Taken from the first chunk
+ encountered."""
+
+
+class VectorStoreBase(ABC):
+ """Abstract base class for vector store backends.
+
+ Subclasses implement the concrete connection and query logic for a
+ specific vector database (Chroma, Milvus, Qdrant, FAISS, etc.).
+
+ A single instance is shared across the entire application. The
+ underlying client SDK is expected to handle connection pooling and
+ thread safety internally.
+ """
+
+ # ------------------------------------------------------------------
+ # Lifecycle
+ # ------------------------------------------------------------------
+
+ async def __aenter__(self) -> Self:
+ """Enter the async context — open connections if needed.
+
+ The default implementation is a no-op. Subclasses that need
+ explicit connection setup should override this.
+
+ Returns:
+ `VectorStoreBase`: ``self``.
+ """
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: Any,
+ ) -> None:
+ """Exit the async context — close connections if needed.
+
+ The default implementation is a no-op.
+ """
+
+ # ------------------------------------------------------------------
+ # Collection management
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def create_collection(
+ self,
+ name: str,
+ dimensions: int,
+ ) -> None:
+ """Create a new collection (vector index).
+
+ If the collection already exists, implementations should raise
+ or silently no-op depending on the backend's semantics.
+
+ Args:
+ name (`str`):
+ The collection name. Typically, the knowledge base ID.
+ dimensions (`int`):
+ The fixed vector dimensionality for this collection.
+ All vectors inserted later must have this many elements.
+ """
+
+ @abstractmethod
+ async def delete_collection(self, name: str) -> None:
+ """Delete a collection and all its data.
+
+ Args:
+ name (`str`):
+ The collection name to delete.
+ """
+
+ @abstractmethod
+ async def has_collection(self, name: str) -> bool:
+ """Check whether a collection exists.
+
+ Args:
+ name (`str`):
+ The collection name to check.
+
+ Returns:
+ `bool`: ``True`` if the collection exists.
+ """
+
+ # ------------------------------------------------------------------
+ # Data operations
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def insert(
+ self,
+ collection: str,
+ records: list[VectorRecord],
+ ) -> None:
+ """Insert records into a collection.
+
+ Args:
+ collection (`str`):
+ The target collection name.
+ records (`list[VectorRecord]`):
+ The records to insert (each carrying a
+ :class:`Chunk` and its embedding vector).
+ """
+
+ @abstractmethod
+ async def delete(
+ self,
+ collection: str,
+ document_id: str,
+ ) -> None:
+ """Delete all records belonging to one source document.
+
+ Identifies records by the :attr:`VectorRecord.document_id`
+ field that backends persist at insertion time. This matches
+ the typical RAG workflow where a user uploads or removes a
+ file as a unit.
+
+ Args:
+ collection (`str`):
+ The target collection name.
+ document_id (`str`):
+ The source document ID whose records should be
+ removed.
+ """
+
+ # ------------------------------------------------------------------
+ # Search
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def search(
+ self,
+ collection: str,
+ query_vector: list[float],
+ top_k: int = 5,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[VectorSearchResult]:
+ """Find the most similar records to a query vector.
+
+ Args:
+ collection (`str`):
+ The collection to search.
+ query_vector (`list[float]`):
+ The query embedding vector.
+ top_k (`int`, defaults to ``5``):
+ Maximum number of results to return.
+ metadata_filter (`dict[str, Any] | None`, optional):
+ If provided, restrict the search to records whose
+ ``chunk.metadata`` matches every ``key == value`` pair
+ in this dict. Backends translate this into a native
+ payload filter. Used for defense-in-depth
+ cross-tenant scoping when an isolation strategy
+ co-locates multiple knowledge bases inside the same
+ collection.
+
+ Returns:
+ `list[VectorSearchResult]`:
+ Results ordered by descending similarity score.
+ """
+
+ # ------------------------------------------------------------------
+ # Document listing
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ async def list_documents(
+ self,
+ collection: str,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[DocumentSummary]:
+ """List all distinct source documents indexed in a collection.
+
+ Aggregates records by :attr:`VectorRecord.document_id` and
+ returns one :class:`DocumentSummary` per document. Backends
+ are free to use whatever scrolling / aggregation primitive
+ they expose; this method is expected to be O(documents) not
+ O(chunks) on backends that support payload-only scans.
+
+ Args:
+ collection (`str`):
+ The target collection name.
+ metadata_filter (`dict[str, Any] | None`, optional):
+ If provided, restrict aggregation to records whose
+ ``chunk.metadata`` matches every ``key == value`` pair
+ in this dict. Used together with the search-time
+ filter when an isolation strategy co-locates multiple
+ knowledge bases inside the same collection.
+
+ Returns:
+ `list[DocumentSummary]`:
+ One summary per distinct ``document_id``, in
+ unspecified order.
+ """
diff --git a/src/agentscope/state/_state.py b/src/agentscope/state/_state.py
index 6f08b2fff..3e5f216b4 100644
--- a/src/agentscope/state/_state.py
+++ b/src/agentscope/state/_state.py
@@ -8,7 +8,14 @@ import aiofiles.os
from .._utils._common import _generate_id
from ._task import Task
-from ..message import TextBlock, DataBlock, Msg
+from ..message import (
+ TextBlock,
+ DataBlock,
+ Msg,
+ ToolCallBlock,
+ ToolResultBlock,
+ HintBlock,
+)
from ..permission import PermissionContext
@@ -182,3 +189,33 @@ class AgentState(BaseModel):
middle_context: dict[str, Any] = Field(default_factory=dict)
"""The context that allow the middlewares to store/get data across
different replies."""
+
+ def append_context(
+ self,
+ name: str,
+ blocks: list[
+ TextBlock | DataBlock | HintBlock | ToolCallBlock | ToolResultBlock
+ ],
+ ) -> None:
+ """Append the given blocks to the agent's own message with the current
+ `reply_id`. If such message doesn't exist, a new assistant message
+ with agent's name and current reply ID will be created.
+ """
+ # If append to the latest message
+ if (
+ self.context
+ and self.context[-1].role == "assistant"
+ and self.context[-1].name == name
+ and self.context[-1].id == self.reply_id
+ ):
+ self.context[-1].content.extend(blocks)
+ else:
+ # Create a new assistant message with the current reply ID
+ self.context.append(
+ Msg(
+ id=self.reply_id,
+ role="assistant",
+ name=name,
+ content=blocks,
+ ),
+ )
diff --git a/tests/app_lifespan_dedicated_test.py b/tests/app_lifespan_dedicated_test.py
new file mode 100644
index 000000000..05d33ce2c
--- /dev/null
+++ b/tests/app_lifespan_dedicated_test.py
@@ -0,0 +1,332 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""End-to-end wiring test for dedicated-deployment knowledge-base upload.
+
+Boots the FastAPI app with ``enable_index_worker=False`` so the API
+process does NOT host an :class:`IndexWorker`. Dispatch happens
+through the message bus: a ``MessageBusDispatcher`` writes the task
+to the shared queue and publishes the signal. In a real deployment
+a separate worker process would pick it up; here we run an
+:class:`IndexTaskConsumer` against a stub worker inside the test
+to confirm the producer side reaches the bus correctly.
+
+What this test guards:
+
+- the API's lifespan accepts ``enable_index_worker=False`` without
+ raising;
+- an upload returns ``201`` and persists a ``pending`` record;
+- the message bus carries the dispatch out of the API process so
+ a worker subscribed on the same bus can consume it;
+- the consumer's ``worker.process`` is invoked exactly once per
+ dispatch, with the same ids the API recorded in storage.
+
+We deliberately do NOT drive the document to ``ready`` here — that
+path is already covered by the embedded-mode upload test. The
+purpose of this test is to lock down the bus hop introduced by
+:class:`MessageBusDispatcher`.
+"""
+import asyncio
+import tempfile
+from typing import Any
+from unittest.async_case import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+from fastapi.testclient import TestClient
+
+from agentscope.app import create_app
+from agentscope.app._service import IndexTaskConsumer
+from agentscope.app.rag.blob_store import LocalBlobStore
+from agentscope.app.rag.knowledge_base_manager import (
+ KnowledgeBaseManagerBase,
+ KnowledgeBaseNotFoundError,
+)
+from agentscope.app.rag.knowledge_base_manager._dimension_policy import (
+ DimensionPolicy,
+ DimensionPolicyKind,
+)
+from agentscope.app.message_bus import RedisMessageBus
+from agentscope.app.storage import (
+ EmbeddingModelConfig,
+ KnowledgeBaseRecord,
+ RedisStorage,
+)
+from agentscope.app.workspace_manager._base import WorkspaceManagerBase
+from agentscope.rag import VectorStoreBase
+from agentscope.rag._vdb._vector_store import (
+ DocumentSummary,
+ VectorRecord,
+ VectorSearchResult,
+)
+
+
+# ----------------------------------------------------------------------
+# Test doubles — borrowed in spirit from service_knowledge_base_upload_test
+# but trimmed: the dedicated-mode test does not drive embedding.
+# ----------------------------------------------------------------------
+
+
+class _FakeVectorStore(VectorStoreBase):
+ """Bare minimum to satisfy create_app's vector-store wiring."""
+
+ def __init__(self) -> None:
+ self._collections: dict[str, list[VectorRecord]] = {}
+
+ async def create_collection(self, name: str, dimensions: int) -> None:
+ self._collections.setdefault(name, [])
+
+ async def delete_collection(self, name: str) -> None:
+ self._collections.pop(name, None)
+
+ async def has_collection(self, name: str) -> bool:
+ return name in self._collections
+
+ async def insert(
+ self,
+ collection: str,
+ records: list[VectorRecord],
+ ) -> None:
+ self._collections.setdefault(collection, []).extend(records)
+
+ async def delete(self, collection: str, document_id: str) -> None:
+ self._collections[collection] = [
+ r
+ for r in self._collections.get(collection, [])
+ if r.document_id != document_id
+ ]
+
+ async def search(
+ self,
+ collection: str,
+ query_vector: list[float],
+ top_k: int = 5,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[VectorSearchResult]:
+ return []
+
+ async def list_documents(
+ self,
+ collection: str,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[DocumentSummary]:
+ return []
+
+
+class _FakeKbManager(KnowledgeBaseManagerBase):
+ """KB manager that resolves knowledge bases via storage only.
+
+ Returns a noop knowledge for ``get_knowledge`` because dedicated
+ mode does not exercise embedding in this test — the worker stub
+ intercepts ``process`` before the knowledge call.
+ """
+
+ async def get_dimension_policy(self) -> DimensionPolicy:
+ return DimensionPolicy(kind=DimensionPolicyKind.ANY, dimension=None)
+
+ async def create_knowledge_base(
+ self,
+ user_id: str,
+ name: str,
+ description: str,
+ embedding_model_config: EmbeddingModelConfig,
+ ) -> KnowledgeBaseRecord:
+ raise NotImplementedError
+
+ async def delete_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> bool:
+ return False
+
+ async def get_knowledge(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> Any:
+ record = await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if record is None:
+ raise KnowledgeBaseNotFoundError(
+ f"Knowledge base {knowledge_base_id!r} not found.",
+ )
+ raise NotImplementedError # unused in this test
+
+
+class _NoopWorkspaceManager(WorkspaceManagerBase):
+ """Workspace manager that does nothing."""
+
+ async def get_workspace(self, *args: Any, **kwargs: Any) -> Any:
+ raise NotImplementedError
+
+ async def create_workspace(self, *args: Any, **kwargs: Any) -> Any:
+ raise NotImplementedError
+
+ async def close(self, workspace_id: str) -> None:
+ return None
+
+ async def close_all(self) -> None:
+ return None
+
+
+def _make_storage(fr: fakeredis.aioredis.FakeRedis) -> RedisStorage:
+ class _FakeStorage(RedisStorage):
+ async def __aenter__(self) -> "_FakeStorage": # type: ignore[override]
+ self._client = fr
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ return _FakeStorage()
+
+
+def _make_bus(fr: fakeredis.aioredis.FakeRedis) -> RedisMessageBus:
+ class _FakeBus(RedisMessageBus):
+ async def __aenter__(self) -> "_FakeBus": # type: ignore[override]
+ self._client = fr
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ return _FakeBus()
+
+
+class _RecordingWorker:
+ """Stub worker that records each ``process`` invocation.
+
+ Stands in for :class:`IndexWorker` in the test so we can verify
+ that the dispatch hop landed without spinning up the full
+ parse → chunk → embed pipeline.
+ """
+
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+ self.notify = asyncio.Event()
+
+ async def process(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Record the dispatched task and signal the test.
+
+ Stands in for :class:`IndexWorker.process_one` so the lifespan
+ tests can assert that the API process forwarded the right
+ ``user_id`` / ``knowledge_base_id`` / ``document_id`` triple.
+
+ Args:
+ user_id (`str`):
+ The owning user id.
+ knowledge_base_id (`str`):
+ The parent knowledge base id.
+ document_id (`str`):
+ The document id to "process".
+ """
+ self.calls.append(
+ {
+ "user_id": user_id,
+ "knowledge_base_id": knowledge_base_id,
+ "document_id": document_id,
+ },
+ )
+ self.notify.set()
+
+
+class DedicatedModeUploadFlowTest(IsolatedAsyncioTestCase):
+ """The producer side reaches the bus; a separate consumer sees it."""
+
+ async def asyncSetUp(self) -> None:
+ self._tmp = tempfile.TemporaryDirectory()
+ self._fr = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ self._vector_store = _FakeVectorStore()
+ storage = _make_storage(self._fr)
+ self._api_message_bus = _make_bus(self._fr)
+
+ self._app = create_app(
+ storage=storage,
+ message_bus=self._api_message_bus,
+ workspace_manager=_NoopWorkspaceManager(),
+ knowledge_base_manager=_FakeKbManager(
+ storage=storage,
+ vector_store=self._vector_store,
+ ),
+ blob_store=LocalBlobStore(root_dir=self._tmp.name),
+ enable_index_worker=False,
+ )
+
+ # Seed a knowledge base directly so we don't have to mock the
+ # manager's create flow over HTTP.
+ kb_record = KnowledgeBaseRecord(
+ user_id="user-1",
+ name="kb",
+ description="",
+ embedding_model_config=EmbeddingModelConfig(
+ type="openai_credential",
+ credential_id="cred-1",
+ model="text-embedding-3-small",
+ dimensions=1,
+ ),
+ collection_name="",
+ )
+ kb_record.collection_name = f"kb_{kb_record.id}"
+ await self._vector_store.create_collection(
+ kb_record.collection_name,
+ 1,
+ )
+ storage._client = self._fr
+ await storage.upsert_knowledge_base("user-1", kb_record)
+ storage._client = None
+ self._kb_id = kb_record.id
+
+ async def asyncTearDown(self) -> None:
+ await self._fr.aclose()
+ self._tmp.cleanup()
+
+ async def test_upload_dispatches_through_message_bus(self) -> None:
+ """An upload in dedicated mode reaches a separate consumer."""
+ # The consumer's bus is a SEPARATE RedisMessageBus instance
+ # bound to the same fakeredis store. Production wiring would
+ # be two TCP-connected clients; here they share the in-memory
+ # backend, which exercises the bus contract correctly.
+ consumer_bus = _make_bus(self._fr)
+ worker = _RecordingWorker()
+
+ async with consumer_bus, IndexTaskConsumer(
+ message_bus=consumer_bus,
+ worker=worker,
+ ):
+ headers = {"X-User-ID": "user-1"}
+ with TestClient(self._app) as client:
+ files = {
+ "file": (
+ "hello.txt",
+ b"hello world\n" * 16,
+ "text/plain",
+ ),
+ }
+ resp = client.post(
+ f"/knowledge_bases/{self._kb_id}/documents",
+ files=files,
+ headers=headers,
+ )
+ self.assertEqual(resp.status_code, 201, resp.text)
+ body = resp.json()
+ document_id = body["document_id"]
+
+ # The consumer's worker should see the dispatch.
+ await asyncio.wait_for(worker.notify.wait(), timeout=5.0)
+
+ self.assertEqual(
+ worker.calls,
+ [
+ {
+ "user_id": "user-1",
+ "knowledge_base_id": self._kb_id,
+ "document_id": document_id,
+ },
+ ],
+ )
diff --git a/tests/blob_store_s3_test.py b/tests/blob_store_s3_test.py
new file mode 100644
index 000000000..67a865f63
--- /dev/null
+++ b/tests/blob_store_s3_test.py
@@ -0,0 +1,159 @@
+# -*- coding: utf-8 -*-
+"""Tests for :class:`S3BlobStore`.
+
+Uses ``moto.server.ThreadedMotoServer``: a real HTTP S3 endpoint
+served in-process on a thread. The aioboto3 client talks to it over
+TCP the way it would talk to AWS / MinIO / R2 — so the test
+exercises the real wire path (and the ``endpoint_url`` plumbing the
+production deployment will rely on for non-AWS services).
+
+We deliberately avoid ``moto.mock_aws()`` because that decorator
+patches ``botocore``'s endpoint layer, which does not play nicely
+with ``aiobotocore``: the patched response object is sync, but
+aiobotocore awaits ``http_response.content`` and gets a TypeError.
+The threaded server bypasses every monkey-patch path and gives us
+end-to-end coverage.
+
+Properties under test:
+
+- A blob written through ``write_stream`` reads back identical
+ bytes via ``open``.
+- The URI emitted is ``s3://{bucket}/{key}`` and round-trips
+ through ``exists`` / ``delete``.
+- ``exists`` distinguishes present from missing without raising.
+- ``delete`` is idempotent.
+- Bad URIs raise ``ValueError`` before any network call.
+- A store used outside ``async with`` raises ``RuntimeError`` —
+ callers MUST manage lifecycle via :class:`AsyncExitStack`.
+"""
+import io
+import os
+import socket
+from typing import TYPE_CHECKING
+from unittest import IsolatedAsyncioTestCase
+
+import boto3
+from moto.server import ThreadedMotoServer
+
+if TYPE_CHECKING:
+ from agentscope.app.rag.blob_store import S3BlobStore
+
+
+_BUCKET = "test-blobs"
+_REGION = "us-east-1"
+
+
+def _pick_port() -> int:
+ """Find an unused TCP port to bind moto on."""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+class S3BlobStoreTest(IsolatedAsyncioTestCase):
+ """Round-trip + URI parsing + streaming behaviour."""
+
+ def setUp(self) -> None:
+ # ThreadedMotoServer needs explicit credentials — without
+ # them aiobotocore looks for the AWS config chain and may
+ # fail on CI runners without credentials baked in.
+ self._env_overrides = {
+ "AWS_ACCESS_KEY_ID": "testing",
+ "AWS_SECRET_ACCESS_KEY": "testing",
+ "AWS_SECURITY_TOKEN": "testing",
+ "AWS_SESSION_TOKEN": "testing",
+ "AWS_DEFAULT_REGION": _REGION,
+ }
+ self._saved_env = {k: os.environ.get(k) for k in self._env_overrides}
+ for k, v in self._env_overrides.items():
+ os.environ[k] = v
+
+ port = _pick_port()
+ self._endpoint_url = f"http://127.0.0.1:{port}"
+ self._server = ThreadedMotoServer(ip_address="127.0.0.1", port=port)
+ self._server.start()
+
+ client = boto3.client(
+ "s3",
+ region_name=_REGION,
+ endpoint_url=self._endpoint_url,
+ )
+ client.create_bucket(Bucket=_BUCKET)
+
+ def tearDown(self) -> None:
+ self._server.stop()
+ for k, prev in self._saved_env.items():
+ if prev is None:
+ os.environ.pop(k, None)
+ else:
+ os.environ[k] = prev
+
+ def _store(self) -> "S3BlobStore":
+ """Build a fresh :class:`S3BlobStore` pointing at the moto endpoint.
+
+ Returns:
+ `S3BlobStore`:
+ The store under test, configured for the moto-backed
+ ``_BUCKET`` in ``_REGION``.
+ """
+ # Import inside the method so the skip decorator can fire
+ # without the import path running.
+ from agentscope.app.rag.blob_store import S3BlobStore
+
+ return S3BlobStore(
+ bucket=_BUCKET,
+ region_name=_REGION,
+ endpoint_url=self._endpoint_url,
+ use_ssl=False,
+ )
+
+ async def test_write_open_round_trip(self) -> None:
+ """A blob written through ``write_stream`` reads back the
+ same bytes via ``open`` and the URI is the documented
+ ``s3://{bucket}/{key}`` shape."""
+ async with self._store() as store:
+ payload = b"hello world\n" * 100 # ~1.2 KiB
+ uri = await store.write_stream(
+ "kb/abc/doc-1",
+ io.BytesIO(payload),
+ )
+ self.assertEqual(uri, "s3://test-blobs/kb/abc/doc-1")
+
+ received: list[bytes] = []
+ async with store.open(uri) as fp:
+ while True:
+ chunk = await fp.read(64)
+ if not chunk:
+ break
+ received.append(chunk)
+ self.assertEqual(b"".join(received), payload)
+
+ async def test_exists_and_delete(self) -> None:
+ """``exists`` flips from ``True`` to ``False`` after
+ ``delete``; ``delete`` is idempotent on a missing key."""
+ async with self._store() as store:
+ uri = await store.write_stream(
+ "kb/abc/doc-2",
+ io.BytesIO(b"data"),
+ )
+ self.assertTrue(await store.exists(uri))
+ await store.delete(uri)
+ self.assertFalse(await store.exists(uri))
+ # Second delete is a no-op.
+ await store.delete(uri)
+
+ async def test_bad_uri_scheme_rejected(self) -> None:
+ """Non-``s3://`` URIs are refused before any network call."""
+ async with self._store() as store:
+ with self.assertRaises(ValueError):
+ await store.exists("local://kb/abc/doc-3")
+ with self.assertRaises(ValueError):
+ await store.delete("s3://wrong-bucket/kb/abc/doc-4")
+
+ async def test_methods_require_aenter(self) -> None:
+ """Calling a blob method without entering the context fails
+ loudly — production code MUST manage the lifecycle through
+ ``async with`` / ``AsyncExitStack``."""
+ store = self._store() # not entered
+ with self.assertRaises(RuntimeError):
+ await store.write_stream("kb/abc/doc-5", io.BytesIO(b""))
diff --git a/tests/embedding_dashscope_test.py b/tests/embedding_dashscope_test.py
index b1e4c1e96..68e0cd3ed 100644
--- a/tests/embedding_dashscope_test.py
+++ b/tests/embedding_dashscope_test.py
@@ -72,7 +72,7 @@ class DashScopeListModelsTest(IsolatedAsyncioTestCase):
self.assertIn("multimodal-embedding-v1", names)
async def test_hidden_dimensions(self) -> None:
- """multimodal-embedding-v1 has hidden dimensions."""
+ """multimodal-embedding-v1 declares a fixed dimension (no enum)."""
cards = DashScopeEmbeddingModel.list_models()
v1 = next(c for c in cards if c.name == "multimodal-embedding-v1")
self.assertDictEqual(
@@ -89,33 +89,26 @@ class DashScopeListModelsTest(IsolatedAsyncioTestCase):
"image/bmp",
],
"output_types": ["application/x-embedding"],
+ "dimensions": 1024,
+ "supported_dimensions": None,
"context_size": 512,
"parameter_schema": {
"type": "object",
"properties": {},
"required": [],
},
- "parameter_overrides": {
- "dimensions": {"hidden": True, "default": 1024},
- },
+ "parameter_overrides": {},
},
)
async def test_visible_dimensions(self) -> None:
- """qwen3-vl-embedding exposes dimension choices."""
+ """qwen3-vl-embedding exposes dimension choices on the card."""
cards = DashScopeEmbeddingModel.list_models()
qwen = next(c for c in cards if c.name == "qwen3-vl-embedding")
- dims = qwen.parameter_schema["properties"]["dimensions"]
- self.assertDictEqual(
- dims,
- {
- "default": 2560,
- "description": "The output embedding vector dimensions.",
- "enum": [2560, 2048, 1536, 1024, 768, 512, 256],
- "exclusiveMinimum": 0,
- "title": "Dimensions",
- "type": "integer",
- },
+ self.assertEqual(qwen.dimensions, 2560)
+ self.assertEqual(
+ qwen.supported_dimensions,
+ [2560, 2048, 1536, 1024, 768, 512, 256],
)
@@ -129,7 +122,7 @@ class DashScopeTextCallTest(IsolatedAsyncioTestCase):
model = DashScopeEmbeddingModel(
credential=_cred(),
model="text-embedding-v4",
- parameters=DashScopeEmbeddingModel.Parameters(dimensions=2),
+ dimensions=2,
)
result = await model(["hello", "world"])
self.assertDictEqual(
@@ -150,6 +143,7 @@ class DashScopeTextCallTest(IsolatedAsyncioTestCase):
model = DashScopeEmbeddingModel(
credential=_cred(),
model="text-embedding-v4",
+ dimensions=1024,
)
with self.assertRaises(ValueError):
await model([_img()])
@@ -161,6 +155,7 @@ class DashScopeTextCallTest(IsolatedAsyncioTestCase):
model = DashScopeEmbeddingModel(
credential=_cred(),
model="text-embedding-v4",
+ dimensions=1024,
retry_delay=0.0,
)
with self.assertRaises(RuntimeError):
@@ -175,7 +170,7 @@ class DashScopeMultimodalCallTest(IsolatedAsyncioTestCase):
model = DashScopeEmbeddingModel(
credential=_cred(),
model="qwen3-vl-embedding",
- parameters=DashScopeEmbeddingModel.Parameters(dimensions=2),
+ dimensions=2,
)
model._call_multimodal = AsyncMock(
return_value=_mock_resp([[0.1, 0.2], [0.3, 0.4]]),
@@ -198,7 +193,7 @@ class DashScopeMultimodalCallTest(IsolatedAsyncioTestCase):
model = DashScopeEmbeddingModel(
credential=_cred(),
model="qwen3-vl-embedding",
- parameters=DashScopeEmbeddingModel.Parameters(dimensions=1),
+ dimensions=1,
)
call_count = 0
@@ -217,7 +212,7 @@ class DashScopeMultimodalCallTest(IsolatedAsyncioTestCase):
model = DashScopeEmbeddingModel(
credential=_cred(),
model="qwen3-vl-embedding",
- parameters=DashScopeEmbeddingModel.Parameters(dimensions=1),
+ dimensions=1,
)
call_count = 0
diff --git a/tests/embedding_gemini_test.py b/tests/embedding_gemini_test.py
index 868f67201..67fa05bc1 100644
--- a/tests/embedding_gemini_test.py
+++ b/tests/embedding_gemini_test.py
@@ -55,29 +55,15 @@ class GeminiListModelsTest(IsolatedAsyncioTestCase):
"status": "active",
"input_types": ["text/plain"],
"output_types": ["application/x-embedding"],
+ "dimensions": 3072,
+ "supported_dimensions": [3072, 1536, 768, 512, 256, 128],
"context_size": 2048,
"parameter_schema": {
"type": "object",
- "properties": {
- "dimensions": {
- "default": 3072,
- "description": (
- "The output embedding vector dimensions."
- ),
- "enum": [3072, 1536, 768, 512, 256, 128],
- "exclusiveMinimum": 0,
- "title": "Dimensions",
- "type": "integer",
- },
- },
+ "properties": {},
"required": [],
},
- "parameter_overrides": {
- "dimensions": {
- "default": 3072,
- "enum": [3072, 1536, 768, 512, 256, 128],
- },
- },
+ "parameter_overrides": {},
},
)
@@ -88,10 +74,7 @@ class GeminiListModelsTest(IsolatedAsyncioTestCase):
self.assertIn("image/png", card.input_types)
self.assertIn("application/pdf", card.input_types)
self.assertEqual(card.context_size, 8192)
- self.assertEqual(
- card.parameter_schema["properties"]["dimensions"]["enum"],
- [3072, 1536, 768],
- )
+ self.assertEqual(card.supported_dimensions, [3072, 1536, 768])
class GeminiTextCallTest(IsolatedAsyncioTestCase):
diff --git a/tests/embedding_ollama_test.py b/tests/embedding_ollama_test.py
index 16d268c61..202f23d79 100644
--- a/tests/embedding_ollama_test.py
+++ b/tests/embedding_ollama_test.py
@@ -47,7 +47,7 @@ class OllamaEmbeddingCallTest(IsolatedAsyncioTestCase):
model = OllamaEmbeddingModel(
credential=_cred(),
model="nomic-embed-text",
- parameters=OllamaEmbeddingModel.Parameters(dimensions=2),
+ dimensions=2,
)
model._call_api = AsyncMock(
return_value=_mock_resp([[0.1, 0.2], [0.3, 0.4]]),
@@ -70,7 +70,7 @@ class OllamaEmbeddingCallTest(IsolatedAsyncioTestCase):
model = OllamaEmbeddingModel(
credential=OllamaCredential(host="http://gpu:11434"),
model="test",
- parameters=OllamaEmbeddingModel.Parameters(dimensions=768),
+ dimensions=768,
)
self.assertEqual(model.dimensions, 768)
self.assertEqual(model.host, "http://gpu:11434")
@@ -80,7 +80,7 @@ class OllamaEmbeddingCallTest(IsolatedAsyncioTestCase):
model = OllamaEmbeddingModel(
credential=_cred(),
model="test",
- parameters=OllamaEmbeddingModel.Parameters(dimensions=1),
+ dimensions=1,
)
model.batch_size = 2
call_count = 0
diff --git a/tests/embedding_openai_test.py b/tests/embedding_openai_test.py
index 00fddae1a..a79611691 100644
--- a/tests/embedding_openai_test.py
+++ b/tests/embedding_openai_test.py
@@ -47,29 +47,15 @@ class OpenAIListModelsTest(IsolatedAsyncioTestCase):
"status": "active",
"input_types": ["text/plain"],
"output_types": ["application/x-embedding"],
+ "dimensions": 1536,
+ "supported_dimensions": [1536, 1024, 768, 512, 256],
"context_size": 8191,
"parameter_schema": {
"type": "object",
- "properties": {
- "dimensions": {
- "default": 1536,
- "description": (
- "The output embedding vector dimensions."
- ),
- "enum": [1536, 1024, 768, 512, 256],
- "exclusiveMinimum": 0,
- "title": "Dimensions",
- "type": "integer",
- },
- },
+ "properties": {},
"required": [],
},
- "parameter_overrides": {
- "dimensions": {
- "default": 1536,
- "enum": [1536, 1024, 768, 512, 256],
- },
- },
+ "parameter_overrides": {},
},
)
@@ -89,7 +75,7 @@ class OpenAIEmbeddingCallTest(IsolatedAsyncioTestCase):
model = OpenAIEmbeddingModel(
credential=OpenAICredential(api_key="k"),
model="text-embedding-3-small",
- parameters=OpenAIEmbeddingModel.Parameters(dimensions=2),
+ dimensions=2,
)
result = await model(["hello", "world"])
@@ -120,7 +106,7 @@ class OpenAIEmbeddingCallTest(IsolatedAsyncioTestCase):
model = OpenAIEmbeddingModel(
credential=OpenAICredential(api_key="k"),
model="text-embedding-3-small",
- parameters=OpenAIEmbeddingModel.Parameters(dimensions=1),
+ dimensions=1,
)
model.batch_size = 2
@@ -147,6 +133,7 @@ class OpenAIEmbeddingCallTest(IsolatedAsyncioTestCase):
model = OpenAIEmbeddingModel(
credential=OpenAICredential(api_key="k"),
model="text-embedding-3-small",
+ dimensions=1536,
)
result = await model([])
@@ -187,7 +174,7 @@ class OpenAIEmbeddingCallTest(IsolatedAsyncioTestCase):
model = OpenAIEmbeddingModel(
credential=OpenAICredential(api_key="k"),
model="text-embedding-3-small",
- parameters=OpenAIEmbeddingModel.Parameters(dimensions=1),
+ dimensions=1,
retry_delay=0.0,
)
result = await model(["hello"])
diff --git a/tests/index_worker_lease_test.py b/tests/index_worker_lease_test.py
new file mode 100644
index 000000000..f5399b6b3
--- /dev/null
+++ b/tests/index_worker_lease_test.py
@@ -0,0 +1,196 @@
+# -*- coding: utf-8 -*-
+"""Regression tests for :class:`IndexWorker.process` lease handling.
+
+The pipeline must stop the moment the lease has been stolen by the
+sweeper — otherwise the original worker and the worker that just took
+over both write the same document into the vector store, producing
+duplicate chunks (PR #1926 unresolved review #discussion_r3479544207).
+"""
+import asyncio
+from datetime import timedelta
+from typing import Any
+from unittest import IsolatedAsyncioTestCase
+
+from agentscope.app._service._index_worker import IndexWorker
+
+
+class _LeaseStorage:
+ """Minimal storage stub recording lifecycle calls.
+
+ Driven by a per-document ``renew_results`` queue so tests can stage
+ a "renew returns True a few times, then False" pattern that mirrors
+ a sweeper reaping a slow worker.
+ """
+
+ def __init__(self) -> None:
+ self.acquire_returns: bool = True
+ self.renew_results: list[bool] = []
+ self.released: list[dict] = []
+ self.status_updates: list[dict] = []
+ self.renew_calls = 0
+
+ async def acquire_knowledge_document_lease(
+ self,
+ **kwargs: Any,
+ ) -> bool:
+ """Return the staged ``acquire_returns`` flag."""
+ del kwargs
+ return self.acquire_returns
+
+ async def renew_knowledge_document_lease(
+ self,
+ **kwargs: Any,
+ ) -> bool:
+ """Pop next staged renew result; default to ``True`` once drained."""
+ del kwargs
+ self.renew_calls += 1
+ if not self.renew_results:
+ return True
+ return self.renew_results.pop(0)
+
+ async def release_knowledge_document_lease(
+ self,
+ **kwargs: Any,
+ ) -> None:
+ """Record the release call so tests can assert it ran."""
+ self.released.append(kwargs)
+
+ async def update_knowledge_document_status(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ status: str,
+ error: str | None = None,
+ chunk_count: int | None = None,
+ ) -> None:
+ """Record the status transition for later assertion."""
+ del user_id, knowledge_base_id, document_id
+ self.status_updates.append(
+ {
+ "status": status,
+ "error": error,
+ "chunk_count": chunk_count,
+ },
+ )
+
+
+class _SlowPipelineWorker(IndexWorker):
+ """Replaces ``_run_pipeline`` with a long sleep so we can race the
+ lease timer.
+
+ The whole point of the regression is "what happens if a worker is
+ *still in_progress* when its lease is taken away" — the only way to
+ test that deterministically without standing up an embedding model
+ and a vector store is to make the pipeline trivially long-running.
+ """
+
+ def __init__(self, storage: _LeaseStorage, pipeline_seconds: float):
+ # Skip the real __init__ — we only need a handful of fields.
+ self._storage = storage # type: ignore[assignment]
+ self._node_id = "test-node"
+ self._lease_ttl = timedelta(seconds=10)
+ self._sem = asyncio.Semaphore(4)
+ # Renew quickly so a False result is visible within the test.
+ self._renew_interval = timedelta(seconds=0.05)
+ self._pipeline_seconds = pipeline_seconds
+ self.pipeline_started = asyncio.Event()
+ self.pipeline_cancelled = False
+ self.pipeline_completed = False
+
+ async def _run_pipeline(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Sleep ``pipeline_seconds`` so the test can race the heartbeat."""
+ del user_id, knowledge_base_id, document_id
+ self.pipeline_started.set()
+ try:
+ await asyncio.sleep(self._pipeline_seconds)
+ self.pipeline_completed = True
+ except asyncio.CancelledError:
+ self.pipeline_cancelled = True
+ raise
+
+
+class IndexWorkerLeaseTest(IsolatedAsyncioTestCase):
+ """Pipeline-vs-heartbeat race coverage."""
+
+ async def test_lost_lease_cancels_pipeline_and_marks_error(self) -> None:
+ """Renew returning False mid-pipeline must abort the pipeline.
+
+ Otherwise the original worker keeps running while the new
+ worker (that took over the lease) also runs — both end up
+ inserting the same chunks into the vector store.
+ """
+ storage = _LeaseStorage()
+ # First renew succeeds, second renew fails (sweeper stole it).
+ storage.renew_results = [True, False]
+
+ worker = _SlowPipelineWorker(storage, pipeline_seconds=5.0)
+ # Bound the test so a regression hangs visibly rather than
+ # silently passing.
+ await asyncio.wait_for(
+ worker.process("u", "kb", "doc-1"),
+ timeout=3.0,
+ )
+
+ self.assertTrue(
+ worker.pipeline_started.is_set(),
+ "Pipeline never started.",
+ )
+ self.assertTrue(
+ worker.pipeline_cancelled,
+ "Pipeline was NOT cancelled after the lease was lost — "
+ "this is the regression PR #1926 review flagged.",
+ )
+ self.assertFalse(
+ worker.pipeline_completed,
+ "Pipeline ran to completion despite the lost lease.",
+ )
+
+ # _mark_error must have recorded the lost-lease reason.
+ errors = [u for u in storage.status_updates if u["status"] == "error"]
+ self.assertEqual(len(errors), 1)
+ self.assertIn("Lost lease", errors[0]["error"])
+
+ # Release is still called (and is a safe no-op server-side).
+ self.assertEqual(len(storage.released), 1)
+
+ async def test_happy_path_cancels_heartbeat_and_releases(self) -> None:
+ """Normal completion still tears the heartbeat down cleanly."""
+ storage = _LeaseStorage()
+ # Heartbeat always succeeds.
+ storage.renew_results = []
+
+ worker = _SlowPipelineWorker(storage, pipeline_seconds=0.05)
+ await asyncio.wait_for(
+ worker.process("u", "kb", "doc-ok"),
+ timeout=2.0,
+ )
+
+ self.assertTrue(worker.pipeline_completed)
+ self.assertFalse(worker.pipeline_cancelled)
+ # No error update on the happy path.
+ self.assertEqual(
+ [u for u in storage.status_updates if u["status"] == "error"],
+ [],
+ )
+ self.assertEqual(len(storage.released), 1)
+
+ async def test_not_acquired_short_circuits(self) -> None:
+ """When the lease is already held by another worker, do nothing."""
+ storage = _LeaseStorage()
+ storage.acquire_returns = False
+
+ worker = _SlowPipelineWorker(storage, pipeline_seconds=5.0)
+ await asyncio.wait_for(
+ worker.process("u", "kb", "doc-locked"),
+ timeout=1.0,
+ )
+
+ self.assertFalse(worker.pipeline_started.is_set())
+ # No release either — we never held the lease.
+ self.assertEqual(storage.released, [])
diff --git a/tests/mem0_agentscope_adapter_test.py b/tests/mem0_agentscope_adapter_test.py
index 9ff67d416..552febef0 100644
--- a/tests/mem0_agentscope_adapter_test.py
+++ b/tests/mem0_agentscope_adapter_test.py
@@ -296,11 +296,12 @@ class _FakeEmbeddingModel(EmbeddingModelBase):
super().__init__(
credential=DashScopeCredential(api_key="fake"),
model="fake-embed",
- parameters=self.Parameters(dimensions=3),
+ parameters=self.Parameters(),
context_size=8192,
batch_size=10,
max_retries=0,
retry_delay=0.0,
+ dimensions=3,
)
self.received: list[list[str]] = []
diff --git a/tests/middleware_rag_test.py b/tests/middleware_rag_test.py
new file mode 100644
index 000000000..49955b69e
--- /dev/null
+++ b/tests/middleware_rag_test.py
@@ -0,0 +1,550 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for the :class:`RAGMiddleware` class."""
+from contextlib import AsyncExitStack
+from types import SimpleNamespace
+from typing import Any, AsyncGenerator
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString
+
+from agentscope.embedding import EmbeddingResponse
+from agentscope.event import EventType, HintBlockEvent
+from agentscope.message import (
+ Base64Source,
+ DataBlock,
+ Msg,
+ TextBlock,
+ UserMsg,
+)
+from agentscope.middleware import RAGMiddleware
+from agentscope.rag import Chunk, KnowledgeBase, QdrantStore, VectorRecord
+
+
+_HINT_SOURCE = '{"label": "KnowledgeBase", "sublabel": ""}'
+
+_EXPECTED_HINT = (
+ "<system-reminder>The following content is retrieved from the "
+ "knowledge base(s) and may be helpful for the current "
+ "request:\n"
+ "<content>[1] (source: doc-1.txt)\n"
+ "Paris is in France.</content></system-reminder>"
+)
+
+
+class _StubEmbeddingModel:
+ """A stub embedding model returning a fixed vector per input."""
+
+ supports_multimodal = False
+ dimensions = 3
+
+ def __init__(self, vector: list[float]) -> None:
+ """Initialize the stub.
+
+ Args:
+ vector (`list[float]`):
+ The vector returned for every input.
+ """
+ self.vector = vector
+ self.calls: list[list] = []
+
+ async def __call__(self, inputs: list) -> EmbeddingResponse:
+ """Return the fixed vector for each input.
+
+ Args:
+ inputs (`list`):
+ The input queries.
+
+ Returns:
+ `EmbeddingResponse`:
+ The response with one fixed vector per input.
+ """
+ self.calls.append(inputs)
+ return EmbeddingResponse(embeddings=[self.vector] * len(inputs))
+
+
+def _make_record(
+ text: str,
+ vector: list[float],
+ document_id: str,
+) -> VectorRecord:
+ """Build a VectorRecord for testing.
+
+ Args:
+ text (`str`):
+ The chunk text content.
+ vector (`list[float]`):
+ The embedding vector.
+ document_id (`str`):
+ The ID of the source document the record belongs to.
+
+ Returns:
+ `VectorRecord`:
+ The constructed record.
+ """
+ return VectorRecord(
+ vector=vector,
+ document_id=document_id,
+ chunk=Chunk(
+ content=TextBlock(text=text),
+ source=f"{document_id}.txt",
+ chunk_index=0,
+ total_chunks=1,
+ ),
+ )
+
+
+def _make_agent(
+ context: list[Msg] | None = None,
+ cur_iter: int = 0,
+) -> Any:
+ """Build a minimal stand-in for an Agent.
+
+ Args:
+ context (`list[Msg] | None`, optional):
+ The initial agent context.
+ cur_iter (`int`, defaults to ``0``):
+ Value for ``state.cur_iter``; the middleware only searches
+ on the first reasoning step (``0``).
+
+ Returns:
+ `Any`:
+ An object with ``name`` and ``state.context`` /
+ ``state.reply_id`` / ``state.session_id`` /
+ ``state.cur_iter`` / ``state.append_context``.
+ """
+
+ msgs: list[Msg] = context if context is not None else []
+
+ def _append_context(name: str, blocks: list) -> None:
+ # Always append a new assistant carrier message keyed on the
+ # static reply_id used in these tests. Mirrors the real
+ # ``AgentState.append_context`` for the purposes of the
+ # middleware's reverse-scan removal logic.
+ carrier = Msg(name=name, role="assistant", content=blocks)
+ carrier.id = "reply-1"
+ msgs.append(carrier)
+
+ state = SimpleNamespace(
+ context=msgs,
+ reply_id="reply-1",
+ session_id="session-1",
+ cur_iter=cur_iter,
+ append_context=_append_context,
+ )
+ return SimpleNamespace(name="assistant", state=state)
+
+
+async def _drain(generator: AsyncGenerator) -> list:
+ """Exhaust an async generator into a list.
+
+ Args:
+ generator (`AsyncGenerator`):
+ The generator to drain.
+
+ Returns:
+ `list`:
+ All yielded items.
+ """
+ return [item async for item in generator]
+
+
+class RAGMiddlewareTest(IsolatedAsyncioTestCase):
+ """The test cases for the :class:`RAGMiddleware` class."""
+
+ async def asyncSetUp(self) -> None:
+ """Create an in-memory store seeded with one collection +
+ one :class:`KnowledgeBase` handle wired to it."""
+ self._exit_stack = AsyncExitStack()
+ self.store = await self._exit_stack.enter_async_context(
+ QdrantStore(location=":memory:"),
+ )
+ await self.store.create_collection("kb-1", dimensions=3)
+ await self.store.insert(
+ "kb-1",
+ [
+ _make_record("Paris is in France.", [1.0, 0.0, 0.0], "doc-1"),
+ _make_record("Cats are mammals.", [0.0, 1.0, 0.0], "doc-2"),
+ ],
+ )
+ self.embedding_model = _StubEmbeddingModel([1.0, 0.0, 0.0])
+ # Build the KnowledgeBase handle once; tests share it. The
+ # collection already exists, so ``ensure_collection`` will
+ # short-circuit on first use.
+ self.knowledge = KnowledgeBase(
+ name="paris-kb",
+ description="Trivia about Paris and cats.",
+ embedding_model=self.embedding_model,
+ vector_store=self.store,
+ collection="kb-1",
+ )
+
+ async def asyncTearDown(self) -> None:
+ """Close the store after each test."""
+ await self._exit_stack.aclose()
+
+ def _middleware(
+ self,
+ knowledges: list[KnowledgeBase] | None = None,
+ **kwargs: Any,
+ ) -> RAGMiddleware:
+ """Build a middleware bound to ``self.knowledge`` with a
+ :class:`SearchConfig` assembled from ``kwargs``.
+
+ Args:
+ knowledges (`list[KnowledgeBase] | None`, optional):
+ Override the bound knowledge bases. Defaults to
+ ``[self.knowledge]``.
+ **kwargs (`Any`):
+ Forwarded to :class:`SearchConfig` (e.g. ``mode``,
+ ``top_k``, ``score_threshold``, ``emit_hint_event``,
+ ``persist_hint``).
+
+ Returns:
+ `RAGMiddleware`:
+ The middleware under test.
+ """
+ return RAGMiddleware(
+ knowledge_bases=knowledges
+ if knowledges is not None
+ else [
+ self.knowledge,
+ ],
+ parameters=RAGMiddleware.Parameters(**kwargs),
+ )
+
+ async def _run_with_inputs(
+ self,
+ middleware: RAGMiddleware,
+ agent: Any,
+ inputs: Msg | list[Msg] | None,
+ context_during_reasoning: list[dict] | None = None,
+ ) -> list:
+ """Drive ``on_reply`` → ``on_reasoning`` end-to-end.
+
+ Mirrors the real agent loop: ``on_reply`` captures the inputs
+ in the middleware's scratchpad, then ``on_reasoning`` runs
+ (with ``state.cur_iter == 0``) and may inject a hint. The
+ reasoning step yields a sentinel ``"reasoning-evt"`` so callers
+ can assert event order; if ``context_during_reasoning`` is
+ provided it is filled with a dump of ``agent.state.context`` as
+ seen by the innermost reasoning callback.
+
+ Args:
+ middleware (`RAGMiddleware`):
+ The middleware under test.
+ agent (`Any`):
+ The fake agent.
+ inputs (`Msg | list[Msg] | None`):
+ The reply inputs to pass through ``on_reply``.
+ context_during_reasoning (`list[dict] | None`, optional):
+ When provided, receives a dump of the agent context as
+ seen by the wrapped (innermost) reasoning call.
+
+ Returns:
+ `list`:
+ All events yielded by the on_reply → on_reasoning chain.
+ """
+
+ async def reasoning_next(**_kwargs: Any) -> AsyncGenerator:
+ if context_during_reasoning is not None:
+ context_during_reasoning.extend(
+ msg.model_dump() for msg in agent.state.context
+ )
+ yield "reasoning-evt"
+
+ async def reply_next(**_kwargs: Any) -> AsyncGenerator:
+ # The reply branch drives the reasoning branch — same as
+ # the real composition.
+ async for evt in middleware.on_reasoning(
+ agent=agent,
+ input_kwargs={"tool_choice": None},
+ next_handler=reasoning_next,
+ ):
+ yield evt
+
+ return await _drain(
+ middleware.on_reply(
+ agent=agent,
+ input_kwargs={"inputs": inputs},
+ next_handler=reply_next,
+ ),
+ )
+
+ # ------------------------------------------------------------------
+ # Static mode (auto-injection)
+ # ------------------------------------------------------------------
+
+ async def test_static_one_shot_injection(self) -> None:
+ """The hint participates in one reasoning step and is removed
+ afterwards (``persist_hint=False``, default)."""
+ middleware = self._middleware(
+ mode="static",
+ top_k=1,
+ emit_hint_event=False,
+ )
+ agent = _make_agent()
+ seen_context: list[dict] = []
+
+ events = await self._run_with_inputs(
+ middleware,
+ agent,
+ UserMsg(name="user", content="Where is Paris?"),
+ context_during_reasoning=seen_context,
+ )
+
+ # No HintBlockEvent (emit_hint_event=False); only downstream
+ # events.
+ self.assertEqual(events, ["reasoning-evt"])
+
+ # The reasoning callback observed exactly one carrier message
+ # holding the injected hint block.
+ self.assertEqual(len(seen_context), 1)
+ carrier = seen_context[0]
+ self.assertEqual(carrier["role"], "assistant")
+ self.assertEqual(carrier["id"], "reply-1")
+ self.assertEqual(len(carrier["content"]), 1)
+ block = carrier["content"][0]
+ self.assertEqual(block["type"], "hint")
+ self.assertEqual(block["source"], _HINT_SOURCE)
+ self.assertEqual(block["hint"], _EXPECTED_HINT)
+
+ # One-shot: after on_reasoning unwinds, the carrier is emptied.
+ post = [msg.model_dump() for msg in agent.state.context]
+ self.assertEqual(len(post), 1)
+ self.assertEqual(post[0]["content"], [])
+
+ async def test_static_persistent_injection(self) -> None:
+ """``persist_hint=True`` keeps the hint in the context."""
+ middleware = self._middleware(
+ mode="static",
+ top_k=1,
+ persist_hint=True,
+ emit_hint_event=False,
+ )
+ agent = _make_agent()
+ seen_context: list[dict] = []
+
+ await self._run_with_inputs(
+ middleware,
+ agent,
+ UserMsg(name="user", content="Where is Paris?"),
+ context_during_reasoning=seen_context,
+ )
+
+ self.assertEqual(
+ [msg.model_dump() for msg in agent.state.context],
+ seen_context,
+ )
+
+ async def test_static_event_emission(self) -> None:
+ """``emit_hint_event=True`` yields one :class:`HintBlockEvent`."""
+ middleware = self._middleware(
+ mode="static",
+ top_k=1,
+ emit_hint_event=True,
+ )
+ agent = _make_agent()
+
+ events = await self._run_with_inputs(
+ middleware,
+ agent,
+ UserMsg(name="user", content="Where is Paris?"),
+ )
+
+ self.assertEqual(len(events), 2)
+ self.assertIsInstance(events[0], HintBlockEvent)
+ self.assertEqual(
+ events[0].model_dump(),
+ {
+ "type": EventType.HINT_BLOCK,
+ "reply_id": "reply-1",
+ "block_id": AnyString(),
+ "source": _HINT_SOURCE,
+ "hint": _EXPECTED_HINT,
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "metadata": {},
+ },
+ )
+ self.assertEqual(events[1], "reasoning-evt")
+
+ async def test_static_skips_event_inputs(self) -> None:
+ """Non-message inputs (resumption events / ``None``) skip the
+ search entirely."""
+ middleware = self._middleware(mode="static")
+ agent = _make_agent()
+
+ events = await self._run_with_inputs(middleware, agent, None)
+
+ self.assertEqual(events, ["reasoning-evt"])
+ self.assertEqual(self.embedding_model.calls, [])
+ self.assertEqual(agent.state.context, [])
+
+ async def test_multimodal_query_extraction(self) -> None:
+ """DataBlocks reach the embedding model when it declares
+ ``supports_multimodal``."""
+ self.embedding_model.supports_multimodal = True
+ middleware = self._middleware(
+ mode="static",
+ top_k=1,
+ emit_hint_event=False,
+ )
+ agent = _make_agent()
+ data_block = DataBlock(
+ source=Base64Source(data="aGk=", media_type="image/png"),
+ )
+
+ await self._run_with_inputs(
+ middleware,
+ agent,
+ UserMsg(
+ name="user",
+ content=[TextBlock(text="What is this?"), data_block],
+ ),
+ )
+
+ # The query path prepends ``{name}: `` to the first text
+ # block; the data block is passed through verbatim.
+ self.assertEqual(len(self.embedding_model.calls), 1)
+ query = self.embedding_model.calls[0]
+ self.assertEqual(len(query), 2)
+ self.assertEqual(query[0].text, "user: What is this?")
+ self.assertEqual(query[1], data_block)
+
+ async def test_multimodal_blocks_dropped_for_text_only_model(
+ self,
+ ) -> None:
+ """A text-only embedding model silently drops DataBlock queries
+ (no exception, no crash)."""
+ middleware = self._middleware(
+ mode="static",
+ top_k=1,
+ emit_hint_event=False,
+ )
+ agent = _make_agent()
+ data_block = DataBlock(
+ source=Base64Source(data="aGk=", media_type="image/png"),
+ )
+
+ await self._run_with_inputs(
+ middleware,
+ agent,
+ UserMsg(
+ name="user",
+ content=[TextBlock(text="What is this?"), data_block],
+ ),
+ )
+
+ # ``KnowledgeBase.search`` strips the DataBlock when the bound
+ # embedding model isn't multimodal — the model only saw text.
+ self.assertEqual(len(self.embedding_model.calls), 1)
+ for item in self.embedding_model.calls[0]:
+ self.assertNotIsInstance(item, DataBlock)
+
+ # ------------------------------------------------------------------
+ # Agentic mode (tool exposure)
+ # ------------------------------------------------------------------
+
+ async def test_agentic_list_tools(self) -> None:
+ """Agentic mode exposes the search tool; static mode none."""
+ agentic_tools = await self._middleware(mode="agentic").list_tools()
+ static_tools = await self._middleware(mode="static").list_tools()
+
+ self.assertEqual(
+ [tool.name for tool in agentic_tools],
+ ["search_knowledge"],
+ )
+ self.assertEqual(static_tools, [])
+
+ async def test_agentic_no_auto_injection(self) -> None:
+ """Agentic mode never searches or injects automatically."""
+ middleware = self._middleware(mode="agentic")
+ agent = _make_agent()
+
+ events = await self._run_with_inputs(
+ middleware,
+ agent,
+ UserMsg(name="user", content="Where is Paris?"),
+ )
+
+ self.assertEqual(events, ["reasoning-evt"])
+ self.assertEqual(self.embedding_model.calls, [])
+ self.assertEqual(agent.state.context, [])
+
+ async def test_search_knowledge_tool_call(self) -> None:
+ """The tool returns a formatted ``ToolChunk`` for a query.
+
+ ``_SearchKnowledgeTool.call`` is a regular async function (not
+ an async generator), so ``ToolBase.__call__`` awaits it and
+ returns the single ``ToolChunk`` directly.
+ """
+ middleware = self._middleware(mode="agentic", top_k=1)
+ tool = (await middleware.list_tools())[0]
+
+ chunk = await tool(query="Where is Paris?")
+
+ self.assertEqual(
+ chunk.model_dump(),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ "[1] (source: doc-1.txt)\nParis is in France."
+ ),
+ "id": AnyString(),
+ },
+ ],
+ "state": "success",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
+ async def test_search_knowledge_tool_input_schema_enum(self) -> None:
+ """The tool's ``input_schema`` narrows ``knowledge_bases.items``
+ to the equipped KB names."""
+ middleware = self._middleware(mode="agentic")
+ tool = (await middleware.list_tools())[0]
+
+ schema = tool.input_schema
+ kb_schema = schema["properties"]["knowledge_bases"]
+ # Pydantic emits Optional[list[str]] as anyOf; pick the array
+ # branch.
+ array_variant = next(
+ v for v in kb_schema["anyOf"] if v.get("type") == "array"
+ )
+ self.assertEqual(array_variant["items"]["enum"], ["paris-kb"])
+
+ async def test_search_knowledge_tool_filters_by_name(self) -> None:
+ """Passing ``knowledge_bases=[<unknown>]`` returns the
+ ``"No relevant content found."`` notice without touching the
+ embedding model."""
+ middleware = self._middleware(mode="agentic", top_k=1)
+ tool = (await middleware.list_tools())[0]
+
+ chunk = await tool(
+ query="Where is Paris?",
+ knowledge_bases=["does-not-exist"],
+ )
+
+ self.assertEqual(
+ [b["text"] for b in chunk.model_dump()["content"]],
+ ["No relevant content found."],
+ )
+ self.assertEqual(self.embedding_model.calls, [])
+
+ # ------------------------------------------------------------------
+ # Config validation
+ # ------------------------------------------------------------------
+
+ async def test_hint_template_must_have_context_placeholder(self) -> None:
+ """:class:`SearchConfig` rejects a template without exactly one
+ ``{context}``."""
+ with self.assertRaises(ValueError):
+ RAGMiddleware.Parameters(hint_template="no placeholder here")
+ with self.assertRaises(ValueError):
+ RAGMiddleware.Parameters(hint_template="{context} twice {context}")
+ # Exactly one placeholder is fine.
+ RAGMiddleware.Parameters(hint_template="wrapped: {context}.")
diff --git a/tests/rag_chunker_approx_token_test.py b/tests/rag_chunker_approx_token_test.py
new file mode 100644
index 000000000..db18e3e2c
--- /dev/null
+++ b/tests/rag_chunker_approx_token_test.py
@@ -0,0 +1,204 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for the ApproxTokenChunker class."""
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString
+
+from agentscope.message import Base64Source, DataBlock, TextBlock
+from agentscope.rag import ApproxTokenChunker, Chunk, Section
+
+
+def _dump_chunks(chunks: list[Chunk]) -> list[dict]:
+ """Convert chunks into plain dicts for whole-structure comparison.
+
+ Args:
+ chunks (`list[Chunk]`):
+ The chunks to convert.
+
+ Returns:
+ `list[dict]`:
+ The chunks as plain dicts.
+ """
+ return [chunk.model_dump() for chunk in chunks]
+
+
+class ApproxTokenChunkerTest(IsolatedAsyncioTestCase):
+ """The test cases for the ApproxTokenChunker class."""
+
+ async def test_short_text_single_chunk(self) -> None:
+ """Short text should produce a single chunk."""
+ chunker = ApproxTokenChunker(chunk_size=512, overlap=50)
+ sections = [
+ Section(
+ content=TextBlock(text="Hello world!"),
+ source="a.txt",
+ metadata={"page": 1},
+ ),
+ ]
+
+ chunks = await chunker.chunk(sections)
+
+ self.assertEqual(
+ _dump_chunks(chunks),
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "Hello world!",
+ "id": AnyString(),
+ },
+ "source": "a.txt",
+ "chunk_index": 0,
+ "total_chunks": 1,
+ "metadata": {"page": 1},
+ },
+ ],
+ )
+
+ async def test_long_text_split_with_overlap(self) -> None:
+ """Long text should be split into overlapping chunks."""
+ # chunk_size=10 tokens -> 40-byte window, overlap=2 -> 8-byte step
+ # back, so for ASCII text the windows start at 0, 32, 64, ...
+ chunker = ApproxTokenChunker(chunk_size=10, overlap=2)
+ text = "abcdefghij" * 20 # 200 ASCII chars => 50 approx tokens
+ sections = [
+ Section(
+ content=TextBlock(text=text),
+ source="b.txt",
+ ),
+ ]
+
+ chunks = await chunker.chunk(sections)
+
+ self.assertEqual(
+ _dump_chunks(chunks),
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": text[start : start + 40],
+ "id": AnyString(),
+ },
+ "source": "b.txt",
+ "chunk_index": index,
+ "total_chunks": 6,
+ "metadata": {},
+ }
+ for index, start in enumerate([0, 32, 64, 96, 128, 160])
+ ],
+ )
+
+ async def test_data_block_pass_through(self) -> None:
+ """DataBlock sections should pass through unchanged."""
+ chunker = ApproxTokenChunker(chunk_size=10, overlap=2)
+ data_block = DataBlock(
+ source=Base64Source(data="aGk=", media_type="image/png"),
+ )
+ sections = [
+ Section(
+ content=TextBlock(text="x" * 100),
+ source="c.pdf",
+ ),
+ Section(
+ content=data_block,
+ source="c.pdf",
+ metadata={"page": 2},
+ ),
+ ]
+
+ chunks = await chunker.chunk(sections)
+
+ self.assertEqual(
+ _dump_chunks(chunks),
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "x" * 40,
+ "id": AnyString(),
+ },
+ "source": "c.pdf",
+ "chunk_index": 0,
+ "total_chunks": 4,
+ "metadata": {},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "x" * 40,
+ "id": AnyString(),
+ },
+ "source": "c.pdf",
+ "chunk_index": 1,
+ "total_chunks": 4,
+ "metadata": {},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "x" * 36,
+ "id": AnyString(),
+ },
+ "source": "c.pdf",
+ "chunk_index": 2,
+ "total_chunks": 4,
+ "metadata": {},
+ },
+ {
+ "content": {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": "aGk=",
+ "media_type": "image/png",
+ },
+ "name": None,
+ },
+ "source": "c.pdf",
+ "chunk_index": 3,
+ "total_chunks": 4,
+ "metadata": {"page": 2},
+ },
+ ],
+ )
+ # The DataBlock instance itself is passed through, not copied
+ self.assertIs(chunks[-1].content, data_block)
+
+ async def test_no_cross_section_merging(self) -> None:
+ """Chunks must never combine content from two sections."""
+ chunker = ApproxTokenChunker(chunk_size=512, overlap=50)
+ sections = [
+ Section(content=TextBlock(text="first"), source="d.txt"),
+ Section(content=TextBlock(text="second"), source="d.txt"),
+ ]
+
+ chunks = await chunker.chunk(sections)
+
+ self.assertEqual(
+ _dump_chunks(chunks),
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "first",
+ "id": AnyString(),
+ },
+ "source": "d.txt",
+ "chunk_index": 0,
+ "total_chunks": 2,
+ "metadata": {},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "second",
+ "id": AnyString(),
+ },
+ "source": "d.txt",
+ "chunk_index": 1,
+ "total_chunks": 2,
+ "metadata": {},
+ },
+ ],
+ )
diff --git a/tests/rag_parser_test.py b/tests/rag_parser_test.py
new file mode 100644
index 000000000..ccbcc29a2
--- /dev/null
+++ b/tests/rag_parser_test.py
@@ -0,0 +1,670 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for the file parsers in :mod:`agentscope.rag._parser`.
+
+PDF / PPTX fixtures are produced in-memory via :mod:`reportlab` and
+:mod:`python-pptx` so the tests have no on-disk dependencies and can
+run anywhere ``agentscope[rag]`` is installed.
+"""
+import base64
+import io
+import os
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString
+
+from agentscope.rag import (
+ ImageParser,
+ PDFParser,
+ PPTParser,
+ TextParser,
+)
+
+
+# Smallest valid PNG ever — a single transparent pixel. Used wherever
+# a test needs "some image bytes" without depending on Pillow.
+_PNG_PIXEL: bytes = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgAAIAAAUA"
+ "AarVyFEAAAAASUVORK5CYII=",
+)
+_PNG_PIXEL_B64: str = base64.b64encode(_PNG_PIXEL).decode("utf-8")
+
+
+def _make_pdf(pages: list[str]) -> bytes:
+ """Render the supplied page strings to a PDF in memory."""
+ from reportlab.pdfgen import canvas
+
+ buffer = io.BytesIO()
+ pdf = canvas.Canvas(buffer)
+ for page in pages:
+ pdf.drawString(72, 720, page)
+ pdf.showPage()
+ pdf.save()
+ return buffer.getvalue()
+
+
+def _make_pptx_simple(slides: list[str]) -> bytes:
+ """Build a PPTX in memory with one text shape per slide."""
+ from pptx import Presentation
+
+ prs = Presentation()
+ blank_layout = prs.slide_layouts[5] # title-only layout
+ for text in slides:
+ slide = prs.slides.add_slide(blank_layout)
+ slide.shapes.title.text = text
+ buffer = io.BytesIO()
+ prs.save(buffer)
+ return buffer.getvalue()
+
+
+def _make_pptx_rich() -> bytes:
+ """Build a richer PPTX with text, a table, and an embedded image.
+
+ Slide 1: a single title text shape.
+ Slide 2: a title text shape, a 2x2 table, and a trailing text shape.
+ Slide 3: an embedded PNG image only (blank title).
+ """
+ from pptx import Presentation
+ from pptx.util import Inches
+
+ prs = Presentation()
+ blank_layout = prs.slide_layouts[5]
+
+ slide1 = prs.slides.add_slide(blank_layout)
+ slide1.shapes.title.text = "Hello"
+
+ slide2 = prs.slides.add_slide(blank_layout)
+ slide2.shapes.title.text = "Header"
+ table = slide2.shapes.add_table(
+ rows=2,
+ cols=2,
+ left=Inches(1),
+ top=Inches(2),
+ width=Inches(4),
+ height=Inches(1),
+ ).table
+ table.cell(0, 0).text = "A"
+ table.cell(0, 1).text = "B"
+ table.cell(1, 0).text = "1"
+ table.cell(1, 1).text = "2"
+ trailing = slide2.shapes.add_textbox(
+ Inches(1),
+ Inches(4),
+ Inches(4),
+ Inches(1),
+ )
+ trailing.text_frame.text = "Footer"
+
+ slide3 = prs.slides.add_slide(blank_layout)
+ slide3.shapes.title.text = "" # blank title
+ slide3.shapes.add_picture(
+ io.BytesIO(_PNG_PIXEL),
+ Inches(1),
+ Inches(1),
+ Inches(1),
+ Inches(1),
+ )
+
+ buffer = io.BytesIO()
+ prs.save(buffer)
+ return buffer.getvalue()
+
+
+class TextParserTest(IsolatedAsyncioTestCase):
+ """Behavioural coverage for :class:`TextParser`."""
+
+ async def test_decode_bytes(self) -> None:
+ """Bytes are decoded with the configured encoding."""
+ parser = TextParser()
+ sections = await parser.parse(b"hello", "x.txt")
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "hello",
+ "id": AnyString(),
+ },
+ "source": "x.txt",
+ "metadata": {},
+ },
+ ],
+ )
+
+ async def test_pre_decoded_string_round_trips(self) -> None:
+ """``str`` inputs skip the decode step when no such file exists."""
+ parser = TextParser()
+ sections = await parser.parse("preset", "x.md")
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "preset",
+ "id": AnyString(),
+ },
+ "source": "x.md",
+ "metadata": {},
+ },
+ ],
+ )
+
+ async def test_string_input_treated_as_path(self) -> None:
+ """A ``str`` that names an existing file is read as a path."""
+ import tempfile
+
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ suffix=".txt",
+ delete=False,
+ ) as f:
+ f.write("from disk")
+ path = f.name
+ try:
+ parser = TextParser()
+ sections = await parser.parse(path, "x.txt")
+ self.assertEqual(len(sections), 1)
+ self.assertEqual(sections[0].content.text, "from disk")
+ finally:
+ os.unlink(path)
+
+ async def test_bad_encoding_raises_value_error(self) -> None:
+ """An undecodable byte sequence surfaces a clear error."""
+ parser = TextParser(encoding="ascii")
+ with self.assertRaises(ValueError):
+ await parser.parse(b"\xff\xfe", "bad.txt")
+
+
+class PDFParserTest(IsolatedAsyncioTestCase):
+ """Behavioural coverage for :class:`PDFParser`."""
+
+ async def test_one_section_per_page(self) -> None:
+ """Each page in the PDF round-trips to its own Section."""
+ pdf_bytes = _make_pdf(["First page text", "Second page text"])
+ parser = PDFParser()
+ sections = await parser.parse(pdf_bytes, "demo.pdf")
+
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "First page text\n",
+ "id": AnyString(),
+ },
+ "source": "demo.pdf",
+ "metadata": {"page": 1},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "Second page text\n",
+ "id": AnyString(),
+ },
+ "source": "demo.pdf",
+ "metadata": {"page": 2},
+ },
+ ],
+ )
+
+ async def test_string_input_treated_as_path(self) -> None:
+ """``str`` is interpreted as a filesystem path to the PDF."""
+ import tempfile
+
+ pdf_bytes = _make_pdf(["Hello"])
+ with tempfile.NamedTemporaryFile(
+ suffix=".pdf",
+ delete=False,
+ ) as f:
+ f.write(pdf_bytes)
+ path = f.name
+ try:
+ parser = PDFParser()
+ sections = await parser.parse(path, "demo.pdf")
+ self.assertEqual(len(sections), 1)
+ finally:
+ os.unlink(path)
+
+ async def test_missing_path_raises_file_not_found(self) -> None:
+ """A ``str`` pointing at a missing path raises FileNotFoundError."""
+ parser = PDFParser()
+ with self.assertRaises(FileNotFoundError):
+ await parser.parse("/no/such/file.pdf", "x.pdf")
+
+ async def test_invalid_bytes_raise_value_error(self) -> None:
+ """Garbage bytes surface as :class:`ValueError`."""
+ parser = PDFParser()
+ with self.assertRaises(ValueError):
+ await parser.parse(b"not a pdf", "broken.pdf")
+
+ async def test_supported_extensions(self) -> None:
+ """``.pdf`` is the only extension exposed to the file picker."""
+ self.assertEqual(PDFParser.supported_extensions(), [".pdf"])
+
+
+class ImageParserTest(IsolatedAsyncioTestCase):
+ """Behavioural coverage for :class:`ImageParser`."""
+
+ async def test_wraps_bytes_in_data_block(self) -> None:
+ """A single Section is emitted with the image as a DataBlock."""
+ parser = ImageParser()
+ sections = await parser.parse(_PNG_PIXEL, "pixel.png")
+
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": _PNG_PIXEL_B64,
+ "media_type": "image/png",
+ },
+ "name": "pixel.png",
+ },
+ "source": "pixel.png",
+ "metadata": {"media_type": "image/png"},
+ },
+ ],
+ )
+
+ async def test_media_type_sniffed_from_jpeg(self) -> None:
+ """JPEG magic bytes yield ``image/jpeg``."""
+ jpeg_bytes = b"\xff\xd8\xff\xe0rest-of-jpeg"
+ parser = ImageParser()
+ sections = await parser.parse(jpeg_bytes, "x.jpg")
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": base64.b64encode(jpeg_bytes).decode(
+ "utf-8",
+ ),
+ "media_type": "image/jpeg",
+ },
+ "name": "x.jpg",
+ },
+ "source": "x.jpg",
+ "metadata": {"media_type": "image/jpeg"},
+ },
+ ],
+ )
+
+ async def test_string_input_treated_as_path(self) -> None:
+ """``str`` is interpreted as a filesystem path to the image."""
+ import tempfile
+
+ with tempfile.NamedTemporaryFile(
+ suffix=".png",
+ delete=False,
+ ) as f:
+ f.write(_PNG_PIXEL)
+ path = f.name
+ try:
+ parser = ImageParser()
+ sections = await parser.parse(path, "pixel.png")
+ self.assertEqual(len(sections), 1)
+ finally:
+ os.unlink(path)
+
+ async def test_missing_path_raises_file_not_found(self) -> None:
+ """A ``str`` pointing at a missing path raises FileNotFoundError."""
+ parser = ImageParser()
+ with self.assertRaises(FileNotFoundError):
+ await parser.parse("/no/such/file.png", "x.png")
+
+
+class PPTParserTest(IsolatedAsyncioTestCase):
+ """Behavioural coverage for :class:`PPTParser`."""
+
+ async def test_simple_deck_text_only(self) -> None:
+ """A simple text-only deck round-trips through wrapping tags."""
+ pptx_bytes = _make_pptx_simple(["Alpha", "Beta"])
+ parser = PPTParser(include_image=False)
+ sections = await parser.parse(pptx_bytes, "demo.pptx")
+
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=1>\nAlpha\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "demo.pptx",
+ "metadata": {"slide": 1},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=2>\nBeta\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "demo.pptx",
+ "metadata": {"slide": 2},
+ },
+ ],
+ )
+
+ async def test_without_slide_tags(self) -> None:
+ """Disabling prefix/suffix removes the slide tags entirely."""
+ pptx_bytes = _make_pptx_simple(["Alpha"])
+ parser = PPTParser(
+ include_image=False,
+ slide_prefix=None,
+ slide_suffix=None,
+ )
+ sections = await parser.parse(pptx_bytes, "demo.pptx")
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "Alpha",
+ "id": AnyString(),
+ },
+ "source": "demo.pptx",
+ "metadata": {"slide": 1},
+ },
+ ],
+ )
+
+ async def test_table_merges_with_surrounding_text_by_default(
+ self,
+ ) -> None:
+ """``separate_table=False`` merges the table into the running
+ text section."""
+ pptx_bytes = _make_pptx_rich()
+ parser = PPTParser(include_image=False, separate_table=False)
+ sections = await parser.parse(pptx_bytes, "rich.pptx")
+
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=1>\nHello\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 1},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": (
+ "<slide index=2>\n"
+ "Header\n"
+ "| A | B |\n"
+ "| --- | --- |\n"
+ "| 1 | 2 |\n\n"
+ "Footer\n"
+ "</slide>"
+ ),
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=3>\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 3},
+ },
+ ],
+ )
+
+ async def test_table_separated_when_separate_table_true(self) -> None:
+ """``separate_table=True`` flushes the running text around the
+ table."""
+ pptx_bytes = _make_pptx_rich()
+ parser = PPTParser(include_image=False, separate_table=True)
+ sections = await parser.parse(pptx_bytes, "rich.pptx")
+
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=1>\nHello\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 1},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=2>\nHeader",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": (
+ "| A | B |\n" "| --- | --- |\n" "| 1 | 2 |\n"
+ ),
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "Footer\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=3>\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 3},
+ },
+ ],
+ )
+
+ async def test_image_emits_data_block(self) -> None:
+ """An embedded picture becomes its own DataBlock section."""
+ pptx_bytes = _make_pptx_rich()
+ parser = PPTParser(include_image=True, separate_table=True)
+ sections = await parser.parse(pptx_bytes, "rich.pptx")
+
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=1>\nHello\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 1},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=2>\nHeader",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": (
+ "| A | B |\n" "| --- | --- |\n" "| 1 | 2 |\n"
+ ),
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "Footer\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=3>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 3},
+ },
+ {
+ "content": {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": _PNG_PIXEL_B64,
+ "media_type": "image/png",
+ },
+ "name": "rich.pptx",
+ },
+ "source": "rich.pptx",
+ "metadata": {
+ "slide": 3,
+ "media_type": "image/png",
+ },
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 3},
+ },
+ ],
+ )
+
+ async def test_table_json_format(self) -> None:
+ """``table_format="json"`` emits the JSON marker payload."""
+ pptx_bytes = _make_pptx_rich()
+ parser = PPTParser(
+ include_image=False,
+ separate_table=True,
+ table_format="json",
+ )
+ sections = await parser.parse(pptx_bytes, "rich.pptx")
+
+ self.assertEqual(
+ [s.model_dump() for s in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=1>\nHello\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 1},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=2>\nHeader",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": (
+ "<system-info>A table loaded as a JSON "
+ "array:</system-info>\n"
+ '[["A", "B"], ["1", "2"]]'
+ ),
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "Footer\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 2},
+ },
+ {
+ "content": {
+ "type": "text",
+ "text": "<slide index=3>\n</slide>",
+ "id": AnyString(),
+ },
+ "source": "rich.pptx",
+ "metadata": {"slide": 3},
+ },
+ ],
+ )
+
+ async def test_table_format_validation(self) -> None:
+ """Unknown ``table_format`` raises :class:`ValueError`."""
+ with self.assertRaises(ValueError):
+ PPTParser(table_format="csv") # type: ignore[arg-type]
+
+ async def test_string_input_treated_as_path(self) -> None:
+ """``str`` is interpreted as a filesystem path to the PPTX."""
+ import tempfile
+
+ pptx_bytes = _make_pptx_simple(["Alpha"])
+ with tempfile.NamedTemporaryFile(
+ suffix=".pptx",
+ delete=False,
+ ) as f:
+ f.write(pptx_bytes)
+ path = f.name
+ try:
+ parser = PPTParser(include_image=False)
+ sections = await parser.parse(path, "demo.pptx")
+ self.assertEqual(len(sections), 1)
+ finally:
+ os.unlink(path)
+
+ async def test_missing_path_raises_file_not_found(self) -> None:
+ """A ``str`` pointing at a missing path raises FileNotFoundError."""
+ parser = PPTParser()
+ with self.assertRaises(FileNotFoundError):
+ await parser.parse("/no/such/file.pptx", "x.pptx")
diff --git a/tests/rag_vdb_qdrant_test.py b/tests/rag_vdb_qdrant_test.py
new file mode 100644
index 000000000..54acd8499
--- /dev/null
+++ b/tests/rag_vdb_qdrant_test.py
@@ -0,0 +1,376 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for the QdrantStore class."""
+from contextlib import AsyncExitStack
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from utils import AnyString
+
+from agentscope.message import TextBlock
+from agentscope.rag import (
+ Chunk,
+ QdrantStore,
+ VectorRecord,
+ VectorSearchResult,
+)
+
+
+def _dump_results(results: list[VectorSearchResult]) -> list[dict]:
+ """Convert search results into plain dicts for whole-structure
+ comparison.
+
+ Args:
+ results (`list[VectorSearchResult]`):
+ The search results to convert.
+
+ Returns:
+ `list[dict]`:
+ The results as plain dicts.
+ """
+ return [result.model_dump() for result in results]
+
+
+def _make_record(
+ text: str,
+ vector: list[float],
+ document_id: str,
+ chunk_index: int = 0,
+ total_chunks: int = 1,
+) -> VectorRecord:
+ """Build a VectorRecord for testing.
+
+ Args:
+ text (`str`):
+ The chunk text content.
+ vector (`list[float]`):
+ The embedding vector.
+ document_id (`str`):
+ The ID of the source document the record belongs to.
+ chunk_index (`int`, defaults to ``0``):
+ The chunk index within the document.
+ total_chunks (`int`, defaults to ``1``):
+ The total number of chunks in the document.
+
+ Returns:
+ `VectorRecord`:
+ The constructed record.
+ """
+ return VectorRecord(
+ vector=vector,
+ document_id=document_id,
+ chunk=Chunk(
+ content=TextBlock(text=text),
+ source=f"{document_id}.txt",
+ chunk_index=chunk_index,
+ total_chunks=total_chunks,
+ ),
+ )
+
+
+class QdrantStoreTest(IsolatedAsyncioTestCase):
+ """The test cases for the QdrantStore class."""
+
+ async def asyncSetUp(self) -> None:
+ """Create an in-memory Qdrant store before each test."""
+ self._exit_stack = AsyncExitStack()
+ self.store = await self._exit_stack.enter_async_context(
+ QdrantStore(location=":memory:"),
+ )
+
+ async def asyncTearDown(self) -> None:
+ """Close the store after each test."""
+ await self._exit_stack.aclose()
+
+ async def test_collection_lifecycle(self) -> None:
+ """Collections can be created, checked, and deleted."""
+ self.assertEqual(await self.store.has_collection("kb-1"), False)
+
+ await self.store.create_collection("kb-1", dimensions=3)
+ self.assertEqual(await self.store.has_collection("kb-1"), True)
+
+ # Creating an existing collection is a no-op
+ await self.store.create_collection("kb-1", dimensions=3)
+ self.assertEqual(await self.store.has_collection("kb-1"), True)
+
+ await self.store.delete_collection("kb-1")
+ self.assertEqual(await self.store.has_collection("kb-1"), False)
+
+ async def test_insert_and_search(self) -> None:
+ """Inserted records are searchable, ordered by similarity."""
+ await self.store.create_collection("kb-1", dimensions=3)
+ await self.store.insert(
+ "kb-1",
+ [
+ _make_record(
+ "Hello world!",
+ [1.0, 0.0, 0.0],
+ document_id="doc-1",
+ chunk_index=0,
+ total_chunks=2,
+ ),
+ _make_record(
+ "Goodbye world!",
+ [0.0, 1.0, 0.0],
+ document_id="doc-1",
+ chunk_index=1,
+ total_chunks=2,
+ ),
+ ],
+ )
+
+ results = await self.store.search(
+ "kb-1",
+ query_vector=[1.0, 0.0, 0.0],
+ top_k=2,
+ )
+
+ self.assertEqual(
+ _dump_results(results),
+ [
+ {
+ "score": 1.0,
+ "document_id": "doc-1",
+ "chunk": {
+ "content": {
+ "type": "text",
+ "text": "Hello world!",
+ "id": AnyString(),
+ },
+ "source": "doc-1.txt",
+ "chunk_index": 0,
+ "total_chunks": 2,
+ "metadata": {},
+ },
+ },
+ {
+ "score": 0.0,
+ "document_id": "doc-1",
+ "chunk": {
+ "content": {
+ "type": "text",
+ "text": "Goodbye world!",
+ "id": AnyString(),
+ },
+ "source": "doc-1.txt",
+ "chunk_index": 1,
+ "total_chunks": 2,
+ "metadata": {},
+ },
+ },
+ ],
+ )
+
+ async def test_search_top_k(self) -> None:
+ """top_k limits the number of returned results."""
+ await self.store.create_collection("kb-1", dimensions=3)
+ await self.store.insert(
+ "kb-1",
+ [
+ _make_record("A", [1.0, 0.0, 0.0], document_id="doc-1"),
+ _make_record("B", [0.9, 0.1, 0.0], document_id="doc-2"),
+ _make_record("C", [0.0, 0.0, 1.0], document_id="doc-3"),
+ ],
+ )
+
+ results = await self.store.search(
+ "kb-1",
+ query_vector=[1.0, 0.0, 0.0],
+ top_k=1,
+ )
+
+ self.assertEqual(
+ _dump_results(results),
+ [
+ {
+ "score": 1.0,
+ "document_id": "doc-1",
+ "chunk": {
+ "content": {
+ "type": "text",
+ "text": "A",
+ "id": AnyString(),
+ },
+ "source": "doc-1.txt",
+ "chunk_index": 0,
+ "total_chunks": 1,
+ "metadata": {},
+ },
+ },
+ ],
+ )
+
+ async def test_delete_by_document_id(self) -> None:
+ """delete removes all records of one document only."""
+ await self.store.create_collection("kb-1", dimensions=3)
+ await self.store.insert(
+ "kb-1",
+ [
+ _make_record(
+ "doc1-chunk0",
+ [1.0, 0.0, 0.0],
+ document_id="doc-1",
+ chunk_index=0,
+ total_chunks=2,
+ ),
+ _make_record(
+ "doc1-chunk1",
+ [0.9, 0.1, 0.0],
+ document_id="doc-1",
+ chunk_index=1,
+ total_chunks=2,
+ ),
+ _make_record(
+ "doc2-chunk0",
+ [0.0, 1.0, 0.0],
+ document_id="doc-2",
+ ),
+ ],
+ )
+
+ await self.store.delete("kb-1", document_id="doc-1")
+
+ results = await self.store.search(
+ "kb-1",
+ query_vector=[1.0, 0.0, 0.0],
+ top_k=5,
+ )
+
+ self.assertEqual(
+ _dump_results(results),
+ [
+ {
+ "score": 0.0,
+ "document_id": "doc-2",
+ "chunk": {
+ "content": {
+ "type": "text",
+ "text": "doc2-chunk0",
+ "id": AnyString(),
+ },
+ "source": "doc-2.txt",
+ "chunk_index": 0,
+ "total_chunks": 1,
+ "metadata": {},
+ },
+ },
+ ],
+ )
+
+ async def test_insert_empty_records(self) -> None:
+ """Inserting an empty record list is a no-op."""
+ await self.store.create_collection("kb-1", dimensions=3)
+ await self.store.insert("kb-1", [])
+
+ results = await self.store.search(
+ "kb-1",
+ query_vector=[1.0, 0.0, 0.0],
+ )
+
+ self.assertEqual(_dump_results(results), [])
+
+ async def test_list_documents_aggregates_by_document_id(self) -> None:
+ """list_documents groups chunks by document_id."""
+ await self.store.create_collection("kb-1", dimensions=3)
+
+ def _record_with_metadata(
+ text: str,
+ document_id: str,
+ metadata: dict,
+ chunk_index: int = 0,
+ total_chunks: int = 1,
+ ) -> VectorRecord:
+ return VectorRecord(
+ vector=[1.0, 0.0, 0.0],
+ document_id=document_id,
+ chunk=Chunk(
+ content=TextBlock(text=text),
+ source=metadata.get("filename", f"{document_id}.txt"),
+ chunk_index=chunk_index,
+ total_chunks=total_chunks,
+ metadata=metadata,
+ ),
+ )
+
+ await self.store.insert(
+ "kb-1",
+ [
+ _record_with_metadata(
+ "A",
+ "doc-1",
+ {"filename": "alpha.txt", "media_type": "text/plain"},
+ 0,
+ 2,
+ ),
+ _record_with_metadata(
+ "B",
+ "doc-1",
+ {"filename": "alpha.txt", "media_type": "text/plain"},
+ 1,
+ 2,
+ ),
+ _record_with_metadata(
+ "C",
+ "doc-2",
+ {"filename": "beta.md", "media_type": "text/markdown"},
+ 0,
+ 1,
+ ),
+ ],
+ )
+
+ summaries = await self.store.list_documents("kb-1")
+ summaries_by_id = {s.document_id: s for s in summaries}
+
+ self.assertEqual(set(summaries_by_id), {"doc-1", "doc-2"})
+ self.assertEqual(summaries_by_id["doc-1"].chunk_count, 2)
+ self.assertEqual(summaries_by_id["doc-1"].source, "alpha.txt")
+ self.assertEqual(
+ summaries_by_id["doc-1"].metadata,
+ {"filename": "alpha.txt", "media_type": "text/plain"},
+ )
+ self.assertEqual(summaries_by_id["doc-2"].chunk_count, 1)
+ self.assertEqual(summaries_by_id["doc-2"].source, "beta.md")
+
+ async def test_search_metadata_filter(self) -> None:
+ """search applies the metadata_filter as a payload predicate."""
+ await self.store.create_collection("kb-1", dimensions=3)
+
+ def _record(
+ text: str,
+ document_id: str,
+ kb_scope: str,
+ ) -> VectorRecord:
+ return VectorRecord(
+ vector=[1.0, 0.0, 0.0],
+ document_id=document_id,
+ chunk=Chunk(
+ content=TextBlock(text=text),
+ source=f"{document_id}.txt",
+ chunk_index=0,
+ total_chunks=1,
+ metadata={"kb_scope": kb_scope},
+ ),
+ )
+
+ await self.store.insert(
+ "kb-1",
+ [
+ _record("A", "doc-1", "kb-a"),
+ _record("B", "doc-2", "kb-b"),
+ ],
+ )
+
+ results = await self.store.search(
+ "kb-1",
+ query_vector=[1.0, 0.0, 0.0],
+ top_k=5,
+ metadata_filter={"kb_scope": "kb-a"},
+ )
+ self.assertEqual([r.document_id for r in results], ["doc-1"])
+
+ results = await self.store.search(
+ "kb-1",
+ query_vector=[1.0, 0.0, 0.0],
+ top_k=5,
+ metadata_filter={"kb_scope": "kb-b"},
+ )
+ self.assertEqual([r.document_id for r in results], ["doc-2"])
diff --git a/tests/service_enqueue_index_task_test.py b/tests/service_enqueue_index_task_test.py
new file mode 100644
index 000000000..1d495c4f7
--- /dev/null
+++ b/tests/service_enqueue_index_task_test.py
@@ -0,0 +1,154 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Tests for :func:`agentscope.app._bus_ops.enqueue_index_task`.
+
+The helper is a three-line composition over two bus primitives —
+``queue_push`` and ``publish`` — so the tests verify only that:
+
+- the queued payload carries the three fields the
+ :class:`~agentscope.app._service.IndexTaskConsumer` reads;
+- a signal is published exactly once per call;
+- both primitives reach the production
+ :class:`~agentscope.app.message_bus.RedisMessageBus` backend
+ (proxied by ``fakeredis``), not just an in-memory mock — keeping
+ the test honest against the wire-level contract the worker side
+ relies on.
+
+If a future change adds metadata to the payload, this test is the
+contract gate: callers are expected to keep ``user_id`` /
+``knowledge_base_id`` / ``document_id`` as the primary keys.
+"""
+import asyncio
+from contextlib import AsyncExitStack
+from unittest import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+
+from agentscope.app._bus_ops import enqueue_index_task
+from agentscope.app.message_bus import MessageBusKeys, RedisMessageBus
+
+
+def _make_bus(fr: fakeredis.aioredis.FakeRedis) -> RedisMessageBus:
+ """Construct a :class:`RedisMessageBus` bound to *fr*.
+
+ Args:
+ fr (`fakeredis.aioredis.FakeRedis`):
+ The fake Redis client to inject into the bus.
+
+ Returns:
+ `RedisMessageBus`:
+ A bus subclass whose ``__aenter__`` skips the real
+ connection setup and binds *fr* as the client.
+ """
+
+ class _B(RedisMessageBus):
+ """Test-only bus that reuses the supplied fakeredis client."""
+
+ async def __aenter__(
+ self,
+ ) -> "RedisMessageBus": # type: ignore[override]
+ """Bind the pre-supplied fakeredis client and return self.
+
+ Returns:
+ `RedisMessageBus`:
+ This bus, ready for the with-block body.
+ """
+ self._client = fr
+ return self
+
+ async def aclose(self) -> None:
+ """Drop the client reference without touching the network."""
+ self._client = None
+
+ return _B()
+
+
+class TestEnqueueIndexTask(IsolatedAsyncioTestCase):
+ """Verifies the queue_push + publish composition."""
+
+ async def asyncSetUp(self) -> None:
+ """Wire a fakeredis-backed bus into an async exit stack."""
+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ self._stack = AsyncExitStack()
+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))
+
+ async def asyncTearDown(self) -> None:
+ """Tear the exit stack and the fakeredis client down."""
+ await self._stack.aclose()
+ await self.fr.aclose()
+
+ async def test_enqueue_pushes_payload_and_publishes_signal(
+ self,
+ ) -> None:
+ """One enqueue puts one structured entry on the durable queue
+ and one opaque payload on the signal channel.
+
+ Order matters: the queue push must precede the publish so a
+ worker woken by the signal is guaranteed to find the entry
+ when it drains. We do not assert order directly (would
+ require instrumenting the bus), but we assert both primitives
+ landed.
+ """
+ ready = asyncio.Event()
+ received: list[dict] = []
+
+ async def _signal_consumer() -> None:
+ """Consume one signal payload and exit."""
+ async for payload in self.bus.subscribe(
+ MessageBusKeys.index_tasks_signal(),
+ on_ready=ready.set,
+ ):
+ received.append(payload)
+ break
+
+ task = asyncio.create_task(_signal_consumer())
+ await asyncio.wait_for(ready.wait(), timeout=2.0)
+
+ await enqueue_index_task(
+ self.bus,
+ user_id="u",
+ knowledge_base_id="kb",
+ document_id="doc",
+ )
+ await asyncio.wait_for(task, timeout=2.0)
+
+ # Signal was published.
+ self.assertEqual(len(received), 1)
+
+ # Queue holds the structured entry under the well-known key.
+ entries = await self.bus.queue_drain(
+ MessageBusKeys.index_tasks_queue(),
+ max_count=10,
+ )
+ self.assertEqual(len(entries), 1)
+ _entry_id, payload = entries[0]
+ self.assertEqual(
+ payload,
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "doc",
+ },
+ )
+
+ async def test_double_enqueue_queues_twice(self) -> None:
+ """Two enqueues for the same document leave two entries on
+ the queue — the helper is intentionally not deduplicating,
+ the worker's lease CAS is the dedup contract."""
+ await enqueue_index_task(
+ self.bus,
+ user_id="u",
+ knowledge_base_id="kb",
+ document_id="doc",
+ )
+ await enqueue_index_task(
+ self.bus,
+ user_id="u",
+ knowledge_base_id="kb",
+ document_id="doc",
+ )
+ entries = await self.bus.queue_drain(
+ MessageBusKeys.index_tasks_queue(),
+ max_count=10,
+ )
+ self.assertEqual(len(entries), 2)
diff --git a/tests/service_index_task_consumer_test.py b/tests/service_index_task_consumer_test.py
new file mode 100644
index 000000000..839d2eb99
--- /dev/null
+++ b/tests/service_index_task_consumer_test.py
@@ -0,0 +1,399 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Tests for :class:`IndexTaskConsumer` — the worker-process side of
+the message-bus index dispatch flow.
+
+Verifies the four behaviours callers rely on:
+
+- Lifecycle is purely ACM: ``__aenter__`` starts the loop and performs
+ an initial drain; ``__aexit__`` cancels the loop and any in-flight
+ ``worker.process`` task cleanly.
+- A signal triggers a queue drain; each entry is dispatched as a
+ ``worker.process`` call.
+- Entries left on the queue from before ``__aenter__`` are picked up
+ on the initial drain without waiting for a fresh signal.
+- Malformed entries are logged and skipped, not raised; later valid
+ entries still dispatch.
+- An exception inside ``worker.process`` is logged but does not crash
+ the consumer loop — subsequent signals still drain.
+
+Mirrors :mod:`service_wakeup_dispatcher_test` deliberately; the
+flows are identical at the primitive level.
+"""
+import asyncio
+from contextlib import asynccontextmanager
+from typing import AsyncGenerator, Callable
+from unittest import IsolatedAsyncioTestCase
+
+from agentscope.app._service import IndexTaskConsumer
+from agentscope.app.message_bus import MessageBus, MessageBusKeys
+
+
+class _FakeBus(MessageBus):
+ """In-memory bus with just enough behaviour for the consumer.
+
+ Implements the primitives the consumer actually uses
+ (``queue_push`` / ``queue_drain`` / ``subscribe`` / ``publish``)
+ and stubs the others. The consumer reaches for the bus through
+ the well-known channel/key constants — no domain methods exist
+ on the bus.
+ """
+
+ def __init__(self) -> None:
+ self.queues: dict[str, list[tuple[str, dict]]] = {}
+ self._channels: dict[str, asyncio.Queue] = {}
+ self._next = 0
+ self._locks: set[str] = set()
+
+ def _channel(self, key: str) -> asyncio.Queue:
+ return self._channels.setdefault(key, asyncio.Queue())
+
+ # Mode A — queue
+ async def queue_push(
+ self,
+ key: str,
+ payload: dict,
+ *,
+ ttl_secs: int | None = None,
+ ) -> str:
+ self._next += 1
+ entry_id = str(self._next)
+ self.queues.setdefault(key, []).append((entry_id, payload))
+ return entry_id
+
+ async def queue_drain(
+ self,
+ key: str,
+ *,
+ max_count: int,
+ ) -> list[tuple[str, dict]]:
+ entries = self.queues.get(key, [])[:max_count]
+ self.queues[key] = self.queues.get(key, [])[max_count:]
+ return entries
+
+ async def queue_delete(self, key: str) -> None:
+ self.queues.pop(key, None)
+
+ # Mode C — log (unused)
+ async def log_append(
+ self,
+ key: str,
+ payload: dict,
+ *,
+ max_len: int | None = None,
+ ttl_secs: int | None = None,
+ ) -> str:
+ return "n/a"
+
+ async def log_read(
+ self,
+ key: str,
+ since: str | None = None,
+ max_count: int = 100,
+ ) -> list[tuple[str, dict]]:
+ return []
+
+ async def log_trim(
+ self,
+ key: str,
+ before_id: str | None = None,
+ ) -> None:
+ return None
+
+ # Mode D — pub/sub
+ async def publish(self, key: str, payload: dict) -> None:
+ await self._channel(key).put(payload)
+
+ async def subscribe(
+ self,
+ key: str,
+ *,
+ on_ready: Callable[[], None] | None = None,
+ ) -> AsyncGenerator[dict, None]:
+ if on_ready is not None:
+ on_ready()
+ while True:
+ yield await self._channel(key).get()
+
+ # Mode E — lock
+ @asynccontextmanager
+ async def acquire_lock(
+ self,
+ key: str,
+ *,
+ ttl_secs: int = 600,
+ ) -> AsyncGenerator[None, None]:
+ self._locks.add(key)
+ try:
+ yield
+ finally:
+ self._locks.discard(key)
+
+ async def is_locked(self, key: str) -> bool:
+ return key in self._locks
+
+ # Mode F — registry (unused by IndexTaskConsumer; raise so any
+ # accidental dependency surfaces immediately rather than silently
+ # passing through a stub).
+ async def registry_set(
+ self,
+ namespace: str,
+ field: str,
+ value: str,
+ *,
+ ttl_secs: int | None = None,
+ ) -> None:
+ raise NotImplementedError
+
+ async def registry_del(self, namespace: str, field: str) -> None:
+ raise NotImplementedError
+
+ async def registry_exists(self, namespace: str, field: str) -> bool:
+ raise NotImplementedError
+
+ async def registry_getall(self, namespace: str) -> dict[str, str]:
+ raise NotImplementedError
+
+ async def registry_drop(self, namespace: str) -> None:
+ raise NotImplementedError
+
+
+class _RecordingWorker:
+ """Records calls to :meth:`process` so tests can assert dispatch.
+
+ The real ``IndexWorker`` has many more methods, but the consumer
+ only ever invokes :meth:`process` — so the test surface stays
+ narrow on purpose.
+ """
+
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+ self.notify = asyncio.Event()
+ self.fail_on_doc: str | None = None
+ self.process_delay = 0.0
+
+ async def process(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ document_id: str,
+ ) -> None:
+ """Record the call and signal the test, optionally failing or
+ sleeping first to exercise the consumer's error and timing
+ paths.
+
+ Args:
+ user_id (`str`):
+ The owning user id forwarded by the consumer.
+ knowledge_base_id (`str`):
+ The knowledge base id forwarded by the consumer.
+ document_id (`str`):
+ The document id forwarded by the consumer.
+
+ Raises:
+ `RuntimeError`:
+ When ``fail_on_doc`` matches ``document_id`` — used by
+ the consumer-resilience tests.
+ """
+ if self.process_delay:
+ await asyncio.sleep(self.process_delay)
+ self.calls.append(
+ {
+ "user_id": user_id,
+ "knowledge_base_id": knowledge_base_id,
+ "document_id": document_id,
+ },
+ )
+ self.notify.set()
+ if self.fail_on_doc and document_id == self.fail_on_doc:
+ raise RuntimeError(f"boom for {document_id}")
+
+
+async def _yield_a_few_times(ticks: int = 8) -> None:
+ """Yield the event loop a few times so spawned tasks make progress."""
+ for _ in range(ticks):
+ await asyncio.sleep(0)
+
+
+class TestIndexTaskConsumerDispatch(IsolatedAsyncioTestCase):
+ """Verifies the signal-driven dispatch path."""
+
+ async def test_signal_drives_dispatch(self) -> None:
+ """A signal causes the queue to be drained and each entry
+ dispatched as ``worker.process``."""
+ bus = _FakeBus()
+ worker = _RecordingWorker()
+ async with IndexTaskConsumer(message_bus=bus, worker=worker):
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "d1",
+ },
+ )
+ await bus.publish(MessageBusKeys.index_tasks_signal(), {})
+
+ await asyncio.wait_for(worker.notify.wait(), timeout=2.0)
+
+ self.assertEqual(
+ worker.calls,
+ [
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "d1",
+ },
+ ],
+ )
+
+ async def test_initial_drain_picks_up_pending_entries(self) -> None:
+ """Entries on the queue from before ``__aenter__`` are picked
+ up without waiting for a fresh signal."""
+ bus = _FakeBus()
+ worker = _RecordingWorker()
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "pre",
+ },
+ )
+
+ async with IndexTaskConsumer(message_bus=bus, worker=worker):
+ await asyncio.wait_for(worker.notify.wait(), timeout=2.0)
+
+ self.assertEqual(
+ worker.calls,
+ [
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "pre",
+ },
+ ],
+ )
+
+ async def test_malformed_entry_skipped(self) -> None:
+ """A queue entry missing required fields is logged and
+ skipped, not raised; later valid entries still dispatch."""
+ bus = _FakeBus()
+ worker = _RecordingWorker()
+
+ async with IndexTaskConsumer(message_bus=bus, worker=worker):
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {"oops": True},
+ )
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "d2",
+ },
+ )
+ await bus.publish(MessageBusKeys.index_tasks_signal(), {})
+ await asyncio.wait_for(worker.notify.wait(), timeout=2.0)
+
+ self.assertEqual(
+ worker.calls,
+ [
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "d2",
+ },
+ ],
+ )
+
+ async def test_worker_exception_is_isolated(self) -> None:
+ """An exception inside ``worker.process`` for one entry does
+ not stop subsequent entries from dispatching."""
+ bus = _FakeBus()
+ worker = _RecordingWorker()
+ worker.fail_on_doc = "boom"
+
+ async with IndexTaskConsumer(message_bus=bus, worker=worker):
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "boom",
+ },
+ )
+ await bus.publish(MessageBusKeys.index_tasks_signal(), {})
+ # Reset notify so we can wait for the *second* dispatch.
+ await _yield_a_few_times()
+ worker.notify.clear()
+
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "ok",
+ },
+ )
+ await bus.publish(MessageBusKeys.index_tasks_signal(), {})
+ await asyncio.wait_for(worker.notify.wait(), timeout=2.0)
+
+ doc_ids = [c["document_id"] for c in worker.calls]
+ self.assertEqual(doc_ids, ["boom", "ok"])
+
+
+class TestIndexTaskConsumerLifecycle(IsolatedAsyncioTestCase):
+ """Tests covering the ``__aenter__`` / ``__aexit__`` ACM behaviour."""
+
+ async def test_exit_cancels_loop_cleanly(self) -> None:
+ """``__aexit__`` cancels the consumer's loop task and returns
+ without re-raising the cancellation."""
+ bus = _FakeBus()
+ worker = _RecordingWorker()
+ consumer = IndexTaskConsumer(message_bus=bus, worker=worker)
+
+ # pylint: disable=unnecessary-dunder-call
+ await consumer.__aenter__()
+ loop_task = consumer._task
+ self.assertIsNotNone(loop_task)
+
+ await consumer.__aexit__(None, None, None)
+
+ self.assertIsNone(consumer._task)
+ self.assertTrue(loop_task.cancelled() or loop_task.done())
+
+ async def test_exit_drains_inflight_tasks(self) -> None:
+ """``__aexit__`` cancels in-flight ``worker.process`` tasks
+ and waits for them to settle so exceptions surface in logs
+ and the event loop does not close on top of running
+ coroutines."""
+ bus = _FakeBus()
+ worker = _RecordingWorker()
+ # Make worker.process slow so the consumer exits while one
+ # process call is still mid-flight.
+ worker.process_delay = 0.2
+
+ consumer = IndexTaskConsumer(message_bus=bus, worker=worker)
+ # pylint: disable=unnecessary-dunder-call
+ await consumer.__aenter__()
+
+ await bus.queue_push(
+ MessageBusKeys.index_tasks_queue(),
+ {
+ "user_id": "u",
+ "knowledge_base_id": "kb",
+ "document_id": "slow",
+ },
+ )
+ await bus.publish(MessageBusKeys.index_tasks_signal(), {})
+ # Give the loop a tick to start the worker task.
+ await asyncio.sleep(0)
+ self.assertGreaterEqual(len(consumer._inflight), 1)
+
+ await consumer.__aexit__(None, None, None)
+
+ # The in-flight set is cleared and the consumer task is gone.
+ self.assertEqual(consumer._inflight, set())
+ self.assertIsNone(consumer._task)
diff --git a/tests/service_knowledge_base_upload_test.py b/tests/service_knowledge_base_upload_test.py
new file mode 100644
index 000000000..195735e65
--- /dev/null
+++ b/tests/service_knowledge_base_upload_test.py
@@ -0,0 +1,444 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""End-to-end wiring test for the knowledge-base upload pipeline.
+
+Boots the full FastAPI app via :func:`create_app` against fakeredis +
+in-memory KB-side fakes, then drives the upload → status → list →
+delete flow through ``TestClient``. Verifies that:
+
+* ``create_app`` wires the new ``blob_store`` / dispatcher / sweeper /
+ service into ``app.state`` correctly;
+* the upload endpoint streams bytes into the blob store, persists a
+ ``pending`` record, and dispatches the worker;
+* the in-process worker drives the record to ``ready`` through the
+ parse → chunk → index phases;
+* the status / list endpoints surface the lifecycle correctly;
+* delete tears down the vector-store and storage records together.
+"""
+import asyncio
+import tempfile
+from typing import Any
+from unittest.async_case import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+from fastapi.testclient import TestClient
+
+from agentscope.app import create_app
+from agentscope.app.rag.blob_store import LocalBlobStore
+from agentscope.app.rag.knowledge_base_manager import (
+ KnowledgeBaseManagerBase,
+ KnowledgeBaseNotFoundError,
+)
+from agentscope.app.rag.knowledge_base_manager._dimension_policy import (
+ DimensionPolicy,
+ DimensionPolicyKind,
+)
+from agentscope.app.message_bus import RedisMessageBus
+from agentscope.app.storage import (
+ EmbeddingModelConfig,
+ KnowledgeBaseRecord,
+ RedisStorage,
+)
+from agentscope.app.workspace_manager._base import WorkspaceManagerBase
+from agentscope.rag import VectorStoreBase
+from agentscope.rag._vdb._vector_store import (
+ DocumentSummary,
+ VectorRecord,
+ VectorSearchResult,
+)
+
+
+# ----------------------------------------------------------------------
+# Test doubles
+# ----------------------------------------------------------------------
+
+
+class _FakeVectorStore(VectorStoreBase):
+ """In-memory vector store — records are kept by collection.
+
+ The worker never reads back from it, so there is no need for real
+ similarity math; we only have to honour the ``insert`` / ``delete``
+ / ``has_collection`` contract.
+ """
+
+ def __init__(self) -> None:
+ self._collections: dict[str, list[VectorRecord]] = {}
+
+ async def create_collection(self, name: str, dimensions: int) -> None:
+ self._collections.setdefault(name, [])
+
+ async def delete_collection(self, name: str) -> None:
+ self._collections.pop(name, None)
+
+ async def has_collection(self, name: str) -> bool:
+ return name in self._collections
+
+ async def insert(
+ self,
+ collection: str,
+ records: list[VectorRecord],
+ ) -> None:
+ self._collections.setdefault(collection, []).extend(records)
+
+ async def delete(self, collection: str, document_id: str) -> None:
+ bucket = self._collections.get(collection)
+ if bucket is None:
+ return
+ self._collections[collection] = [
+ r for r in bucket if r.document_id != document_id
+ ]
+
+ async def search(
+ self,
+ collection: str,
+ query_vector: list[float],
+ top_k: int = 5,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[VectorSearchResult]:
+ return []
+
+ async def list_documents(
+ self,
+ collection: str,
+ metadata_filter: dict[str, Any] | None = None,
+ ) -> list[DocumentSummary]:
+ return []
+
+
+class _FakeKnowledge:
+ """Minimal stand-in for :class:`KnowledgeBase` used by the worker.
+
+ Bypasses embedding-model construction — instead just funnels the
+ chunks into the bound :class:`_FakeVectorStore` with a fixed
+ zero-vector so ``insert_document`` succeeds end-to-end.
+ """
+
+ def __init__(
+ self,
+ vector_store: _FakeVectorStore,
+ collection_name: str,
+ ) -> None:
+ self._vector_store = vector_store
+ self._collection_name = collection_name
+
+ async def insert_document(
+ self,
+ chunks: list,
+ document_id: str | None = None,
+ document_metadata: dict | None = None,
+ ) -> str:
+ """Pretend to embed and insert ``chunks`` into the bound store.
+
+ The fake skips the real embedding step — it stamps a single
+ scalar vector on every record so the upload pipeline can be
+ exercised without an embedding model.
+
+ Args:
+ chunks (`list`):
+ The parsed and chunked document content.
+ document_id (`str | None`, optional):
+ Caller-supplied document id; the fake just echoes it
+ back rather than generating a UUID.
+ document_metadata (`dict | None`, optional):
+ Document-level metadata; ignored — the upload tests
+ don't assert on metadata propagation.
+
+ Returns:
+ `str`:
+ The (caller-supplied) document id, or ``""`` when
+ none was passed.
+ """
+ del document_metadata # unused — see docstring
+ records = [
+ VectorRecord(
+ vector=[0.0],
+ document_id=document_id or "",
+ chunk=chunk,
+ )
+ for chunk in chunks
+ ]
+ await self._vector_store.insert(self._collection_name, records)
+ return document_id or ""
+
+ async def delete_document(self, document_id: str) -> None:
+ """Remove every record for ``document_id`` from the bound store.
+
+ Args:
+ document_id (`str`):
+ The document whose records should be deleted.
+ """
+ await self._vector_store.delete(self._collection_name, document_id)
+
+ async def search(self, queries: list, top_k: int = 5) -> list:
+ """Return an empty result list — search is out of scope here.
+
+ Args:
+ queries (`list`):
+ The query inputs; ignored.
+ top_k (`int`, defaults to ``5``):
+ The maximum result count; ignored.
+
+ Returns:
+ `list`:
+ Always empty — the upload tests do not exercise
+ retrieval.
+ """
+ del queries, top_k # unused — see docstring
+ return []
+
+
+class _FakeKbManager(KnowledgeBaseManagerBase):
+ """KB manager that uses the storage + a fake vector store directly.
+
+ Skips the real ``CollectionPerKbManager`` so we don't need a live
+ embedding model — the indexing pipeline only requires
+ ``insert_document`` / ``delete_document``, which the
+ :class:`_FakeKnowledge` returned here implements directly.
+ """
+
+ async def get_dimension_policy(self) -> DimensionPolicy:
+ return DimensionPolicy(kind=DimensionPolicyKind.ANY, dimension=None)
+
+ async def create_knowledge_base(
+ self,
+ user_id: str,
+ name: str,
+ description: str,
+ embedding_model_config: EmbeddingModelConfig,
+ ) -> KnowledgeBaseRecord:
+ record = KnowledgeBaseRecord(
+ user_id=user_id,
+ name=name,
+ description=description,
+ embedding_model_config=embedding_model_config,
+ collection_name="",
+ )
+ record.collection_name = f"kb_{record.id}"
+ await self._vector_store.create_collection(
+ name=record.collection_name,
+ dimensions=embedding_model_config.dimensions,
+ )
+ return await self._storage.upsert_knowledge_base(user_id, record)
+
+ async def delete_knowledge_base(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> bool:
+ record = await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if record is None:
+ return False
+ await self._vector_store.delete_collection(record.collection_name)
+ return await self._storage.delete_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+
+ async def get_knowledge(
+ self,
+ user_id: str,
+ knowledge_base_id: str,
+ ) -> _FakeKnowledge:
+ record = await self._storage.get_knowledge_base(
+ user_id,
+ knowledge_base_id,
+ )
+ if record is None:
+ raise KnowledgeBaseNotFoundError(
+ f"Knowledge base {knowledge_base_id!r} not found.",
+ )
+ return _FakeKnowledge(
+ vector_store=self._vector_store,
+ collection_name=record.collection_name,
+ )
+
+
+class _NoopWorkspaceManager(WorkspaceManagerBase):
+ """Workspace manager that does nothing — the KB pipeline never
+ touches it, but ``create_app`` requires one to be wired in."""
+
+ async def get_workspace(self, *args: Any, **kwargs: Any) -> Any:
+ raise NotImplementedError
+
+ async def create_workspace(self, *args: Any, **kwargs: Any) -> Any:
+ raise NotImplementedError
+
+ async def close(self, workspace_id: str) -> None:
+ return None
+
+ async def close_all(self) -> None:
+ return None
+
+
+def _make_storage(fr: fakeredis.aioredis.FakeRedis) -> RedisStorage:
+ """Build a RedisStorage already bound to *fr*.
+
+ Pre-populates ``_client`` so the lifespan's ``__aenter__`` no-ops on
+ the connection-pool side and just reuses our fakeredis handle.
+ """
+
+ class _FakeStorage(RedisStorage):
+ async def __aenter__(self) -> "_FakeStorage":
+ self._client = fr
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ return _FakeStorage()
+
+
+def _make_bus(fr: fakeredis.aioredis.FakeRedis) -> RedisMessageBus:
+ """Build a RedisMessageBus bound to *fr* (same trick as in the bus
+ tests)."""
+
+ class _FakeBus(RedisMessageBus):
+ async def __aenter__(self) -> "_FakeBus":
+ self._client = fr
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ return _FakeBus()
+
+
+# ----------------------------------------------------------------------
+# Tests
+# ----------------------------------------------------------------------
+
+
+class KnowledgeBaseUploadFlowTest(IsolatedAsyncioTestCase):
+ """End-to-end wiring of the upload pipeline through ``TestClient``."""
+
+ async def asyncSetUp(self) -> None:
+ self._tmp = tempfile.TemporaryDirectory()
+ self._fr = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ self._vector_store = _FakeVectorStore()
+ storage = _make_storage(self._fr)
+ message_bus = _make_bus(self._fr)
+
+ self._app = create_app(
+ storage=storage,
+ message_bus=message_bus,
+ workspace_manager=_NoopWorkspaceManager(),
+ knowledge_base_manager=_FakeKbManager(
+ storage=storage,
+ vector_store=self._vector_store,
+ ),
+ blob_store=LocalBlobStore(root_dir=self._tmp.name),
+ )
+ # Seed a knowledge base directly through storage so we don't
+ # have to mock the manager's create flow over HTTP.
+ kb_record = KnowledgeBaseRecord(
+ user_id="user-1",
+ name="kb",
+ description="",
+ embedding_model_config=EmbeddingModelConfig(
+ type="openai_credential",
+ credential_id="cred-1",
+ model="text-embedding-3-small",
+ dimensions=1,
+ ),
+ collection_name="",
+ )
+ kb_record.collection_name = f"kb_{kb_record.id}"
+ await self._vector_store.create_collection(
+ kb_record.collection_name,
+ 1,
+ )
+
+ # Drop the seed record into fakeredis directly — we need the KB
+ # in place before lifespan starts the sweeper.
+ storage._client = self._fr
+ await storage.upsert_knowledge_base("user-1", kb_record)
+ storage._client = None
+ self._kb_id = kb_record.id
+
+ async def asyncTearDown(self) -> None:
+ await self._fr.aclose()
+ self._tmp.cleanup()
+
+ async def test_upload_drives_document_to_ready(self) -> None:
+ """Upload a small text file and observe the lifecycle."""
+ headers = {"X-User-ID": "user-1"}
+ with TestClient(self._app) as client:
+ files = {
+ "file": (
+ "hello.txt",
+ b"hello world\n" * 16,
+ "text/plain",
+ ),
+ }
+ resp = client.post(
+ f"/knowledge_bases/{self._kb_id}/documents",
+ files=files,
+ headers=headers,
+ )
+ self.assertEqual(resp.status_code, 201, resp.text)
+ body = resp.json()
+ document_id = body["document_id"]
+ self.assertEqual(body["filename"], "hello.txt")
+ self.assertIn(body["status"], ("pending", "ready"))
+
+ # Wait for the in-process worker to drive the record to
+ # ``ready``. We poll with a generous overall timeout — the
+ # actual work is < 100 ms but CI machines can be slow.
+ deadline = 5.0
+ poll = 0.05
+ elapsed = 0.0
+ final_status = body["status"]
+ while elapsed < deadline:
+ resp = client.get(
+ f"/knowledge_bases/{self._kb_id}/documents/status",
+ params={"ids": document_id},
+ headers=headers,
+ )
+ self.assertEqual(resp.status_code, 200, resp.text)
+ items = resp.json()["items"]
+ self.assertEqual(len(items), 1, items)
+ final_status = items[0]["status"]
+ if final_status in ("ready", "error"):
+ break
+ await asyncio.sleep(poll)
+ elapsed += poll
+ self.assertEqual(final_status, "ready", items)
+
+ # Listing shows the document with the same ``ready`` state.
+ resp = client.get(
+ f"/knowledge_bases/{self._kb_id}/documents",
+ headers=headers,
+ )
+ self.assertEqual(resp.status_code, 200, resp.text)
+ documents = resp.json()["documents"]
+ self.assertEqual(len(documents), 1)
+ self.assertEqual(documents[0]["id"], document_id)
+ self.assertEqual(documents[0]["status"], "ready")
+ self.assertGreaterEqual(documents[0]["chunk_count"], 1)
+
+ # Delete and confirm the listing comes back empty.
+ resp = client.delete(
+ f"/knowledge_bases/{self._kb_id}/documents/{document_id}",
+ headers=headers,
+ )
+ self.assertEqual(resp.status_code, 204, resp.text)
+ resp = client.get(
+ f"/knowledge_bases/{self._kb_id}/documents",
+ headers=headers,
+ )
+ self.assertEqual(resp.json()["documents"], [])
+
+ async def test_status_for_unknown_id_is_silently_skipped(self) -> None:
+ """Asking for a non-existent doc returns an empty items list."""
+ headers = {"X-User-ID": "user-1"}
+ with TestClient(self._app) as client:
+ resp = client.get(
+ f"/knowledge_bases/{self._kb_id}/documents/status",
+ params={"ids": "does-not-exist"},
+ headers=headers,
+ )
+ self.assertEqual(resp.status_code, 200, resp.text)
+ self.assertEqual(resp.json()["items"], [])
diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.py
index 47589e220..61bcb2d18 100644
--- a/tests/service_toolkit_test.py
+++ b/tests/service_toolkit_test.py
@@ -178,6 +178,7 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):
agent_record=agent,
session_record=session,
extra_factory=None,
+ middlewares=[],
)
names = set(_tool_names(toolkit))
@@ -232,6 +233,7 @@ class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):
agent_record=agent,
session_record=session,
extra_factory=None,
+ middlewares=[],
)
names = set(_tool_names(toolkit))
# Only TeamSay from the team toolset.
@@ -268,6 +270,7 @@ class TestGetToolkitSchedulingGuard(IsolatedAsyncioTestCase):
agent_record=agent,
session_record=session,
extra_factory=None,
+ middlewares=[],
)
names = set(_tool_names(toolkit))
for missing in (
@@ -323,5 +326,6 @@ class TestGetToolkitExtraFactory(IsolatedAsyncioTestCase):
agent_record=agent,
session_record=session,
extra_factory=factory,
+ middlewares=[],
)
self.assertIn("my-extra", _tool_names(toolkit))
diff --git a/tests/storage_redis_knowledge_base_test.py b/tests/storage_redis_knowledge_base_test.py
new file mode 100644
index 000000000..f828c73e6
--- /dev/null
+++ b/tests/storage_redis_knowledge_base_test.py
@@ -0,0 +1,110 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Unit tests for the knowledge base persistence layer of RedisStorage."""
+from unittest.async_case import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+
+from agentscope.app.storage import (
+ EmbeddingModelConfig,
+ KnowledgeBaseRecord,
+ RedisStorage,
+)
+
+
+def make_storage() -> RedisStorage:
+ """Create a RedisStorage instance backed by fakeredis."""
+ storage = RedisStorage.__new__(RedisStorage)
+ storage._client = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ storage.key_ttl = None
+ storage.key_config = RedisStorage.KeyConfig()
+ return storage
+
+
+def make_record(user_id: str, name: str = "kb") -> KnowledgeBaseRecord:
+ """Build a KnowledgeBaseRecord with a default embedding config."""
+ return KnowledgeBaseRecord(
+ user_id=user_id,
+ name=name,
+ description="desc",
+ embedding_model_config=EmbeddingModelConfig(
+ type="openai_credential",
+ credential_id="cred-1",
+ model="text-embedding-3-small",
+ dimensions=1536,
+ ),
+ collection_name="kb_abc",
+ )
+
+
+class KnowledgeBaseStorageTest(IsolatedAsyncioTestCase):
+ """Tests for the KnowledgeBaseRecord CRUD methods on RedisStorage."""
+
+ async def test_upsert_get_list_delete(self) -> None:
+ """Round-trip and isolation across users."""
+ storage = make_storage()
+
+ rec_a = make_record("user-1", "first")
+ rec_b = make_record("user-1", "second")
+ rec_c = make_record("user-2", "other")
+
+ stored_a = await storage.upsert_knowledge_base("user-1", rec_a)
+ stored_b = await storage.upsert_knowledge_base("user-1", rec_b)
+ stored_c = await storage.upsert_knowledge_base("user-2", rec_c)
+
+ # get returns the persisted record for the right owner
+ fetched = await storage.get_knowledge_base("user-1", stored_a.id)
+ self.assertEqual(fetched.id, stored_a.id)
+ self.assertEqual(fetched.name, "first")
+
+ # cross-user lookups return None
+ self.assertIsNone(
+ await storage.get_knowledge_base("user-2", stored_a.id),
+ )
+
+ # list scoped to user-1 returns only its records
+ listed = await storage.list_knowledge_bases("user-1")
+ self.assertEqual(
+ sorted(r.id for r in listed),
+ sorted([stored_a.id, stored_b.id]),
+ )
+
+ # delete only the requested record; other users are untouched
+ deleted = await storage.delete_knowledge_base("user-1", stored_a.id)
+ self.assertTrue(deleted)
+ self.assertIsNone(
+ await storage.get_knowledge_base("user-1", stored_a.id),
+ )
+ self.assertEqual(
+ [r.id for r in await storage.list_knowledge_bases("user-1")],
+ [stored_b.id],
+ )
+ self.assertEqual(
+ [r.id for r in await storage.list_knowledge_bases("user-2")],
+ [stored_c.id],
+ )
+
+ # double-delete returns False
+ self.assertFalse(
+ await storage.delete_knowledge_base("user-1", stored_a.id),
+ )
+
+ async def test_upsert_rejects_user_id_mismatch(self) -> None:
+ """upsert refuses records whose user_id does not match arg."""
+ storage = make_storage()
+ rec = make_record("user-1")
+ with self.assertRaises(ValueError):
+ await storage.upsert_knowledge_base("user-2", rec)
+
+ async def test_upsert_overwrites_and_preserves_created_at(self) -> None:
+ """Re-upsert with same id keeps created_at, refreshes updated_at."""
+ storage = make_storage()
+ rec = make_record("user-1")
+ first = await storage.upsert_knowledge_base("user-1", rec)
+
+ rec.name = "renamed"
+ second = await storage.upsert_knowledge_base("user-1", rec)
+
+ self.assertEqual(second.id, first.id)
+ self.assertEqual(second.created_at, first.created_at)
+ self.assertEqual(second.name, "renamed")