GITBOOK-99: Add Hexabot Plugins Development Guide

This commit is contained in:
Chedli Ben Yaghlane 2024-12-17 14:51:44 +00:00 committed by gitbook-bot
parent fb82bb4393
commit a4c8eda6da
No known key found for this signature in database
GPG Key ID: 07D2180C7B12D0FF
11 changed files with 481 additions and 24 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

View File

@ -0,0 +1,7 @@
---
title: Untitled
---
{% content-ref url="../../developer-guide/setup-node.js-with-nvm.md" %}
[setup-node.js-with-nvm.md](../../developer-guide/setup-node.js-with-nvm.md)
{% endcontent-ref %}

View File

@ -21,7 +21,7 @@ Welcome to the Hexabot Documentation! Hexabot is a powerful and versatile open-s
## Key Features
Hexabot comes equipped with a comprehensive suite of features to empower your chatbot development:
Hexabot comes equipped with a comprehensive suite of features to empower your chatbot development:q
* **Intuitive Visual Editor:** Build complex conversation flows without coding using our drag-and-drop interface and a diverse library of pre-built blocks.
* **NLU Engine:** Leverage state-of-the-art NLU technology to understand user intent, extract key information, and deliver personalized responses.
@ -34,19 +34,19 @@ Hexabot comes equipped with a comprehensive suite of features to empower your ch
This documentation is a valuable resource for:
* **New Users:** Get started with Hexabot, learn the basics of chatbot creation, and build your first conversational chatbot.
* Experienced Users: Explore advanced features, optimize your existing chatbots, and discover best practices for chatbot development.
* Developers: Integrate Hexabot with your applications, leverage our APIs, and extend the platform's functionality by developing add-ons for Hexabot.
* Administrators: Manage users, configure settings, and ensure the smooth operation of Hexabot within your organization.
* **Experienced Users**: Explore advanced features, optimize your existing chatbots, and discover best practices for chatbot development.
* **Developers**: Integrate Hexabot with your applications, leverage our APIs, and extend the platform's functionality by developing add-ons for Hexabot.
* **Administrators**: Manage users, configure settings, and ensure the smooth operation of Hexabot within your organization.
## How to Use This Documentation
To navigate this documentation effectively:
* Search: Use the search bar to quickly find information on specific topics or keywords.
* Navigation: Browse through the table of contents to explore different sections and find the information you need.
* Links: Follow links to related articles and resources for in-depth explanations and examples.
* **Search**: Use the search bar to quickly find information on specific topics or keywords.
* **Navigation**: Browse through the table of contents to explore different sections and find the information you need.
* **Links**: Follow links to related articles and resources for in-depth explanations and examples.
Feedback: We encourage you to provide feedback and suggestions for improvement. Your input helps us make this documentation even better.
Feedback: We encourage you to provide feedback and suggestions for improvement. Your input helps us make this documentation even better. 
## Contacting Support

View File

@ -62,8 +62,8 @@
* [Hexabot API](developer-guide/hexabot-api.md)
* [Hexabot NLU Engine](developer-guide/hexabot-nlu-engine.md)
* [Plugins](developer-guide/integrations/README.md)
* [Hexabot Plugin Development](developer-guide/integrations/hexabot-plugin-development.md)
* [Build Your First plugin](developer-guide/integrations/build-your-first-plugin.md)
* [RAG Plugin](developer-guide/integrations/openapi.md)
* [SMTP Configuration and Emails](developer-guide/smtp-configuration-and-emails.md)
## Key Concepts

View File

@ -1,5 +1,53 @@
# Plugins
{% hint style="info" %}
This section is currently under development (WIP)
{% endhint %}
Hexabot's powerful plugin system lets you extend the chatbot platform's functionality by adding new features and integrations. The Hexabot Extension Library offers a growing collection of plugins built by the community, ready to be installed and used in your own projects. These plugins can range from simple utility enhancements to complex integrations with external services. This page explains how to install and use existing plugins within your Hexabot environment, enabling you to enhance your chatbots with minimal effort.
## **Installing Plugins**
Plugins are distributed through npm (Node Package Manager) and can be installed using the command line. The Hexabot CLI makes installation of any available plugin very simple and straightforward.
### **General Installation Process**
To install a plugin, you'll use the following general command pattern in the root directory of your Hexabot project:
```bash
npm install hexabot-plugin-[name-of-the-plugin]
```
**Plugin Naming Convention:**
By convention, all official Hexabot plugins and most plugins published by the community on the NPM registry will have package names that start with the prefix `hexabot-plugin-`. This makes the plugins easier to identify, search for, and install.
### **Example: Installing the Google Gemini Plugin for RAG**
As a concrete example, let's consider the [Google Gemini Plugin](https://hexabot.ai/extensions), which enables RAG (Retrieval-Augmented Generation) capabilities for your Hexabot chatbots using Googles Gemini API. This powerful plugin allows your chatbot to leverage external knowledge when generating responses. To install this plugin:
1. **Open your terminal:** Navigate to the root directory of your Hexabot project using your terminal.
2. **Run the installation command:** Copy and paste the following command and press enter: This command will download and install the Gemini plugin and all related dependencies.
```bash
npm install hexabot-plugin-gemini
```
3. **Plugin Activation :** After installing a plugin, you may need to restart Hexabot for the plugin's custom block to be detected and available in the block library. Additional activation steps may also be required, depending on the specific plugin. Be sure to check the plugins installation instructions in its documentation and repository for any particular instructions.
### **Important Notes:**
* **Dependency Management:** During the installation process, npm will automatically handle any plugin dependencies (other packages that the plugin relies on), making setup seamless.
* **Plugin activation**: No additional activation step is needed, once you install the plugin, the related custom block will automatically be added to the Hexabot block library.
* **Reporting Issues:** If you encounter any problems during installation, please report it to the plugin's repository or the Hexabot community. This is important to improve the plugin's stability and availability for all users.
### **Using the Installed Plugin**
After successful installation, the plugin's custom blocks will be automatically available within the Hexabot Visual Editor. Follow these steps to start utilizing your newly installed plugin:
1. **Open the Visual Editor:** Access the Hexabot Visual Editor through your web browser.
2. **Locate the Plugin Block:** Find the plugin's custom block within the Custom blocks section of the visual editor.
3. **Add the block to your flow:** Drag and drop the block into your conversation flow on the canvas.
4. **Configure the Block:** Click on the block to configure its settings, such as API keys or other plugin-specific parameters.
5. **Test your flow:** Save your flow and test it in the Live Chat Widget to experience the full capabilities of the plugin you have installed.
### **Additional Information:**
* **Plugin Documentation:** Always consult the README.md file of the plugin (often available on the plugin's public repository or GitHub repo) for more details on how to use it.
* **Extension Library:** Visit the :point\_right::jigsaw: [Hexabot Extensions Library](https://hexabot.ai/extensions) to discover other plugins that might enhance your flow capabilities. 

View File

@ -1,6 +1,379 @@
# Build Your First plugin
{% hint style="info" %}
This section is currently under development (WIP)
{% endhint %}
Hexabot's functionalities can be extended by developing and installing extensions from the [Extension Library](https://hexabot.ai/extensions). This allows to add features like text-to-action responses and third-party system integrations.
If you want to write your custom block or integration to extend Hexabot blocks library, this guide will walk you through the process of creating a custom plugin for Hexabot.
### Prerequisites
* **Node.js:** Ensure you have Node.js and a package manager (npm or yarn) installed.
{% include "../../.gitbook/includes/untitled.md" %}
* **Docker :** Ensure you have Docker installed.
{% content-ref url="../setting-up-docker-for-development-and-production.md" %}
[setting-up-docker-for-development-and-production.md](../setting-up-docker-for-development-and-production.md)
{% endcontent-ref %}
* **Hexabot Source Code:** Clone the [Hexabot repository](https://github.com/Hexastack/Hexabot) and set up your development environment according to the main [Hexabot documentation](../../quickstart/installation.md#installation).
* **TypeScript and React:** Being familiar with [TypeScript](https://www.typescriptlang.org/docs/) and [React](https://react.dev/learn) makes Hexabot Plugin development much smoother. But don't worry if you're just getting started our detailed guide will walk you through creating your first plugin.
## Plugin Structure
Hexabot plugins interact with Hexabot's existing infrastructure and can be managed through the Hexabot UI. Each plugin typically includes:
* **A Manifest file :** To define the plugin meta-data.
* **Integration Code:** Code that defines how the plugin interacts with Hexabot and external APIs (like Google Gemini in this case).
* **Configuration Settings:** Customizable settings to tailor the plugins behaviour.
* **i18n translation directory** 
A Hexabot plugins resides in the following directory `/extensions/plugins/` within the root folder of the Hexabot project. Here's the recommended project structure:
<pre><code><strong>hexabot-plugin-example/
</strong>
├── README.md // Plugin documentation
├── index.plugin.ts // Main plugin entry point
├── package.json // Plugin manifest
├── settings.json // Plugin settings
├── i18n/ // Translation directory
│ └── en/
│ └── title.json
</code></pre>
## Step-by-step guide
This guide will walk you through creating a custom plugin for Hexabot, using a basic example: a block that retrieves and displays the current time. This approach can be expanded further to create all kinds of custom blocks, allowing you to add new functionality that aligns perfectly with your project needs.
### Create Your Plugin Directory
* Navigate to `extensions/plugins/` folder in your Hexabot project.
* Create a new folder named `hexabot-plugin-time`
### Create README.md
Inside the `hexabot-plugin-time` folder, create `README.md` file. The file provides an overview and essential details about the usage of your plugin.
{% code fullWidth="false" %}
```markdown
## Plugin Name
**Plugin Description**:
Briefly explains what the plugin is about.
**Features**:
Key functionalities of the plugin.
**Prerequisites**:
Tools, libraries or skills required.
**Installation Instructions**:
Steps to set up the plugin.
**Configuration**:
Details on how to configure or adapt the plugin to specific needs.
**Usage Guide**:
How to use the plugin.
```
{% endcode %}
### Create `package.json`
The `package.json` is the manifest file of your plugin. It describes the plugin to Hexabot:
```json
{
"name": "hexabot-plugin-example",
"version": "1.0.0",
"author": "Your Name",
"description": "A brief description of your plugin."
}
```
Inside the hexabot-plugin-time folder, create package.json and add the following:
```json
{
"name": "hexabot-plugin-time",
"version": "1.0.0",
"author": "Your Name",
"description": "Hexabot plugin to get the current time."
}
```
### Create `settings.ts`
Creating a new Hexabot plugin will help you create a new custom block in the [Visual editor](../../user-guide/visual-editor/). The `settings.ts` file is the place where you'll be able to define the settings of your custom block, whether it's setting up API authentication or any other configurations.&#x20;
In the same folder, create `settings.ts` file and paste the following::
```typescript
import { PluginSetting } from '@/plugins/types';
import { SettingType } from '@/setting/schemas/types';
export default [
{
label: 'response_message',
group: 'default',
type: SettingType.multiple_text,
value: ['Time now is: ', 'Right now it\'s: '],
},
] as const satisfies PluginSetting[];
```
Later, the block configuration menu will display these settings, as illustrated below&#x20;
<figure><img src="../../.gitbook/assets/image (30).png" alt=""><figcaption></figcaption></figure>
### Create i18n folder
This folder stores translations for your plugin into multiple languages. You can add as many languages as needed by creating a new folder for each language under `i18n` folder. Place under each language file a JSON document that will define your translation for a specific language. For example, the file `title.json` includes the translation of your plugin name.
* Inside the hexabot-plugin-time directory, create a new folder named i18n
* Inside the i18n folder, create a new folder named en
```json
{
"currenttime_plugin": "Hexabot Plugin Current Time"
}
```
Refer to this example of Gemini Plugin to better understand how to define your i18n translation string :&#x20;
{% embed url="https://github.com/Hexastack/hexabot-plugin-gemini/tree/main/i18n/en" %}
### Building a Custom Block
1. **Implement Block Logic (index.plugin.ts):**
This plugin example returns the current time when sending 'time' keyword in the chat to trigger the conversation flow. You can learn more about creating your flow and managing blocks [here](../../quickstart/create-your-first-flow.md).
Inside the same directory hexabot-plugin-time create the `index.plugin.ts` with the following code:
**Let's start by importing necessary modules and services:**
Import all the necessary modules, services, and types required for the plugin.
```typescript
import { Injectable } from '@nestjs/common';
import { BlockService } from 'hexabot/src/chat/services/block.service';
import { SettingService } from 'hexabot/src/setting/services/setting.service';
import { Block } from '@/chat/schemas/block.schema';
import { Context } from '@/chat/schemas/types/context';
import {
OutgoingMessageFormat,
StdOutgoingEnvelope,
StdOutgoingTextEnvelope,
} from '@/chat/schemas/types/message';
import { BaseBlockPlugin } from '@/plugins/base-block-plugin';
import { PluginService } from '@/plugins/plugins.service';
import { PluginBlockTemplate } from '@/plugins/types';
import SETTINGS from './settings';
```
**Define the plugin class and specify its template:**
Create a class `CurrentTimePlugin` extending `BaseBlockPlugin` and define the plugin's template with patterns, conversation starter, and a display name.
```typescript
@Injectable()
export class CurrentTimePlugin extends BaseBlockPlugin<typeof SETTINGS> {
template: PluginBlockTemplate = {
patterns: ['time'],
starts_conversation: true,
name: 'Current Time Plugin',
};
```
* @Injectable(): Decorator that makes the class injectable within the NestJS framework (Hexabots backend).
* CurrentTimePlugin extends BaseBlockPlugin\<typeof SETTINGS>: Defines our plugin class, inheriting from BaseBlockPlugin and specifying that the settings are defined by our previously created settings.ts file.
* template: Defines the metadata about the plugin block like:
* patterns: The list of keywords that will trigger the block.
* starts\_conversation: Whether the block can start a conversation or should it only be triggered by previous messages.
* name: The name of the block that will appear in the visual editor.
**Constructor to initialize services:**
Initialize the necessary services (`PluginService`, `BlockService`, and `SettingService`) in the constructor.
```typescript
constructor(
pluginService: PluginService,
private readonly blockService: BlockService,
private readonly settingService: SettingService,
) {
super('currenttime-plugin', pluginService);
}
```
**Define the `getPath` method:**
Add `getPath()` method, which is need by Hexabot to identify the directory name of the current module and locating the plugin's files.
```typescript
getPath(): string {
return __dirname;
}
```
#### Define the **`Process()` method to handle block main logic:**
The `process` method performs the main logic of the block:
* Fetch settings and arguments.
* Get the current time and format it.
* Generate a random response message by combining the formatted time with a predefined message.
* Create an outgoing message envelope with the response text.
* Return the message envelope.
```typescript
async process(
block: Block,
context: Context,
_convId: string,
): Promise<StdOutgoingEnvelope> {
const settings = await this.settingService.getSettings();
const args = this.getArguments(block);
const now = new Date();
const formattedTime = now.toLocaleTimeString('en-US', { hour12: false });
const response: string =
this.blockService.getRandom([...args.response_message]) + formattedTime;
const msg: StdOutgoingTextEnvelope = {
format: OutgoingMessageFormat.text,
message: {
text: this.blockService.processText(
response,
context,
context.vars,
settings,
),
},
};
return msg;
}
}
```
#### Final Code:
:tada: Below is the complete code for the `CurrentTimePlugin`:
```typescript
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { Injectable } from '@nestjs/common';
import { BlockService } from 'hexabot/src/chat/services/block.service';
import { SettingService } from 'hexabot/src/setting/services/setting.service';
import { Block } from '@/chat/schemas/block.schema';
import { Context } from '@/chat/schemas/types/context';
import {
OutgoingMessageFormat,
StdOutgoingEnvelope,
StdOutgoingTextEnvelope,
} from '@/chat/schemas/types/message';
import { BaseBlockPlugin } from '@/plugins/base-block-plugin';
import { PluginService } from '@/plugins/plugins.service';
import { PluginBlockTemplate } from '@/plugins/types';
import SETTINGS from './settings';
@Injectable()
export class CurrentTimePlugin extends BaseBlockPlugin<typeof SETTINGS> {
template: PluginBlockTemplate = {
// default trigger for you custom block
patterns: ['time'],
// if set to true then your block comes as entrypoint by default
starts_conversation: true,
// displayed name for your plugin
name: 'Current Time Plugin',
};
constructor(
pluginService: PluginService,
private readonly blockService: BlockService,
private readonly settingService: SettingService,
) {
super('currenttime-plugin', pluginService);
}
getPath(): string {
return __dirname;
}
async process(
block: Block,
context: Context,
_convId: string,
): Promise<StdOutgoingEnvelope> {
const settings = await this.settingService.getSettings();
const args = this.getArguments(block);
const now = new Date();
const formattedTime = now.toLocaleTimeString('en-US', { hour12: false });
/**
* getRandom() function will pick randomly a string from response_message value
* array defined in the settings file to build the response.
*/
const response: string =
this.blockService.getRandom([...args.response_message]) +
' ⌚ ' +
formattedTime;
/**
* returned response from your custom block when triggering it, in this example
* it returns a text message displaying time now.
*/
const msg: StdOutgoingTextEnvelope = {
format: OutgoingMessageFormat.text,
message: {
text: this.blockService.processText(
response,
context,
context.vars,
settings,
),
},
};
return msg;
}
}
```
### Test your plugin
1. Restart Hexabot and test your plugin thoroughly. This is needed so that Hexabot recognises the newly added plugin.
2. Test in Visual Editor: Open the Visual Editor, your custom block named Current Time Plugin should be available within the Block Library. Add it to a conversation flow and use the time keyword on the Live Chat Tester, the block should return the formatted time.
\
The following represents what your custom plugin will look like based on the example above:
<figure><img src="../../.gitbook/assets/Screenshot from 2024-12-10 16-49-00.png" alt=""><figcaption></figcaption></figure>
## Publishing your plugin
After completing your plugin, be sure to connect with the Hexabot community on [Discord](https://discord.gg/rNb9t2MFkG) to showcase your plugin and work in the show-n-tell channel.&#x20;
Consider publishing your plugin to a repository (e.g., NPM, GitHub) for others to use and continue to improve it.
### Hexabot's Extensions Library
The Hexabot Extension Library is built by the community, for the community. Contributors can share their extensions, allowing everyone to benefit from a growing collection of plugins, channels, and helpers to enhance their chatbots. [https://hexabot.ai/extensions](https://hexabot.ai/extensions)
## Plugins examples
{% embed url="https://github.com/Hexastack/hexabot-plugin-gemini" %}
{% embed url="https://github.com/Hexastack/hexabot-plugin-chatgpt" %}
This guide should give you a solid foundation to start developing plugins for Hexabot. Remember that the best way to learn is to dive in, experiment, and build. Don't hesitate to refer back to the core Hexabot documentation and our Discord community as you continue your development journey!&#x20;

View File

@ -0,0 +1,37 @@
# Hexabot Plugin Development
Hexabot is designed to be a versatile and extensible chatbot platform. One of its core strengths lies in its plugin system, which allows developers to drastically expand its capabilities beyond the built-in features. Plugins in Hexabot are essentially self-contained modules that integrate seamlessly into the platform, providing a way to introduce custom logic, connect to external services.
At its core, the plugin helps create custom blocks that can be added to the Hexabots block library (the blocks library is explained more deeply in the[ Visual Editor](../../user-guide/visual-editor/) section). These new custom blocks allow you to extend the functionality of the conversation flows, meaning your chatbot can handle a wide variety of tasks, like text-to-action response or even complex third-party system integrations.
## Why Develop Hexabot Plugins?
* **Custom Functionality:** Implement specific logic tailored to your unique use case.
* Third-Party Integrations: Connect Hexabot to external APIs, databases, and other services.
* **Enhanced Automation:** Create advanced conversational actions, such as data lookups or complex workflows.
* **Offer a native product experience:** Add native integration with your product by providing a dedicated plugin for Hexabot, developers and startup founders can offer their product and services directly within the Hexabot ecosystem.
* **Expand Hexabot ecosystem:** Share your plugins with other Hexabot users through the Extension Library. Your plugins can become a valuable tool for other users, empowering Hexabot community to learn, grow, and achieve more, together (You can learn more about the extension library in the[ Hexabots Extensions Library](https://hexabot.ai/extensions) section).
### Plugin Structure
A typical Hexabot plugin, residing within the /extensions/plugins/ directory of the Hexabot project, adheres to the following recommended structure:
```
hexabot-plugin-example/
├── README.md // Plugin documentation
├── index.plugin.ts // Main plugin entry point
├── package.json // Plugin manifest
├── settings.json // Plugin settings
├── i18n/ // Translation directory
│ └── en/
│ └── title.json
```
Lets break down each component:
1. `README.md`: Provides an overview, instructions, and other relevant information about your plugin. The documentation should clearly explain what the plugin does, its features, any prerequisites, installation instructions, configuration details, and usage examples.
2. `index.plugin.ts`: The heart of your plugin. This file contains the core logic that will govern the plugin's behaviour. This includes how the plugin interacts with Hexabot and any external services it may utilize.
3. `package.json`: Acts as the manifest for the plugin. Its where you define the plugin's name, version, dependencies, and other essential metadata required for Hexabot to properly identify and handle the plugin. (More details in the[ package.json](https://docs.google.com/document/d/1PyNwF9DHOY8omTm1n8snPrxc9MDHd5vlz6KNM7GuSJ0/edit#package.json) section)
4. `settings.ts`: Defines the customizable settings for your plugin block. This will allow you to tweak its behaviour in the Visual editor. You'll be able to define UI elements such as Text Inputs, Checkboxes, etc. (More details in the[ settings.ts](https://docs.google.com/document/d/1PyNwF9DHOY8omTm1n8snPrxc9MDHd5vlz6KNM7GuSJ0/edit#settings.ts) section).
5. `i18n/`: The internationalization folder where you store translations for your plugin, allowing it to be localized for different languages. Each language gets a separate folder (e.g., en for English, fr for French) containing translation files (e.g., title.json for your plugins display name). (More details in the[ i18n](https://docs.google.com/document/d/1PyNwF9DHOY8omTm1n8snPrxc9MDHd5vlz6KNM7GuSJ0/edit#i18n) section)

View File

@ -1,6 +0,0 @@
# RAG Plugin
{% hint style="info" %}
This section is currently under development (WIP)
{% endhint %}

View File

@ -26,9 +26,7 @@ Before starting, ensure you have the following:
* #### Install NPM
{% content-ref url="../developer-guide/setup-node.js-with-nvm.md" %}
[setup-node.js-with-nvm.md](../developer-guide/setup-node.js-with-nvm.md)
{% endcontent-ref %}
{% include "../.gitbook/includes/untitled.md" %}
***