mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-10-28 19:35:27 +08:00
A Workspace installs a plugin once, but that single installation is reused by several product objects: every processor for a Runner, every knowledge base for a KnowledgeEngine / Parser / Retriever, and many conversations or page requests for the other component kinds. The platform storage key carries no processor or knowledge-base dimension, so a plugin must fold that identity into its own keys. - certified-plugins: add "one installation, many usages" with the isolation dimensions per component kind, and "when an installation is revoked" documenting BasePlugin.on_installation_revoked, its trigger set, the absent invocation context and the no-op/failure semantics. - component pages (runner, knowledge-engine, knowledge-retriever, parser, tool, command, event-listener, page): add a short component-specific section with that component's own rules and a link to the contract page. - Align the background-work rule with the SDK contract: the SDK does not track ownership of detached work, so a plugin must keep its own binding-keyed registry and stop it in the revocation hook. All three locales carry the same sections.
189 lines
8.3 KiB
Plaintext
189 lines
8.3 KiB
Plaintext
---
|
|
title: "コンポーネント: Tool"
|
|
---
|
|
|
|
LangBotの組み込みLocal Agentは、実行中にツールを呼び出して外部世界と対話します。現在、プラグインとMCPの両方を通じてツールを追加することがサポートされています。
|
|
|
|
## Toolコンポーネントの追加
|
|
|
|
1つのプラグインには任意の数のツールを含めることができます。プラグインディレクトリでコマンド`lbp comp Tool`を実行し、プロンプトに従ってツール設定を入力します。
|
|
|
|
```bash
|
|
➜ HelloPlugin > lbp comp Tool
|
|
Generating component Tool...
|
|
Tool name: get_weather_alerts
|
|
Tool description: Get weather alerts for a US state.
|
|
Component Tool generated successfully.
|
|
組件 Tool 生成成功。
|
|
```
|
|
|
|
これにより、`components/tools/`ディレクトリに`get_weather_alerts.yaml`と`get_weather_alerts.py`ファイルが生成されます。`.yaml`ファイルはツールの基本情報を定義し、`.py`ファイルはツールハンドラです:
|
|
|
|
```bash
|
|
➜ HelloPlugin > tree
|
|
...
|
|
├── components
|
|
│ ├── __init__.py
|
|
│ └── tools
|
|
│ ├── __init__.py
|
|
│ ├── get_weather_alerts.py
|
|
│ └── get_weather_alerts.yaml
|
|
...
|
|
```
|
|
|
|
## マニフェストファイル: Tool
|
|
|
|
```yaml
|
|
apiVersion: v1 # 変更しないでください
|
|
kind: Tool # 変更しないでください
|
|
metadata:
|
|
name: get_weather_alerts # ツール名、LLM認識用
|
|
label:
|
|
en_US: GetWeatherAlerts # ツール表示名、LangBot UIに表示、多言語対応
|
|
zh_Hans: GetWeatherAlerts
|
|
description:
|
|
en_US: 'Get weather alerts for a US state.' # ツール説明、LangBot UIに表示、多言語対応。オプション
|
|
zh_Hans: '獲取美国某个州的天気預警'
|
|
spec:
|
|
parameters: [] # ツールパラメータ、会話コンテキストに基づいてLLMが生成する値
|
|
llm_prompt: 'Get weather alerts for a US state.' # ツールプロンプト、LLMがこのツールを呼び出すかどうかを判断するため
|
|
execution:
|
|
python:
|
|
path: get_weather_alerts.py # ツールハンドラ、変更しないでください
|
|
attr: GetWeatherAlerts # ツールハンドラクラス名、get_weather_alerts.pyのクラス名と一致
|
|
```
|
|
|
|
## プラグイン処理
|
|
|
|
以下のコードがデフォルトで生成されます(`components/tools/<tool_name>.py`)。`GetWeatherAlerts`クラスの`call`メソッドでこのツールの呼び出しと戻り値のロジックを実装する必要があります。
|
|
|
|
```python
|
|
# Auto generated by LangBot Plugin SDK.
|
|
# Please refer to https://langbot.app/docs/en/plugin/dev/tutor.html for more details.
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from langbot_plugin.api.definition.components.tool.tool import Tool
|
|
from langbot_plugin.api.entities.builtin.provider import session as provider_session
|
|
|
|
|
|
class GetWeatherAlerts(Tool):
|
|
|
|
async def call(self, params: dict[str, Any], session: provider_session.Session, query_id: int) -> str:
|
|
"""Fill your tool code here"""
|
|
return {}
|
|
```
|
|
|
|
`call`メソッドでこのツールを実装します:
|
|
|
|
<Info>
|
|
天気検索ツールの例は、MCPの[サーバー作成例](https://modelcontextprotocol.io/quickstart/server)から来ています。
|
|
</Info>
|
|
|
|
```python
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from langbot_plugin.api.definition.components.tool.tool import Tool
|
|
from langbot_plugin.api.entities.builtin.provider import session as provider_session
|
|
import httpx
|
|
|
|
# 定数
|
|
NWS_API_BASE = "https://api.weather.gov"
|
|
USER_AGENT = "weather-app/1.0"
|
|
|
|
|
|
async def make_nws_request(url: str) -> dict[str, Any] | None:
|
|
"""適切なエラー処理を使用してNWS APIにリクエストを行う。"""
|
|
headers = {
|
|
"User-Agent": USER_AGENT,
|
|
"Accept": "application/geo+json"
|
|
}
|
|
async with httpx.AsyncClient() as client:
|
|
try:
|
|
response = await client.get(url, headers=headers, timeout=30.0)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except Exception:
|
|
return None
|
|
|
|
def format_alert(feature: dict) -> str:
|
|
"""アラート機能を読みやすい文字列にフォーマットする。"""
|
|
props = feature["properties"]
|
|
return f"""
|
|
Event: {props.get('event', 'Unknown')}
|
|
Area: {props.get('areaDesc', 'Unknown')}
|
|
Severity: {props.get('severity', 'Unknown')}
|
|
Description: {props.get('description', 'No description available')}
|
|
Instructions: {props.get('instruction', 'No specific instructions provided')}
|
|
"""
|
|
|
|
class GetWeatherAlerts(Tool):
|
|
|
|
async def call(self, params: dict[str, Any], session: provider_session.Session, query_id: int) -> str:
|
|
"""Fill your tool code here"""
|
|
state = params.get("state", "CA")
|
|
|
|
url = f"{NWS_API_BASE}/alerts/active/area/{state}"
|
|
data = await make_nws_request(url)
|
|
|
|
if not data or "features" not in data:
|
|
return "Unable to fetch alerts or no alerts found."
|
|
|
|
if not data["features"]:
|
|
return "No active alerts for this state."
|
|
|
|
alerts = [format_alert(feature) for feature in data["features"]]
|
|
return "\n---\n".join(alerts)
|
|
```
|
|
|
|
このツールでは、`params`から`state`パラメータを取得し、NWS APIを呼び出してその州の天気アラートを取得する必要があるため、マニフェストファイルの`parameters`で`state`パラメータを定義する必要があります。
|
|
|
|
`parameters`フォーマットは[JSON Schema](https://json-schema.org/docs)に従い、[OpenAI Function Calling機能](https://platform.openai.com/docs/guides/function-calling#defining-functions)でサポートされており、そのルートタイプは`type: object`に固定されています。`properties`にパラメータを追加し、`required`に必須パラメータの説明を追加してください。
|
|
|
|
```yaml
|
|
...
|
|
spec:
|
|
parameters:
|
|
type: object # 変更しないでください
|
|
properties: # 変更しないでください、ここにパラメータを追加
|
|
state:
|
|
type: string
|
|
description: 'Two-letter US state code (e.g. CA, NY)'
|
|
required: # ここに必須パラメータの説明を追加
|
|
- state
|
|
...
|
|
```
|
|
|
|
このツールは`httpx`ライブラリも使用しているため、プラグインディレクトリの`requirements.txt`に`httpx`依存関係を追加する必要があります。
|
|
|
|
```txt
|
|
# HelloPlugin/requirements.txt
|
|
langbot-plugin # デフォルトで既に存在
|
|
httpx
|
|
```
|
|
|
|
次に、プラグインディレクトリでコマンド`lbp run`を実行してデバッグを開始します。LangBotでツール呼び出しをサポートするモデルを設定し、対応するパイプラインでそのモデルの使用を選択してこのツールを使用します。
|
|
|
|
<img width="600" src="/images/zh/plugin/dev/components/tool_use_in_chat.png" />
|
|
|
|
## 1 つの installation、複数の用途
|
|
|
|
1 つの Tool は**複数のプロセッサと会話**から呼び出されます(1 つのイベントで複数のプラグインプロセッサが起動し得ます):
|
|
|
|
- 設定は呼び出しごとに読み取ってください(`self.get_plugin_config()` または `ctx.config`)。`initialize()` で読み取ってインスタンスにキャッシュしないでください。
|
|
- 呼び出し引数、戻り値、会話データをインスタンスフィールドやモジュールレベルの変数に残さないでください。会話の識別子は現在の呼び出しの `session` / `query_id` から取得します。
|
|
- 同時呼び出しは同じインスタンスを共有するため、インスタンスフィールドは書き込みが交錯します。呼び出しをまたいで保持するデータは Host ストレージに置き、対応するプロセッサまたは会話の識別子をキーに含めてください。
|
|
- installation 単位でプロセス内キャッシュを保持する場合は、`on_installation_revoked(binding)` で解放してください。
|
|
|
|
完全な仕様は[認証プラグインと共有実行](/ja/plugin/certified-plugins)を参照してください。
|
|
|
|
## 次のステップ
|
|
|
|
ツールの基本的な使い方を学びました。次は:
|
|
|
|
- Tool が受け取る [`session` と `query_id`](/ja/plugin/dev/apis/agent-run#tool)を確認します。
|
|
- [LangBot API](/ja/plugin/dev/apis/common)を確認します。
|