Skip to content

Commit

Permalink
📝 docs: add plugin en docs
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Jan 1, 2024
1 parent a9ce4a1 commit 40045f8
Show file tree
Hide file tree
Showing 26 changed files with 1,029 additions and 7 deletions.
2 changes: 1 addition & 1 deletion docs/api/plugin-channel.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ atomId: PluginChannel
description: Provides detailed explanations of message types for plugin communication
nav:
title: API
order: 2
order: 100
---

# PluginChannel Communication Messages
Expand Down
2 changes: 1 addition & 1 deletion docs/api/plugin-channel.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ atomId: PluginChannel
description: 提供了关于插件通信的消息类型的详细说明
nav:
title: API
order: 10
order: 100
apiHeader:
pkg: '@lobehub/chat-plugin-sdk'
---
Expand Down
45 changes: 45 additions & 0 deletions docs/guides/client-sdk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
title: Client SDK
group: Plugin Frontend
order: 2
---

# LobeChat Client SDK

The LobeChat Client SDK is a frontend development toolkit provided to plugin developers, allowing plugins to communicate efficiently and securely with the LobeChat application. Through this SDK, developers can easily access data passed to the plugin by LobeChat, send messages, update plugin status, and manage plugin configuration information.

The core functionality of the SDK is to encapsulate all the underlying communication logic required to interact with LobeChat, including using the browser's `postMessage` and `addEventListener` methods for cross-window communication. This means that developers do not need to delve into complex communication protocols and can focus on implementing plugin functionality.

## Usage Example

### Obtaining Plugin Initialization Information

When the plugin is loaded, developers may need to obtain the initialization parameters and configuration passed by LobeChat. Using the LobeChat Client SDK, this can be easily accomplished with the following lines of code:

```javascript
import { lobeChat } from '@lobehub/chat-plugin-sdk/client';

// Obtain initialization information
lobeChat.getPluginPayload().then((payload) => {
console.log('Plugin Name:', payload.name);
console.log('Plugin Arguments:', payload.arguments);
console.log('Plugin Settings:', payload.settings);
});
```

### Updating Plugin Message Content

If the plugin needs to send messages during interaction with the user, it can use the methods provided by the SDK to update the message content:

```javascript
import { lobeChat } from '@lobehub/chat-plugin-sdk/client';

// Send message content
lobeChat.setPluginMessage('Welcome to using our plugin!');
```

The LobeChat Client SDK is a powerful assistant for plugin developers, providing a complete, concise, and powerful set of tools to implement various interactive features of LobeChat plugins. With these tools, developers can focus more on innovation and enhancing user experience without worrying about the implementation details of communication mechanisms.

## API

For the complete usage API of the LobeChat Client SDK, please refer to: [LobeChat Client SDK API Documentation](/en-US/api/lobe-chat-client).
53 changes: 53 additions & 0 deletions docs/guides/communication-mechanisms.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
title: Plugin Communication
group: Concepts
order: 4
---

# Overview of Plugin Communication Mechanism

## Server Communication

For plugins of type `default` and `markdown`, you need to provide a backend service (standalone plugins can be pure frontend applications) to exchange data and process requests with the LobeChat core.

The following will introduce the implementation principles and key details of server communication between the LobeChat core and plugins.

### Plugin Server Communication Process

The server communication between the LobeChat core and plugins is coordinated through a middleware layer, namely the [Plugin Gateway](https://github.com/lobehub/chat-plugins-gateway), to ensure the security and flexibility of communication. It also provides a standardized protocol to manage requests and responses.

1. **Request Initialization**: The LobeChat core sends a request to the Gateway via HTTP POST, carrying a `PluginRequestPayload` containing the plugin identifier, API name, parameters, and other information.
2. **Gateway Processing**: Upon receiving the request, the Gateway parses the `PluginRequestPayload` in the request body and performs parameter validation.
3. **Request Handling and Response**: After successful validation, the Gateway calls the plugin's server based on the API name and parameters in the request, obtains the response, encapsulates the processing result as response data, and sends it back to the LobeChat core via HTTP response.
4. **Error Handling**: If an error occurs during request processing, the Gateway generates an error response, including the error type and message, and returns it to the LobeChat core.

### Gateway Communication Implementation Details

The following are key implementation details of the LobeChat plugin server:

- **Request Payload Processing**: The Gateway determines the plugin's identity by parsing the `identifier` in the `PluginRequestPayload` and executes the corresponding API logic based on the `apiName`.
- **Plugin Manifest Retrieval**: If the request payload does not include the plugin manifest, the Gateway retrieves it from the [Plugin Store Index](https://github.com/lobehub/lobe-chat-plugins) to ensure correct identification and functionality of the plugin.
- **Parameter Validation**: The Gateway validates the parameters in the request based on the API parameter pattern defined in the plugin manifest to ensure their validity and security.
- **Setting Handling**: The Gateway adds the plugin's requested settings to the request header, allowing the plugin to retrieve the settings, such as API keys or other authentication information, using the `getPluginSettingsFromRequest` method.
- **OpenAPI Support**: If the plugin manifest specifies an [OpenAPI manifest](/zh-CN/guides/openapi), the Gateway will utilize `SwaggerClient` to interact with third-party services defined in the OpenAPI specification.

### Error Handling

Error handling in server communication is crucial. The Gateway defines various error types, such as `PluginErrorType.MethodNotAllowed` indicating an unsupported request method, and `PluginErrorType.PluginGatewayError` indicating a gateway error, ensuring clear error feedback to the LobeChat core in case of issues. For detailed error types, please refer to: [Server Error Types](/zh-CN/api/error)

## Frontend Communication

The frontend communication between the LobeChat core and plugins is based on the HTML5 `window.postMessage` API, which allows secure communication between pages from different origins. In this mechanism, the LobeChat core can securely exchange information with embedded plugins (usually through `<iframe>` embedding).

### Frontend Communication Process

The following is an overview of the communication process:

1. **Initialization of Communication**: When the plugin is loaded and ready to interact with the LobeChat core, it can use the `lobeChat.getPluginPayload()` method to obtain initialization data. Behind the scenes, the plugin listens for the `message` event, waiting for the initialization message from the LobeChat core, and upon receiving it, returns the parsed plugin parameters, name, settings, and status.
2. **Receiving Plugin Payload**: The plugin receives initialization data from the LobeChat core by calling the `lobeChat.getPluginPayload()` method. This method internally listens for the `message` event, waiting for and processing the message containing the required plugin data sent by the LobeChat core.
3. **Retrieving and Updating Basic Information**: The plugin can call methods such as `lobeChat.setPluginSettings(settings)`, `lobeChat.setPluginMessage(content)`, `lobeChat.setPluginState(key, value)` to update settings, message content, and plugin state.
4. **Custom Trigger Actions**: For standalone plugins, custom control of AI message triggering and assistant message creation can be achieved using methods like `lobeChat.triggerAIMessage(id)` and \`lobeChat.createAssistantMessage(content), providing a richer product experience.

In summary, communication between LobeChat and plugins is achieved through asynchronous message exchange using the `postMessage` API. The plugin can request data, receive data, update state, trigger messages, etc., while the LobeChat core is responsible for responding to these requests and providing the required data. This mechanism allows plugins to operate independently and effectively communicate with the LobeChat core.

Additionally, we provide the `lobeChat` method in the SDK to simplify plugin frontend communication. Through the series of methods provided by `lobeChat`, communication details are abstracted, enabling plugins to interact with the LobeChat core using a concise API.
2 changes: 1 addition & 1 deletion docs/guides/communication-mechanisms.zh-CN.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: 插件通信
group: 基本概念
order: 3
order: 4
---

# 插件通信机制概述
Expand Down
33 changes: 33 additions & 0 deletions docs/guides/default-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
title: Default Type Plugin
group: Plugin Types
order: 0
---

# Default Type Plugin

The `default` plugin is the default type of plugin, mainly used for pure backend-driven plugins and display-oriented plugins, without rich interactive capabilities such as editing or deletion. They are suitable for scenarios that do not require complex user interaction and mainly rely on GPT for content summarization.

For example, the officially implemented website crawler plugin:

![web-crawler](https://github.com/lobehub/lobe-chat/assets/28616219/8a7191af-da07-4419-a0a1-37792b5c0c51)

Search engine plugin:

![search-engine](https://github.com/lobehub/lobe-chat/assets/28616219/573a905f-6df4-476b-8e1e-6c3098808ef8)

And all compatible OpenAI ChatGPT plugins are of the `default` type.

## How to Choose

By default, we recommend choosing the `default` type plugin because default plugins cover common mainstream scenarios, such as:

- You want the plugin's content to be summarized or further processed by GPT.
- Your plugin requires simple backend processing and tight integration with GPT's responses.
- The plugin you need is mainly used for content display, may require custom frontend display, but does not involve user interaction with the plugin (such as clicking confirm buttons);

For example, a website content summarization plugin, where the user provides a link, and the plugin returns summary information, which is then interpreted or supplemented by GPT.

## Developing Default Plugins

The [tutorial](/zh-CN/quick-start/define-plugin-manifest) in the quick start has already introduced the development process of default plugins, so it will not be repeated here.
81 changes: 81 additions & 0 deletions docs/guides/js-server.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
title: JavaScript Server
group: Plugin Server
order: 6
---

# JavaScript Server

When developing LobeChat plugins, you may need a server to handle requests and send responses. This document will guide you through developing plugins on the server using JavaScript and recommend using the Vercel platform for deployment.

## Vercel as a Server Platform

[Vercel](https://vercel.com/) is a cloud platform that provides simple deployment and hosting services, suitable for static websites and server-side applications. For LobeChat plugin development, the following features of Vercel are very useful:

- **Simple deployment process**: You can deploy your code to the cloud in a few simple steps.
- **Custom domain support**: Vercel allows you to associate your service with a custom domain.
- **Automatic scaling**: Resources are automatically scaled based on traffic to ensure service availability.

## Edge Runtime Example

Edge Runtime is an execution environment provided by Vercel, allowing your code to run on a global edge network, reducing latency and improving response speed.

Here is an example of a plugin server using Edge Runtime:

```ts
import { PluginErrorType, createErrorResponse } from '@lobehub/chat-plugin-sdk';

import { manClothes, womanClothes } from '@/data';
import { RequestData, ResponseData } from '@/type';

export const config = {
runtime: 'edge',
};

export default async (req: Request) => {
if (req.method !== 'POST') {
return createErrorResponse(PluginErrorType.MethodNotAllowed);
}

const { gender, mood } = (await req.json()) as RequestData;

const clothes = gender === 'man' ? manClothes : womanClothes;

const result: ResponseData = {
clothes: mood ? clothes[mood] : Object.values(clothes).flat(),
mood,
today: Date.now(),
};

return new Response(JSON.stringify(result));
};
```

In this example, the server receives a POST request and returns the corresponding clothing recommendation data based on the request content.

## Node Runtime Example

If you are more familiar with the Node.js environment, Vercel also supports Node Runtime. Here is an example of a server using Node Runtime:

```ts
import type { VercelRequest, VercelResponse } from '@vercel/node';

import fetchContent from './_utils';

export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
res.status(405).send('Method Not Allowed');
return;
}

const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body;

const result = await fetchContent(data);

res.status(200).send(result);
}
```

In this example, the server handles POST requests and processes the request content using a utility function `fetchContent`, then returns the processed result.

Whether you choose Edge Runtime or Node Runtime, Vercel provides a convenient deployment and runtime environment for LobeChat plugin server development. You can choose the appropriate execution environment based on your needs and familiar technology stack, and leverage the advantages of Vercel to enhance user experience.
60 changes: 60 additions & 0 deletions docs/guides/markdown-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
title: Markdown Type Plugin
group:
title: Plugin Types
order: 1
order: 2
---

# Markdown Type Plugin

The `Markdown` plugin type allows plugins to return content in Markdown format directly displayed in the chat. This rendering method is suitable for scenarios where the result is clear and does not need to be sent to AI for processing again. For example, when a user asks for specific information, the plugin can directly return a Markdown message containing the answer, without the need for additional AI summarization process. In addition, plugins of this type by default will not trigger AI messages, thus avoiding unnecessary AI calls.

![clothes](https://github.com/lobehub/lobe-chat/assets/28616219/7077a4d4-5b0f-4d4e-b332-d79b7df2b411)

## How to Choose

You can choose the `markdown` plugin if your needs align with the following scenarios:

- You need to quickly return clear, formatted text results.
- You do not require complex front-end interactions, but want the results to support rich Markdown format display.
- You want to avoid unnecessary AI summarization or processing and directly display the results to the user.
- Your plugin is for answering simple and specific queries, such as time or name queries.

For example, a plugin that queries the current time, when a user asks "What time is it in Beijing now?" the plugin returns a formatted Markdown message displaying the current time.

## Configuring as a Markdown Plugin

### Configure the Manifest

In the plugin's `manifest.json` file, set the `type` field to `markdown`.

```json
{
"type": "markdown"
}
```

### Adjust the Output Request Format

Additionally, you need to return your request in plain text in Markdown format:

```ts
export default async (req: Request) => {
// ... Other implementation code

return new Response(
`Since your mood is ${result.mood}, I recommend you wear ${result.clothes
.map((c) => c.name)
.join('')}.`,
);
};
```

The effect is as follows:

![clothes](https://github.com/lobehub/lobe-chat/assets/28616219/7077a4d4-5b0f-4d4e-b332-d79b7df2b411)

## Plugin Example

You can view the [Markdown Plugin Example](https://github.com/lobehub/chat-plugin-template/blob/main/public/manifest-markdown.json) in the chat-plugin-template to understand the implementation of the markdown type plugin.
51 changes: 51 additions & 0 deletions docs/guides/openapi-schema.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
title: OpenAPI Schema
group: Plugin Server
order: 4
---

# Configuring and Using OpenAPI Schema

LobeChat's plugin mechanism provides a powerful and flexible way to extend chat functionality. At the same time, support for the OpenAPI specification makes plugin development more standardized and convenient. This document aims to guide developers on how to configure and use the OpenAPI schema in the LobeChat server implementation, thereby creating plugins that seamlessly integrate with LobeChat.

## Role of OpenAPI in LobeChat Plugins

Through the OpenAPI schema, developers can define the API interface of the plugin, including the request path, method, parameters, responses, and more. LobeChat interprets the OpenAPI document to understand how to interact with the plugin, allowing users to install and use the plugin through LobeChat's interface without needing to worry about the specific implementation details of the interface.

### Step 1: Build Your Service API

Develop your service API and ensure that it can respond to LobeChat's requests and return appropriate responses. You can use any language and framework of your choice to build this API.

### Step 2: Create an OpenAPI Document

Use the OpenAPI specification to describe your service, including defining the API's paths, operations, parameters, responses, and more. You can choose to write your OpenAPI document in YAML or JSON format. Ensure that the document contains all the necessary details so that LobeChat can interact with your service correctly.

### Step 3: Create the LobeChat Plugin Manifest File

Create a `manifest.json` file that includes the plugin's metadata and configuration information. Most importantly, provide the URL of your OpenAPI document in the `openapi` field.

Example of the Plugin Manifest Schema:

```json5
{
openapi: 'https://yourdomain.com/path/to/openapi.json',
api: [], // No need to configure the api field after setting up openapi

// ... Other configurations
}
```

## Key Elements of the OpenAPI Specification

When creating an OpenAPI document, ensure that it includes the following:

- **Basic Information**: Such as title, description, version, and more.
- **Server URL**: The URL of the API server.
- **Endpoints**: Available API paths and operations.
- **Parameters**: Input and output parameters for each operation.
- **Authentication**: The authentication methods used by the API.
- **Responses**: Common response messages and error codes.

## Integrating with LobeChat Using OpenAPI

Once your API and OpenAPI document are ready, you can install and test your plugin in the LobeChat UI. Users will be able to interact with your service through the endpoints defined in your OpenAPI document.
Loading

0 comments on commit 40045f8

Please sign in to comment.