mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-10-29 03:46:37 +08:00
178 lines
7.0 KiB
Plaintext
178 lines
7.0 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" />
|
|
|
|
## 次のステップ
|
|
|
|
ツールの基本的な使い方を学びました。次は:
|
|
|
|
- Tool が受け取る [`session` と `query_id`](/ja/plugin/dev/apis/agent-run#tool)を確認します。
|
|
- [LangBot API](/ja/plugin/dev/apis/common)を確認します。
|