### Clone and Run LobeChat Plugin SDK Locally Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/README.md Instructions for cloning the repository, installing dependencies with Bun, and starting the development server. ```bash git clone https://github.com/lobehub/chat-plugin-sdk.git cd chat-plugin-sdk bun install bun dev ``` -------------------------------- ### Initialize and Run Plugin Project Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/get-start.md Use this command to clone the template, install dependencies, and start your local plugin development server. ```bash $ git clone https://github.com/lobehub/chat-plugin-template.git $ cd chat-plugin-template $ npm i $ npm run dev ``` -------------------------------- ### Example Plugin Manifest Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/define-plugin-manifest.md This is an example of a plugin manifest file. It defines the API endpoints, UI configuration, gateway URL, identifier, and version for a plugin. ```json { "$schema": "../node_modules/@lobehub/chat-plugin-sdk/schema.json", "api": [ { "url": "http://localhost:3400/api/clothes", "name": "recommendClothes", "description": "Recommend clothes based on the user's mood", "parameters": { "properties": { "mood": { "description": "Current mood of the user, optional values are: happy, sad, anger, fear, surprise, disgust", "enums": ["happy", "sad", "anger", "fear", "surprise", "disgust"], "type": "string" }, "gender": { "type": "string", "enum": ["man", "woman"], "description": "User's gender, this information needs to be obtained from the user" } }, "required": ["mood", "gender"], "type": "object" } } ], "gateway": "http://localhost:3400/api/gateway", "identifier": "chat-plugin-template", "ui": { "url": "http://localhost:3400", "height": 200 }, "version": "1" } ``` -------------------------------- ### Plugin Manifest Configuration Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/define-plugin-manifest.md Example of a manifest.json file with UI and gateway configurations. This is useful for local development and testing. ```json { "$schema": "../node_modules/@lobehub/chat-plugin-sdk/schema.json", "api": [], "gateway": "http://localhost:3400/api/gateway", "identifier": "plugin-identifier", "ui": { "url": "http://localhost:3400", "height": 200 }, "version": "1" } ``` -------------------------------- ### Install @lobehub/ui with npm Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-fontend.md Install the @lobehub/ui component library using npm. This library is designed for React-based plugin UI development within LobeChat. ```bash npm install @lobehub/ui ``` -------------------------------- ### Install Chat Plugin SDK with bun Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-fontend.md Install the LobeChat Chat Plugin SDK using bun. This is a prerequisite for developing frontend components for default and standalone plugins. ```bash bun i @lobehub/chat-plugin-sdk ``` -------------------------------- ### Example Plugin Manifest Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-manifest.md A sample JSON file demonstrating a typical LobeChat plugin manifest, including API definitions, gateway, identifier, and UI configuration. ```json { "$schema": "../node_modules/@lobehub/chat-plugin-sdk/schema.json", "api": [ { "url": "http://localhost:3400/api/clothes", "name": "recommendClothes", "description": "Recommend clothes based on the user's mood", "parameters": { "properties": { "mood": { "description": "The user's current mood, optional values are: happy, sad, anger, fear, surprise, disgust", "enums": ["happy", "sad", "anger", "fear", "surprise", "disgust"], "type": "string" }, "gender": { "type": "string", "enum": ["man", "woman"], "description": "User's gender, this information is known only after asking the user" } }, "required": ["mood", "gender"], "type": "object" } } ], "gateway": "http://localhost:3400/api/gateway", "identifier": "chat-plugin-template", "ui": { "url": "http://localhost:3400", "height": 200 }, "version": "1" } ``` -------------------------------- ### Install @lobehub/ui with yarn Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-fontend.md Install the @lobehub/ui component library using yarn. This library is designed for React-based plugin UI development within LobeChat. ```bash yarn add @lobehub/ui ``` -------------------------------- ### Get Plugin Initialization Information with Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/client-sdk.md Obtain initialization parameters and configuration passed by LobeChat when the plugin is loaded. This requires importing the `lobeChat` object from the SDK. ```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); }); ``` -------------------------------- ### Install Chat Plugin SDK with pnpm Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-fontend.md Install the LobeChat Chat Plugin SDK using pnpm. This is a prerequisite for developing frontend components for default and standalone plugins. ```bash pnpm i @lobehub/chat-plugin-sdk ``` -------------------------------- ### Simple Authentication Mode Configuration Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/server-auth.md Configure required authentication fields like API keys in the plugin's settings. This example shows how to require a SerpAPI API key. ```json { "settings": { "type": "object", "required": ["SERPAPI_API_KEY"], "properties": { "SERPAPI_API_KEY": { "title": "SerpAPI API Key", "description": "This plugin uses SerpAPI as the search service. For more information, please visit the [SerpAPI website](https://serpapi.com/).", "type": "string", "minLength": 64, "maxLength": 64, "format": "password" } } } } ``` -------------------------------- ### Example Function Call Schema Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/define-plugin-manifest.md This JSON structure demonstrates how plugin API interfaces are represented as functions for GPT, including their names, descriptions, and parameters conforming to JSON Schema. ```json { "functions": [ { "name": "realtimeWeather", "description": "Get the current weather condition", "parameters": { "type": "object", "properties": { "city": { "description": "City name", "type": "string" } }, "required": ["city"] } } ], "messages": [ { "role": "user", "content": "What should I wear tomorrow?" }, { "role": "assistant", "content": "Please tell me the city you are in." }, { "role": "user", "content": "Hangzhou" } ] } ``` -------------------------------- ### Plugin Manifest Schema with OpenAPI URL Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/openapi-schema.md This is an example of a plugin manifest file. The 'openapi' field should point to the URL of your OpenAPI JSON document. The 'api' field is not needed if 'openapi' is configured. ```json { "openapi": "https://yourdomain.com/path/to/openapi.json", "api": [], // No need to configure the api field after setting up openapi // ... Other configurations } ``` -------------------------------- ### Define Plugin Settings with JSON Schema Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/plugin-settings.md Use the 'settings' field in your plugin's manifest to define configuration options using JSON Schema. This example shows how to define a required API key. ```json { "settings": { "type": "object", "required": ["SERPAPI_API_KEY"], "properties": { "SERPAPI_API_KEY": { "title": "SerpAPI API Key", "description": "we use SerpAPI as backend service [Learn more](https://github.com/lobehub/chat-plugin-search-engine)", "type": "string", "minLength": 64, "maxLength": 64, "format": "password" } } } // ... } ``` -------------------------------- ### Get Plugin Payload with LobeChat Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Use this method to retrieve function call information for initializing a plugin. It returns a promise that resolves with the plugin's name and arguments. ```typescript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; lobeChat.getPluginPayload().then((payload) => { console.log(payload); }); // payload: // { // name: 'showMJ', // arguments: { // rawInput: '一只小黄鸭摄影师,在湖边度假,在冬天的下雪天。湖面结冰了', // }, // }; ``` -------------------------------- ### Get Plugin Settings from Request Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/get-plugin-settings-from-request.md Use this function to extract plugin settings from a request object. Ensure the request includes the `Lobe-Plugin-Settings` header. Returns `undefined` if parsing fails. ```typescript import { createHeadersWithPluginSettings, getPluginSettingsFromRequest, } from '@lobehub/chat-plugin-sdk'; const req = new Request('https://api.example.com', { headers: createHeadersWithPluginSettings({ theme: 'dark' }), }); const settings = getPluginSettingsFromRequest(req); console.log(settings); // 输出: { theme: "dark" } ``` -------------------------------- ### Get Plugin Settings with LobeChat Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Retrieve the configuration settings stored by a plugin within LobeChat. This method allows access to the plugin's persistent settings. ```typescript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; lobeChat.getPluginSettings().then((state) => { console.log(state); }); ``` -------------------------------- ### Get Plugin State with LobeChat Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Retrieve the runtime state associated with a plugin using a specific key. This allows for accessing and utilizing stored plugin states. ```typescript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; lobeChat.getPluginState('counter').then((state) => { console.log(state); }); ``` -------------------------------- ### Handle Plugin Request Errors with createErrorResponse Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-error-type.md Use `PluginErrorType` with `createErrorResponse` to handle different types of errors in plugin service requests. This example shows how to check the request method and return an appropriate error. ```typescript import { PluginErrorType, createErrorResponse } from '@lobehub/chat-plugin-sdk'; export default async (req: Request) => { if (req.method !== 'POST') return createErrorResponse(PluginErrorType.MethodNotAllowed); // ... }; ``` -------------------------------- ### Create a Local Plugin Gateway with Edge Runtime Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/plugin-server.md This code demonstrates how to set up a local plugin gateway using the `@lobehub/chat-plugins-gateway` package. This is necessary for custom plugins to handle requests from LobeChat when using a local service. ```typescript import { createLobeChatPluginGateway } from '@lobehub/chat-plugins-gateway'; export const config = { runtime: 'edge', }; export default async createLobeChatPluginGateway(); ``` -------------------------------- ### Get Plugin Message with LobeChat Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Retrieve the serialized and deserialized content of a plugin message. This method is useful for accessing the data payload sent by a plugin. ```typescript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; lobeChat.getPluginMessage().then((message) => { console.log(message); }); ``` -------------------------------- ### Create Local Gateway Route (Node.js Runtime) Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/server-gateway.md For Node.js serverless APIs outside of Next.js, use `createGatewayOnNodeRuntime` from `@lobehub/chat-plugins-gateway` to establish the plugin gateway. ```typescript import { createGatewayOnNodeRuntime } from '@lobehub/chat-plugins-gateway'; export default createGatewayOnNodeRuntime(); ``` -------------------------------- ### useOnStandalonePluginInit Hook Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/use-on-standalone-init.md This hook is used to listen for the initialization of standalone type plugins. It takes a callback function that will be executed once when the component mounts, receiving the plugin's initialization payload. ```APIDOC ## useOnStandalonePluginInit ### Description Listens for the initialization event of standalone type plugins. The provided callback function is executed once when the component mounts, receiving the plugin's initialization payload. ### Syntax ```ts useOnStandalonePluginInit(callback: (payload: PluginPayload) => void): void; ``` ### Parameters #### Callback Function - **callback** (`(payload: PluginPayload) => void`) - Required - A callback function that will be invoked when the plugin initialization event is triggered. The payload of the plugin initialization event will be passed as a parameter to this function. ### Type Definition for PluginPayload ```ts interface PluginPayload { args?: T; // Plugin initialization event parameters func: string; // Plugin initialization event function name } ``` ### Notes - This hook must be used within a React functional component. - The callback function will only be executed once when the component is mounted. - Inside the callback function, you can process the payload of the plugin initialization event, such as obtaining initialization parameters or calling initialization functions. ### Request Example ```tsx import { useOnStandalonePluginInit } from '@lobehub/chat-plugin-sdk/client'; const Demo = () => { useOnStandalonePluginInit((payload) => { console.log('插件初始化事件触发'); console.log('payload:', payload); }); return
监听插件初始化事件
; }; export default Demo; ``` ``` -------------------------------- ### Get Plugin Message from LobeChat Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/plugin-ui.md Actively request data from LobeChat using the `getPluginMessage` method. This method is asynchronous and can be used with data fetching libraries for caching and automatic updates. ```tsx import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; import { memo, useEffect, useState } from 'react'; import { ResponseData } from '@/type'; const Render = memo(() => { const [data, setData] = useState(); useEffect(() => { // Get the current message of the plugin from LobeChat lobeChat.getPluginMessage().then((e: ResponseData) => { setData(e); }); }, []); return <>...; }); export default Render; ``` -------------------------------- ### Create Local Gateway Route (Next.js) Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/server-gateway.md Use the `createLobeChatPluginGateway` function from `@lobehub/chat-plugins-gateway` to quickly set up a gateway route in your Next.js API directory. This function handles request forwarding, response aggregation, and security validation automatically. ```typescript import { createLobeChatPluginGateway } from '@lobehub/chat-plugins-gateway'; export default createLobeChatPluginGateway(); ``` -------------------------------- ### Clone the Plugin Template Repository Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/template.md Use this command to clone the official LobeChat plugin template to your local machine. ```bash git clone https://github.com/lobehub/chat-plugin-template.git ``` -------------------------------- ### Parse Plugin Metadata Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-meta-store.md Demonstrates how to use the pluginMetaSchema to parse and validate plugin metadata. Ensure the schema is imported correctly before use. ```typescript import { pluginMetaSchema } from '@lobehub/chat-plugin-sdk'; const meta = { author: 'John Doe', createAt: '2022-01-01', homepage: 'http://example.com', identifier: 'plugin-identifier', manifest: 'http://example.com/manifest', meta: { avatar: 'http://example.com/avatar.png', tags: ['tag1', 'tag2'], }, schemaVersion: 1, }; const result = pluginMetaSchema.parse(meta); console.log(result); // 输出:{ author: 'John Doe', createAt: '2022-01-01', homepage: 'http://example.com', identifier: 'plugin-identifier', manifest: 'http://example.com/manifest', meta: { avatar: 'http://example.com/avatar.png', tags: ['tag1', 'tag2'] }, schemaVersion: 1 } ``` -------------------------------- ### getPluginSettingsFromRequest Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/get-plugin-settings-from-request.md Retrieves the plugin settings object from a standard request object. The settings are expected to be serialized in the 'Lobe-Plugin-Settings' header. If the header is missing or malformed, it returns undefined. ```APIDOC ## getPluginSettingsFromRequest ### Description Used to retrieve the plugin settings string from the request. ### Syntax ```ts const settings = getPluginSettingsFromRequest(req: Request): T | undefined; ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { createHeadersWithPluginSettings, getPluginSettingsFromRequest, } from '@lobehub/chat-plugin-sdk'; const req = new Request('https://api.example.com', { headers: createHeadersWithPluginSettings({ theme: 'dark' }), }); const settings = getPluginSettingsFromRequest(req); console.log(settings); // 输出: { theme: "dark" } ``` ### Response #### Success Response (200) - **settings** (T | undefined) - The deserialized plugin settings object or undefined if not found or parsing fails. #### Response Example ```json { "theme": "dark" } ``` ### Notes - Ensure the incoming request object contains the `Lobe-Plugin-Settings` header. - Returns `undefined` if the plugin settings string fails to parse. ``` -------------------------------- ### getPluginSettings Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Retrieves the configuration settings stored by the plugin within LobeChat. ```APIDOC ## getPluginSettings ### Description Used to retrieve the configuration information stored by the plugin in LobeChat. ### Method `GET` (Implicit, as it's a retrieval operation) ### Endpoint `/client/getPluginSettings` (Conceptual, as it uses postMessage) ### Parameters None ### Response #### Success Response - **T** (any) - The plugin configuration settings. #### Response Example ```json { "example": "settings object" } ``` ``` -------------------------------- ### Initialize Standalone Plugin Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md For standalone plugins, use this to notify LobeChat that the plugin has been initialized. This message is specific to plugins of type 'standalone'. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.initStandalonePlugin; ``` -------------------------------- ### Model Processes Plugin Response and Responds to User Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-invoke.md The model receives plugin response data and formulates a natural language response for the user. ```json { "content": "Based on the weather forecast provided by the plugin, the weather in your location tomorrow will be sunny with a high of 25 degrees and a low of 18 degrees. The temperature is suitable for outdoor activities. It is recommended to wear light clothing and sunglasses.", "role": "assistant" } ``` -------------------------------- ### Edge Runtime Plugin Server Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/js-server.md Handles POST requests for plugin data using Vercel's Edge Runtime. It expects JSON input with 'gender' and 'mood' to return clothing recommendations. ```typescript 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)); }; ``` -------------------------------- ### Node Runtime Plugin Server Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/js-server.md Handles POST requests for plugin data using Vercel's Node Runtime. It parses the request body and uses a utility function to fetch and return content. ```typescript 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); } ``` -------------------------------- ### Configure Plugin UI in manifest.json Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-fontend.md Configure the 'ui' field in the manifest.json file for plugins requiring a frontend. This specifies the iframe loading method, dimensions, and URL. ```json "ui": { "height": 500, "mode": "iframe", "url": "http://example.com/iframe", "width": 800 } ``` -------------------------------- ### getPluginPayload Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Retrieves the Function Call information necessary to initialize a plugin. This includes the function name and its arguments. ```APIDOC ## getPluginPayload ### Description Get the Function Call information to initialize the plugin. ### Method `GET` (Implicit, as it's a retrieval operation) ### Endpoint `/client/getPluginPayload` (Conceptual, as it uses postMessage) ### Parameters None directly, but the returned payload has the following structure: ```typescript interface PluginPayload { arguments?: T; name: string; } ``` ### Response #### Success Response - **name** (string) - The API name of the Function Call. - **arguments** (object) - The parameter object of the Function Call. - **state** (any) - Optional. If present, the plugin message has state. - **settings** (object) - The plugin settings. #### Response Example ```json { "name": "showMJ", "arguments": { "rawInput": "一只小黄鸭摄影师,在湖边度假,在冬天的下雪天。湖面结冰了" } } ``` ``` -------------------------------- ### Render Plugin Settings to Plugin Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md Used for the main program to render plugin settings to the plugin. This is part of the settings related communication. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.renderPluginSettings; ``` -------------------------------- ### Access Plugin Settings in Server Request Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/plugin-settings.md Retrieve plugin settings from an incoming request using `getPluginSettingsStringFromRequest`. If settings are missing, return `PluginErrorType.PluginSettingsInvalid` to prompt user configuration. ```typescript import { PluginErrorType, createErrorResponse, getPluginSettingsStringFromRequest, } from '@lobehub/chat-plugin-sdk'; export default async (req: Request) => { // Obtain the settings information const settings = getPluginSettingsStringFromRequest(req); if (!settings) // If not obtained successfully, you can trigger the plugin configuration interface // by sending PluginErrorType.PluginSettingsInvalid return createErrorResponse(PluginErrorType.PluginSettingsInvalid, { message: 'Plugin settings not found.', }); // ... }; ``` -------------------------------- ### Notify Plugin Ready for Rendering Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md Use this to notify the LobeChat host that the plugin is ready for rendering. The main program will send plugin information after receiving this message. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.pluginReadyForRender; ``` -------------------------------- ### Implement Plugin API with Edge Runtime Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/quick-start/plugin-server.md This snippet shows how to implement a plugin's API endpoint using the Edge Runtime. It handles POST requests, parses JSON input, and returns a structured response or an error if the method is not allowed. ```typescript 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: clothes[mood] || [], mood, today: Date.now(), }; return new Response(JSON.stringify(result)); }; ``` -------------------------------- ### Configure Manifest for Markdown Plugin Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/markdown-plugin.md Set the 'type' field to 'markdown' in your plugin's manifest.json file to designate it as a Markdown type plugin. ```json { "type": "markdown" } ``` -------------------------------- ### Initiate Plugin Message Request Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md Use this for a plugin to initiate a message request to LobeChat. This is part of the message content related communication. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.fetchPluginMessage; ``` -------------------------------- ### setPluginSettings Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Updates the configuration settings for the plugin within LobeChat. Supports partial updates. ```APIDOC ## setPluginSettings ### Description This method is used to update the configuration information of the plugin. ### Method `POST` (Implicit, as it's an update operation) ### Endpoint `/client/setPluginSettings` (Conceptual, as it uses postMessage) ### Parameters #### Request Body - **settings** (object) - Required - The plugin configuration information to be updated. This is a partial update. ### Request Example ```json { "settings": { "theme": "dark", "fontSize": 12 } } ``` ``` -------------------------------- ### Weather Plugin Returns Forecast Data Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-invoke.md The weather forecast plugin processes a request and returns structured weather data in JSON format. ```json { "content": { "forecast": { "city": "user's location", "date": "tomorrow's date", "condition": "sunny", "temperature": { "high": 25, "low": 18 }, "advice": "The temperature is suitable for outdoor activities. It is recommended to wear light clothing and sunglasses." } }, "name": "queryWeatherForecast", "role": "function" } ``` -------------------------------- ### Set Plugin Settings with LobeChat Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Update the configuration settings for a plugin. This method performs a partial update, allowing specific settings to be modified without affecting others. ```typescript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; lobeChat.setPluginSettings({ theme: 'dark', fontSize: 12 }); ``` -------------------------------- ### Configure Plugin Type as Standalone Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/standalone-plugin.md Set the 'type' field to 'standalone' in your plugin's manifest.json file to designate it as a standalone plugin. ```json { // Other configurations... type: 'standalone' } ``` -------------------------------- ### Return Markdown Formatted Output Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/markdown-plugin.md Ensure your plugin returns a Response object with a plain text body formatted in Markdown. This is used for direct display to the user. ```typescript 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('、')}.`, ); }; ``` -------------------------------- ### Listen for Standalone Plugin Initialization Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/use-on-standalone-init.md Use this hook inside a React functional component to subscribe to plugin initialization events. The callback function will execute only once upon component mount, processing the initialization payload. ```tsx import { useOnStandalonePluginInit } from '@lobehub/chat-plugin-sdk/client'; const Demo = () => { useOnStandalonePluginInit((payload) => { console.log('插件初始化事件触发'); console.log('payload:', payload); }); return
监听插件初始化事件
; }; export default Demo; ``` -------------------------------- ### Render Plugin State to Plugin Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md Used for the main program to render plugin state to the plugin. This is part of the plugin runtime related communication. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.renderPluginState; ``` -------------------------------- ### Configure Local Plugin Gateway Address Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/server-gateway.md Specify the local Plugin Gateway address in your plugin's `manifest.json` file to enable direct communication for local debugging. This helps resolve cross-origin issues. ```json { "gateway": "http://localhost:3400/api/gateway" } ``` -------------------------------- ### pluginApiSchema Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-manifest.md Defines the data schema for a single plugin API, including its name, description, parameters, and URL. ```APIDOC ## pluginApiSchema ### Description Defines the data schema for a single plugin API, including its name, description, parameters, and URL. ### Schema Definitions #### pluginApiSchema | Property | Type | Description | | ------------- | ------------ | ----------------------------------------- | | `description` | `string` | Description of the plugin API | | `name` | `string` | Name of the plugin API | | `parameters` | `JSONSchema` | Definition of the plugin API's parameters | | `url` | `string` | URL of the plugin API | ``` -------------------------------- ### PluginManifestSchema Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-manifest.md Defines the data schema for the plugin manifest file. It includes details about the plugin's APIs, gateway, identifier, OpenAPI documentation, settings, and UI configuration. ```APIDOC ## PluginManifestSchema ### Description Defines the data schema for the plugin manifest file. It includes details about the plugin's APIs, gateway, identifier, OpenAPI documentation, settings, and UI configuration. ### Schema Definitions #### pluginManifestSchema | Property | Type | Description | | ------------ | ----------------------- | ----------------------------------------- | | `api` | `pluginApiSchema[]` | List of APIs for the plugin | | `gateway` | `string` (optional) | URL of the plugin's gateway | | `identifier` | `string` | Identifier of the plugin | | `openapi` | `string` (optional) | URL of the plugin's OpenAPI documentation | | `settings` | `JSONSchema` (optional) | Definition of the plugin's settings data | | `ui` | `object` (optional) | Configuration for the plugin's UI | | `ui.height` | `number` (optional) | Height of the plugin's UI | | `ui.mode` | `'iframe'` (optional) | Mode of the plugin's UI | | `ui.url` | `string` | URL of the plugin's UI | | `ui.width` | `number` (optional) | Width of the plugin's UI | ``` -------------------------------- ### setPluginState Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Updates the specified runtime state information for the plugin using a key-value pair. ```APIDOC ## setPluginState ### Description This method is used to update the specified state information of the plugin. ### Method `POST` (Implicit, as it's an update operation) ### Endpoint `/client/setPluginState` (Conceptual, as it uses postMessage) ### Parameters #### Request Body - **key** (string) - Required - The key value of the state information to be updated. - **value** (any) - Required - The value of the state information to be updated. ### Request Example ```json { "key": "counter", "value": 5 } ``` ``` -------------------------------- ### Define Plugin API Schema Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-manifest.md This snippet defines the Zod schema for a plugin's API, including its name, description, parameters, and URL. It uses a nested `JSONSchema` definition for parameters. ```typescript import { z } from 'zod'; const JSONSchema = z.object({ properties: z.object({}), type: z.enum(['object']), }); const pluginApiSchema = z.object({ description: z.string(), name: z.string(), parameters: JSONSchema, url: z.string().url(), }); export default pluginApiSchema; ``` -------------------------------- ### getPluginState Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Retrieves runtime state information stored within a message using a specified key. ```APIDOC ## getPluginState ### Description Used to retrieve the runtime state stored in the message. ### Method `GET` (Implicit, as it's a retrieval operation) ### Endpoint `/client/getPluginState` (Conceptual, as it uses postMessage) ### Parameters #### Query Parameters - **key** (string) - Required - The key value of the state information to be retrieved. ### Response #### Success Response - **T** (any) - The retrieved state value. #### Response Example ```json { "example": "state value" } ``` ``` -------------------------------- ### Plugin Manifest Schema Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-manifest.md Defines the structure of the LobeChat plugin manifest file, outlining all available configuration fields and their types. ```typescript { "api": Array, "author": String, "createAt": String, "gateway": String, "homepage": String, "identifier": String, "meta": { "avatar": String, "description": String, "tags": Array, "title": String }, "openapi": String, "settings": JSONSchema, "systemRole": String, "type": Enum['default', 'markdown', 'standalone'], "ui": { "height": Number, "mode": Enum['iframe', 'module'], "url": String, "width": Number } } ``` -------------------------------- ### Request Plugin Settings Information Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md Used for the plugin to actively request plugin settings information from LobeChat. This is part of the settings related communication. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.fetchPluginSettings; ``` -------------------------------- ### Model Generates Function Call for Weather Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-invoke.md The model generates a Function Call to request weather forecast data from a plugin based on user intent. ```json { "content": { "arguments": { "city": "user's location", "date": "tomorrow's date" } }, "name": "queryWeatherForecast", "role": "function" } ``` -------------------------------- ### Update Plugin Message Content with Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/client-sdk.md Send messages during user interaction by updating the message content using the `setPluginMessage` method. This requires importing the `lobeChat` object from the SDK. ```javascript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; // Send message content lobeChat.setPluginMessage('Welcome to using our plugin!'); ``` -------------------------------- ### usePluginState Hook Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/use-plugin-state.md Retrieves and updates the running state of a plugin. It takes a unique key and an initial value, returning the current state and a function to update it. ```APIDOC ## usePluginState Hook ### Description Used to retrieve and update the running state of the plugin. ### Syntax ```ts const [value, updateValue] = usePluginState(key, initialValue); ``` ### Parameters #### Parameters - **key** (string) - Required - Unique identifier for the state - **initialValue** (T) - Required - Initial value of the state ### Return value #### Return Value - **value** (T) - Current value of the state - **updateValue** ((value: T) => void) - Function to update the state ### Example ```tsx import { usePluginState } from '@lobehub/chat-plugin-sdk/client'; const Demo = () => { const [count, setCount] = usePluginState('count', 0); const increment = () => { setCount(count + 1); }; return (

当前计数值:{count}

); }; export default Demo; ``` ### Notes - Make sure to use `usePluginState` within a React function component. - The `key` parameter must be of type string and is used to uniquely identify the plugin state. - The `initialValue` parameter is the initial value of the state. - `value` represents the current state value, obtained through destructuring assignment. - `updateValue` is the function to update the state value, which accepts a new value as a parameter. - In the example above, we use 'usePluginState' to manage the state of a counter. The initial value is 0, and each click of the button increases the counter value by 1. ``` -------------------------------- ### Parse Plugin Manifest Data Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-manifest.md Use this snippet to parse plugin manifest data against the defined schema. Ensure you have imported the `pluginManifestSchema` from '@lobehub/chat-plugin-sdk'. ```typescript import { pluginManifestSchema } from '@lobehub/chat-plugin-sdk'; const manifestData = { api: [ { description: 'API Description', name: 'API Name', parameters: { properties: {}, type: 'object', }, url: 'http://example.com/api', }, ], gateway: 'http://example.com/gateway', identifier: 'plugin-identifier', openapi: 'http://example.com/openapi', settings: { properties: {}, type: 'object', }, ui: { height: 500, mode: 'iframe', url: 'http://example.com/plugin', width: 800, }, }; const result = pluginManifestSchema.parse(manifestData); console.log(result); ``` -------------------------------- ### LobeChat Sends API Request to Weather Plugin Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-invoke.md LobeChat converts a Function Call into an HTTP POST request to a weather forecast plugin server. ```http POST /weather-forecast HTTP/1.1 Host: plugin.example.com Content-Type: application/json { "city": "user's location", "date": "tomorrow's date" } ``` -------------------------------- ### Set Plugin State with LobeChat Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Update the specified state information for a plugin using a key-value pair. This method is essential for managing and modifying plugin runtime states. ```typescript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; lobeChat.setPluginState('counter', 5); ``` -------------------------------- ### Parse Plugin API Data Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-manifest.md Use this snippet to parse individual plugin API data against the `pluginApiSchema`. Ensure you have imported `pluginApiSchema` from '@lobehub/chat-plugin-sdk'. ```typescript import { pluginApiSchema } from '@lobehub/chat-plugin-sdk'; const apiData = { description: 'API Description', name: 'API Name', parameters: { properties: {}, type: 'object', }, url: 'http://example.com/api', }; const result = pluginApiSchema.parse(apiData); console.log(result); ``` -------------------------------- ### User Inquiry for Weather Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/guides/plugin-invoke.md Represents a user's request to LobeChat for weather information. ```json { "content": "Will my outdoor activities be affected by the weather tomorrow?", "role": "user" } ``` -------------------------------- ### Send Updated Plugin Settings Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md Used for the plugin to send updated plugin settings to LobeChat. This is part of the settings related communication. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.updatePluginSettings; ``` -------------------------------- ### Set Plugin Message with LobeChat Client SDK Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Send messages to LobeChat to update the plugin message content. The provided content will be serialized and sent, allowing the conversation to continue. ```typescript import { lobeChat } from '@lobehub/chat-plugin-sdk/client'; lobeChat.setPluginMessage({ title: 'Hello', message: 'Welcome to my plugin' }); ``` -------------------------------- ### useWatchPluginMessage Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/use-watch-plugin-message.md A React Hook that encapsulates the Chat Plugin SDK to listen for plugin messages sent from LobeChat. It returns the message data and a loading status. ```APIDOC ## useWatchPluginMessage ### Description This React Hook allows you to listen for plugin messages sent from LobeChat. It provides a convenient way to access message data within your React components. ### Syntax ```ts const { data, loading } = useWatchPluginMessage(); ``` ### Parameters This hook does not accept any direct parameters. ### Return Value - **data** (T): The data of the message sent by the plugin. The type `T` is generic and should be specified based on the expected message payload. - **loading** (boolean): A boolean value indicating whether the message data is currently being loaded. `true` if loading, `false` otherwise. ### Usage Example ```tsx import { useWatchPluginMessage } from '@lobehub/chat-plugin-sdk/client'; const MyComponent = () => { const { data, loading } = useWatchPluginMessage(); if (loading) { return
Loading plugin message...
; } return (

Plugin Message Data:

{JSON.stringify(data, null, 2)}
); }; export default MyComponent; ``` ### Notes - Ensure that `useWatchPluginMessage` is used within a React functional component. ``` -------------------------------- ### Request Plugin State Information Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/plugin-channel.md Used for the plugin to actively request plugin state information from LobeChat. This is part of the plugin runtime related communication. ```typescript import { PluginChannel } from '@lobehub/chat-plugin-sdk'; const channel = PluginChannel.fetchPluginState; ``` -------------------------------- ### getPluginMessage Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/lobe-chat-client.md Retrieves the serialized plugin message content from LobeChat and deserializes it into a JSON object. ```APIDOC ## getPluginMessage ### Description Used to retrieve the content of the plugin message (`content` field). LobeChat serializes the message object returned by the plugin and stores it in the `content` field. This method retrieves the content of this field and deserializes it into a JSON object. ### Method `GET` (Implicit, as it's a retrieval operation) ### Endpoint `/client/getPluginMessage` (Conceptual, as it uses postMessage) ### Parameters None ### Response #### Success Response - **T** (object) - The deserialized plugin message content. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Manage Plugin State with usePluginState Source: https://github.com/lobehub/chat-plugin-sdk/blob/master/docs/api/use-plugin-state.md Use this hook within a React function component to manage state for a plugin. Ensure the key is a unique string identifier for the state. ```tsx import { usePluginState } from '@lobehub/chat-plugin-sdk/client'; const Demo = () => { const [count, setCount] = usePluginState('count', 0); const increment = () => { setCount(count + 1); }; return (

当前计数值:{count}

); }; export default Demo; ```