The Knowledge Engine component allows plugins to provide full knowledge base indexing and retrieval capabilities for LangBot. When users create a knowledge base in LangBot, they can choose a Knowledge Engine provided by a plugin to manage document ingestion, retrieval, and deletion. Plugins can also bridge advanced knowledge base services such as Dify, RAGFlow, FastGPT, and more.
## Adding a Knowledge Engine Component
A single plugin can add any number of Knowledge Engines. Execute the command `lbp comp KnowledgeEngine` in the plugin directory and follow the prompts to enter the Knowledge Engine configuration.
```bash
➜ MyRAGPlugin > lbp comp KnowledgeEngine
Generating component KnowledgeEngine...
Knowledge Engine name: simple_rag
Knowledge Engine description: A simple Knowledge Engine with built-in chunking and retrieval
Component KnowledgeEngine generated successfully.
```
This will generate `simple_rag.yaml` and `simple_rag.py` files in the `components/knowledge_engine/` directory. The `.yaml` file defines the Knowledge Engine's basic information and configuration schemas, and the `.py` file is the handler for this engine:
```bash
➜ MyRAGPlugin > tree
...
├── components
│ ├── __init__.py
│ └── knowledge_engine
│ ├── __init__.py
│ ├── simple_rag.py
│ └── simple_rag.yaml
...
```
## Manifest File: Knowledge Engine
```yaml
apiVersion: v1 # Do not modify
kind: KnowledgeEngine # Do not modify
metadata:
name: simple_rag # Knowledge Engine name, used to identify this engine
label:
en_US: Simple Knowledge Engine # Engine display name, shown in LangBot's UI, supports multiple languages
zh_Hans: 简易 RAG 引擎
ja_JP: シンプル RAG エンジン
description:
en_US: 'A simple Knowledge Engine with built-in chunking and retrieval'
zh_Hans: '内置分块和检索能力的简易 RAG 引擎'
ja_JP: 'チャンキングと検索を内蔵したシンプルなRAGエンジン'
spec:
creation_schema: # Configuration parameters users fill in when creating a knowledge base
- name: chunk_size
label:
en_US: Chunk Size
zh_Hans: 分块大小
type: integer
required: false
default: 500
- name: chunk_overlap
label:
en_US: Chunk Overlap
zh_Hans: 分块重叠
type: integer
required: false
default: 50
retrieval_schema: # Configurable parameters during retrieval
- name: score_threshold
label:
en_US: Score Threshold
zh_Hans: 分数阈值
type: float
required: false
default: 0.5
execution:
python:
path: simple_rag.py # Engine handler, do not modify
attr: SimpleRag # Class name of the engine handler, consistent with the class name in simple_rag.py
```
For configuration item format reference, see: [Plugin Manifest Configuration Format](/en/plugin/dev/basic-info)
### creation_schema and retrieval_schema
Unlike the old `KnowledgeRetriever` component which used a single `spec.config`, KnowledgeEngine uses two separate schemas:
- **creation_schema**: Parameters users fill in when creating a knowledge base. These are passed to the plugin via `creation_settings` during ingestion and retrieval.
- **retrieval_schema**: Parameters users can adjust when querying the knowledge base. These are passed to the plugin via `retrieval_settings`.
## Capability Declaration
KnowledgeEngine can declare its supported capabilities. LangBot uses these capability declarations to determine UI behavior and available operations:
```python
from langbot_plugin.api.definition.components.knowledge_engine.engine import KnowledgeEngine, KnowledgeEngineCapability
class SimpleRag(KnowledgeEngine):
@classmethod
def get_capabilities(cls) -> list[str]:
return [
KnowledgeEngineCapability.DOC_INGESTION, # Supports document upload and processing
]
```
Available capability constants:
| Capability | Description |
|-----------|-------------|
| `DOC_INGESTION` | Supports document upload and processing. When declared, LangBot shows a "Documents" tab in the knowledge base details. If the plugin is used to bridge other knowledge base services or does not require users to upload documents, this capability declaration can be omitted. |
| `DOC_PARSING` | Supports native document parsing (file-to-text extraction). When declared, users can choose to use the Knowledge Engine's built-in parsing when uploading documents, without needing an external [Parser plugin](./parser). If not declared, an external Parser plugin must be installed to upload documents. |
<Info>
Other retrieval behaviors (such as reranking, hybrid search, etc.) are controlled by the plugin's `retrieval_schema` and do not need capability flags.
The following code will be generated by default (`components/knowledge_engine/<engine_name>.py`). You need to implement the three core methods: `ingest`, `retrieve`, and `delete_document`. See the official [LangRAG knowledge engine](https://github.com/langbot-app/LangBot/tree/master/plugins/KnowledgeEngine/LangRAG) for a complete implementation.
**RetrievalContext** contains the following information:
```python
class RetrievalContext(pydantic.BaseModel):
query: str # Query text
knowledge_base_id: str | None # Knowledge base ID
collection_id: str | None # Vector collection ID
retrieval_settings: dict # Retrieval configuration (fields from retrieval_schema)
creation_settings: dict # Knowledge base creation configuration
filters: dict # Metadata filter conditions (Chroma-style where syntax)
```
<Info>
The LangBot host automatically injects a default `top_k` value (default 5) into `retrieval_settings` before passing it to the plugin. Plugins can access it via `context.retrieval_settings.get('top_k', 5)`.
The `filters` field contains Chroma-style `where` filter conditions extracted from `retrieval_settings`. When the caller provides `filters` in the retrieval settings (e.g., filtering by time range, file type, or custom metadata fields), the host populates this field so plugins can apply them during retrieval. If no filters are provided, this field is an empty dict.
</Info>
**RetrievalResponse** should return the retrieval results:
```python
class RetrievalResponse(pydantic.BaseModel):
results: list[RetrievalResultEntry] # List of retrieval results
total_found: int # Total number of matches
metadata: dict # Additional metadata
```
**RetrievalResultEntry** represents a single retrieval result:
```python
class RetrievalResultEntry(pydantic.BaseModel):
id: str # Result ID
content: list[ContentElement] # Content, create using ContentElement.from_text()
metadata: dict # Metadata
distance: float # Distance score (smaller is more relevant)
score: float | None = None # Similarity score (larger is more relevant)
```
### Document Deletion
The `delete_document` method is called when a user deletes a document from the knowledge base:
KnowledgeEngine components can call LangBot host-provided RAG APIs via `self.plugin`, including embedding model invocation, vector database operations, and file retrieval.
### Invoke Embedding Model
```python
async def invoke_embedding(
self,
embedding_model_uuid: str,
texts: list[str],
) -> list[list[float]]:
"""Generate embeddings using host's embedding model
Each result returned by `vector_search` is a dict containing `id` (vector ID), `score` (distance score), and `metadata` (metadata provided during upsert). If you need text content in retrieval results, store the text in metadata during ingestion.
</Info>
### Vector Delete
```python
async def vector_delete(
self,
collection_id: str,
file_ids: list[str] | None = None,
filters: dict | None = None,
) -> int:
"""Delete vectors from host's vector database
Args:
collection_id: Target collection ID
file_ids: File IDs whose vectors should be deleted
filters: Optional metadata filters for deletion
Returns:
Number of deleted items
"""
# Usage example
deleted = await self.plugin.vector_delete(
collection_id="kb_uuid",
file_ids=["doc_001"],
)
```
<Info>
The `filters` parameter supports Chroma-style `where` syntax for metadata filtering. Multiple top-level keys are AND-ed. Supported operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`. Example: `{"file_id": {"$eq": "abc"}}`.
**Note:** Chroma, Qdrant, and SeekDB store full metadata and can filter on any field. Milvus and pgvector only store `text`, `file_id`, and `chunk_uuid` — filters on other fields will be silently ignored.
A single knowledge engine is used by **several knowledge bases** at once, and the platform storage key `(instance, Workspace, owner type, plugin, key)` carries no knowledge-base dimension:
- Persistence and cache keys must include the **knowledge-base ID**, otherwise vectors and document state of different knowledge bases overwrite each other.
- Locks and reconciliation state must be keyed by `(installation, knowledge base)`; **a failure while ingesting one knowledge base must not block ingestion or retrieval of the others under the same installation**.
- Only a dispatched mutation with an unknown outcome should enter a state that needs manual reconciliation; deterministic validation errors and pre-dispatch cancellation must not affect later calls.
- Telemetry and diagnostic failures must not affect the work: never let a log or report failure interrupt ingestion or retrieval, and never write tenant data into a process-wide singleton.
- If you keep per-installation process-local caches or state, release them in `on_installation_revoked(binding)`.
See [Certified plugins and shared runtime](/en/plugin/certified-plugins) for the full specification.
The existing ingestion callback and `get_knowledge_file_stream(context.file_object.storage_path)` call also handle Artifact-backed knowledge files. Treat `storage_path` as opaque: `artifact:<knowledge_file_uuid>` identifies a Core-managed business reference, not a local path or a transferable permission. Core authorizes the installed engine for that knowledge base before returning bounded bytes. Do not replace this call with direct storage access. Existing uploads and `file_id` consumers keep their existing interface. See [Artifact imports](/en/develop/artifacts#knowledge-base-artifact-imports) for import and deletion semantics.