Repository navigation
zh plugin dev components tool
LangBot 内置的 Local Agent 在执行期间会根据场景调用工具以与外界交互,目前支持通过插件和 MCP 两种方式添加工具。
单个插件中能添加任意数量的工具,请在插件目录执行命令lbp comp Tool,并根据提示输入工具的配置。
➜ 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是该工具的处理程序:
➜ HelloPlugin > tree
...
├── components
│ ├── __init__.py
│ └── tools
│ ├── __init__.py
│ ├── get_weather_alerts.py
│ └── get_weather_alerts.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/<工具名称>.py),您需要在GetWeatherAlerts类的call方法中实现此工具的调用和返回逻辑。
# 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 方法中,实现该工具:
Note
天气获取工具用例来自 MCP 的 Server 编写示例。
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
# Constants
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
async def make_nws_request(url: str) -> dict[str, Any] | None:
"""Make a request to the NWS API with proper error handling."""
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:
"""Format an alert feature into a readable string."""
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,受 OpenAI Function Calling 特性支持,且其根类型固定为type: object,请在properties中添加参数,并在required中添加必填参数说明。
...
spec:
parameters:
type: object # 请勿修改
properties: # 请勿修改,在此处添加参数
state:
type: string
description: 'Two-letter US state code (e.g. CA, NY)'
required: # 在此添加必填参数说明
- state
...本工具中还使用了httpx库,我们需要在插件目录的requirements.txt中添加httpx依赖。
# HelloPlugin/requirements.txt
langbot-plugin # 默认已存在
httpx现在在插件目录执行命令lbp run,启动调试。在 LangBot 中配置支持工具调用的模型,并在对应流水线上选择使用该模型,即可使用该工具。
一个 Tool 会被多个处理器与会话调用(同一事件可以触发多个插件处理器):
- 配置每次调用读取(
self.get_plugin_config()或ctx.config),不要在initialize()中读取后缓存到实例。 - 不要把调用参数、返回结果或会话数据留在实例字段或模块级变量上;会话身份从当前调用的
session/query_id取。 - 并发调用会共享同一个实例,实例字段会被交织写入;需要跨调用保留的数据放 Host 存储,键包含对应处理器或会话身份。
- 如果按安装维护了进程内缓存,请在
on_installation_revoked(binding)中释放。
以上约束的完整说明见认证插件与共享运行。
您已经了解了工具的基本用法,接下来可以:
- 查看 Tool 的
session和query_id说明 - 查看 LangBot API
Automatically synchronized from langbot-app/langbot-docs.
简体中文
指南
开发者
- 插件开发
- 插件 SDK API
- 核心开发
文章
- 浏览
- 产品动态
- 技术解析
- 教程与集成
- 公告
API 参考
- Service API
English
Guides
- Quick Start
- Installation
-
Configure Bots
- Bots
- Discord
- Telegram
- Slack
- Mattermost
- LINE
- Web Page Bot
- HTTP Bot
- KOOK
- Feishu
- DingTalk
- WeChat Official Account
- QQ (OneBot v11)
- Satori (QQ & Multi-Platform)
- QQ Official Bot
- WeCom (Enterprise WeChat)
- AI Configuration
- Advanced Operations
- Using Plugins
Developers
-
Plugin Development
- Plugin Development Tutorial
- Completing Plugin Configuration Information
- Plugin Directory Structure
- Component Development
- Code Style Guide
- Certified plugins and shared runtime
- Publish Plugin
- Migration Guide
- Plugin SDK API
- Core Development
Articles
- Browse
- Product Updates
- Engineering
-
Tutorials & Integrations
- LangTARS: Open-Source AI Agent for Remote PC Control — Works with Dify, n8n & 10+ Messaging Platforms
- How to Connect DeepSeek R1 to WeChat, Discord & Telegram in 5 Minutes (FREE)
- Deploy Your Own AI Bot to Discord, Telegram & WeChat in 5 Minutes
- Finally Got My Dify Agent Working in Discord, Telegram and Slack
- How I Built a Multi-Platform AI Bot with Langflow's Drag-and-Drop Workflows
- How I Built a Multi-Platform AI Chatbot with n8n and LangBot
- LangBot 4.6.0 External Knowledge Base Tutorial: Integrating Dify with LangBot for RAG-powered Conversations
- Announcements
API Reference
- Service API
Other pages
日本語
ガイド
開発者
- プラグイン開発
- プラグイン SDK API
- コア開発
記事
- 一覧
- 製品アップデート
- エンジニアリング
-
チュートリアルと連携
- LangTARS:Dify・n8n と連携するオープンソース PC 操作 Agent
- DeepSeek R1 を WeChat・Discord・Telegram に5分で接続する方法
- AI Bot を Discord・Telegram・WeChat に5分でデプロイ
- Dify Agent を Discord・Telegram・Slack で動かす
- Langflow のドラッグ&ドロップでマルチプラットフォーム AI Bot を構築
- n8n と LangBot でマルチプラットフォーム AI Chatbot を構築
- LangBot 4.6.0 外部ナレッジベース入門:Dify と連携した RAG 会話
- お知らせ
API リファレンス
- Service API