doc: fix problems

This commit is contained in:
Junyan Qin
2025-05-14 11:50:09 +08:00
parent 49a6b163a5
commit 33651b2fb1
16 changed files with 280 additions and 568 deletions
+3 -2
View File
@@ -211,6 +211,7 @@ export default defineConfig({
},
},
en: {
title: "LangBot Docs",
label: "English",
lang: "en",
link: "/en/",
@@ -315,7 +316,7 @@ export default defineConfig({
],
},
{
text: "Configure Dialogue Models",
text: "Configure Models",
link: "/en/deploy/models/readme",
},
{
@@ -323,7 +324,7 @@ export default defineConfig({
link: "/en/deploy/pipelines/readme",
},
{
text: "System Environment Settings",
text: "System Settings",
link: "/en/deploy/settings",
},
{
+33
View File
@@ -0,0 +1,33 @@
# Docker Deployment
:::warning
It is recommended that you first learn the following:
- Usage of `Docker` and `Docker Compose`
- Docker container network communication configuration methods
:::
:::info
- Please ensure Git, Docker, and Docker Compose are installed
:::
Clone the project:
```bash
git clone https://github.com/RockChinQ/LangBot
cd LangBot
```
Start the container:
```bash
docker compose up
```
The container maps port `5300` for WebUI access. You can visit `http://127.0.0.1:5300` to view the WebUI.
It also maps ports `2280-2290` for reserved for message platform adapters.
After completing the LangBot deployment, please continue reading:
- [Bot Configuration Documentation](/en/deploy/platforms/readme).
- [Model Configuration Documentation](/en/deploy/models/readme).
+86
View File
@@ -0,0 +1,86 @@
# Manual Deployment
:::warning
1. Please use Python 3.10.1 (not including 3.10.0) or higher version, 3.10.14 is recommended. You need to install Python if you don't have it.
2. This method is not recommended, manual deployment may not be supported in the future. Please consider using Docker deployment.
:::
## Installing the Main Program
1. Go to the [Release](https://github.com/RockChinQ/LangBot/releases) page to download the latest version of the zip package (recommended) `langbot-xxx-all.zip` (do not download Source Code as it does not include WebUI). Extract it and open a command line (terminal) in the extracted directory.
![Download Release](/assets/image/zh/deploy/langbot/manual/dl_release.png)
:::info
You can also use the following commands to clone the latest code (may contain unstable code) and use it:
```bash
# Clone the main repository
git clone https://github.com/RockChinQ/LangBot
cd LangBot
```
If you are in mainland China, you can clone from the [GitCode mirror](https://gitcode.com/RockChinQ/LangBot):
```bash
git clone https://gitcode.com/RockChinQ/LangBot
cd LangBot
```
Then manually build the frontend:
```bash
# Build frontend, requires NodeJS >= 22
cd web
npm install && npm run build
cd ..
```
:::
2. (Recommended) Create a virtual environment
On some Linux systems that use system package managers to manage Python dependencies, dependency conflicts may occur, so please use venv to create a virtual environment. Windows users can skip this step.
```bash
python -m venv venv
source venv/bin/activate
```
3. Install dependencies
```bash
pip install -r requirements.txt
```
Or use Tsinghua mirror
```bash
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
```
4. Run the main program once to generate configuration files
```bash
python main.py
```
You will see the following message:
```
_ ___ _
| | __ _ _ _ __ _| _ ) ___| |_
| |__/ _` | ' \/ _` | _ \/ _ \ _|
|____\__,_|_||_\__, |___/\___/\__|
|___/
⭐️Open Source: https://github.com/RockChinQ/LangBot
📖Documentation: https://docs.langbot.app
The following files do not exist and have been automatically generated. Please modify the configuration files as needed and restart:
- plugins/__init__.py
...
```
You can now use Ctrl+C to exit the program and continue to the [Deploy Message Platform](/en/deploy/platforms/readme) page.
+53
View File
@@ -0,0 +1,53 @@
# aaPanel Deployment
Deploy LangBot with one click using [aaPanel](https://www.bt.cn/new/download.html?r=dk_LangBot).
:::warning
- Unless you plan to use message platforms like Discord or Feishu that don't require additional containers, or you are familiar with Docker container networking on aaPanel, it's not recommended to use one-click deployment with aaPanel. Please consider using [Docker deployment](/en/deploy/langbot/docker).
- If you already have aaPanel installed, please update to version **9.2.0** or higher
:::
## Installing aaPanel
> Recommended server systems (from aaPanel): Debian 12, Ubuntu 22, etc.
>
> This document assumes you have a server with a public IPv4 address. If you're using a home machine without a public IP, you can access the relevant pages through the internal network mentioned below.
Open [aaPanel](https://www.bt.cn/new/download.html?r=dk_LangBot), use the Linux panel installation script provided by aaPanel official, and select the corresponding script based on your system.
![Install aaPanel](/assets/image/zh/deploy/langbot/one-click/bt_install_01.png)
Copy the corresponding script and paste it into your server to execute.
## Installing LangBot
After waiting for a while, aaPanel installation will be complete.
You'll see a message similar to this, copy the external panel address and open it in your browser.
![aaPanel Access Address](/assets/image/zh/deploy/langbot/one-click/bt_install_02.png)
When you first open it, you should see a popup for `Recommended Installation Suite`. You can skip this by closing it.
Then click on `docker` in the sidebar. If it's your first time, you'll be prompted to install Docker and Docker Compose services. Click "Install Now" if prompted, or ignore if already installed.
Then go to `Docker -> App Store`, search for `LangBot` (note the case sensitivity), click `Install`, and use the default configuration.
After a short wait, you'll see a container named `langbot_XXXX` showing as `Running`.
![Create LangBot Container](/assets/image/zh/deploy/langbot/one-click/bt_langbot_01.png)
Click the red circle in the image above to view the running logs.
![View LangBot Container Logs](/assets/image/zh/deploy/langbot/one-click/bt_langbot_02.png)
You can see the external and internal access paths for the WebUI configuration page (visual configuration page). Copy the public address, for example `http://xxx.xxx.xxx.xxx:5300` (where xxx.xxx.xxx.xxx is your aaPanel IP, and 5300 is the port number, which may vary as shown in the image).
After opening it, enter your admin email and password, then click initialize.
You can then proceed with configuration in the visual interface.
If you prefer to directly modify JSON configuration files, you can look at the local mapping directory shown in the image above. Go to the installation directory, where the `data` folder is used to store configuration files, and the `plugins` folder is used for plugin-related files.
Next, please continue reading the [Deploy Message Platform](/en/deploy/platforms/readme) page.
+7 -7
View File
@@ -7,14 +7,14 @@ Bots are used to receive message events from messaging platforms and call pipeli
| Platform | Status | Notes | Tutorial |
| ------ | ---- | ---- | ---- |
| OneBot v11 | ✅ | Uses a regular QQ account as a bot, requires an independent protocol client, supports OneBot v11 | [NapCat](/en/deploy/platforms/qq/aiocqhttp/napcat) <br> [Lagrange](/en/deploy/platforms/qq/aiocqhttp/lagrange) <br> [LiteLoaderQQNT](/en/deploy/platforms/qq/aiocqhttp/llonebot) |
| QQ Official Bot | ✅ | Connects to the QQ Open Platform bot API | [Tutorial](/en/deploy/platforms/qq/official_webhook) |
| Discord | ✅ | | [Tutorial](/en/deploy/platforms/discord) |
| Telegram | ✅ | | [Tutorial](/en/deploy/platforms/telegram) |
| Slack | ✅ | | [Tutorial](/en/deploy/platforms/slack) |
| Lark | ✅ | | [Tutorial](/en/deploy/platforms/lark) |
| DingTalk | ✅ | | [Tutorial](/en/deploy/platforms/dingtalk) |
| WeCom (Enterprise WeChat) | ✅ | Enterprise internal bot | [Tutorial](/en/deploy/platforms/wecom/wecom) |
| WeCom Customer Service | ✅ | Enterprise external bot | [Tutorial](/en/deploy/platforms/wecom/wecomcs) |
| WeChat Official Account | ✅ | WeChat public platform bot | [Tutorial](/en/deploy/platforms/wxoa) |
| Personal WeChat | ✅ | Personal WeChat bot | [Gewechat](/en/deploy/platforms/wechat/gewechat) |
| Feishu (Lark) | ✅ | | [Tutorial](/en/deploy/platforms/lark) |
| DingTalk | ✅ | | [Tutorial](/en/deploy/platforms/dingtalk) |
| Discord | ✅ | | [Tutorial](/en/deploy/platforms/discord) |
| Telegram | ✅ | | [Tutorial](/en/deploy/platforms/telegram) |
| Slack | ✅ | | [Tutorial](/en/deploy/platforms/slack) |
| OneBot v11 | ✅ | Uses a personal QQ account as a bot, requires an independent protocol client, supports OneBot v11 | [NapCat](/en/deploy/platforms/qq/aiocqhttp/napcat) <br> [Lagrange](/en/deploy/platforms/qq/aiocqhttp/lagrange) <br> [LiteLoaderQQNT](/en/deploy/platforms/qq/aiocqhttp/llonebot) |
| QQ Official Bot | ✅ | Connects to the QQ Open Platform bot API | [Tutorial](/en/deploy/platforms/qq/official_webhook) |
+3 -3
View File
@@ -1,3 +1,3 @@
---
redirect: /en/insight/guide
---
<script setup>
window.location.href = '/zh/insight/guide'
</script>
+2 -16
View File
@@ -6,20 +6,6 @@
Collected at: https://blog.thelazy.top/tags/langbot
## Project Discussion QQ Groups
## 🥰 Community
> Please read the documentation carefully before joining the group to ask questions, if you cannot solve the problem then join the group to ask
### 🥰 Community Main Groups
Answering various questions
- LangBot Community (3): 966235608 ([Link](https://qm.qq.com/q/JLi38whHum))
- [Full] LangBot Community (2): 1030838208 ([Link](https://qm.qq.com/q/PF9OuQCCcM))
- [Full] LangBot Community (1): 619154800 ([Link](https://qm.qq.com/q/1K9GjQuza))
### 🧩 Plugin Development Group
Plugin development, publishing, and discussion
- LangBot Plugin Development: 1032327138 ([Link](https://qm.qq.com/q/G7ENGTjeou))
Join our community on Discord: [![Discord](https://img.shields.io/discord/1335141740050649118?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb)](https://discord.gg/wdNEHETs87)
+2 -6
View File
@@ -1,10 +1,6 @@
# Welcome to LangBot Documentation Center
# Welcome to LangBot Documentation
LangBot is an open-source Large Language Model (LLM) native instant messaging robot platform that supports multiple messaging platforms and model providers. It provides support for LLMOps platforms such as Dify and Alibaba Cloud Bailian. It also offers a WebUI for users to quickly deploy and use.
:::info
This is the documentation for LangBot 4.0. For 3.0 documentation, please [visit here](https://v3.docs.langbot.app).
:::
LangBot is an open-source Large Language Model (LLM) native instant messaging bot platform that supports multiple messaging platforms and model providers. It provides support for LLMOps platforms such as Dify. It also offers a WebUI for users to quickly deploy and use.
## Documentation Structure
+2 -2
View File
@@ -81,10 +81,10 @@ Message platform events are defined in `pkg/platform/types/events.py`.
In addition to the above entities, there are also entities such as `Friend` and `Group`, which are defined in `pkg/platform/types/entities.py`.
They are generally included in the above event objects, from which you can get some information not included in the plugin events.
## Accessing Message Platform Underlying API
## Accessing Message Platform Low-Level API
In order to smooth out the differences between various platforms, LangBot provides an abstraction layer on top of the message platform APIs, namely the content described above and the platform adapters in the `pkg/platform/sources` directory.
However, due to the large differences between platforms, the entities and API encapsulation in the abstraction layer are not complete. If your plugin needs to access specific platform functions, you can access the underlying API according to the following instructions.
However, due to the large differences between platforms, the entities and API encapsulation in the abstraction layer are not complete. If your plugin needs to access specific platform functions, you can access the low-level API according to the following instructions.
:::info
The `adapter` here is the instantiated object of each adapter, corresponding to the `xxxAdapter(adapter.MessagePlatformAdapter)` class in each file under `pkg/platform/sources/`. It can be obtained from the plugin event's `query.adapter`, for example:
+25 -159
View File
@@ -1,176 +1,42 @@
# How to Integrate with Dify?
# Using Dify with LangBot
This guide explains how to integrate LangBot with Dify, a powerful LLMOps platform that allows you to create and deploy AI applications.
[Dify](https://dify.ai) is an open-source large language model (LLM) application development platform. It combines the concepts of Backend as Service and LLMOps, enabling developers to quickly build production-grade generative AI applications.
Dify can create chat assistants (including Chatflow), Agents, text generation applications, workflows, and other types of applications.
## What is Dify?
LangBot currently supports three types of Dify applications: `Chat Assistant` (including Chatflow), `Agent`, and `Workflow`.
[Dify](https://dify.ai) is an open-source LLMOps platform that helps you build, deploy, and monitor AI applications. It provides a user-friendly interface for creating AI applications without writing code, as well as APIs for integrating with other systems.
## Creating an Application in Dify
## Integration Methods
Please follow the [Dify documentation](https://docs.dify.ai) to deploy Dify and create your application.
There are two ways to integrate LangBot with Dify:
After publishing your application, go to the `Access API` page of your application to generate an API key.
1. **Service API**: Use Dify's Service API to access applications created in Dify
2. **Completion API**: Use Dify's Completion API as a model provider in LangBot
![Dify Application API Key](/assets/image/zh/workshop/dify-service-api/dify_sv_api_01.png)
This guide focuses on the Service API integration, which is the recommended approach for most use cases.
Save the API server and API key for configuring LangBot's pipeline `AI Capability`.
## Prerequisites
:::info
The above is an example for Dify cloud service version. If you are using the self-hosted community version, please use your own Dify service address as the `base-url` in LangBot, and add `/v1` as the path.
Before you begin, you need:
- If LangBot and Dify are deployed on the same host and both are deployed using Docker, you can refer to the article: [Network Configuration Details](/zh/workshop/network-details.html#langbot-%E5%92%8C%E6%B6%88%E6%81%AF%E5%B9%B3%E5%8F%B0%E5%9D%87%E8%BF%90%E8%A1%8C%E5%9C%A8-docker-%E5%AE%B9%E5%99%A8%E4%B8%AD). In this case, add `langbot-network` to the `networks` of all containers in the docker-compose.yaml file that starts Dify, add the container name `dify-nginx` to the `nginx` container, and finally set `base-url` to `http://dify-nginx/v1` in the LangBot configuration.
- For other cases, please consult your company's operations team.
:::
1. A Dify account and a deployed application
2. The API key for your Dify application
3. LangBot version 4.0 or higher
## Configuring LangBot
## Step 1: Create a Dify Application
Open the LangBot WebUI page, add a new pipeline or switch to the AI capability configuration page in an existing pipeline.
1. Sign up or log in to [Dify](https://dify.ai)
2. Create a new application or use an existing one
3. Configure your application with the desired model, prompt, and other settings
4. Deploy your application
5. Go to the API Reference section and copy your API key
![Setting Development Item](/assets/image/zh/deploy/pipelines/dify/dify01.png)
## Step 2: Configure LangBot
::: info
### Workflow Output Key
### Method 1: Configure via WebUI
If you are using a Dify workflow application, please use `summary` as the key to pass the output content.
1. Access the LangBot WebUI at `http://your-server-ip:5300`
2. Navigate to the "Models" section
3. Click "Add Provider"
4. Select "Dify" as the provider type
5. Enter your Dify API key and application ID
6. Save the configuration
![Dify Workflow Application Output Key](/assets/image/zh/workshop/dify-service-api/dify_workflow_output_key.png)
### Method 2: Configure via Configuration File
## Output Processing
Edit the `data/config.yaml` file and add the Dify provider:
```yaml
providers:
- id: dify
type: dify
config:
api_key: "your-dify-api-key"
application_id: "your-dify-application-id"
base_url: "https://api.dify.ai/v1" # Optional, defaults to Dify's official API endpoint
```
## Step 3: Test the Integration
Send a test message to your bot:
```
!model use dify
Hello, how are you?
```
The bot should respond using your Dify application.
## Advanced Configuration
### Using Multiple Dify Applications
You can configure multiple Dify applications in LangBot:
```yaml
providers:
- id: dify-general
type: dify
config:
api_key: "your-dify-api-key-1"
application_id: "your-dify-application-id-1"
- id: dify-specialized
type: dify
config:
api_key: "your-dify-api-key-2"
application_id: "your-dify-application-id-2"
```
### Configuring Input Variables
If your Dify application uses input variables, you can configure them in LangBot:
```yaml
providers:
- id: dify
type: dify
config:
api_key: "your-dify-api-key"
application_id: "your-dify-application-id"
input_variables:
- name: "user_name"
value: "{sender.name}"
- name: "group_name"
value: "{group.name}"
```
### Using Dify's File Capabilities
If your Dify application supports file inputs, you can configure LangBot to handle them:
```yaml
providers:
- id: dify
type: dify
config:
api_key: "your-dify-api-key"
application_id: "your-dify-application-id"
file_enabled: true
```
When file support is enabled, users can send files to the bot, and they will be forwarded to Dify:
```
!model use dify
[Attach a file]
Can you analyze this document?
```
## Troubleshooting
### Connection Issues
If you're having trouble connecting to Dify, check:
1. Your API key is correct
2. Your application ID is correct
3. Your Dify application is deployed and active
4. Your server can access the Dify API endpoint
### Response Format Issues
If the responses from Dify don't look right:
1. Check your Dify application's prompt configuration
2. Make sure your application is using the correct model
3. Verify that your application is configured for chat completion (not text completion)
### Rate Limiting
If you're hitting rate limits:
1. Check your Dify plan's rate limits
2. Consider implementing rate limiting in LangBot
3. Upgrade your Dify plan if necessary
## Example Use Cases
### Customer Support Bot
Create a Dify application for customer support, with knowledge of your products and services, and integrate it with LangBot to provide automated customer support in your messaging channels.
### Content Creation Assistant
Create a Dify application for content creation, with templates and guidelines for your brand, and integrate it with LangBot to help your team create content more efficiently.
### Data Analysis Bot
Create a Dify application for data analysis, with the ability to interpret and visualize data, and integrate it with LangBot to provide data insights on demand.
## Conclusion
Integrating LangBot with Dify allows you to leverage Dify's powerful LLMOps capabilities while using LangBot's messaging platform integrations. This combination provides a flexible and powerful solution for deploying AI applications across multiple messaging platforms.
For more information, check out the [Dify documentation](https://docs.dify.ai) and the [LangBot documentation](https://docs.langbot.app).
When using a workflow application or Agent application, if you enable `track-function-calls` in LangBot's pipeline `Output Processing`, a message of `calling function xxx` will be output to the user when Dify executes each tool call.
However, if you are using `ChatFlow` under the `chat` application (Chat Assistant -> Workflow Orchestration), it will only output the text returned by the Answer (direct reply) node regardless of the settings.
:::
+27 -366
View File
@@ -1,389 +1,50 @@
# How to Implement a Message Platform Adapter?
# Implementing a Message Platform Adapter
This guide explains how to implement a custom message platform adapter for LangBot, allowing you to connect the bot to new messaging platforms.
This article will use the `aiocqhttp` adapter as an example to explain how to implement a new message platform adapter for LangBot, in order to integrate new message platform protocols such as WhatsApp and Discord.
## Overview
## Registration
LangBot uses a modular architecture that allows for easy integration with various messaging platforms. The core component for platform integration is the `MessageSourceAdapter`, which handles the communication between LangBot and the messaging platform.
```text
Add a new message platform adapter, for example: integrate WhatsApp, Discord, etc.
![architecture](/assets/image/zh/deploy/bots/arch.png)
- Base class: `pkg.platform.adapter.MessageSourceAdapter`
- Decorator: `pkg.platform.adapter.adapter_class(name: str)`
- Reference implementation: `pkg.platform.sources/`
```
## Prerequisites
To implement a message platform adapter, we essentially need to implement a class that inherits from the `base class` and register it using the `decorator`. Finally, it will be available for users to select and use during runtime.
Before implementing a platform adapter, you should:
### Contributing to the Main Repository
1. Understand the API of the messaging platform you want to integrate with
2. Have basic knowledge of Python and asynchronous programming
3. Be familiar with LangBot's architecture and event system
## Implementation Steps
### Step 1: Create a New Adapter Class
Create a new Python file in the `langbot/bot/adapters` directory:
Create a new file `aiocqhttp.py` in the `pkg/platform/sources/` directory:
```python
from langbot.bot import MessageSourceAdapter
from langbot.message import Message, PersonSource, GroupSource, Sender
from langbot.event import PersonNormalMessageReceived, GroupNormalMessageReceived
from .. import adapter
class MyPlatformAdapter(MessageSourceAdapter):
"""
Adapter for MyPlatform.
"""
def __init__(self, config):
"""
Initialize the adapter.
Args:
config: The adapter configuration
"""
super().__init__(config)
self.config = config
# Initialize platform-specific client
self.client = None
@adapter.adapter_class("aiocqhttp")
class AiocqhttpAdapter(adapter.MessageSourceAdapter):
pass
```
### Step 2: Implement the Required Methods
Implement the required methods for the adapter:
Also import this module in `pkg/platform/manager.py` at line 40:
```python
async def start(self):
"""
Start the adapter.
"""
# Initialize and start the platform client
self.client = MyPlatformClient(
api_key=self.config.get("api_key"),
# Other platform-specific configuration
)
# Register event handlers
self.client.on_message(self.on_message)
# Start the client
await self.client.start()
async def stop(self):
"""
Stop the adapter.
"""
# Stop the platform client
if self.client:
await self.client.stop()
async def send_message(self, source, content, **kwargs):
"""
Send a message to a specific destination.
Args:
source: The destination to send the message to
content: The content of the message
**kwargs: Additional arguments
Returns:
The message ID
"""
# Send the message using the platform client
if isinstance(source, PersonSource):
# Send a direct message
message_id = await self.client.send_direct_message(
source.identity,
content,
**kwargs
)
elif isinstance(source, GroupSource):
# Send a group message
message_id = await self.client.send_group_message(
source.identity,
content,
**kwargs
)
else:
raise ValueError(f"Unsupported source type: {type(source)}")
return message_id
from .sources import nakuru, aiocqhttp, qqbotpy
```
### Step 3: Implement Event Handlers
Finally, write your own manifest file by referring to other adapters' manifest files.
Implement event handlers to convert platform-specific events to LangBot events:
## Event and Message Converters
```python
async def on_message(self, platform_message):
"""
Handle a message from the platform.
Args:
platform_message: The platform-specific message
"""
# Convert the platform message to a LangBot message
message = self.convert_message(platform_message)
# Determine the type of message and emit the appropriate event
if isinstance(message.source, PersonSource):
# Emit a person message event
await self.emit(PersonNormalMessageReceived(message))
elif isinstance(message.source, GroupSource):
# Emit a group message event
await self.emit(GroupNormalMessageReceived(message))
def convert_message(self, platform_message):
"""
Convert a platform-specific message to a LangBot message.
Args:
platform_message: The platform-specific message
Returns:
A LangBot message
"""
# Extract message information
message_id = platform_message.get("id")
content = platform_message.get("content")
time = platform_message.get("timestamp")
# Extract sender information
sender_id = platform_message.get("sender_id")
sender_name = platform_message.get("sender_name")
sender = Sender(sender_id, sender_name)
# Determine the source type
if platform_message.get("is_group"):
# Group message
group_id = platform_message.get("group_id")
source = GroupSource("my_platform", group_id)
else:
# Direct message
source = PersonSource("my_platform", sender_id)
# Create and return the message
return Message(
source=source,
content=content,
message_id=message_id,
sender=sender,
time=time
)
```
The main work of a message platform adapter is to `receive events from the message platform protocol, convert them into LangBot's format`, pass them to the core components, and after LangBot's core components process them, pass the content that needs to be replied to the message platform adapter, which then `converts the content into the platform protocol format and sends it to the message platform`.
### Step 4: Register the Adapter
The following diagram shows the processing patterns for two scenarios: message platform protocol without SDK and with mature SDK. In the first case, we need to implement connection management and network format data conversion to LB message Python objects according to the message platform protocol documentation. In the second case, the message platform has a mature SDK, we only need to create connections according to the SDK documentation, register event listeners, and implement message converters.
Register the adapter in the `langbot/bot/adapters/__init__.py` file:
![alt text](/assets/image/zh/workshop/impl-platform-adapter/workshop_impl_platform_adapter_01.png)
```python
from .my_platform import MyPlatformAdapter
In the `pkg.platform.sources.aiocqhttp` file, we can see not only `AiocqhttpAdapter`, but also `class AiocqhttpMessageConverter(adapter.MessageConverter):` and `class AiocqhttpEventConverter(adapter.EventConverter):`.
__all__ = [
# Other adapters
"MyPlatformAdapter",
]
```
- `MessageConverter` is used for converting between LangBot messages and platform messages.
- `EventConverter` is used for converting between LangBot events and platform events.
### Step 5: Add Configuration Schema
Add the configuration schema for your adapter in the `langbot/schema/bot.py` file:
```python
MY_PLATFORM_SCHEMA = {
"type": "object",
"properties": {
"type": {"type": "string", "enum": ["my_platform"]},
"api_key": {"type": "string"},
# Other platform-specific configuration
},
"required": ["type", "api_key"],
}
# Add to the BOT_SCHEMA
BOT_SCHEMA = {
"type": "object",
"properties": {
"bots": {
"type": "array",
"items": {
"oneOf": [
# Other adapter schemas
MY_PLATFORM_SCHEMA,
],
},
},
},
}
```
## Example: Implementing a Discord Adapter
Here's a simplified example of implementing a Discord adapter:
```python
import discord
from langbot.bot import MessageSourceAdapter
from langbot.message import Message, PersonSource, GroupSource, Sender
from langbot.event import PersonNormalMessageReceived, GroupNormalMessageReceived
class DiscordAdapter(MessageSourceAdapter):
"""
Adapter for Discord.
"""
def __init__(self, config):
"""
Initialize the adapter.
Args:
config: The adapter configuration
"""
super().__init__(config)
self.config = config
self.client = discord.Client(intents=discord.Intents.all())
# Register event handlers
@self.client.event
async def on_ready():
print(f"Logged in as {self.client.user}")
@self.client.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == self.client.user:
return
# Convert and emit the message
await self.on_message(message)
async def start(self):
"""
Start the adapter.
"""
# Start the Discord client
await self.client.start(self.config.get("token"))
async def stop(self):
"""
Stop the adapter.
"""
# Stop the Discord client
if self.client:
await self.client.close()
async def send_message(self, source, content, **kwargs):
"""
Send a message to a specific destination.
Args:
source: The destination to send the message to
content: The content of the message
**kwargs: Additional arguments
Returns:
The message ID
"""
# Send the message using the Discord client
if isinstance(source, PersonSource):
# Send a direct message
user = await self.client.fetch_user(int(source.identity))
message = await user.send(content)
return str(message.id)
elif isinstance(source, GroupSource):
# Send a group message
channel = self.client.get_channel(int(source.identity))
message = await channel.send(content)
return str(message.id)
else:
raise ValueError(f"Unsupported source type: {type(source)}")
async def on_message(self, discord_message):
"""
Handle a message from Discord.
Args:
discord_message: The Discord message
"""
# Convert the Discord message to a LangBot message
message = self.convert_message(discord_message)
# Determine the type of message and emit the appropriate event
if isinstance(message.source, PersonSource):
# Emit a person message event
await self.emit(PersonNormalMessageReceived(message))
elif isinstance(message.source, GroupSource):
# Emit a group message event
await self.emit(GroupNormalMessageReceived(message))
def convert_message(self, discord_message):
"""
Convert a Discord message to a LangBot message.
Args:
discord_message: The Discord message
Returns:
A LangBot message
"""
# Extract message information
message_id = str(discord_message.id)
content = discord_message.content
time = discord_message.created_at.timestamp()
# Extract sender information
sender_id = str(discord_message.author.id)
sender_name = discord_message.author.name
sender = Sender(sender_id, sender_name)
# Determine the source type
if discord_message.guild:
# Group message
group_id = str(discord_message.channel.id)
source = GroupSource("discord", group_id)
else:
# Direct message
source = PersonSource("discord", sender_id)
# Create and return the message
return Message(
source=source,
content=content,
message_id=message_id,
sender=sender,
time=time
)
```
## Testing Your Adapter
To test your adapter:
1. Add your adapter configuration to the `data/config.yaml` file:
```yaml
bots:
- id: my_platform
type: my_platform
config:
api_key: your-api-key
# Other platform-specific configuration
```
2. Start LangBot and check the logs for any errors
3. Send a test message on your platform and verify that LangBot receives and processes it
4. Send a test message from LangBot to your platform and verify that it's delivered correctly
## Best Practices
- Handle errors gracefully and provide meaningful error messages
- Implement proper rate limiting to avoid being blocked by the platform
- Use asynchronous programming to avoid blocking the event loop
- Document your adapter thoroughly, including configuration options and limitations
- Follow the platform's terms of service and API guidelines
- Implement proper logging to help with debugging
- Consider implementing reconnection logic for platforms with unstable connections
- Test your adapter thoroughly with different types of messages and scenarios
## Conclusion
Implementing a custom message platform adapter allows you to extend LangBot to work with new messaging platforms. By following the steps and best practices outlined in this guide, you can create a robust and reliable adapter that integrates seamlessly with LangBot's architecture.
If you encounter any issues or have questions, feel free to ask in the [community chat](https://qm.qq.com/q/Nnz7Vbj8OU) or open an issue on [GitHub](https://github.com/RockChinQ/LangBot/issues).
TBC...
+25
View File
@@ -0,0 +1,25 @@
# MCP Ecosystem Details
The [MCP Protocol](https://modelcontextprotocol.io/) is a protocol that describes the interaction between applications and LLMs, and has been adopted by various products. LangBot can act as an MCP Client to connect to MCP Servers, providing extensive tools for LLMs to use during conversations with users.
## Finding MCP Servers
To use MCP tools in LangBot, you need to find and connect to existing MCP Servers.
There are two types of MCP Servers in the market:
- Executable files implemented in Node or Python, communicating with LangBot through `stdio` (standard input/output)
- Web services based on HTTP protocol, communicating with LangBot through HTTP protocol
:::info
- You can check existing MCP Servers in the [MCP Server List](https://github.com/punkpeye/awesome-mcp-servers).
- For online hosted MCP Servers, you can find them at [Composio MCP](https://mcp.composio.dev/).
- To write your own MCP Server, you can refer to the [MCP Protocol Documentation](https://modelcontextprotocol.io/quickstart/server) and [MCP Server Examples](https://modelcontextprotocol.io/examples).
:::
## Configuring MCP Server
Please refer to the [System Settings Documentation](/zh/deploy/settings.html)
After configuration, you can use the `!func` command in chat to view registered MCP tools. When chatting with models that support Function Calling, LangBot will automatically call MCP tools.
+5
View File
@@ -0,0 +1,5 @@
# Integrating Models with PPIO Cloud API
Open the WebUI page, and select [PPIO Cloud](https://ppio.cn/user/register?from=ppinfra&invited_by=QJKFYD&utm_source=github_langbot) when adding a model.
![model](/assets/image/zh/workshop/ppio-integration/model.png)
+3 -3
View File
@@ -1,3 +1,3 @@
---
redirect: /zh/insight/guide
---
<script setup>
window.location.href = '/zh/insight/guide'
</script>
+3 -3
View File
@@ -1,3 +1,3 @@
---
redirect: /zh/insight/guide
---
<script setup>
window.location.href = '/zh/insight/guide'
</script>
+1 -1
View File
@@ -1,4 +1,4 @@
# 欢迎来到 LangBot 文档中心
# 欢迎访问 LangBot 文档
LangBot 是一个开源的大语言模型(LLM)原生即时通信机器人平台,支持多种消息平台和模型供应商。提供对 Dify、阿里云百炼等 LLMOps 平台的支持。并提供 WebUI 供用户快速部署和使用。