Files
LangBot/ja/plugin/dev/apis/common.mdx
T
632c23e841 Docs/rag engine plugin architecture (#82)
* docs: update wiki for RAG engine plugin architecture

Replace KnowledgeRetriever component docs with RAGEngine across all
three languages (zh/en/ja). Key changes:

- Add new rag-engine.mdx component docs covering RAGEngine base class,
  creation_schema/retrieval_schema, capability declarations, lifecycle
  hooks, host RAG APIs, and complete code examples
- Update knowledge base usage docs to reflect unified KB model (remove
  internal/external distinction, add RAG engine selection flow)
- Update component list (add.mdx) and plugin intro to reference RAGEngine
- Add RAG API section to plugin common APIs (invoke_embedding,
  vector_upsert/search/delete, get_rag_file_stream)
- Update docs.json navigation to point to rag-engine pages

Companion to LangBot PR #1995 and SDK PR #34.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: sync with sdk

* docs: update vector API docs with metadata filters, search_type, and documents support

- Replace Warning tags about unimplemented filters with Info tags documenting
  canonical filter format (Chroma-style where syntax) and supported operators
- Document search_type/query_text params for full-text and hybrid search
- Document documents param for vector_upsert
- Update RetrievalContext.filters description from reserved to active
- Add filter usage examples (en/zh/ja)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* docs: enhance RAG Engine documentation across multiple languages

- Expanded the description of the RAG Engine component to include bridging capabilities with advanced knowledge base services like Dify, RAGFlow, and FastGPT.
- Clarified the `DOC_INGESTION` capability description, specifying conditions under which the declaration can be omitted.
- Updated documentation in English, Japanese, and Chinese to ensure consistency and clarity.

* docs: add instructions for show_if conditional rendering

* docs: add Parser component documentation (zh/en/ja)

Add Parser as a new component type in plugin docs. Parser extracts
structured text from binary files (PDF, Word, etc.) before RAG engine
ingestion. Includes manifest format, parse method API, data models
(ParseContext/ParseResult/TextSection), RAGEngine integration via
parsed_content, and cross-plugin invoke_parser API.

Also add DOC_PARSING capability to RAG engine docs and parsed_content
field to IngestionContext.

Companion to SDK PR langbot-app/langbot-plugin-sdk#37 and
LangBot PR langbot-app/LangBot#2000.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* docs: rename RAGEngine components to KnowledgeEngine

* refactor: change rag engine to knowledge engine

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Junyan Qin <[email protected]>
2026-03-09 00:58:41 +08:00

498 lines
16 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "プラグイン共通API"
---
LangBotは、プラグインがさまざまなLangBotモジュールを操作し、メッセージコンテキストを制御するための一連のAPIを提供します。
## リクエストAPI
現在処理中のユーザーリクエスト(メッセージ)に対する操作です。`EventListener`と`Command`コンポーネントでのみ使用可能です。アクセス方法:
- `EventListener`のイベントハンドラメソッド内: `event_context: context.EventContext`オブジェクトの内部メソッド
- `Command`のサブコマンドハンドラメソッド内: `context: ExecuteContext`オブジェクトの内部メソッド
### 直接返信メッセージ
現在のリクエストが存在するセッションにメッセージチェーンで直接返信します。
メッセージチェーンの構築方法については、[メッセージプラットフォームエンティティ](/en/plugin/dev/apis/messages)を参照してください。
```python
async def reply(
self, message_chain: platform_message.MessageChain, quote_origin: bool = False
):
"""メッセージリクエストに返信する
Args:
message_chain (platform.types.MessageChain): LangBotメッセージチェーン
quote_origin (bool): 元のメッセージを引用するかどうか
"""
# 使用例
await event_context.reply(
platform_message.MessageChain([
platform_message.Plain(text="Hello, world!"),
]),
)
```
### Bot UUIDの取得
現在のリクエストを発行したBotのUUIDを取得します。
```python
async def get_bot_uuid(self) -> str:
"""Bot UUIDを取得する"""
# 使用例
bot_uuid = await event_context.get_bot_uuid()
```
### リクエスト変数の設定
単一のリクエスト内の一部の情報は、リクエスト変数に保存されます。Difyなどの外部LLMOpsプラットフォームを使用する場合、[これらの変数はLLMOpsプラットフォームに明示的に渡されます](/en/deploy/pipelines/readme.html#request-variables)。
```python
async def set_query_var(self, key: str, value: Any):
"""クエリ変数を設定する"""
# 使用例
await event_context.set_query_var("key", "value")
```
### リクエスト変数の取得
単一のリクエスト変数を取得します。
```python
async def get_query_var(self, key: str) -> Any:
"""クエリ変数を取得する"""
# 使用例
query_var = await event_context.get_query_var("key")
```
### すべてのリクエスト変数の取得
```python
async def get_query_vars(self) -> dict[str, Any]:
"""すべてのクエリ変数を取得する"""
# 使用例
query_vars = await event_context.get_query_vars()
```
## LangBot API
これらのAPIは、任意のプラグインコンポーネントで呼び出すことができます。アクセス方法:
- プラグインルートディレクトリの`main.py`内: `self`オブジェクトの内部メソッド。これらのAPIはすべて、プラグインクラスの親クラス`BasePlugin`によって提供されます。
- 任意のプラグインコンポーネントクラス内: `self.plugin`オブジェクトの内部メソッド。
### プラグイン設定の取得
プラグイン設定フォーマットは`manifest.yaml`に記述でき、ユーザーはLangBotのプラグイン管理でプラグイン設定フォーマットに従って入力する必要があります。プラグインコードはこのAPIを呼び出してプラグイン設定情報を取得できます。
```python
def get_config(self) -> dict[str, typing.Any]:
"""プラグインの設定を取得する。"""
# 使用例
config = self.plugin.get_config()
```
### LangBotバージョンの取得
LangBotのバージョン番号を取得します。`v<major>.<minor>.<patch>`形式の文字列として返されます。
```python
async def get_langbot_version(self) -> str:
"""LangBotバージョンを取得する"""
# 使用例
langbot_version = await self.plugin.get_langbot_version()
```
### 設定済みBotリストの取得
すべてのBot UUIDのリストを返します。
```python
async def get_bots(self) -> list[str]:
"""すべてのBotを取得する"""
# 使用例
bots = await self.plugin.get_bots()
```
### Bot情報の取得
Bot情報を取得します。
```python
async def get_bot_info(self, bot_uuid: str) -> dict[str, Any]:
"""Bot情報を取得する"""
# 使用例
bot_info = await self.plugin.get_bot_info("de639861-be05-4018-859b-c2e2d3e0d603")
# 返り値の例
{
"uuid": "de639861-be05-4018-859b-c2e2d3e0d603",
"name": "aiocqhttp",
"description": "Migrated from LangBot v3",
"adapter": "aiocqhttp",
"enable": true,
"use_pipeline_name": "ChatPipeline",
"use_pipeline_uuid": "c30a1dca-e91c-452b-83ec-84d635a30028",
"created_at": "2025-05-10T13:53:08",
"updated_at": "2025-08-12T11:27:30",
"adapter_runtime_values": { # Botが現在実行中の場合に存在
"bot_account_id": 960164003 # BotアカウントID
}
}
```
### プロアクティブメッセージの送信
Bot UUIDとターゲットセッションIDを通じてプロアクティブメッセージを送信します。
メッセージチェーンの構築方法については、[メッセージプラットフォームエンティティ](/en/plugin/dev/apis/messages)を参照してください。
```python
async def send_message(
self,
bot_uuid: str,
target_type: str,
target_id: str,
message_chain: platform_message.MessageChain,
) -> None:
"""セッションにメッセージを送信する"""
# 使用例
await self.plugin.send_message(
bot_uuid="de639861-be05-4018-859b-c2e2d3e0d603",
target_type="person",
target_id="1010553892",
message_chain=platform_message.MessageChain([platform_message.Plain(text="Hello, world!")]),
)
```
### 設定済みLLMモデルリストの取得
設定されたすべてのLLMモデルのUUIDのリストを返します。
```python
async def get_llm_models(self) -> list[str]:
"""すべてのLLMモデルを取得する"""
# 使用例
llm_models = await self.plugin.get_llm_models()
```
### LLMモデルの呼び出し
LLMモデルを呼び出し、LLMメッセージを返します。非ストリーミング。
```python
async def invoke_llm(
self,
llm_model_uuid: str,
messages: list[provider_message.Message],
funcs: list[resource_tool.LLMTool] = [],
extra_args: dict[str, Any] = {},
) -> provider_message.Message:
"""LLMモデルを呼び出す"""
# 使用例
llm_message = await self.plugin.invoke_llm(
llm_model_uuid="llm_model_uuid",
messages=[provider_message.Message(role="user", content="Hello, world!")],
funcs=[],
extra_args={},
)
```
### プラグイン永続データの設定
プラグインデータを永続的に保存します。このインターフェースを通じて保存されたデータは、このプラグインのみがアクセスできます。値は手動でbytesに変換する必要があります。
```python
async def set_plugin_storage(self, key: str, value: bytes) -> None:
"""プラグインストレージ値を設定する"""
# 使用例
await self.plugin.set_plugin_storage("key", b"value")
```
### プラグイン永続データの取得
```python
async def get_plugin_storage(self, key: str) -> bytes:
"""プラグインストレージ値を取得する"""
# 使用例
plugin_storage = await self.plugin.get_plugin_storage("key")
```
### すべてのプラグイン永続データキーの取得
```python
async def get_plugin_storage_keys(self) -> list[str]:
"""すべてのプラグインストレージキーを取得する"""
# 使用例
plugin_storage_keys = await self.plugin.get_plugin_storage_keys()
```
### プラグイン永続データの削除
```python
async def delete_plugin_storage(self, key: str) -> None:
"""プラグインストレージ値を削除する"""
# 使用例
await self.plugin.delete_plugin_storage("key")
```
### ワークスペース永続データの取得
このインターフェースを通じて保存されたデータは、すべてのプラグインがアクセスできます。値は手動でbytesに変換する必要があります。
```python
async def set_workspace_storage(self, key: str, value: bytes) -> None:
"""ワークスペースストレージ値を設定する"""
# 使用例
await self.plugin.set_workspace_storage("key", b"value")
```
### ワークスペース永続データの取得
```python
async def get_workspace_storage(self, key: str) -> bytes:
"""ワークスペースストレージ値を取得する"""
# 使用例
workspace_storage = await self.plugin.get_workspace_storage("key")
```
### すべてのワークスペース永続データキーの取得
```python
async def get_workspace_storage_keys(self) -> list[str]:
"""すべてのワークスペースストレージキーを取得する"""
# 使用例
workspace_storage_keys = await self.plugin.get_workspace_storage_keys()
```
### ワークスペース永続データの削除
```python
async def delete_workspace_storage(self, key: str) -> None:
"""ワークスペースストレージ値を削除する"""
# 使用例
await self.plugin.delete_workspace_storage("key")
```
### プラグインファイル型設定フィールドデータの取得
```python
async def get_config_file(self, file_key: str) -> bytes:
"""設定ファイル値を取得する"""
# 使用例
file_bytes = await self.plugin.get_config_file("key")
```
これは[``fileまたはarray[file``](/en/plugin/dev/basic-info.html#type-file)型の設定フィールドと組み合わせて使用します。
## RAG API
これらのAPIは`KnowledgeEngine`コンポーネントがLangBotホストの埋め込みモデル、ベクトルデータベース、ファイルストレージにアクセスするために使用できます。アクセス方法:
- `KnowledgeEngine`コンポーネントクラス内: `self.plugin`オブジェクトの内部メソッド。
### 埋め込みモデルの呼び出し
ホストに設定された埋め込みモデルを使用してテキストのベクトルを生成します。
```python
async def invoke_embedding(
self,
embedding_model_uuid: str,
texts: list[str],
) -> list[list[float]]:
"""埋め込みモデルを使用してベクトルを生成
Args:
embedding_model_uuid: 埋め込みモデルUUID
texts: 埋め込むテキストのリスト
Returns:
ベクトルのリスト、入力テキストごとに1つ
"""
# 使用例
vectors = await self.plugin.invoke_embedding("model_uuid", ["Hello", "World"])
```
### ベクトルの書き込み
ホストのベクトルデータベースにベクトルを書き込みます。
```python
async def vector_upsert(
self,
collection_id: str,
vectors: list[list[float]],
ids: list[str],
metadata: list[dict[str, Any]] | None = None,
documents: list[str] | None = None,
) -> None:
"""ベクトルの書き込み
Args:
collection_id: ターゲットコレクションID
vectors: ベクトルのリスト
ids: ベクトルの一意識別子リスト
metadata: オプションのメタデータリスト
documents: オプションの生テキストドキュメントリスト。全文検索や
混合検索をサポートするバックエンドで必要です。
"""
# 使用例
await self.plugin.vector_upsert(
collection_id="kb_uuid",
vectors=[[0.1, 0.2, ...], [0.3, 0.4, ...]],
ids=["chunk_0", "chunk_1"],
metadata=[{"document_id": "doc1"}, {"document_id": "doc1"}],
documents=["チャンクテキスト 0", "チャンクテキスト 1"],
)
```
### ベクトル検索
ホストのベクトルデータベースで類似ベクトルを検索します。
```python
async def vector_search(
self,
collection_id: str,
query_vector: list[float],
top_k: int = 5,
filters: dict[str, Any] | None = None,
search_type: str = "vector",
query_text: str = "",
) -> list[dict[str, Any]]:
"""ベクトル検索
Args:
collection_id: ターゲットコレクションID
query_vector: 類似性検索のクエリベクトル
top_k: 返す結果の数
filters: オプションのメタデータフィルター
search_type: 検索方式、'vector'、'full_text'、'hybrid' のいずれか
query_text: 生のクエリテキスト、全文検索と混合検索で使用
Returns:
検索結果のリスト(id, score, metadataなどを含むdict)
"""
# 使用例
results = await self.plugin.vector_search(
collection_id="kb_uuid",
query_vector=[0.1, 0.2, ...],
top_k=5,
search_type="hybrid",
query_text="検索クエリ",
)
# 返却フォーマット: [{"id": "chunk_0", "score": 0.123, "metadata": {"document_id": "doc1", ...}}, ...]
```
<Info>
`vector_search`が返す各結果はdictで、`id`(ベクトルID)、`score`(距離スコア)、`metadata`(upsert時に提供したメタデータ)の3つのフィールドを含みます。検索結果にテキスト内容が必要な場合は、取り込み時にmetadataにテキストを保存してください。
</Info>
### ベクトルの削除
ホストのベクトルデータベースからベクトルを削除します。
```python
async def vector_delete(
self,
collection_id: str,
file_ids: list[str] | None = None,
filters: dict[str, Any] | None = None,
) -> int:
"""ベクトルの削除
Args:
collection_id: ターゲットコレクションID
file_ids: 削除するファイルIDのリスト
filters: オプションのメタデータフィルター
Returns:
削除されたアイテム数
"""
# 使用例
deleted = await self.plugin.vector_delete(
collection_id="kb_uuid",
file_ids=["doc_001"],
)
```
<Info>
`filters`パラメータはChromaスタイルの`where`構文によるメタデータフィルタリングをサポートしています。複数のトップレベルキーはAND条件として結合されます。サポートされる演算子:`$eq`、`$ne`、`$gt`、`$gte`、`$lt`、`$lte`、`$in`、`$nin`。
```python
# 暗黙的な $eq
results = await self.plugin.vector_search(
collection_id="kb_uuid",
query_vector=[0.1, 0.2, ...],
filters={"file_id": "abc"},
)
# 比較演算子
results = await self.plugin.vector_search(
collection_id="kb_uuid",
query_vector=[0.1, 0.2, ...],
filters={"created_at": {"$gte": 1700000000}},
)
# リスト演算子
results = await self.plugin.vector_search(
collection_id="kb_uuid",
query_vector=[0.1, 0.2, ...],
filters={"file_type": {"$in": ["pdf", "docx"]}},
)
# フィルターによる削除
deleted = await self.plugin.vector_delete(
collection_id="kb_uuid",
filters={"file_type": {"$eq": "pdf"}},
)
```
**注意:** Chroma、Qdrant、SeekDBは完全なメタデータを保存し、任意のフィールドでフィルタリングできます。MilvusとpgvectorはDB側に`text`、`file_id`、`chunk_uuid`のみ保存しており、それ以外のフィールドでのフィルタリングは無視されます。
</Info>
ホストストレージからアップロードされたファイルの内容を取得します。
```python
async def get_knowledge_file_stream(self, storage_path: str) -> bytes:
"""ファイル内容を取得
Args:
storage_path: ファイルのストレージパス(FileObject.storage_pathから取得)
Returns:
ファイル内容のバイトデータ
"""
# 使用例
file_bytes = await self.plugin.get_knowledge_file_stream(context.file_object.storage_path)
```