doc: zh_hans draft for plugin multilingual readme std (#472)

* doc: zh_hans draft for plugin multilingual readme std

* Docs tools: Successfully completed 3 operations

* Documentation edits made through Mintlify web editor

* Docs tools: 2 succeeded, some failed

Rename operation failed: - Lang 'zh': File 'dify-docs/plugin-dev-zh/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'zh': File 'dify-docs/plugin-dev-zh/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'en': File 'dify-docs/plugin-dev-en/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'en': File 'dify-docs/plugin-dev-en/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'ja': File 'dify-docs/plugin-dev-ja/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'ja': File 'dify-docs/plugin-dev-ja/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'

* Documentation edits made through Mintlify web editor

* Docs tools: 2 succeeded, some failed

Rename operation failed: - Lang 'zh': File 'dify-docs/plugin-dev-zh/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'zh': File 'dify-docs/plugin-dev-zh/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'en': File 'dify-docs/plugin-dev-en/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'en': File 'dify-docs/plugin-dev-en/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'ja': File 'dify-docs/plugin-dev-ja/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'ja': File 'dify-docs/plugin-dev-ja/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'

* Documentation edits made through Mintlify web editor

* Docs tools: 2 succeeded, some failed

Rename operation failed: - Lang 'zh': File 'dify-docs/plugin-dev-zh/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'zh': File 'dify-docs/plugin-dev-zh/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'en': File 'dify-docs/plugin-dev-en/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'en': File 'dify-docs/plugin-dev-en/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'ja': File 'dify-docs/plugin-dev-ja/0211-getting-started-dify-tool.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'
- Lang 'ja': File 'dify-docs/plugin-dev-ja/0411-multilingual-readme.mdx' - Renaming error: Unexpected error: 'str' object has no attribute 'get'

* Documentation edits made through Mintlify web editor

---------

Co-authored-by: alterxyz <88554920+alterxyz@users.noreply.github.com>
Co-authored-by: Riskey <36894937+RiskeyL@users.noreply.github.com>
This commit is contained in:
Junyan Qin (Chin)
2025-09-30 10:41:57 +08:00
committed by GitHub
parent 95ab596360
commit fe4d97fae3
10 changed files with 1145 additions and 1086 deletions

View File

@@ -597,7 +597,8 @@
"plugin-dev-en/0411-plugin-info-by-manifest", "plugin-dev-en/0411-plugin-info-by-manifest",
"plugin-dev-en/0411-remote-debug-a-plugin", "plugin-dev-en/0411-remote-debug-a-plugin",
"plugin-dev-en/0411-tool", "plugin-dev-en/0411-tool",
"plugin-dev-en/0412-model-schema" "plugin-dev-en/0412-model-schema",
"plugin-dev-en/0411-multilingual-readme"
] ]
} }
] ]
@@ -1283,7 +1284,8 @@
"plugin-dev-zh/0411-plugin-info-by-manifest", "plugin-dev-zh/0411-plugin-info-by-manifest",
"plugin-dev-zh/0411-remote-debug-a-plugin", "plugin-dev-zh/0411-remote-debug-a-plugin",
"plugin-dev-zh/0411-tool", "plugin-dev-zh/0411-tool",
"plugin-dev-zh/0412-model-schema" "plugin-dev-zh/0412-model-schema",
"plugin-dev-zh/0411-multilingual-readme"
] ]
} }
] ]
@@ -1936,7 +1938,8 @@
"plugin-dev-ja/0411-plugin-info-by-manifest", "plugin-dev-ja/0411-plugin-info-by-manifest",
"plugin-dev-ja/0411-remote-debug-a-plugin", "plugin-dev-ja/0411-remote-debug-a-plugin",
"plugin-dev-ja/0411-tool", "plugin-dev-ja/0411-tool",
"plugin-dev-ja/0412-model-schema" "plugin-dev-ja/0412-model-schema",
"plugin-dev-ja/0411-multilingual-readme"
] ]
} }
] ]

Binary file not shown.

After

Width:  |  Height:  |  Size: 435 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 462 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 KiB

View File

@@ -1,17 +1,9 @@
--- ---
dimensions: dimensions: "[object Object]"
type: standard_title: "Getting Started Dify Tool"
primary: implementation language: "en"
detail: basic title: "Dify Plugin Development: Hello World Guide"
level: beginner description: "This document provides a detailed tutorial for Dify plugin development from scratch, using the Telegraph publishing plugin as an example, covering environment preparation, project initialization, virtual environment configuration, plugin core logic development, local debugging, plugin metadata enhancement, and packaging for release."
standard_title: Getting Started Dify Tool
language: en
title: 'Dify Plugin Development: Hello World Guide'
description: This document provides a detailed tutorial for Dify plugin development
from scratch, using the Telegraph publishing plugin as an example, covering environment
preparation, project initialization, virtual environment configuration, plugin core
logic development, local debugging, plugin metadata enhancement, and packaging for
release.
--- ---
Welcome to the beginner's guide for Dify plugin development! This tutorial assumes you have basic programming knowledge and experience using the Dify platform. After completing this tutorial, you will master the fundamental process of creating a simple Dify plugin, taking you from a Dify user to a plugin contributor. Welcome to the beginner's guide for Dify plugin development! This tutorial assumes you have basic programming knowledge and experience using the Dify platform. After completing this tutorial, you will master the fundamental process of creating a simple Dify plugin, taking you from a Dify user to a plugin contributor.
@@ -35,35 +27,30 @@ Before starting Dify plugin development, ensure you have the following tools rea
1. **Download:** Visit the [Dify Plugin CLI Releases](https://github.com/langgenius/dify-plugin-daemon/releases) page. Download the latest version of the binary file corresponding to your operating system (Windows, macOS Intel/ARM, Linux). 1. **Download:** Visit the [Dify Plugin CLI Releases](https://github.com/langgenius/dify-plugin-daemon/releases) page. Download the latest version of the binary file corresponding to your operating system (Windows, macOS Intel/ARM, Linux).
2. **Set Execute Permissions (macOS / Linux):** 2. **Set Execute Permissions (macOS / Linux):**
- **The following steps use macOS (Apple Silicon / M series chips) as an example**, assuming the downloaded file is named `dify-plugin-darwin-arm64`. In the terminal, navigate to the directory containing the file and execute the following command to grant execution permissions:
- **The following steps use macOS (Apple Silicon / M series chips) as an example**, assuming the downloaded file is named `dify-plugin-darwin-arm64`. In the terminal, navigate to the directory containing the file and execute the following command to grant execution permissions: ```bash
chmod +x dify-plugin-darwin-arm64
```bash ```
chmod +x dify-plugin-darwin-arm64 - For Linux users, download the corresponding Linux version file and execute a similar command like `chmod +x <downloaded_filename>`.
``` - For Windows users, after downloading the `.exe` file, you can typically run it directly.
- For Linux users, download the corresponding Linux version file and execute a similar command like `chmod +x <downloaded_filename>`.
- For Windows users, after downloading the `.exe` file, you can typically run it directly.
3. **Verify Installation:** 3. **Verify Installation:**
- In the terminal, execute the following command to check if the tool runs properly (replace `./dify-plugin-darwin-arm64` with the actual filename or path you downloaded):
- In the terminal, execute the following command to check if the tool runs properly (replace `./dify-plugin-darwin-arm64` with the actual filename or path you downloaded): ```bash
./dify-plugin-darwin-arm64 version
```bash ```
./dify-plugin-darwin-arm64 version - If the terminal successfully outputs version information (e.g., `v0.0.1-beta.15`), then the installation is successful.
```
- If the terminal successfully outputs version information (e.g., `v0.0.1-beta.15`), then the installation is successful.
> **Tips:** > **Tips:**
> >
> - **macOS Security Prompt:** If macOS initially prompts "Apple cannot verify" or "Cannot open," go to "System Settings" → "Privacy & Security" → "Security" section, find the related prompt and click "Open Anyway" or "Allow." > - **macOS Security Prompt:** If macOS initially prompts "Apple cannot verify" or "Cannot open," go to "System Settings" → "Privacy & Security" → "Security" section, find the related prompt and click "Open Anyway" or "Allow."
> - **Simplify Command:** You can rename the downloaded binary file to a shorter name (e.g., `dify` or `dify-plugin`) for easier use. Example: `mv dify-plugin-darwin-arm64 dify`, then you can use `./dify version`. > - **Simplify Command:** You can rename the downloaded binary file to a shorter name (e.g., `dify` or `dify-plugin`) for easier use. Example: `mv dify-plugin-darwin-arm64 dify`, then you can use `./dify version`.
> - **Global Installation (Optional):** If you want to run the command from any path in your system (e.g., directly typing `dify` instead of `./dify`), you can move the renamed file to a directory included in your system's `PATH` environment variable, such as `/usr/local/bin` (macOS/Linux) or add it to Windows environment variables. > - **Global Installation (Optional):** If you want to run the command from any path in your system (e.g., directly typing `dify` instead of `./dify`), you can move the renamed file to a directory included in your system's `PATH` environment variable, such as `/usr/local/bin` (macOS/Linux) or add it to Windows environment variables.
> - For example (macOS/Linux): `sudo mv dify /usr/local/bin/` > - For example (macOS/Linux): `sudo mv dify /usr/local/bin/`
> - After configuration, typing `dify version` directly in the terminal should successfully output the version number. > - After configuration, typing `dify version` directly in the terminal should successfully output the version number.
**For convenience, this article will use `./dify` as an example command for the Dify plugin development scaffold. Please replace it with your corresponding command based on your actual situation.** **`For convenience, this article will use ./dify as an example command for the Dify plugin development scaffold. Please replace it with your corresponding command based on your actual situation.`**
## 2. Initializing the Plugin Project ## 2. Initializing the Plugin Project
@@ -71,24 +58,24 @@ Now, let's use the scaffold tool to create a new plugin project.
1. Open a terminal and execute the initialization command: 1. Open a terminal and execute the initialization command:
```bash ```bash
./dify plugin init ./dify plugin init
``` ```
2. Enter the basic information for the plugin according to the prompts: 2. Enter the basic information for the plugin according to the prompts:
- **Plugin name:** A unique identifier for the plugin. For example: `telegraph` - **Plugin name:** A unique identifier for the plugin. For example: `telegraph`
- _Constraints: 1-128 characters, can only contain lowercase letters, numbers, hyphens (-), and underscores (_)._ - _Constraints: 1-128 characters, can only contain lowercase letters, numbers, hyphens (-), and underscores (_).\_
- **Author:** The identifier for the plugin author. For example: `your-name` - **Author:** The identifier for the plugin author. For example: `your-name`
- _Constraints: 1-64 characters, can only contain lowercase letters, numbers, hyphens (-), and underscores (_)._ - _Constraints: 1-64 characters, can only contain lowercase letters, numbers, hyphens (-), and underscores (_).\_
- **Description:** A brief description of the plugin's functionality. For example: `A Telegraph plugin that allows you to publish your content easily` - **Description:** A brief description of the plugin's functionality. For example: `A Telegraph plugin that allows you to publish your content easily`
- **Enable multilingual README:** This option allows the generation of multilingual README files for the plugin. After checking this, you can select the languages for which you want to pre-generate README files in the `Languages to generate` section below.
3. **Select Development Language:** When prompted `Select language`, choose `python`. 3. **Select Development Language:** When prompted `Select language`, choose `python`.
4. **Select Plugin Type:** When prompted `Select plugin type`, for this tutorial, choose `tool`. 4. **Select Plugin Type:** When prompted `Select plugin type`, for this tutorial, choose `tool`.
5. **Select Additional Features:** Next, you'll be prompted if you need to include Provider validation, persistent storage, and other additional features. For this simple Hello World plugin, we don't need these yet, so you can press **Enter** to skip all options until you see the success message. 5. **Select Additional Features:** Next, you'll be prompted if you need to include Provider validation, persistent storage, and other additional features. For this simple Hello World plugin, we don't need these yet, so you can press **Enter** to skip all options until you see the success message.
6. **Confirm Creation Success:** When the terminal outputs information similar to the following, it indicates that the plugin project has been successfully created: 6. **Confirm Creation Success:** When the terminal outputs information similar to the following, it indicates that the plugin project has been successfully created:
```bash ```bash
[INFO] plugin telegraph created successfully, you can refer to `telegraph/GUIDE.md` for more information about how to develop it [INFO] plugin telegraph created successfully, you can refer to `telegraph/GUIDE.md` for more information about how to develop it
``` ```
Now, a new folder named `telegraph` (or the plugin name you specified) should appear in your current directory, which is your plugin project. Now, a new folder named `telegraph` (or the plugin name you specified) should appear in your current directory, which is your plugin project.
@@ -102,37 +89,31 @@ This is the **recommended and universal** method, not dependent on any specific
1. **Navigate to the Project Directory:** 1. **Navigate to the Project Directory:**
```bash ```bash
cd telegraph cd telegraph
``` ```
2. **Create a Virtual Environment:** (Recommended to name it `venv`) 2. **Create a Virtual Environment:** (Recommended to name it `venv`)
```bash ```bash
python -m venv venv python -m venv venv
``` ```
3. **Activate the Virtual Environment:** 3. **Activate the Virtual Environment:**
- **macOS / Linux:**
- **macOS / Linux:** ```bash
source venv/bin/activate
```
- **Windows (cmd.exe):**
```bash ```bash
source venv/bin/activate venv\Scripts\activate.bat
``` ```
- **Windows (PowerShell):**
- **Windows (cmd.exe):** ```bash
venv\Scripts\Activate.ps1
```bash ```
venv\Scripts\activate.bat - After successful activation, your terminal prompt will typically display `(venv)` at the beginning.
```
- **Windows (PowerShell):**
```bash
venv\Scripts\Activate.ps1
```
- After successful activation, your terminal prompt will typically display `(venv)` at the beginning.
### 3.2 Installing Basic Dependencies ### 3.2 Installing Basic Dependencies
@@ -148,14 +129,14 @@ If you use VSCode as your code editor, you can leverage its integrated features
1. **Open the Project Folder:** Use VSCode to open the `telegraph` folder you just created. 1. **Open the Project Folder:** Use VSCode to open the `telegraph` folder you just created.
2. **Select Python Interpreter:** 2. **Select Python Interpreter:**
- Open the command palette (macOS: `Cmd+Shift+P`, Windows/Linux: `Ctrl+Shift+P`). - Open the command palette (macOS: `Cmd+Shift+P`, Windows/Linux: `Ctrl+Shift+P`).
- Type and select `Python: Select Interpreter`. - Type and select `Python: Select Interpreter`.
- In the pop-up list, select the Python interpreter in the virtual environment you just created (usually the path includes `.venv/bin/python` or `venv\Scripts\python.exe`). If the list doesn't automatically display it, you can select `Enter interpreter path...` to manually find it. - In the pop-up list, select the Python interpreter in the virtual environment you just created (usually the path includes `.venv/bin/python` or `venv\Scripts\python.exe`). If the list doesn't automatically display it, you can select `Enter interpreter path...` to manually find it.
- _(Please refer to your local corresponding screenshot, which shows the interpreter selection interface)_ - _(Please refer to your local corresponding screenshot, which shows the interpreter selection interface)_
3. **Install Dependencies (If VSCode Prompts):** VSCode may detect the `requirements.txt` file and prompt you to install its dependencies. If prompted, confirm the installation. 3. **Install Dependencies (If VSCode Prompts):** VSCode may detect the `requirements.txt` file and prompt you to install its dependencies. If prompted, confirm the installation.
- _(Please refer to your local corresponding screenshot, which shows the interface for confirming dependency installation)_ - _(Please refer to your local corresponding screenshot, which shows the interface for confirming dependency installation)_
**Please ensure that all subsequent `pip install` commands and running `python -m main` operations are performed in the activated virtual environment.** **`Please ensure that all subsequent pip install commands and running python -m main operations are performed in the activated virtual environment.`**
## 4. Developing the Plugin Core Logic ## 4. Developing the Plugin Core Logic
@@ -187,122 +168,119 @@ Our goal is to implement similar functionality in a Dify plugin.
1. **Install the Dependency Library:** Ensure your virtual environment is activated, then execute in the terminal: 1. **Install the Dependency Library:** Ensure your virtual environment is activated, then execute in the terminal:
```bash ```bash
pip install your-telegraph pip install your-telegraph
``` ```
2. **`Update requirements.txt:`** Open the `requirements.txt` file in the `telegraph` project root directory, and add a line below `dify_plugin` with the name of the library you just installed:
2. **Update `requirements.txt`:** Open the `requirements.txt` file in the `telegraph` project root directory, and add a line below `dify_plugin` with the name of the library you just installed: ```plaintext
dify_plugin
your-telegraph
```
```plaintext This ensures that other developers or deployment environments can easily install all the required dependencies.
dify_plugin
your-telegraph
```
This ensures that other developers or deployment environments can easily install all the required dependencies.
### 4.3 Configuring Provider Credentials ### 4.3 Configuring Provider Credentials
Our example requires a `telegraph_access_token`. We need to define this credential in the Provider configuration so that users can input it when using the plugin. For more information about Provider configuration, please refer to [General Specification Definitions](/plugin-dev-en/0411-general-specifications). Our example requires a `telegraph_access_token`. We need to define this credential in the Provider configuration so that users can input it when using the plugin. For more information about Provider configuration, please refer to [General Specification Definitions](/plugin-dev-en/0411-general-specifications).
1. **Edit the Provider YAML:** Open the `telegraph/provider/telegraph.yaml` file. 1. **Edit the Provider YAML:** Open the `telegraph/provider/telegraph.yaml` file.
2. **Add `credentials_for_provider`:** Add the following content at the end of the file (or at an appropriate location): 2. **`Add credentials_for_provider:`** Add the following content at the end of the file (or at an appropriate location):
```yaml ```yaml
# ... (keep existing identity, name, label, description, icon, etc. unchanged) ... # ... (keep existing identity, name, label, description, icon, etc. unchanged) ...
credentials_for_provider: credentials_for_provider:
telegraph_access_token: # This is the internal name of the credential, to be used in Python code telegraph_access_token: # This is the internal name of the credential, to be used in Python code
type: secret-input # Input type is a password field type: secret-input # Input type is a password field
required: true # This credential is required required: true # This credential is required
label: # Label displayed in the Dify UI (supports multiple languages) label: # Label displayed in the Dify UI (supports multiple languages)
en_US: Telegraph Access Token en_US: Telegraph Access Token
zh_Hans: Telegraph Access Token zh_Hans: Telegraph Access Token
# ... (other languages) # ... (other languages)
placeholder: # Placeholder text for the input field (supports multiple languages) placeholder: # Placeholder text for the input field (supports multiple languages)
en_US: Enter your Telegraph access token en_US: Enter your Telegraph access token
zh_Hans: Please enter your Telegraph access token zh_Hans: Please enter your Telegraph access token
# ... (other languages) # ... (other languages)
help: # Help prompt information (supports multiple languages) help: # Help prompt information (supports multiple languages)
en_US: How to get your Telegraph access token en_US: How to get your Telegraph access token
zh_Hans: How to get your Telegraph access token zh_Hans: How to get your Telegraph access token
# ... (other languages) # ... (other languages)
url: https://telegra.ph/api#createAccount # URL to jump to when clicking the help prompt url: https://telegra.ph/api#createAccount # URL to jump to when clicking the help prompt
``` ```
- **Field Explanations:**
- **Field Explanations:** - `telegraph_access_token`: Unique identifier for the credential, accessed in code via `self.runtime.credentials["telegraph_access_token"]`.
- `telegraph_access_token`: Unique identifier for the credential, accessed in code via `self.runtime.credentials["telegraph_access_token"]`. - `type: secret-input`: Indicates that it will be displayed as a password input field in the Dify interface.
- `type: secret-input`: Indicates that it will be displayed as a password input field in the Dify interface. - `required: true`: Indicates that users must fill in this credential to use tools provided by this plugin.
- `required: true`: Indicates that users must fill in this credential to use tools provided by this plugin. - `label`, `placeholder`, `help`: Provide multilingual interface text.
- `label`, `placeholder`, `help`: Provide multilingual interface text. - `url`: (Optional) Provides a help link for obtaining the credential.
- `url`: (Optional) Provides a help link for obtaining the credential.
### 4.4 Implementing Tool Logic ### 4.4 Implementing Tool Logic
Now let's write the code that actually performs the publishing operation. Now let's write the code that actually performs the publishing operation.
1. **Edit the Tool Python File:** Open `telegraph/tools/telegraph.py`. 1. **Edit the Tool Python File:** Open `telegraph/tools/telegraph.py`.
2. **Implement the `_invoke` Method:** Replace the file contents with the following code: 2. **`Implement the _invoke Method:`** Replace the file contents with the following code:
```python ```python
from collections.abc import Generator from collections.abc import Generator
from typing import Any from typing import Any
from ytelegraph import TelegraphAPI # Import the library we're using from ytelegraph import TelegraphAPI # Import the library we're using
from dify_plugin import Tool from dify_plugin import Tool
from dify_plugin.entities.tool import ToolInvokeMessage from dify_plugin.entities.tool import ToolInvokeMessage
class TelegraphTool(Tool): class TelegraphTool(Tool):
""" """
A simple Telegraph publishing tool. A simple Telegraph publishing tool.
""" """
def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]:
""" """
Create a new Telegraph page based on the input title and content. Create a new Telegraph page based on the input title and content.
Args: Args:
tool_parameters: A dictionary containing the tool input parameters: tool_parameters: A dictionary containing the tool input parameters:
- p_title (str): The title of the Telegraph page. - p_title (str): The title of the Telegraph page.
- p_content (str): The content to publish in Markdown format. - p_content (str): The content to publish in Markdown format.
Yields: Yields:
ToolInvokeMessage: A message containing the URL of the successfully created Telegraph page. ToolInvokeMessage: A message containing the URL of the successfully created Telegraph page.
Raises: Raises:
Exception: If page creation fails, an exception with error information is thrown. Exception: If page creation fails, an exception with error information is thrown.
""" """
# 1. Get credentials from runtime # 1. Get credentials from runtime
try: try:
access_token = self.runtime.credentials["telegraph_access_token"] access_token = self.runtime.credentials["telegraph_access_token"]
except KeyError: except KeyError:
raise Exception("Telegraph Access Token is not configured or invalid. Please provide it in the plugin settings.") raise Exception("Telegraph Access Token is not configured or invalid. Please provide it in the plugin settings.")
# 2. Get tool input parameters # 2. Get tool input parameters
title = tool_parameters.get("p_title", "Untitled") # Use .get to provide default value title = tool_parameters.get("p_title", "Untitled") # Use .get to provide default value
content = tool_parameters.get("p_content", "") content = tool_parameters.get("p_content", "")
if not content: if not content:
raise Exception("Publication content cannot be empty.") raise Exception("Publication content cannot be empty.")
# 3. Call the library to execute operations # 3. Call the library to execute operations
try: try:
telegraph = TelegraphAPI(access_token) # Initialize Telegraph API telegraph = TelegraphAPI(access_token) # Initialize Telegraph API
ph_link = telegraph.create_page_md(title, content) # Create page ph_link = telegraph.create_page_md(title, content) # Create page
except Exception as e: except Exception as e:
# If the library call fails, throw an exception # If the library call fails, throw an exception
raise Exception(f"Telegraph API call failed: {e}") raise Exception(f"Telegraph API call failed: {e}")
# 4. Return results # 4. Return results
# Use create_link_message to generate an output message containing a link # Use create_link_message to generate an output message containing a link
yield self.create_link_message(ph_link) yield self.create_link_message(ph_link)
``` ```
- **Key Points:**
- **Key Points:** - Get credentials from `self.runtime.credentials`.
- Get credentials from `self.runtime.credentials`. - Get the tool's input parameters from `tool_parameters` (parameter names will be defined in YAML in the next step). Using `.get()` is a more robust approach.
- Get the tool's input parameters from `tool_parameters` (parameter names will be defined in YAML in the next step). Using `.get()` is a more robust approach. - Call the `ytelegraph` library to perform the actual operation.
- Call the `ytelegraph` library to perform the actual operation. - Use `try...except` to catch possible errors and throw exceptions.
- Use `try...except` to catch possible errors and throw exceptions. - Use `yield self.create_link_message(url)` to return a result containing a URL to Dify.
- Use `yield self.create_link_message(url)` to return a result containing a URL to Dify.
### 4.5 Configuring Tool Parameters ### 4.5 Configuring Tool Parameters
@@ -311,202 +289,191 @@ We need to tell Dify which input parameters this tool accepts.
1. **Edit the Tool YAML File:** Open `telegraph/tools/telegraph.yaml`. 1. **Edit the Tool YAML File:** Open `telegraph/tools/telegraph.yaml`.
2. **Define Parameters:** Replace or modify the file contents to: 2. **Define Parameters:** Replace or modify the file contents to:
```yaml ```yaml
identity: identity:
name: telegraph_publisher # Unique internal name of the tool name: telegraph_publisher # Unique internal name of the tool
author: your-name author: your-name
label: # Tool name displayed in the Dify UI (multilingual) label: # Tool name displayed in the Dify UI (multilingual)
en_US: Publish to Telegraph en_US: Publish to Telegraph
zh_Hans: Publish to Telegraph zh_Hans: Publish to Telegraph
# ... (other languages) # ... (other languages)
description: description:
human: # Tool description for human users (multilingual) human: # Tool description for human users (multilingual)
en_US: Publish content to Telegraph as a new page. en_US: Publish content to Telegraph as a new page.
zh_Hans: Publish content to Telegraph as a new page. zh_Hans: Publish content to Telegraph as a new page.
# ... (other languages) # ... (other languages)
llm: # Tool description for LLM (used in Agent mode) llm: # Tool description for LLM (used in Agent mode)
A tool that takes a title and markdown content, then publishes it as a new page on Telegraph, returning the URL of the published page. Use this when the user wants to publish formatted text content publicly via Telegraph. A tool that takes a title and markdown content, then publishes it as a new page on Telegraph, returning the URL of the published page. Use this when the user wants to publish formatted text content publicly via Telegraph.
parameters: # Define the list of input parameters for the tool parameters: # Define the list of input parameters for the tool
- name: p_title # Internal name of the parameter, corresponding to the key in Python code - name: p_title # Internal name of the parameter, corresponding to the key in Python code
type: string # Parameter type type: string # Parameter type
required: true # Whether required required: true # Whether required
label: # Parameter label displayed in the Dify UI (multilingual) label: # Parameter label displayed in the Dify UI (multilingual)
en_US: Post Title en_US: Post Title
zh_Hans: Post Title zh_Hans: Post Title
human_description: # Parameter description for human users (multilingual) human_description: # Parameter description for human users (multilingual)
en_US: The title for the Telegraph page. en_US: The title for the Telegraph page.
zh_Hans: The title for the Telegraph page. zh_Hans: The title for the Telegraph page.
llm_description: # Parameter description for LLM (guiding Agent how to fill) llm_description: # Parameter description for LLM (guiding Agent how to fill)
The title of the post. Should be a concise and meaningful plain text string. The title of the post. Should be a concise and meaningful plain text string.
form: llm # Parameter form type ('llm' or 'form') form: llm # Parameter form type ('llm' or 'form')
- name: p_content - name: p_content
type: string type: string
required: true required: true
label: label:
en_US: Content (Markdown) en_US: Content (Markdown)
zh_Hans: Content (Markdown) zh_Hans: Content (Markdown)
human_description: human_description:
en_US: The main content for the Telegraph page, written in Markdown format. en_US: The main content for the Telegraph page, written in Markdown format.
zh_Hans: The main content for the Telegraph page, written in Markdown format. zh_Hans: The main content for the Telegraph page, written in Markdown format.
llm_description: # Emphasizing format requirements is important for LLM llm_description: # Emphasizing format requirements is important for LLM
The full content to be published on the Telegraph page. Must be provided in Markdown format. Ensure proper Markdown syntax for formatting like headings, lists, links, etc. The full content to be published on the Telegraph page. Must be provided in Markdown format. Ensure proper Markdown syntax for formatting like headings, lists, links, etc.
form: llm form: llm
extra: # Additional configuration extra: # Additional configuration
python: python:
source: tools/telegraph.py # Points to the Python file implementing the tool logic source: tools/telegraph.py # Points to the Python file implementing the tool logic
``` ```
- **Field Explanations:**
- **Field Explanations:** - `identity`: Basic information about the tool, `name` is a unique identifier.
- `identity`: Basic information about the tool, `name` is a unique identifier. - `description`: Divided into `human` (for users) and `llm` (for Agent). **`The llm description is crucial for the Agent to correctly understand and use the tool.`**
- `description`: Divided into `human` (for users) and `llm` (for Agent). **The `llm` description is crucial for the Agent to correctly understand and use the tool.** - `parameters`: Defines each input parameter.
- `parameters`: Defines each input parameter. - `name`: Internal name, must match the key in the Python code's `tool_parameters.get("...")`.
- `name`: Internal name, must match the key in the Python code's `tool_parameters.get("...")`. - `type`: Data type (such as `string`, `number`, `boolean`, etc.).
- `type`: Data type (such as `string`, `number`, `boolean`, etc.). - `required`: Whether it must be provided.
- `required`: Whether it must be provided. - `label`, `human_description`, `llm_description`: Similar to descriptions in `identity`, but for specific parameters. **`llm_description should clearly guide the LLM on how to generate or obtain the parameter value, including format requirements (such as Markdown here).`**
- `label`, `human_description`, `llm_description`: Similar to descriptions in `identity`, but for specific parameters. **`llm_description` should clearly guide the LLM on how to generate or obtain the parameter value, including format requirements (such as Markdown here).** - `form`: Defines how the parameter is presented and filled in Dify. `llm` indicates that the parameter value can be input by the user, passed through variables, or determined by the LLM in Agent mode; `form` typically indicates a configuration item that needs to be fixed by the user in the interface. For tool inputs, `llm` is more common.
- `form`: Defines how the parameter is presented and filled in Dify. `llm` indicates that the parameter value can be input by the user, passed through variables, or determined by the LLM in Agent mode; `form` typically indicates a configuration item that needs to be fixed by the user in the interface. For tool inputs, `llm` is more common. - `extra.python.source`: Specifies the path to the Python file implementing this tool's logic (relative to the project root directory).
- `extra.python.source`: Specifies the path to the Python file implementing this tool's logic (relative to the project root directory).
### 4.6 Implementing Provider Credential Validation (Optional but Recommended) ### 4.6 Implementing Provider Credential Validation (Optional but Recommended)
To ensure that the credentials provided by users are valid, we should implement validation logic. To ensure that the credentials provided by users are valid, we should implement validation logic.
1. **Edit the Provider Python File:** Open `telegraph/provider/telegraph.py`. 1. **Edit the Provider Python File:** Open `telegraph/provider/telegraph.py`.
2. **Implement the `_validate_credentials` Method:** Replace the file contents with: 2. **`Implement the _validate_credentials Method:`** Replace the file contents with:
```python ```python
from typing import Any from typing import Any
from dify_plugin import ToolProvider from dify_plugin import ToolProvider
from dify_plugin.errors.tool import ToolProviderCredentialValidationError from dify_plugin.errors.tool import ToolProviderCredentialValidationError
class TelegraphProvider(ToolProvider): class TelegraphProvider(ToolProvider):
def _validate_credentials(self, credentials: dict[str, Any]) -> None: def _validate_credentials(self, credentials: dict[str, Any]) -> None:
""" """
Verify that the provided Telegraph Access Token is valid. Verify that the provided Telegraph Access Token is valid.
Attempt to create a test page using the token. Attempt to create a test page using the token.
If validation fails, a ToolProviderCredentialValidationError exception should be thrown. If validation fails, a ToolProviderCredentialValidationError exception should be thrown.
""" """
access_token = credentials.get("telegraph_access_token") access_token = credentials.get("telegraph_access_token")
if not access_token: if not access_token:
raise ToolProviderCredentialValidationError("Telegraph Access Token cannot be empty.") raise ToolProviderCredentialValidationError("Telegraph Access Token cannot be empty.")
try: try:
# Try to perform a simple operation requiring credentials to validate # Try to perform a simple operation requiring credentials to validate
from ytelegraph import TelegraphAPI from ytelegraph import TelegraphAPI
ph = TelegraphAPI(access_token=access_token) ph = TelegraphAPI(access_token=access_token)
# Try to create a temporary, harmless page as a validation method # Try to create a temporary, harmless page as a validation method
# Note: A better validation method might be to call read-only methods like 'getAccountInfo' (if available) # Note: A better validation method might be to call read-only methods like 'getAccountInfo' (if available)
test_page = ph.create_page_md("Dify Validation Test", "This is a test page created by Dify plugin validation.") test_page = ph.create_page_md("Dify Validation Test", "This is a test page created by Dify plugin validation.")
# If needed, consider immediately editing or deleting this test page, but this would add complexity # If needed, consider immediately editing or deleting this test page, but this would add complexity
# print(f"Validation successful. Test page created: {test_page}") # print(f"Validation successful. Test page created: {test_page}")
except Exception as e: except Exception as e:
# If the API call fails, the credentials are likely invalid # If the API call fails, the credentials are likely invalid
raise ToolProviderCredentialValidationError(f"Telegraph credential validation failed: {e}") raise ToolProviderCredentialValidationError(f"Telegraph credential validation failed: {e}")
``` ```
- **Key Points:**
- **Key Points:** - Get the credentials from the `credentials` dictionary.
- Get the credentials from the `credentials` dictionary. - Perform an API call that requires the credential (preferably a read-only operation like getting account information; if not available, creating a harmless test page is also acceptable, but be aware of potential side effects).
- Perform an API call that requires the credential (preferably a read-only operation like getting account information; if not available, creating a harmless test page is also acceptable, but be aware of potential side effects). - If the API call succeeds, don't throw an exception, indicating validation passed.
- If the API call succeeds, don't throw an exception, indicating validation passed. - If the API call fails, catch the exception and throw a `ToolProviderCredentialValidationError`, including the original error message.
- If the API call fails, catch the exception and throw a `ToolProviderCredentialValidationError`, including the original error message.
## 5. Local Running and Debugging ## 5. Local Running and Debugging
Now you can run the plugin locally and debug it in Dify. Now you can run the plugin locally and debug it in Dify.
1. **Prepare the `.env` File:** 1. **`Prepare the .env File:`**
- Make sure you're still in the `telegraph` project directory.
- Copy the environment variable template file:
- Make sure you're still in the `telegraph` project directory. ```bash
- Copy the environment variable template file: cp .env.example .env
```
```bash - **`Edit the .env File:`** Open the `.env` file you just created and fill in your Dify environment information:
cp .env.example .env
```
- **Edit the `.env` File:** Open the `.env` file you just created and fill in your Dify environment information:
```dotenv
DIFY_API_HOST=https://your-dify-host.com # Replace with your Dify instance address (e.g., https://cloud.dify.ai)
DIFY_API_KEY=your-api-key # Replace with your Dify API key
```
- **Get Host and Key:** Log in to your Dify environment, click the "Plugins" icon in the top right corner, then click the debug icon (or something that looks like a bug). In the pop-up window, copy the "API Key" and "Host Address". _(Please refer to your local corresponding screenshot, which shows the interface for obtaining the key and host address)_
```dotenv
DIFY_API_HOST=https://your-dify-host.com # Replace with your Dify instance address (e.g., https://cloud.dify.ai)
DIFY_API_KEY=your-api-key # Replace with your Dify API key
```
- **Get Host and Key:** Log in to your Dify environment, click the "Plugins" icon in the top right corner, then click the debug icon (or something that looks like a bug). In the pop-up window, copy the "API Key" and "Host Address". _(Please refer to your local corresponding screenshot, which shows the interface for obtaining the key and host address)_
2. **Start the Local Plugin Service:** 2. **Start the Local Plugin Service:**
- Ensure your Python virtual environment is activated.
- In the `telegraph` directory, run the main program:
- Ensure your Python virtual environment is activated. ```bash
- In the `telegraph` directory, run the main program: python -m main
```
```bash - **Observe Terminal Output:** If everything is normal, you should see log information similar to the following, indicating that the plugin tool has been successfully loaded and connected to Dify:
python -m main
```
- **Observe Terminal Output:** If everything is normal, you should see log information similar to the following, indicating that the plugin tool has been successfully loaded and connected to Dify:
```json
{"event": "log", "data": {"level": "INFO", "message": "Installed tool: telegraph_publisher", "timestamp": 1678886400.123456}}
{"event": "log", "data": {"level": "INFO", "message": "Plugin daemon started, waiting for requests...", "timestamp": 1678886400.123457}}
```
```json
{"event": "log", "data": {"level": "INFO", "message": "Installed tool: telegraph_publisher", "timestamp": 1678886400.123456}}
{"event": "log", "data": {"level": "INFO", "message": "Plugin daemon started, waiting for requests...", "timestamp": 1678886400.123457}}
```
3. **View and Test in Dify:** 3. **View and Test in Dify:**
- **Refresh the Dify Page:** Return to your Dify environment (in the browser), refresh the plugin management page (typically `https://your-dify-host.com/plugins`).
- **Refresh the Dify Page:** Return to your Dify environment (in the browser), refresh the plugin management page (typically `https://your-dify-host.com/plugins`). - **Find the Plugin:** You should see a plugin named "Telegraph" (or the `label` you defined in the Provider YAML) in the list, possibly with a "Debugging" mark.
- **Find the Plugin:** You should see a plugin named "Telegraph" (or the `label` you defined in the Provider YAML) in the list, possibly with a "Debugging" mark. - **Add Credentials:** Click on the plugin, and you'll be prompted to enter the "Telegraph Access Token" you defined earlier in `provider/telegraph.yaml`. Enter a valid token and save. If your validation logic (`_validate_credentials`) is implemented correctly, validation will be performed here. _(Please refer to your local corresponding screenshot, which shows the plugin appearing in the list and requesting authorization)_
- **Add Credentials:** Click on the plugin, and you'll be prompted to enter the "Telegraph Access Token" you defined earlier in `provider/telegraph.yaml`. Enter a valid token and save. If your validation logic (`_validate_credentials`) is implemented correctly, validation will be performed here. _(Please refer to your local corresponding screenshot, which shows the plugin appearing in the list and requesting authorization)_ - **Use in Applications:** Now, you can add this tool node in Dify applications (such as Chatbot or Workflow) and try to call it! When you run the application and trigger the tool, the request will be forwarded to your local `python -m main` process for processing. You can see related log output in your local terminal for debugging.
- **Use in Applications:** Now, you can add this tool node in Dify applications (such as Chatbot or Workflow) and try to call it! When you run the application and trigger the tool, the request will be forwarded to your local `python -m main` process for processing. You can see related log output in your local terminal for debugging.
4. **Stop the Local Service:** Press `Ctrl + C` in the terminal to stop the local plugin service. 4. **Stop the Local Service:** Press `Ctrl + C` in the terminal to stop the local plugin service.
This run -> test -> stop -> modify code -> run again cycle is the main workflow for plugin development. This run -\> test -\> stop -\> modify code -\> run again cycle is the main workflow for plugin development.
## 6. Enhancing Plugin Metadata ## 6. Enhancing Plugin Metadata
To make the plugin more professional, discoverable, and understandable, we need to enhance some display information. To make the plugin more professional, discoverable, and understandable, we need to enhance some display information.
1. **Icon:** 1. **Icon:**
- Place an icon file representing your plugin in the `telegraph/_assets` directory (e.g., `icon.png`, `icon.svg`). Square, clear images are recommended. - Place an icon file representing your plugin in the `telegraph/_assets` directory (e.g., `icon.png`, `icon.svg`). Square, clear images are recommended.
2. **Provider Information (`provider/telegraph.yaml`):** 2. **`Provider Information (provider/telegraph.yaml):`**
- Ensure that the `label` (display name), `description` (function description), and `icon` (icon filename, such as `icon.png`) in the `identity` section are filled in and support multiple languages. This information is primarily displayed to users who _use_ the plugin in the Dify application orchestration interface.
- Ensure that the `label` (display name), `description` (function description), and `icon` (icon filename, such as `icon.png`) in the `identity` section are filled in and support multiple languages. This information is primarily displayed to users who _use_ the plugin in the Dify application orchestration interface. ```yaml
identity:
```yaml author: your-name
identity: name: telegraph # Internal name, keep unchanged
author: your-name label:
name: telegraph # Internal name, keep unchanged en_US: Telegraph
label: zh_Hans: Telegraph Publish Article
en_US: Telegraph description:
zh_Hans: Telegraph Publish Article en_US: A Telegraph plugin that allow you publish your content easily
description: zh_Hans: A Telegraph plugin that allows you to publish your content easily
en_US: A Telegraph plugin that allow you publish your content easily icon: icon.png # Reference to the icon filename in the _assets directory
zh_Hans: A Telegraph plugin that allows you to publish your content easily ```
icon: icon.png # Reference to the icon filename in the _assets directory 3. **`Plugin Manifest (manifest.yaml):`**
``` - Edit the `manifest.yaml` file in the project root directory. This is the "ID card" for the entire plugin, and its information will be displayed on the **plugin management page** and **Plugin Marketplace** in Dify.
- Be sure to update or confirm the following fields:
3. **Plugin Manifest (`manifest.yaml`):** - `label`: The **main display name** of the plugin (supports multiple languages).
- `description`: An **overall introduction** to the plugin's functionality (supports multiple languages), which should clearly summarize its core value. Note that the marketplace display may have length limitations.
- Edit the `manifest.yaml` file in the project root directory. This is the "ID card" for the entire plugin, and its information will be displayed on the **plugin management page** and **Plugin Marketplace** in Dify. - `icon`: The **main icon** of the plugin (directly enter the icon filename in the `_assets` directory, such as `icon.png`).
- Be sure to update or confirm the following fields: - `tags`: Add category tags to the plugin, which helps users filter in the marketplace. For optional values, please refer to Dify's enumerations or documentation (such as `media`, `tools`, `data-processing`, etc.). You can refer to the [ToolLabelEnum definition](https://github.com/langgenius/dify-plugin-sdks/blob/main/python/dify_plugin/entities/tool.py).
- `label`: The **main display name** of the plugin (supports multiple languages).
- `description`: An **overall introduction** to the plugin's functionality (supports multiple languages), which should clearly summarize its core value. Note that the marketplace display may have length limitations.
- `icon`: The **main icon** of the plugin (directly enter the icon filename in the `_assets` directory, such as `icon.png`).
- `tags`: Add category tags to the plugin, which helps users filter in the marketplace. For optional values, please refer to Dify's enumerations or documentation (such as `media`, `tools`, `data-processing`, etc.). You can refer to the [ToolLabelEnum definition](https://github.com/langgenius/dify-plugin-sdks/blob/main/python/dify_plugin/entities/tool.py).
```yaml
label:
en_US: Telegraph Publisher
zh_Hans: Telegraph Publishing Assistant
description:
en_US: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
zh_Hans: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
icon: icon.png
tags: ['media', 'content-creation'] # Example tags
# ... (Keep other fields like author, name unchanged)
```
```yaml
label:
en_US: Telegraph Publisher
zh_Hans: Telegraph Publishing Assistant
description:
en_US: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
zh_Hans: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
icon: icon.png
tags: ['media', 'content-creation'] # Example tags
# ... (Keep other fields like author, name unchanged)
```
4. **README and Privacy Policy:** 4. **README and Privacy Policy:**
- `README.md`: Edit the `README.md` file in the project root directory. It will serve as the detailed introduction page for the plugin on the **Marketplace**, and should include richer information such as detailed functionality, usage examples, configuration guide, frequently asked questions, etc. You can refer to the style of the [AWS plugin marketplace page](https://marketplace.dify.ai/plugins/langgenius/aws_tools). - `README.md`: Edit the `README.md` file in the project root directory. It will serve as the detailed introduction page for the plugin on the **Marketplace**, and should include richer information such as detailed functionality, usage examples, configuration guide, frequently asked questions, etc. You can refer to the style of the [AWS plugin marketplace page](https://marketplace.dify.ai/plugins/langgenius/aws_tools).
- `PRIVACY.md`: If you plan to publish the plugin to the official Marketplace, you need to provide a privacy policy document `PRIVACY.md`, describing how the plugin handles data.
<Info>
You can provide READMEs in multiple languages. For more information, see [Multilingual READMEs](/plugin-dev-en/0411-multilingual-readme).
</Info>
- `PRIVACY.md`: If you plan to publish the plugin to the official Marketplace, you need to provide a privacy policy document `PRIVACY.md`, describing how the plugin handles data.
## 7. Packaging the Plugin ## 7. Packaging the Plugin
@@ -514,18 +481,16 @@ When plugin development is complete and passes local testing, you can package it
1. **Return to Parent Directory:** Ensure your terminal's current path is at **one level above** the `telegraph` folder. 1. **Return to Parent Directory:** Ensure your terminal's current path is at **one level above** the `telegraph` folder.
```bash ```bash
cd .. cd ..
``` ```
2. **Execute the Packaging Command:** 2. **Execute the Packaging Command:**
```bash ```bash
./dify plugin package ./telegraph ./dify plugin package ./telegraph
``` ```
(Replace `./telegraph` with the actual path to your plugin project)
(Replace `./telegraph` with the actual path to your plugin project)
3. **Get the Package File:** After successful execution, a file named `telegraph.difypkg` (or `your_plugin_name.difypkg`) will be generated in the current directory. 3. **Get the Package File:** After successful execution, a file named `telegraph.difypkg` (or `your_plugin_name.difypkg`) will be generated in the current directory.
This `.difypkg` file is a complete plugin package. You can: This `.difypkg` file is a complete plugin package. You can:

View File

@@ -0,0 +1,51 @@
---
dimensions:
type:
primary: reference
detail: core
level: beginner
standard_title: Multilingual README
language: en
title: Multilingual README
description: This article introduces the file specifications for Dify plugins' multilingual READMEs and their display rule in Dify Marketplace.
---
You can create multilingual READMEs for your plugin, which will be displayed in [Dify Marketplace](https://marketplace.dify.ai) and other locations based on the user's preferred language.
### README **File Specifications**
| **Language** | Required | Filename | Path | **Description** |
| :------------------ | :------- | :-------------------------- | :----------------------------------------------------- | :--------------------------------------------------------------- |
| **English** | Yes | `README.md` | Plugin root directory | / |
| **Other Languages** | No | `README_<language_code>.md` | In the `readme` folder under the plugin root directory | Currently supports Japanese, Portuguese, and Simplified Chinese. |
Here's an example of the directory structure:
```bash
...
├── main.py
├── manifest.yaml
├── readme
│   ├── README_ja_JP.md
│   ├── README_pt_BR.md
│   └── README_zh_Hans.md
├── README.md
...
```
### How Multilingual READMEs are Displayed **in Marketplace**
When your plugin has a README in the user's preferred language, the plugin's detail page in Dify Marketplace will display that language version of the README.
![](/images/plugin_details_page_en.jpeg)
{/*
Contributing Section
DO NOT edit this section!
It will be automatically generated by the script.
*/}
---
[Edit this page](https://github.com/langgenius/dify-docs/edit/main/plugin-dev-en/0411-multilingual-readme.mdx) | [Report an issue](https://github.com/langgenius/dify-docs/issues/new?template=docs.yml)

View File

@@ -1,13 +1,9 @@
--- ---
dimensions: dimensions: "[object Object]"
type: standard_title: "Getting Started Dify Tool"
primary: implementation language: "ja"
detail: basic title: "Dify プラグイン開発Hello World ガイド"
level: beginner description: "このドキュメントでは、Telegraph公開プラグインの作成を例に、ゼロからのDifyプラグイン開発に関する詳細なチュートリアルを提供します。環境準備、プロジェクト初期化、仮想環境設定、プラグインコアロジック開発、ローカル実行デバッグ、プラグインメタ情報整備、パッケージ化と公開といった手順が含まれます。"
standard_title: Getting Started Dify Tool
language: ja
title: Dify プラグイン開発Hello World ガイド
description: このドキュメントでは、Telegraph公開プラグインの作成を例に、ゼロからのDifyプラグイン開発に関する詳細なチュートリアルを提供します。環境準備、プロジェクト初期化、仮想環境設定、プラグインコアロジック開発、ローカル実行デバッグ、プラグインメタ情報整備、パッケージ化と公開といった手順が含まれます。
--- ---
Dify プラグイン開発入門ガイドへようこそ!このチュートリアルは、基本的なプログラミング知識と Dify プラットフォームの使用経験があることを前提としています。このチュートリアルを完了すると、簡単な Dify プラグインを作成するための基本的な流れを習得し、Dify ユーザーからプラグイン貢献者へとステップアップできます。 Dify プラグイン開発入門ガイドへようこそ!このチュートリアルは、基本的なプログラミング知識と Dify プラットフォームの使用経験があることを前提としています。このチュートリアルを完了すると、簡単な Dify プラグインを作成するための基本的な流れを習得し、Dify ユーザーからプラグイン貢献者へとステップアップできます。
@@ -29,62 +25,57 @@ Dify プラグインの開発を始める前に、お使いの環境に以下の
> より詳細な開発環境準備ガイドについては、[開発ツールの初期化](/plugin-dev-ja/0221-initialize-development-tools) を参照してください。 > より詳細な開発環境準備ガイドについては、[開発ツールの初期化](/plugin-dev-ja/0221-initialize-development-tools) を参照してください。
1. **ダウンロード:** [Dify Plugin CLI Releases](https://github.com/langgenius/dify-plugin-daemon/releases) ページにアクセスします。お使いのオペレーティングシステムWindows, macOS Intel/ARM, Linuxに対応する最新バージョンのバイナリファイルをダウンロードします。 1. **ダウンロード:** [Dify Plugin CLI Releases](https://github.com/langgenius/dify-plugin-daemon/releases) ページにアクセスします。お使いのオペレーティングシステムWindows, macOS Intel/ARM, Linuxに対応する最新バージョンのバイナリファイルをダウンロードします。
2. **実行権限の設定 (macOS / Linux):** 2. **実行権限の設定 (macOS / Linux):**
- **以下の手順は macOS (Apple Silicon / M シリーズチップ) を例としています**。ダウンロードしたファイル名を `dify-plugin-darwin-arm64` と仮定します。ターミナルで、ファイルが存在するディレクトリに移動し、以下のコマンドを実行して実行権限を付与します:
- **以下の手順は macOS (Apple Silicon / M シリーズチップ) を例としています**。ダウンロードしたファイル名を `dify-plugin-darwin-arm64` と仮定します。ターミナルで、ファイルが存在するディレクトリに移動し、以下のコマンドを実行して実行権限を付与します: ```bash
chmod +x dify-plugin-darwin-arm64
```
- Linux ユーザーの場合は、対応する Linux バージョンのファイルをダウンロードし、同様の `chmod +x <downloaded_filename>` コマンドを実行してください。
- Windows ユーザーの場合は、`.exe` ファイルをダウンロードした後、通常は直接実行できます。
3. **インストールの確認:**
- ターミナルで、以下のコマンドを実行してツールが正常に動作するか確認します(`./dify-plugin-darwin-arm64` をダウンロードした実際のファイル名またはパスに置き換えてください):
```bash ```bash
chmod +x dify-plugin-darwin-arm64 ./dify-plugin-darwin-arm64 version
``` ```
- ターミナルにバージョン情報(例:`v0.0.1-beta.15`)が正常に出力されれば、インストールは成功です。
- Linux ユーザーの場合は、対応する Linux バージョンのファイルをダウンロードし、同様の `chmod +x <downloaded_filename>` コマンドを実行してください。
- Windows ユーザーの場合は、`.exe` ファイルをダウンロードした後、通常は直接実行できます。
3. **インストールの確認:**
- ターミナルで、以下のコマンドを実行してツールが正常に動作するか確認します(`./dify-plugin-darwin-arm64` をダウンロードした実際のファイル名またはパスに置き換えてください):
```bash
./dify-plugin-darwin-arm64 version
```
- ターミナルにバージョン情報(例:`v0.0.1-beta.15`)が正常に出力されれば、インストールは成功です。
> **ヒント (Tips):** > **ヒント (Tips):**
> >
> - **macOS のセキュリティ警告:** macOS で初めて実行する際に「Apple は検証できません」または「開けません」と表示された場合は、「システム設定」→「プライバシーとセキュリティ」→「セキュリティ」セクションに移動し、関連するメッセージを見つけて「それでも開く」または「許可」をクリックしてください。 > - **macOS のセキュリティ警告:** macOS で初めて実行する際に「Apple は検証できません」または「開けません」と表示された場合は、「システム設定」→「プライバシーとセキュリティ」→「セキュリティ」セクションに移動し、関連するメッセージを見つけて「それでも開く」または「許可」をクリックしてください。
> - **コマンドの簡略化:** ダウンロードしたバイナリファイル名を短い名前(例:`dify` や `dify-plugin`)に変更すると、後の使用が便利になります。例:`mv dify-plugin-darwin-arm64 dify`、その後は `./dify version` で使用できます。 > - **コマンドの簡略化:** ダウンロードしたバイナリファイル名を短い名前(例:`dify` や `dify-plugin`)に変更すると、後の使用が便利になります。例:`mv dify-plugin-darwin-arm64 dify`、その後は `./dify version` で使用できます。
> - **グローバルインストール(オプション):** システムのどのパスからでも直接コマンドを実行できるようにしたい場合(例:`./dify` ではなく直接 `dify` と入力する)、名前変更後のファイルをシステムの `PATH` 環境変数に含まれるディレクトリ(例:`/usr/local/bin` (macOS/Linux)に移動するか、Windows の環境変数に追加します。 > - **グローバルインストール(オプション):** システムのどのパスからでも直接コマンドを実行できるようにしたい場合(例:`./dify` ではなく直接 `dify` と入力する)、名前変更後のファイルをシステムの `PATH` 環境変数に含まれるディレクトリ(例:`/usr/local/bin` (macOS/Linux)に移動するか、Windows の環境変数に追加します。
> - 例 (macOS/Linux): `sudo mv dify /usr/local/bin/` > - 例 (macOS/Linux): `sudo mv dify /usr/local/bin/`
> - 設定完了後、ターミナルで直接 `dify version` と入力すると、バージョン番号が正常に出力されるはずです。 > - 設定完了後、ターミナルで直接 `dify version` と入力すると、バージョン番号が正常に出力されるはずです。
**便宜上、このドキュメントでは以降、Dify プラグイン開発 CLI コマンドの例として `./dify` を使用します。ご自身の実際の状況に合わせてコマンドを置き換えてください。** **`便宜上、このドキュメントでは以降、Dify プラグイン開発 CLI コマンドの例として ./dify を使用します。ご自身の実際の状況に合わせてコマンドを置き換えてください。`**
## 2. プラグインプロジェクトの初期化 ## 2. プラグインプロジェクトの初期化
それでは、CLI ツールを使用して新しいプラグインプロジェクトを作成しましょう。 それでは、CLI ツールを使用して新しいプラグインプロジェクトを作成しましょう。
1. ターミナルを開き、初期化コマンドを実行します: 1. ターミナルを開き、初期化コマンドを実行します:
```bash ```bash
./dify plugin init ./dify plugin init
``` ```
2. プロンプトに従って、プラグインの基本情報を順に入力します:
- **Plugin name:** プラグインの一意の識別子。例:`telegraph`
- _制約: 長さ 1128 文字、小文字の英数字、ハイフン(-)、アンダースコア(_)のみ使用可能。\_
- **Author:** プラグイン作者の識別子。例:`your-name`
- _制約: 長さ 164 文字、小文字の英数字、ハイフン(-)、アンダースコア(_)のみ使用可能。\_
- **Description:** プラグイン機能の簡単な説明。例:`A Telegraph plugin that allows you to publish your content easily`
- **Enable multilingual README:** このオプションを有効にすると、プラグインの多言語READMEファイルを生成できます。チェックを入れると、下の `Languages to generate` セクションで、事前にREADMEファイルを生成したい言語を選択できます。
3. **開発言語の選択:** `Select language` と表示されたら、`python` を選択してください。
4. **プラグインタイプの選択:** `Select plugin type` と表示されたら、このチュートリアルでは `tool` を選択してください。
5. **追加機能の選択:** 次に、プロバイダー認証、永続ストレージなどの追加機能が必要かどうか尋ねられます。この簡単な Hello World プラグインでは、これらは一時的に不要なので、成功メッセージが表示されるまで **Enter キー** を押してすべてのオプションをスキップできます。
6. **作成成功の確認:** ターミナルに以下のような情報が出力されたら、プラグインプロジェクトは正常に作成されています:
2. プロンプトに従って、プラグインの基本情報を順に入力します: ```bash
- **Plugin name:** プラグインの一意の識別子。例:`telegraph` [INFO] plugin telegraph created successfully, you can refer to `telegraph/GUIDE.md` for more information about how to develop it
- _制約: 長さ 1128 文字、小文字の英数字、ハイフン(-)、アンダースコア(_)のみ使用可能。_ ```
- **Author:** プラグイン作者の識別子。例:`your-name`
- _制約: 長さ 164 文字、小文字の英数字、ハイフン(-)、アンダースコア(_)のみ使用可能。_
- **Description:** プラグイン機能の簡単な説明。例:`A Telegraph plugin that allows you to publish your content easily`
3. **開発言語の選択:** `Select language` と表示されたら、`python` を選択してください。
4. **プラグインタイプの選択:** `Select plugin type` と表示されたら、このチュートリアルでは `tool` を選択してください。
5. **追加機能の選択:** 次に、プロバイダー認証、永続ストレージなどの追加機能が必要かどうか尋ねられます。この簡単な Hello World プラグインでは、これらは一時的に不要なので、成功メッセージが表示されるまで **Enter キー** を押してすべてのオプションをスキップできます。
6. **作成成功の確認:** ターミナルに以下のような情報が出力されたら、プラグインプロジェクトは正常に作成されています:
```bash
[INFO] plugin telegraph created successfully, you can refer to `telegraph/GUIDE.md` for more information about how to develop it
```
これで、現在のディレクトリに `telegraph`(または指定したプラグイン名)という名前の新しいフォルダが表示され、これがプラグインプロジェクトになります。 これで、現在のディレクトリに `telegraph`(または指定したプラグイン名)という名前の新しいフォルダが表示され、これがプラグインプロジェクトになります。
@@ -96,39 +87,33 @@ Dify プラグインの開発を始める前に、お使いの環境に以下の
これは**推奨される一般的な**方法で、特定の IDE に依存しません: これは**推奨される一般的な**方法で、特定の IDE に依存しません:
1. **プロジェクトディレクトリへの移動:** 1. **プロジェクトディレクトリへの移動:**
```bash ```bash
cd telegraph cd telegraph
``` ```
2. **仮想環境の作成:** (名前を `venv` にすることを推奨します)
2. **仮想環境の作成:** (名前を `venv` にすることを推奨します) ```bash
python -m venv venv
```
3. **仮想環境のアクティベート:**
- **macOS / Linux:**
```bash ```bash
python -m venv venv source venv/bin/activate
``` ```
- **Windows (cmd.exe):**
3. **仮想環境のアクティベート:** ```bash
venv\Scripts\activate.bat
```
- **Windows (PowerShell):**
- **macOS / Linux:** ```bash
venv\Scripts\Activate.ps1
```bash ```
source venv/bin/activate - アクティベートに成功すると、通常、ターミナルのプロンプトの前に `(venv)` と表示されます。
```
- **Windows (cmd.exe):**
```bash
venv\Scripts\activate.bat
```
- **Windows (PowerShell):**
```bash
venv\Scripts\Activate.ps1
```
- アクティベートに成功すると、通常、ターミナルのプロンプトの前に `(venv)` と表示されます。
### 3.2 基本的な依存関係のインストール ### 3.2 基本的な依存関係のインストール
@@ -142,16 +127,16 @@ pip install -r requirements.txt
VSCode をコードエディタとして使用している場合、その統合機能を利用して Python 環境を管理できます: VSCode をコードエディタとして使用している場合、その統合機能を利用して Python 環境を管理できます:
1. **プロジェクトフォルダを開く:** 作成した `telegraph` フォルダを VSCode で開きます。 1. **プロジェクトフォルダを開く:** 作成した `telegraph` フォルダを VSCode で開きます。
2. **Python インタープリタの選択:** 2. **Python インタープリタの選択:**
- コマンドパレットを開きます (macOS: `Cmd+Shift+P`, Windows/Linux: `Ctrl+Shift+P`)。 - コマンドパレットを開きます (macOS: `Cmd+Shift+P`, Windows/Linux: `Ctrl+Shift+P`)。
- `Python: Select Interpreter` と入力して選択します。 - `Python: Select Interpreter` と入力して選択します。
- 表示されたリストから、先ほど作成した仮想環境内の Python インタープリタを選択します(通常、パスには `.venv/bin/python` または `venv\Scripts\python.exe` が含まれます)。リストに自動的に表示されない場合は、`Enter interpreter path...` を選択して手動で検索できます。 - 表示されたリストから、先ほど作成した仮想環境内の Python インタープリタを選択します(通常、パスには `.venv/bin/python` または `venv\Scripts\python.exe` が含まれます)。リストに自動的に表示されない場合は、`Enter interpreter path...` を選択して手動で検索できます。
- _(ローカルの対応するスクリーンショットを参照してください。インタープリタ選択画面が表示されています)_ - _(ローカルの対応するスクリーンショットを参照してください。インタープリタ選択画面が表示されています)_
3. **依存関係のインストール (VSCode が提示した場合):** VSCode が `requirements.txt` ファイルを検出し、その中の依存関係をインストールするよう促すことがあります。プロンプトが表示されたら、インストールを確認してください。 3. **依存関係のインストール (VSCode が提示した場合):** VSCode が `requirements.txt` ファイルを検出し、その中の依存関係をインストールするよう促すことがあります。プロンプトが表示されたら、インストールを確認してください。
- _(ローカルの対応するスクリーンショットを参照してください。依存関係のインストール確認画面が表示されています)_ - _(ローカルの対応するスクリーンショットを参照してください。依存関係のインストール確認画面が表示されています)_
**以降のすべての `pip install` コマンドと `python -m main` の実行操作は、アクティベートされた仮想環境で実行してください。** **``以降のすべての pip install コマンドと python -m main の実行操作は、アクティベートされた仮想環境で実行してください。``**
## 4. プラグインコアロジックの開発 ## 4. プラグインコアロジックの開発
@@ -181,363 +166,347 @@ print(ph_link)
### 4.2 プロジェクト依存関係の追加と設定 ### 4.2 プロジェクト依存関係の追加と設定
1. **依存ライブラリのインストール:** 仮想環境がアクティベートされていることを確認し、ターミナルで以下を実行します: 1. **依存ライブラリのインストール:** 仮想環境がアクティベートされていることを確認し、ターミナルで以下を実行します:
```bash ```bash
pip install your-telegraph pip install your-telegraph
``` ```
2. **`requirements.txt の更新:`** プロジェクトルートディレクトリにある `telegraph/requirements.txt` ファイルを開き、`dify_plugin` の下に、先ほどインストールしたライブラリ名を一行追加します:
2. **`requirements.txt` の更新:** プロジェクトルートディレクトリにある `telegraph/requirements.txt` ファイルを開き、`dify_plugin` の下に、先ほどインストールしたライブラリ名を一行追加します: ```plaintext
dify_plugin
your-telegraph
```
```plaintext これにより、他の開発者やデプロイ環境がすべての必要な依存関係を簡単にインストールできるようになります。
dify_plugin
your-telegraph
```
これにより、他の開発者やデプロイ環境がすべての必要な依存関係を簡単にインストールできるようになります。
### 4.3 プロバイダー認証情報の設定 ### 4.3 プロバイダー認証情報の設定
この例では `telegraph_access_token` が必要です。プロバイダー設定でこの認証情報を定義し、ユーザーがプラグインを使用する際に入力できるようにする必要があります。プロバイダー設定の詳細については、[一般仕様定義](/plugin-dev-ja/0411-general-specifications) を参照してください。 この例では `telegraph_access_token` が必要です。プロバイダー設定でこの認証情報を定義し、ユーザーがプラグインを使用する際に入力できるようにする必要があります。プロバイダー設定の詳細については、[一般仕様定義](/plugin-dev-ja/0411-general-specifications) を参照してください。
1. **プロバイダー YAML の編集:** `telegraph/provider/telegraph.yaml` ファイルを開きます。 1. **プロバイダー YAML の編集:** `telegraph/provider/telegraph.yaml` ファイルを開きます。
2. **`credentials_for_provider` の追加:** ファイルの末尾(または適切な場所)に以下の内容を追加します: 2. **`credentials_for_provider の追加:`** ファイルの末尾(または適切な場所)に以下の内容を追加します:
```yaml ```yaml
# ... (ファイルに既にある identity, name, label, description, icon などは変更しません) ... # ... (ファイルに既にある identity, name, label, description, icon などは変更しません) ...
credentials_for_provider: credentials_for_provider:
telegraph_access_token: # これは認証情報の内部名で、Python コードで使用されます telegraph_access_token: # これは認証情報の内部名で、Python コードで使用されます
type: secret-input # 入力タイプはパスワードフィールド type: secret-input # 入力タイプはパスワードフィールド
required: true # この認証情報は必須です required: true # この認証情報は必須です
label: # Dify UI に表示されるラベル (多言語対応) label: # Dify UI に表示されるラベル (多言語対応)
en_US: Telegraph Access Token en_US: Telegraph Access Token
ja: Telegraph アクセストークン ja: Telegraph アクセストークン
# ... (その他の言語) # ... (その他の言語)
placeholder: # 入力フィールドのプレースホルダーテキスト (多言語対応) placeholder: # 入力フィールドのプレースホルダーテキスト (多言語対応)
en_US: Enter your Telegraph access token en_US: Enter your Telegraph access token
ja: Telegraph アクセストークンを入力してください ja: Telegraph アクセストークンを入力してください
# ... (その他の言語) # ... (その他の言語)
help: # ヘルプヒント情報 (多言語対応) help: # ヘルプヒント情報 (多言語対応)
en_US: How to get your Telegraph access token en_US: How to get your Telegraph access token
ja: Telegraph アクセストークンの取得方法 ja: Telegraph アクセストークンの取得方法
# ... (その他の言語) # ... (その他の言語)
url: https://telegra.ph/api#createAccount # ヘルプヒントをクリックしたときにジャンプする URL url: https://telegra.ph/api#createAccount # ヘルプヒントをクリックしたときにジャンプする URL
``` ```
- **フィールドの説明:**
- **フィールドの説明:** - `telegraph_access_token`: 認証情報の一意の識別子。コード内では `self.runtime.credentials["telegraph_access_token"]` を介してユーザーが入力した値にアクセスします。
- `telegraph_access_token`: 認証情報の一意の識別子。コード内では `self.runtime.credentials["telegraph_access_token"]` を介してユーザーが入力した値にアクセスします。 - `type: secret-input`: Dify UI 上でパスワード入力フィールドとして表示されます。
- `type: secret-input`: Dify UI 上でパスワード入力フィールドとして表示されます。 - `required: true`: ユーザーがこのプラグイン提供のツールを使用するには、この認証情報を入力する必要があります。
- `required: true`: ユーザーがこのプラグイン提供のツールを使用するには、この認証情報を入力する必要があります。 - `label`, `placeholder`, `help`: 多言語対応の UI テキストを提供します。
- `label`, `placeholder`, `help`: 多言語対応の UI テキストを提供します。 - `url`: (オプション) 認証情報取得のためのヘルプリンクを提供します。
- `url`: (オプション) 認証情報取得のためのヘルプリンクを提供します。
### 4.4 ツール (Tool) ロジックの実装 ### 4.4 ツール (Tool) ロジックの実装
それでは、実際に公開操作を実行するツールのコードを記述しましょう。 それでは、実際に公開操作を実行するツールのコードを記述しましょう。
1. **ツール Python ファイルの編集:** `telegraph/tools/telegraph.py` を開きます。 1. **ツール Python ファイルの編集:** `telegraph/tools/telegraph.py` を開きます。
2. **`_invoke` メソッドの実装:** ファイルの内容を以下のコードに置き換えます: 2. **`_invoke メソッドの実装:`** ファイルの内容を以下のコードに置き換えます:
```python ```python
from collections.abc import Generator from collections.abc import Generator
from typing import Any from typing import Any
from ytelegraph import TelegraphAPI # 使用するライブラリをインポート from ytelegraph import TelegraphAPI # 使用するライブラリをインポート
from dify_plugin import Tool from dify_plugin import Tool
from dify_plugin.entities.tool import ToolInvokeMessage from dify_plugin.entities.tool import ToolInvokeMessage
class TelegraphTool(Tool): class TelegraphTool(Tool):
""" """
シンプルな Telegraph 公開ツールです。 シンプルな Telegraph 公開ツールです。
""" """
def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]:
""" """
入力されたタイトルと内容に基づいて、新しい Telegraph ページを作成します。 入力されたタイトルと内容に基づいて、新しい Telegraph ページを作成します。
Args: Args:
tool_parameters: ツールの入力パラメータを含む辞書: tool_parameters: ツールの入力パラメータを含む辞書:
- p_title (str): Telegraph ページのタイトル。 - p_title (str): Telegraph ページのタイトル。
- p_content (str): 公開する Markdown 形式の内容。 - p_content (str): 公開する Markdown 形式の内容。
Yields: Yields:
ToolInvokeMessage: 正常に作成された Telegraph ページの URL を含むメッセージ。 ToolInvokeMessage: 正常に作成された Telegraph ページの URL を含むメッセージ。
Raises: Raises:
Exception: ページの作成に失敗した場合、エラー情報を含む例外をスローします。 Exception: ページの作成に失敗した場合、エラー情報を含む例外をスローします。
""" """
# 1. ランタイムから認証情報を取得 # 1. ランタイムから認証情報を取得
try: try:
access_token = self.runtime.credentials["telegraph_access_token"] access_token = self.runtime.credentials["telegraph_access_token"]
except KeyError: except KeyError:
raise Exception("Telegraph アクセストークンが設定されていないか無効です。プラグイン設定で提供してください。") raise Exception("Telegraph アクセストークンが設定されていないか無効です。プラグイン設定で提供してください。")
# 2. ツールの入力パラメータを取得 # 2. ツールの入力パラメータを取得
title = tool_parameters.get("p_title", "Untitled") # .get を使用してデフォルト値を提供 title = tool_parameters.get("p_title", "Untitled") # .get を使用してデフォルト値を提供
content = tool_parameters.get("p_content", "") content = tool_parameters.get("p_content", "")
if not content: if not content:
raise Exception("公開するコンテンツは空にできません。") raise Exception("公開するコンテンツは空にできません。")
# 3. ライブラリを呼び出して操作を実行 # 3. ライブラリを呼び出して操作を実行
try: try:
telegraph = TelegraphAPI(access_token) # Telegraph API を初期化 telegraph = TelegraphAPI(access_token) # Telegraph API を初期化
ph_link = telegraph.create_page_md(title, content) # ページを作成 ph_link = telegraph.create_page_md(title, content) # ページを作成
except Exception as e: except Exception as e:
# ライブラリ呼び出しに失敗した場合、例外をスロー # ライブラリ呼び出しに失敗した場合、例外をスロー
raise Exception(f"Telegraph API の呼び出しに失敗しました: {e}") raise Exception(f"Telegraph API の呼び出しに失敗しました: {e}")
# 4. 結果を返す # 4. 結果を返す
# create_link_message を使用してリンクを含む出力メッセージを生成 # create_link_message を使用してリンクを含む出力メッセージを生成
yield self.create_link_message(ph_link) yield self.create_link_message(ph_link)
``` ```
- **重要なポイント:**
- **重要なポイント:** - `self.runtime.credentials` から認証情報を取得します。
- `self.runtime.credentials` から認証情報を取得します。 - `tool_parameters` からツールの入力パラメータを取得します(パラメータ名は次のステップの YAML で定義します)。`.get()` を使用する方が堅牢な方法です。
- `tool_parameters` からツールの入力パラメータを取得します(パラメータ名は次のステップの YAML で定義します)。`.get()` を使用する方が堅牢な方法です。 - `ytelegraph` ライブラリを呼び出して実際の操作を実行します。
- `ytelegraph` ライブラリを呼び出して実際の操作を実行します。 - `try...except` を使用して起こりうるエラーをキャッチし、例外をスローします。
- `try...except` を使用して起こりうるエラーをキャッチし、例外をスローします。 - `yield self.create_link_message(url)` を使用して URL を含む結果を Dify に返します。
- `yield self.create_link_message(url)` を使用して URL を含む結果を Dify に返します。
### 4.5 ツール (Tool) パラメータの設定 ### 4.5 ツール (Tool) パラメータの設定
このツールがどの入力パラメータを受け取るかを Dify に伝える必要があります。 このツールがどの入力パラメータを受け取るかを Dify に伝える必要があります。
1. **ツール YAML ファイルの編集:** `telegraph/tools/telegraph.yaml` を開きます。 1. **ツール YAML ファイルの編集:** `telegraph/tools/telegraph.yaml` を開きます。
2. **パラメータの定義:** ファイルの内容を以下のように置き換えるか変更します: 2. **パラメータの定義:** ファイルの内容を以下のように置き換えるか変更します:
```yaml ```yaml
identity: identity:
name: telegraph_publisher # ツールの一意の内部名 name: telegraph_publisher # ツールの一意の内部名
author: your-name author: your-name
label: # Dify UI に表示されるツール名 (多言語対応) label: # Dify UI に表示されるツール名 (多言語対応)
en_US: Publish to Telegraph en_US: Publish to Telegraph
ja: Telegraph に公開 ja: Telegraph に公開
# ... (その他の言語) # ... (その他の言語)
description: description:
human: # 人間ユーザー向けのツールの説明 (多言語対応) human: # 人間ユーザー向けのツールの説明 (多言語対応)
en_US: Publish content to Telegraph as a new page. en_US: Publish content to Telegraph as a new page.
ja: コンテンツを新しいページとして Telegraph に公開します。 ja: コンテンツを新しいページとして Telegraph に公開します。
# ... (その他の言語) # ... (その他の言語)
llm: # LLM 向けのツールの説明 (Agent モード用) llm: # LLM 向けのツールの説明 (Agent モード用)
A tool that takes a title and markdown content, then publishes it as a new page on Telegraph, returning the URL of the published page. Use this when the user wants to publish formatted text content publicly via Telegraph. A tool that takes a title and markdown content, then publishes it as a new page on Telegraph, returning the URL of the published page. Use this when the user wants to publish formatted text content publicly via Telegraph.
parameters: # ツールの入力パラメータリストを定義 parameters: # ツールの入力パラメータリストを定義
- name: p_title # パラメータの内部名、Python コードのキーに対応 - name: p_title # パラメータの内部名、Python コードのキーに対応
type: string # パラメータタイプ type: string # パラメータタイプ
required: true # 必須かどうか required: true # 必須かどうか
label: # Dify UI に表示されるパラメータラベル (多言語対応) label: # Dify UI に表示されるパラメータラベル (多言語対応)
en_US: Post Title en_US: Post Title
ja: 記事タイトル ja: 記事タイトル
human_description: # 人間ユーザー向けのパラメータの説明 (多言語対応) human_description: # 人間ユーザー向けのパラメータの説明 (多言語対応)
en_US: The title for the Telegraph page. en_US: The title for the Telegraph page.
ja: Telegraph ページのタイトル。 ja: Telegraph ページのタイトル。
llm_description: # LLM 向けのパラメータの説明 (Agent がどのように入力するかを指示) llm_description: # LLM 向けのパラメータの説明 (Agent がどのように入力するかを指示)
The title of the post. Should be a concise and meaningful plain text string. The title of the post. Should be a concise and meaningful plain text string.
form: llm # パラメータフォームタイプ ('llm' または 'form') form: llm # パラメータフォームタイプ ('llm' または 'form')
- name: p_content - name: p_content
type: string type: string
required: true required: true
label: label:
en_US: Content (Markdown) en_US: Content (Markdown)
ja: 内容 (Markdown) ja: 内容 (Markdown)
human_description: human_description:
en_US: The main content for the Telegraph page, written in Markdown format. en_US: The main content for the Telegraph page, written in Markdown format.
ja: Telegraph ページの主な内容、Markdown 形式で記述してください。 ja: Telegraph ページの主な内容、Markdown 形式で記述してください。
llm_description: # フォーマット要件を強調することは LLM にとって重要 llm_description: # フォーマット要件を強調することは LLM にとって重要
The full content to be published on the Telegraph page. Must be provided in Markdown format. Ensure proper Markdown syntax for formatting like headings, lists, links, etc. The full content to be published on the Telegraph page. Must be provided in Markdown format. Ensure proper Markdown syntax for formatting like headings, lists, links, etc.
form: llm form: llm
extra: # 追加設定 extra: # 追加設定
python: python:
source: tools/telegraph.py # このツールのロジックを実装する Python ファイルを指す source: tools/telegraph.py # このツールのロジックを実装する Python ファイルを指す
``` ```
- **フィールドの説明:**
- **フィールドの説明:** - `identity`: ツールの基本情報、`name` は一意の識別子です。
- `identity`: ツールの基本情報、`name` は一意の識別子です。 - `description`: `human` (ユーザー向け) と `llm` (Agent 向け) に分かれます。**`llm の説明は、Agent がツールを正しく理解して使用できるかどうかにおいて非常に重要です。`**
- `description`: `human` (ユーザー向け) と `llm` (Agent 向け) に分かれます。**`llm` の説明は、Agent がツールを正しく理解して使用できるかどうかにおいて非常に重要です。** - `parameters`: 各入力パラメータを定義します。
- `parameters`: 各入力パラメータを定義します。 - `name`: 内部名、Python コードの `tool_parameters.get("...")` のキーと一致する必要があります。
- `name`: 内部名、Python コードの `tool_parameters.get("...")` のキーと一致する必要があります - `type`: データ型 (例: `string`, `number`, `boolean` など)
- `type`: データ型 (例: `string`, `number`, `boolean` など) - `required`: 提供が必須かどうか
- `required`: 提供が必須かどうか。 - `label`, `human_description`, `llm_description`: `identity` の説明と同様ですが、特定のパラメータに対するものです。**`llm_description は、LLM がそのパラメータの値をどのように生成または取得するか(ここでの Markdown のようなフォーマット要件を含む)を明確に指示する必要があります。`**
- `label`, `human_description`, `llm_description`: `identity` の説明と同様ですが、特定のパラメータに対するものです。**`llm_description` は、LLM がそのパラメータ値をどのように生成または取得するか(ここでの Markdown のようなフォーマット要件を含む)を明確に指示する必要があります。** - `form`: パラメータが Dify でどのように表示され、入力されるかを定義します。`llm` は、そのパラメータ値をユーザーが入力したり、変数を介して渡したり、Agent モードで LLM が自律的に決定したりできることを示します。`form` は通常、ユーザーが UI 上で固定的に入力する必要がある設定項目を示します。ツール入力の場合、`llm` の方が一般的です。
- `form`: パラメータが Dify でどのように表示され、入力されるかを定義します。`llm` は、そのパラメータ値をユーザーが入力したり、変数を介して渡したり、Agent モードで LLM が自律的に決定したりできることを示します。`form` は通常、ユーザーが UI 上で固定的に入力する必要がある設定項目を示します。ツール入力の場合、`llm` の方が一般的です。 - `extra.python.source`: このツールのロジックを実装する Python ファイルのパス(プロジェクトルートディレクトリからの相対パス)を示します。
- `extra.python.source`: このツールのロジックを実装する Python ファイルのパス(プロジェクトルートディレクトリからの相対パス)を示します。
### 4.6 プロバイダー認証情報の検証実装(オプションだが推奨) ### 4.6 プロバイダー認証情報の検証実装(オプションだが推奨)
ユーザーが提供した認証情報が有効であることを保証するために、検証ロジックを実装すべきです。 ユーザーが提供した認証情報が有効であることを保証するために、検証ロジックを実装すべきです。
1. **プロバイダー Python ファイルの編集:** `telegraph/provider/telegraph.py` を開きます。 1. **プロバイダー Python ファイルの編集:** `telegraph/provider/telegraph.py` を開きます。
2. **`_validate_credentials` メソッドの実装:** ファイルの内容を以下に置き換えます: 2. **`_validate_credentials メソッドの実装:`** ファイルの内容を以下に置き換えます:
```python ```python
from typing import Any from typing import Any
from dify_plugin import ToolProvider from dify_plugin import ToolProvider
from dify_plugin.errors.tool import ToolProviderCredentialValidationError from dify_plugin.errors.tool import ToolProviderCredentialValidationError
class TelegraphProvider(ToolProvider): class TelegraphProvider(ToolProvider):
def _validate_credentials(self, credentials: dict[str, Any]) -> None: def _validate_credentials(self, credentials: dict[str, Any]) -> None:
""" """
提供された Telegraph アクセストークンが有効かどうかを検証します。 提供された Telegraph アクセストークンが有効かどうかを検証します。
このトークンを使用してテストページを作成しようとします。 このトークンを使用してテストページを作成しようとします。
検証に失敗した場合、ToolProviderCredentialValidationError 例外をスローする必要があります。 検証に失敗した場合、ToolProviderCredentialValidationError 例外をスローする必要があります。
""" """
access_token = credentials.get("telegraph_access_token") access_token = credentials.get("telegraph_access_token")
if not access_token: if not access_token:
raise ToolProviderCredentialValidationError("Telegraph アクセストークンは空にできません。") raise ToolProviderCredentialValidationError("Telegraph アクセストークンは空にできません。")
try: try:
# 認証情報が必要な簡単な操作を実行して検証を試みる # 認証情報が必要な簡単な操作を実行して検証を試みる
from ytelegraph import TelegraphAPI from ytelegraph import TelegraphAPI
ph = TelegraphAPI(access_token=access_token) ph = TelegraphAPI(access_token=access_token)
# 検証手段として、一時的で無害なページを作成してみる # 検証手段として、一時的で無害なページを作成してみる
# 注意: より良い検証方法は、API の 'getAccountInfo' などの読み取り専用メソッドを呼び出すことです(存在する場合) # 注意: より良い検証方法は、API の 'getAccountInfo' などの読み取り専用メソッドを呼び出すことです(存在する場合)
test_page = ph.create_page_md("Dify Validation Test", "This is a test page created by Dify plugin validation.") test_page = ph.create_page_md("Dify Validation Test", "This is a test page created by Dify plugin validation.")
# 必要であれば、このテストページをすぐに編集または削除することを検討できますが、複雑さが増します # 必要であれば、このテストページをすぐに編集または削除することを検討できますが、複雑さが増します
# print(f"Validation successful. Test page created: {test_page}") # print(f"Validation successful. Test page created: {test_page}")
except Exception as e: except Exception as e:
# API 呼び出しに失敗した場合、認証情報が無効である可能性が高い # API 呼び出しに失敗した場合、認証情報が無効である可能性が高い
raise ToolProviderCredentialValidationError(f"Telegraph 認証情報の検証に失敗しました: {e}") raise ToolProviderCredentialValidationError(f"Telegraph 認証情報の検証に失敗しました: {e}")
``` ```
- **重要なポイント:**
- **重要なポイント:** - `credentials` 辞書から認証情報を取得します。
- `credentials` 辞書から認証情報を取得します - その認証情報が必要な API 呼び出しを実行します(アカウント情報の取得など、読み取り専用操作が望ましいです。もしなければ、無害なテストページを作成することもできますが、副作用の可能性に注意してください)
- その認証情報が必要な API 呼び出しを実行します(アカウント情報の取得など、読み取り専用操作が望ましいです。もしなければ、無害なテストページを作成することもできますが、副作用の可能性に注意してください) - API 呼び出しが成功した場合、例外はスローされず、検証が通過したことを示します
- API 呼び出しが成功した場合、例外はスローされず、検証が通過したことを示します。 - API 呼び出しが失敗した場合、例外をキャッチして `ToolProviderCredentialValidationError` をスローし、元のエラーメッセージを含めます。
- API 呼び出しが失敗した場合、例外をキャッチして `ToolProviderCredentialValidationError` をスローし、元のエラーメッセージを含めます。
## 5. ローカルでの実行とデバッグ ## 5. ローカルでの実行とデバッグ
これでプラグインをローカルで実行し、Dify でデバッグできます。 これでプラグインをローカルで実行し、Dify でデバッグできます。
1. **`.env` ファイルの準備:** 1. **`.env ファイルの準備:`**
- `telegraph` プロジェクトディレクトリにいることを確認してください。
- 環境変数テンプレートファイルをコピーします:
- `telegraph` プロジェクトディレクトリにいることを確認してください。 ```bash
- 環境変数テンプレートファイルをコピーします: cp .env.example .env
```
- **`.env ファイルの編集:`** 作成したばかりの `.env` ファイルを開き、Dify 環境情報を入力します:
```bash ```dotenv
cp .env.example .env DIFY_API_HOST=https://your-dify-host.com # ご自身の Dify インスタンスアドレスに置き換えてください (例: https://cloud.dify.ai)
``` DIFY_API_KEY=your-api-key # ご自身の Dify API キーに置き換えてください
```
- **ホストとキーの取得:** Dify 環境にログインし、右上の「プラグイン」アイコンをクリックし、次にデバッグアイコンまたは虫のような形をクリックします。ポップアップウィンドウで、「API キー (Key)」と「ホストアドレス (Host)」をコピーします。 _(ローカルの対応するスクリーンショットを参照してください。キーとホストアドレスの取得画面が表示されています)_
2. **ローカルプラグインサービスの起動:**
- Python 仮想環境がアクティベートされていることを確認してください。
- `telegraph` ディレクトリで、メインプログラムを実行します:
- **`.env` ファイルの編集:** 作成したばかりの `.env` ファイルを開き、Dify 環境情報を入力します: ```bash
python -m main
```
- **ターミナル出力の確認:** すべてが正常であれば、以下のようなログ情報が表示され、プラグインツールが正常にロードされ、Dify に接続されたことを示します:
```dotenv ```json
DIFY_API_HOST=https://your-dify-host.com # ご自身の Dify インスタンスアドレスに置き換えてください (例: https://cloud.dify.ai) {"event": "log", "data": {"level": "INFO", "message": "Installed tool: telegraph_publisher", "timestamp": 1678886400.123456}}
DIFY_API_KEY=your-api-key # ご自身の Dify API キーに置き換えてください {"event": "log", "data": {"level": "INFO", "message": "Plugin daemon started, waiting for requests...", "timestamp": 1678886400.123457}}
``` ```
3. **Dify での確認とテスト:**
- **Dify ページを更新:** Dify 環境(ブラウザ)に戻り、プラグイン管理ページ (通常は `https://your-dify-host.com/plugins`) を更新します。
- **プラグインを検索:** リストに "Telegraph" (またはプロバイダー YAML で定義した `label`) という名前のプラグインが表示され、「デバッグ中」のマークが付いている場合があります。
- **認証情報を追加:** そのプラグインをクリックすると、以前 `provider/telegraph.yaml` で定義した "Telegraph Access Token" の入力を求められます。有効なトークンを入力して保存します。検証ロジック (`_validate_credentials`) が正しく実装されていれば、ここで検証が行われます。 _(ローカルの対応するスクリーンショットを参照してください。プラグインがリストに表示され、認証を要求する画面が表示されています)_
- **アプリケーションで使用:** これで、Dify のアプリケーションChatbot や Workflow など)にこのツールノードを追加し、呼び出すことができます!アプリケーションで実行してツールをトリガーすると、リクエストはローカルで実行されている `python -m main` プロセスに転送されて処理されます。ローカルターミナルで関連するログ出力を確認し、デバッグできます。
4. **ローカルサービスの停止:** ターミナルで `Ctrl + C` を押すと、ローカルプラグインサービスを停止できます。
- **ホストとキーの取得:** Dify 環境にログインし、右上の「プラグイン」アイコンをクリックし、次にデバッグアイコンまたは虫のような形をクリックします。ポップアップウィンドウで、「API キー (Key)」と「ホストアドレス (Host)」をコピーします。 _(ローカルの対応するスクリーンショットを参照してください。キーとホストアドレスの取得画面が表示されています)_ この実行 -\> テスト -\> 停止 -\> コード修正 -\> 再実行のサイクルが、プラグイン開発の主なフローです。
2. **ローカルプラグインサービスの起動:**
- Python 仮想環境がアクティベートされていることを確認してください。
- `telegraph` ディレクトリで、メインプログラムを実行します:
```bash
python -m main
```
- **ターミナル出力の確認:** すべてが正常であれば、以下のようなログ情報が表示され、プラグインツールが正常にロードされ、Dify に接続されたことを示します:
```json
{"event": "log", "data": {"level": "INFO", "message": "Installed tool: telegraph_publisher", "timestamp": 1678886400.123456}}
{"event": "log", "data": {"level": "INFO", "message": "Plugin daemon started, waiting for requests...", "timestamp": 1678886400.123457}}
```
3. **Dify での確認とテスト:**
- **Dify ページを更新:** Dify 環境(ブラウザ)に戻り、プラグイン管理ページ (通常は `https://your-dify-host.com/plugins`) を更新します。
- **プラグインを検索:** リストに "Telegraph" (またはプロバイダー YAML で定義した `label`) という名前のプラグインが表示され、「デバッグ中」のマークが付いている場合があります。
- **認証情報を追加:** そのプラグインをクリックすると、以前 `provider/telegraph.yaml` で定義した "Telegraph Access Token" の入力を求められます。有効なトークンを入力して保存します。検証ロジック (`_validate_credentials`) が正しく実装されていれば、ここで検証が行われます。 _(ローカルの対応するスクリーンショットを参照してください。プラグインがリストに表示され、認証を要求する画面が表示されています)_
- **アプリケーションで使用:** これで、Dify のアプリケーションChatbot や Workflow など)にこのツールノードを追加し、呼び出すことができます!アプリケーションで実行してツールをトリガーすると、リクエストはローカルで実行されている `python -m main` プロセスに転送されて処理されます。ローカルターミナルで関連するログ出力を確認し、デバッグできます。
4. **ローカルサービスの停止:** ターミナルで `Ctrl + C` を押すと、ローカルプラグインサービスを停止できます。
この実行 -> テスト -> 停止 -> コード修正 -> 再実行のサイクルが、プラグイン開発の主なフローです。
## 6. プラグインメタ情報の整備 ## 6. プラグインメタ情報の整備
プラグインをより専門的に、発見・理解しやすくするために、いくつかの表示情報を整備する必要があります。 プラグインをより専門的に、発見・理解しやすくするために、いくつかの表示情報を整備する必要があります。
1. **アイコン (Icon):** 1. **アイコン (Icon):**
- `telegraph/_assets` ディレクトリに、プラグインを表すアイコンファイル(例:`icon.png`, `icon.svg`)を配置します。正方形で鮮明な画像を推奨します。 - `telegraph/_assets` ディレクトリに、プラグインを表すアイコンファイル(例:`icon.png`, `icon.svg`)を配置します。正方形で鮮明な画像を推奨します。
2. **プロバイダー情報 (`provider/telegraph.yaml`):** 2. **`プロバイダー情報 (provider/telegraph.yaml):`**
- `identity` セクションの `label` (表示名)、`description` (機能説明)、`icon` (アイコンファイル名、例:`icon.png` を記入) が入力され、多言語対応していることを確認します。この情報は主に Dify アプリケーションオーケストレーションインターフェースでプラグインを\_使用する\_ユーザーに表示されます。
- `identity` セクションの `label` (表示名)、`description` (機能説明)、`icon` (アイコンファイル名、例:`icon.png` を記入) が入力され、多言語対応していることを確認します。この情報は主に Dify アプリケーションオーケストレーションインターフェースでプラグインを_使用する_ユーザーに表示されます。 ```yaml
identity:
author: your-name
name: telegraph # 内部名、変更なし
label:
en_US: Telegraph
ja: Telegraph 記事公開
description:
en_US: A Telegraph plugin that allow you publish your content easily
ja: コンテンツを簡単に公開できるTelegraphプラグイン
icon: icon.png # _assets ディレクトリ内のアイコンファイル名を参照
```
3. **`プラグインマニフェスト (manifest.yaml):`**
- プロジェクトルートディレクトリにある `telegraph/manifest.yaml` ファイルを編集します。これはプラグイン全体の「身分証明書」のようなもので、その情報は Dify の**プラグイン管理ページ**や**プラグインマーケットプレイス (Marketplace)** に表示されます。
- 以下のフィールドを必ず更新または確認してください:
- `label`: プラグインの**主要な表示名** (多言語対応)。
- `description`: プラグイン機能の**全体的な概要** (多言語対応)。その核心的な価値を明確に要約する必要があります。マーケットプレイスでの表示には文字数制限があることに注意してください。
- `icon`: プラグインの**メインアイコン** (`_assets` ディレクトリ内のアイコンファイル名を直接記入、例:`icon.png`)。
- `tags`: プラグインに分類タグを追加し、ユーザーがマーケットプレイスでフィルタリングするのに役立ちます。選択可能な値は、Dify が提供する列挙型またはドキュメントの説明を参照してください (例: `media`, `tools`, `data-processing` など)。[ToolLabelEnum 定義](https://github.com/langgenius/dify-plugin-sdks/blob/main/python/dify_plugin/entities/tool.py) を参照してください。
```yaml ```yaml
identity: label:
author: your-name en_US: Telegraph Publisher
name: telegraph # 内部名、変更なし ja: Telegraph 公開アシスタント
label: description:
en_US: Telegraph en_US: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
ja: Telegraph 記事公開 ja: Dify アプリケーションから直接 Telegraph ページにコンテンツを簡単に公開できます。Markdown 形式をサポートしています。
description: icon: icon.png
en_US: A Telegraph plugin that allow you publish your content easily tags: ['media', 'content-creation'] # タグの例
ja: コンテンツを簡単に公開できるTelegraphプラグイン # ... (author, name など他のフィールドは変更なし)
icon: icon.png # _assets ディレクトリ内のアイコンファイル名を参照 ```
``` 4. **README とプライバシーポリシー:**
- `README.md`: プロジェクトルートディレクトリの `README.md` ファイルを編集します。これはプラグインの **Marketplace** 上の詳細な紹介ページとなり、機能詳細、使用例、設定ガイド、よくある質問など、より豊富な情報を含めるべきです。[AWS プラグインマーケットプレイスページ](https://marketplace.dify.ai/plugins/langgenius/aws_tools) のスタイルを参考にしてください。
3. **プラグインマニフェスト (`manifest.yaml`):** <Info>
多言語でREADMEを提供することができます。詳細については、[多言語 README](/plugin-dev-ja/0411-multilingual-readme) をご覧ください。
- プロジェクトルートディレクトリにある `telegraph/manifest.yaml` ファイルを編集します。これはプラグイン全体の「身分証明書」のようなもので、その情報は Dify の**プラグイン管理ページ**や**プラグインマーケットプレイス (Marketplace)** に表示されます。 </Info>
- 以下のフィールドを必ず更新または確認してください: - `PRIVACY.md`: プラグインを公式 Marketplace に公開する予定がある場合は、プラグインがデータをどのように処理するかを説明するプライバシーポリシー説明ファイル `PRIVACY.md` を提供する必要があります。
- `label`: プラグインの**主要な表示名** (多言語対応)。
- `description`: プラグイン機能の**全体的な概要** (多言語対応)。その核心的な価値を明確に要約する必要があります。マーケットプレイスでの表示には文字数制限があることに注意してください。
- `icon`: プラグインの**メインアイコン** (`_assets` ディレクトリ内のアイコンファイル名を直接記入、例:`icon.png`)。
- `tags`: プラグインに分類タグを追加し、ユーザーがマーケットプレイスでフィルタリングするのに役立ちます。選択可能な値は、Dify が提供する列挙型またはドキュメントの説明を参照してください (例: `media`, `tools`, `data-processing` など)。[ToolLabelEnum 定義](https://github.com/langgenius/dify-plugin-sdks/blob/main/python/dify_plugin/entities/tool.py) を参照してください。
```yaml
label:
en_US: Telegraph Publisher
ja: Telegraph 公開アシスタント
description:
en_US: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
ja: Dify アプリケーションから直接 Telegraph ページにコンテンツを簡単に公開できます。Markdown 形式をサポートしています。
icon: icon.png
tags: ['media', 'content-creation'] # タグの例
# ... (author, name など他のフィールドは変更なし)
```
4. **README とプライバシーポリシー:**
- `README.md`: プロジェクトルートディレクトリの `README.md` ファイルを編集します。これはプラグインの **Marketplace** 上の詳細な紹介ページとなり、機能詳細、使用例、設定ガイド、よくある質問など、より豊富な情報を含めるべきです。[AWS プラグインマーケットプレイスページ](https://marketplace.dify.ai/plugins/langgenius/aws_tools) のスタイルを参考にしてください。
- `PRIVACY.md`: プラグインを公式 Marketplace に公開する予定がある場合は、プラグインがデータをどのように処理するかを説明するプライバシーポリシー説明ファイル `PRIVACY.md` を提供する必要があります。
## 7. プラグインのパッケージ化 ## 7. プラグインのパッケージ化
プラグイン開発が完了し、ローカルテストに合格したら、配布またはインストール用に `.difypkg` ファイルにパッケージ化できます。プラグインのパッケージ化と公開の詳細については、[公開概要](/plugin-dev-ja/0321-release-overview) を参照してください。 プラグイン開発が完了し、ローカルテストに合格したら、配布またはインストール用に `.difypkg` ファイルにパッケージ化できます。プラグインのパッケージ化と公開の詳細については、[公開概要](/plugin-dev-ja/0321-release-overview) を参照してください。
1. **親ディレクトリに戻る:** ターミナルの現在のパスが `telegraph` フォルダの**一つ上**であることを確認してください。 1. **親ディレクトリに戻る:** ターミナルの現在のパスが `telegraph` フォルダの**一つ上**であることを確認してください。
```bash ```bash
cd .. cd ..
``` ```
2. **パッケージ化コマンドの実行:**
2. **パッケージ化コマンドの実行:** ```bash
./dify plugin package ./telegraph
```
```bash `./telegraph` をプラグインプロジェクトの実際のパスに置き換えてください)
./dify plugin package ./telegraph 3. **パッケージファイルの取得:** コマンドが正常に実行されると、現在のディレクトリに `telegraph.difypkg` (または `あなたのプラグイン名.difypkg`) という名前のファイルが生成されます。
```
`./telegraph` をプラグインプロジェクトの実際のパスに置き換えてください)
3. **パッケージファイルの取得:** コマンドが正常に実行されると、現在のディレクトリに `telegraph.difypkg` (または `あなたのプラグイン名.difypkg`) という名前のファイルが生成されます。
この `.difypkg` ファイルは完全なプラグインパッケージです。これを以下のことができます: この `.difypkg` ファイルは完全なプラグインパッケージです。これを以下のことができます:
- Dify のプラグイン管理ページで手動で**アップロードしてインストール**する。 - Dify のプラグイン管理ページで手動で**アップロードしてインストール**する。
- 他の人に**共有**してインストールしてもらう。 - 他の人に**共有**してインストールしてもらう。
- Dify の規範と手順に従って、**公式プラグインマーケットプレイス (Marketplace)** に公開し、すべての Dify ユーザーがあなたのプラグインを発見して使用できるようにする。具体的な公開手順については、[Dify マーケットプレイスへの公開](/plugin-dev-ja/0322-release-to-dify-marketplace) を参照してください。 - Dify の規範と手順に従って、**公式プラグインマーケットプレイス (Marketplace)** に公開し、すべての Dify ユーザーがあなたのプラグインを発見して使用できるようにする。具体的な公開手順については、[Dify マーケットプレイスへの公開](/plugin-dev-ja/0322-release-to-dify-marketplace) を参照してください。
おめでとうございます! これで最初の Dify プラグインの開発、デバッグ、整備、パッケージ化の全プロセスを完了しました。この基礎を元に、より複雑で強力なプラグイン機能を探求できます。 おめでとうございます! これで最初の Dify プラグインの開発、デバッグ、整備、パッケージ化の全プロセスを完了しました。この基礎を元に、より複雑で強力なプラグイン機能を探求できます。
## 次の学習ステップ ## 次の学習ステップ
- [リモートでプラグインをデバッグする](/plugin-dev-ja/0411-remote-debug-a-plugin) - より高度なプラグインデバッグテクニックを学ぶ - [リモートでプラグインをデバッグする](/plugin-dev-ja/0411-remote-debug-a-plugin) - より高度なプラグインデバッグテクニックを学ぶ
- [永続ストレージ](/plugin-dev-ja/0411-persistent-storage-kv) - プラグインでデータストレージを使用する方法を学ぶ - [永続ストレージ](/plugin-dev-ja/0411-persistent-storage-kv) - プラグインでデータストレージを使用する方法を学ぶ
- [Slack ボットプラグイン開発例](/plugin-dev-ja/0432-develop-a-slack-bot-plugin) - より複雑なプラグイン開発事例を見る - [Slack ボットプラグイン開発例](/plugin-dev-ja/0432-develop-a-slack-bot-plugin) - より複雑なプラグイン開発事例を見る
- [ツールプラグイン](/plugin-dev-ja/0222-tool-plugin) - ツールプラグインの高度な機能を探る - [ツールプラグイン](/plugin-dev-ja/0222-tool-plugin) - ツールプラグインの高度な機能を探る
{/* {/*
Contributing Section Contributing Section

View File

@@ -0,0 +1,51 @@
---
dimensions:
type:
primary: reference
detail: core
level: beginner
standard_title: Multilingual README
language: ja
title: 多言語 README
description: この記事では、プラグインの多言語 README のファイル仕様と、Dify Marketplace での表示ルールについて説明します。
---
Dify プラグインは多言語 README に対応しており、[Dify Marketplace](https://marketplace.dify.ai/?language=ja-Jp) などでユーザーの優先言語に合わせて対応する README を表示します。
### README ファイルの仕様
| **言語** | **必須** | **ファイル名** | **保存パス** | **説明** |
| :------ | :------ | :------------------ | :-------------------------------- | :------------------------------ |
| 英语 | はい | `README.md` | プラグインのルートディレクトリ直下 | / |
| その他の言語 | いいえ | `README_<言語識別子>.md` | プラグインのルートディレクトリ直下の `readme` フォルダ内 | 現在、日本語、ポルトガル語、簡体字中国語をサポートしています。 |
ディレクトリ構造の例は以下の通りです。
```bash
...
├── main.py
├── manifest.yaml
├── readme
│   ├── README_ja_JP.md
│   ├── README_pt_BR.md
│   └── README_zh_Hans.md
├── README.md
...
```
### Marketplace での表示ルール
プラグインがユーザーの使用言語に対応した README ファイルを提供している場合、Dify Marketplace のプラグイン詳細ページには、その言語版の README が表示されます。
![](/images/plugin_details_page_jp.jpeg)
{/*
Contributing Section
DO NOT edit this section!
It will be automatically generated by the script.
*/}
---
[このページを編集する](https://github.com/langgenius/dify-docs/edit/main/plugin-dev-ja/0411-multilingual-readme.mdx) | [問題を報告する](https://github.com/langgenius/dify-docs/issues/new?template=docs.yml)

View File

@@ -1,13 +1,9 @@
--- ---
dimensions: dimensions: "[object Object]"
type: standard_title: "Getting Started Dify Tool"
primary: implementation language: "zh"
detail: basic title: "Dify 插件开发Hello World 指南"
level: beginner description: "本文档提供了从零开始Dify插件开发的详细教程以创建Telegraph发布插件为例涉及环境准备、项目初始化、虚拟环境配置、插件核心逻辑开发、本地运行调试、插件元信息完善以及打包发布等环节。"
standard_title: Getting Started Dify Tool
language: zh
title: Dify 插件开发Hello World 指南
description: 本文档提供了从零开始Dify插件开发的详细教程以创建Telegraph发布插件为例涉及环境准备、项目初始化、虚拟环境配置、插件核心逻辑开发、本地运行调试、插件元信息完善以及打包发布等环节。
--- ---
欢迎阅读 Dify 插件开发的入门指南!本教程假设您具备基本的编程背景知识,并有使用 Dify 平台的经验。完成本教程后,您将掌握创建简单 Dify 插件的基础流程,从 Dify 用户迈向插件贡献者。 欢迎阅读 Dify 插件开发的入门指南!本教程假设您具备基本的编程背景知识,并有使用 Dify 平台的经验。完成本教程后,您将掌握创建简单 Dify 插件的基础流程,从 Dify 用户迈向插件贡献者。
@@ -31,35 +27,30 @@ description: 本文档提供了从零开始Dify插件开发的详细教程
1. **下载:** 访问 [Dify Plugin CLI Releases](https://github.com/langgenius/dify-plugin-daemon/releases) 页面。根据您的操作系统Windows, macOS Intel/ARM, Linux下载对应的最新版本二进制文件。 1. **下载:** 访问 [Dify Plugin CLI Releases](https://github.com/langgenius/dify-plugin-daemon/releases) 页面。根据您的操作系统Windows, macOS Intel/ARM, Linux下载对应的最新版本二进制文件。
2. **设置执行权限 (macOS / Linux):** 2. **设置执行权限 (macOS / Linux):**
- **以下步骤以 macOS (Apple Silicon / M 系列芯片) 为例**,假设下载的文件名为 `dify-plugin-darwin-arm64`。在终端中,进入文件所在目录,并执行以下命令赋予其执行权限:
- **以下步骤以 macOS (Apple Silicon / M 系列芯片) 为例**,假设下载的文件名为 `dify-plugin-darwin-arm64`。在终端中,进入文件所在目录,并执行以下命令赋予其执行权限: ```bash
chmod +x dify-plugin-darwin-arm64
```bash ```
chmod +x dify-plugin-darwin-arm64 - 对于 Linux 用户,请下载对应的 Linux 版本文件并执行类似 `chmod +x <downloaded_filename>` 的命令。
``` - 对于 Windows 用户,下载 `.exe` 文件后通常可直接运行。
- 对于 Linux 用户,请下载对应的 Linux 版本文件并执行类似 `chmod +x <downloaded_filename>` 的命令。
- 对于 Windows 用户,下载 `.exe` 文件后通常可直接运行。
3. **验证安装:** 3. **验证安装:**
- 在终端中,执行以下命令检查工具是否能正常运行(请将 `./dify-plugin-darwin-arm64` 替换为您下载的实际文件名或路径):
- 在终端中,执行以下命令检查工具是否能正常运行(请将 `./dify-plugin-darwin-arm64` 替换为您下载的实际文件名或路径): ```bash
./dify-plugin-darwin-arm64 version
```bash ```
./dify-plugin-darwin-arm64 version - 如果终端成功输出了版本号信息(例如 `v0.0.1-beta.15`),则说明安装成功。
```
- 如果终端成功输出了版本号信息(例如 `v0.0.1-beta.15`),则说明安装成功。
> **提示 (Tips):** > **提示 (Tips):**
> >
> - **macOS 安全提示:** 若在 macOS 上首次运行时提示“Apple 无法验证”或“无法打开”,请前往“系统设置”→“隐私与安全性”→“安全性”部分,找到相关提示并点击“仍要打开”或“允许”。 > - **macOS 安全提示:** 若在 macOS 上首次运行时提示“Apple 无法验证”或“无法打开”,请前往“系统设置”→“隐私与安全性”→“安全性”部分,找到相关提示并点击“仍要打开”或“允许”。
> - **简化命令:** 您可以将下载的二进制文件重命名为一个更短的名称(例如 `dify` 或 `dify-plugin`),以便后续使用。示例:`mv dify-plugin-darwin-arm64 dify`,之后即可使用 `./dify version`。 > - **简化命令:** 您可以将下载的二进制文件重命名为一个更短的名称(例如 `dify` 或 `dify-plugin`),以便后续使用。示例:`mv dify-plugin-darwin-arm64 dify`,之后即可使用 `./dify version`。
> - **全局安装 (可选):** 如果希望在系统的任何路径下都能直接运行该命令(例如,直接输入 `dify` 而不是 `./dify`),可以将重命名后的文件移动到系统的 `PATH` 环境变量包含的目录中,例如 `/usr/local/bin` (macOS/Linux) 或添加到 Windows 的环境变量中。 > - **全局安装 (可选):** 如果希望在系统的任何路径下都能直接运行该命令(例如,直接输入 `dify` 而不是 `./dify`),可以将重命名后的文件移动到系统的 `PATH` 环境变量包含的目录中,例如 `/usr/local/bin` (macOS/Linux) 或添加到 Windows 的环境变量中。
> - 例如 (macOS/Linux): `sudo mv dify /usr/local/bin/` > - 例如 (macOS/Linux): `sudo mv dify /usr/local/bin/`
> - 配置完成后,直接在终端输入 `dify version` 应能成功输出版本号。 > - 配置完成后,直接在终端输入 `dify version` 应能成功输出版本号。
**为方便起见,本文后续将使用 `./dify` 作为 Dify 插件开发脚手架命令的示例。请根据您的实际情况替换为对应的命令。** **`为方便起见,本文后续将使用 ./dify 作为 Dify 插件开发脚手架命令的示例。请根据您的实际情况替换为对应的命令。`**
## 2. 初始化插件项目 ## 2. 初始化插件项目
@@ -67,24 +58,24 @@ description: 本文档提供了从零开始Dify插件开发的详细教程
1. 打开终端,执行初始化命令: 1. 打开终端,执行初始化命令:
```bash ```bash
./dify plugin init ./dify plugin init
``` ```
2. 根据提示依次输入插件的基本信息: 2. 根据提示依次输入插件的基本信息:
- **Plugin name:** 插件的唯一标识符。例如:`telegraph` - **Plugin name:** 插件的唯一标识符。例如:`telegraph`
- _约束: 长度 1-128 字符,只能包含小写字母、数字、连字符(-)和下划线(\_)。_ - _约束: 长度 1-128 字符,只能包含小写字母、数字、连字符(-)和下划线(\_)。_
- **Author:** 插件作者的标识符。例如:`your-name` - **Author:** 插件作者的标识符。例如:`your-name`
- _约束: 长度 1-64 字符,只能包含小写字母、数字、连字符(-)和下划线(\_)。_ - _约束: 长度 1-64 字符,只能包含小写字母、数字、连字符(-)和下划线(\_)。_
- **Description:** 对插件功能的简短描述。例如:`A Telegraph plugin that allows you to publish your content easily` - **Description:** 对插件功能的简短描述。例如:`A Telegraph plugin that allows you to publish your content easily`
- **Enable multilingual README:** 插件多语言 README 选项。勾选后,可在下方的 `Languages to generate` 中选择需要预置 README 文件的语种。
3. **选择开发语言:** 当提示 `Select language` 时,请选择 `python`。 3. **选择开发语言:** 当提示 `Select language` 时,请选择 `python`。
4. **选择插件类型:** 当提示 `Select plugin type` 时,对于本教程,请选择 `tool`。 4. **选择插件类型:** 当提示 `Select plugin type` 时,对于本教程,请选择 `tool`。
5. **选择附加功能:** 接下来会提示是否需要包含 Provider 验证、持久存储等附加功能。对于这个简单的 Hello World 插件,我们暂时不需要这些,可以直接按 **回车键** 跳过所有选项,直到看到成功信息。 5. **选择附加功能:** 接下来会提示是否需要包含 Provider 验证、持久存储等附加功能。对于这个简单的 Hello World 插件,我们暂时不需要这些,可以直接按 **回车键** 跳过所有选项,直到看到成功信息。
6. **确认创建成功:** 当终端输出类似以下信息时,表示插件项目已成功创建: 6. **确认创建成功:** 当终端输出类似以下信息时,表示插件项目已成功创建:
```bash ```bash
[INFO] plugin telegraph created successfully, you can refer to `telegraph/GUIDE.md` for more information about how to develop it [INFO] plugin telegraph created successfully, you can refer to `telegraph/GUIDE.md` for more information about how to develop it
``` ```
现在,您的当前目录下应该出现了一个名为 `telegraph` (或您指定的插件名) 的新文件夹,这就是您的插件项目。 现在,您的当前目录下应该出现了一个名为 `telegraph` (或您指定的插件名) 的新文件夹,这就是您的插件项目。
@@ -98,37 +89,31 @@ description: 本文档提供了从零开始Dify插件开发的详细教程
1. **进入项目目录:** 1. **进入项目目录:**
```bash ```bash
cd telegraph cd telegraph
``` ```
2. **创建虚拟环境:** (建议命名为 `venv`) 2. **创建虚拟环境:** (建议命名为 `venv`)
```bash ```bash
python -m venv venv python -m venv venv
``` ```
3. **激活虚拟环境:** 3. **激活虚拟环境:**
- **macOS / Linux:**
- **macOS / Linux:** ```bash
source venv/bin/activate
```
- **Windows (cmd.exe):**
```bash ```bash
source venv/bin/activate venv\Scripts\activate.bat
``` ```
- **Windows (PowerShell):**
- **Windows (cmd.exe):** ```bash
venv\Scripts\Activate.ps1
```bash ```
venv\Scripts\activate.bat - 激活成功后,您的终端提示符前通常会显示 `(venv)` 字样。
```
- **Windows (PowerShell):**
```bash
venv\Scripts\Activate.ps1
```
- 激活成功后,您的终端提示符前通常会显示 `(venv)` 字样。
### 3.2 安装基础依赖 ### 3.2 安装基础依赖
@@ -144,14 +129,14 @@ pip install -r requirements.txt
1. **打开项目文件夹:** 使用 VSCode 打开刚刚创建的 `telegraph` 文件夹。 1. **打开项目文件夹:** 使用 VSCode 打开刚刚创建的 `telegraph` 文件夹。
2. **选择 Python 解释器:** 2. **选择 Python 解释器:**
- 打开命令面板 (macOS: `Cmd+Shift+P`, Windows/Linux: `Ctrl+Shift+P`)。 - 打开命令面板 (macOS: `Cmd+Shift+P`, Windows/Linux: `Ctrl+Shift+P`)。
- 输入并选择 `Python: Select Interpreter`。 - 输入并选择 `Python: Select Interpreter`。
- 在弹出的列表中,选择您刚刚创建的虚拟环境中的 Python 解释器(通常路径包含 `.venv/bin/python` 或 `venv\Scripts\python.exe`)。如果列表没有自动显示,您可以选择 `Enter interpreter path...` 手动查找。 - 在弹出的列表中,选择您刚刚创建的虚拟环境中的 Python 解释器(通常路径包含 `.venv/bin/python` 或 `venv\Scripts\python.exe`)。如果列表没有自动显示,您可以选择 `Enter interpreter path...` 手动查找。
- _(请参考您本地对应的截图 ,它展示了选择解释器的界面)_ - _(请参考您本地对应的截图 ,它展示了选择解释器的界面)_
3. **安装依赖 (若 VSCode 提示):** VSCode 可能会检测到 `requirements.txt` 文件并提示您安装其中的依赖项。如果出现提示,请确认安装。 3. **安装依赖 (若 VSCode 提示):** VSCode 可能会检测到 `requirements.txt` 文件并提示您安装其中的依赖项。如果出现提示,请确认安装。
- _(请参考您本地对应的截图 ,它展示了确认安装依赖的界面)_ - _(请参考您本地对应的截图 ,它展示了确认安装依赖的界面)_
**请确保后续的所有 `pip install` 命令和运行 `python -m main` 的操作都在已激活的虚拟环境中执行。** **`请确保后续的所有 pip install 命令和运行 python -m main 的操作都在已激活的虚拟环境中执行。`**
## 4. 开发插件核心逻辑 ## 4. 开发插件核心逻辑
@@ -183,122 +168,119 @@ print(ph_link)
1. **安装依赖库:** 确保您的虚拟环境已激活,然后在终端中执行: 1. **安装依赖库:** 确保您的虚拟环境已激活,然后在终端中执行:
```bash ```bash
pip install your-telegraph pip install your-telegraph
``` ```
2. **`更新 requirements.txt:`** 打开项目根目录下的 `telegraph/requirements.txt` 文件,在 `dify_plugin` 下面添加一行,写入刚刚安装的库名:
2. **更新 `requirements.txt`:** 打开项目根目录下的 `telegraph/requirements.txt` 文件,在 `dify_plugin` 下面添加一行,写入刚刚安装的库名: ```plaintext
dify_plugin
your-telegraph
```
```plaintext 这样做可以确保其他开发者或部署环境能够方便地安装所有必需的依赖。
dify_plugin
your-telegraph
```
这样做可以确保其他开发者或部署环境能够方便地安装所有必需的依赖。
### 4.3 配置 Provider 凭证 ### 4.3 配置 Provider 凭证
我们的示例需要 `telegraph_access_token`。我们需要在 Provider 配置中定义这个凭证,以便用户在使用插件时可以输入。关于 Provider 配置的更多信息,请参考[一般规范定义](/plugin-dev-zh/0411-general-specifications)。 我们的示例需要 `telegraph_access_token`。我们需要在 Provider 配置中定义这个凭证,以便用户在使用插件时可以输入。关于 Provider 配置的更多信息,请参考[一般规范定义](/plugin-dev-zh/0411-general-specifications)。
1. **编辑 Provider YAML:** 打开 `telegraph/provider/telegraph.yaml` 文件。 1. **编辑 Provider YAML:** 打开 `telegraph/provider/telegraph.yaml` 文件。
2. **添加 `credentials_for_provider`:** 在文件末尾(或适当位置)添加以下内容: 2. **`添加 credentials_for_provider:`** 在文件末尾(或适当位置)添加以下内容:
```yaml ```yaml
# ... (文件可能已有的 identity, name, label, description, icon 等保持不变) ... # ... (文件可能已有的 identity, name, label, description, icon 等保持不变) ...
credentials_for_provider: credentials_for_provider:
telegraph_access_token: # 这是凭证的内部名称,将在 Python 代码中使用 telegraph_access_token: # 这是凭证的内部名称,将在 Python 代码中使用
type: secret-input # 输入类型为密码框 type: secret-input # 输入类型为密码框
required: true # 此凭证是必需的 required: true # 此凭证是必需的
label: # 在 Dify UI 中显示的标签 (支持多语言) label: # 在 Dify UI 中显示的标签 (支持多语言)
en_US: Telegraph Access Token en_US: Telegraph Access Token
zh_Hans: Telegraph 访问令牌 zh_Hans: Telegraph 访问令牌
# ... (其他语言) # ... (其他语言)
placeholder: # 输入框的提示文字 (支持多语言) placeholder: # 输入框的提示文字 (支持多语言)
en_US: Enter your Telegraph access token en_US: Enter your Telegraph access token
zh_Hans: 请输入您的 Telegraph 访问令牌 zh_Hans: 请输入您的 Telegraph 访问令牌
# ... (其他语言) # ... (其他语言)
help: # 帮助提示信息 (支持多语言) help: # 帮助提示信息 (支持多语言)
en_US: How to get your Telegraph access token en_US: How to get your Telegraph access token
zh_Hans: 如何获取 Telegraph 访问令牌 zh_Hans: 如何获取 Telegraph 访问令牌
# ... (其他语言) # ... (其他语言)
url: https://telegra.ph/api#createAccount # 点击帮助提示时跳转的 URL url: https://telegra.ph/api#createAccount # 点击帮助提示时跳转的 URL
``` ```
- **字段解释:**
- **字段解释:** - `telegraph_access_token`: 凭证的唯一标识符,代码中通过 `self.runtime.credentials["telegraph_access_token"]` 来访问用户输入的值。
- `telegraph_access_token`: 凭证的唯一标识符,代码中通过 `self.runtime.credentials["telegraph_access_token"]` 来访问用户输入的值 - `type: secret-input`: 表示在 Dify 界面上会显示为密码输入框
- `type: secret-input`: 表示在 Dify 界面上会显示为密码输入框 - `required: true`: 表示用户必须填写此凭证才能使用该插件提供的工具
- `required: true`: 表示用户必须填写此凭证才能使用该插件提供的工具 - `label`, `placeholder`, `help`: 提供多语言界面文本
- `label`, `placeholder`, `help`: 提供多语言界面文本 - `url`: (可选) 提供一个获取凭证的帮助链接
- `url`: (可选) 提供一个获取凭证的帮助链接。
### 4.4 实现工具 (Tool) 逻辑 ### 4.4 实现工具 (Tool) 逻辑
现在我们来编写实际执行发布操作的工具代码。 现在我们来编写实际执行发布操作的工具代码。
1. **编辑 Tool Python 文件:** 打开 `telegraph/tools/telegraph.py`。 1. **编辑 Tool Python 文件:** 打开 `telegraph/tools/telegraph.py`。
2. **实现 `_invoke` 方法:** 将文件内容替换为以下代码: 2. **`实现 _invoke 方法:`** 将文件内容替换为以下代码:
```python ```python
from collections.abc import Generator from collections.abc import Generator
from typing import Any from typing import Any
from ytelegraph import TelegraphAPI # 导入我们使用的库 from ytelegraph import TelegraphAPI # 导入我们使用的库
from dify_plugin import Tool from dify_plugin import Tool
from dify_plugin.entities.tool import ToolInvokeMessage from dify_plugin.entities.tool import ToolInvokeMessage
class TelegraphTool(Tool): class TelegraphTool(Tool):
""" """
一个简单的 Telegraph 发布工具。 一个简单的 Telegraph 发布工具。
""" """
def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]: def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]:
""" """
根据输入的标题和内容,创建一个新的 Telegraph 页面。 根据输入的标题和内容,创建一个新的 Telegraph 页面。
Args: Args:
tool_parameters: 一个包含工具输入参数的字典: tool_parameters: 一个包含工具输入参数的字典:
- p_title (str): Telegraph 页面的标题。 - p_title (str): Telegraph 页面的标题。
- p_content (str): 要发布的 Markdown 格式的内容。 - p_content (str): 要发布的 Markdown 格式的内容。
Yields: Yields:
ToolInvokeMessage: 包含成功创建的 Telegraph 页面 URL 的消息。 ToolInvokeMessage: 包含成功创建的 Telegraph 页面 URL 的消息。
Raises: Raises:
Exception: 如果页面创建失败,则抛出包含错误信息的异常。 Exception: 如果页面创建失败,则抛出包含错误信息的异常。
""" """
# 1. 从运行时获取凭证 # 1. 从运行时获取凭证
try: try:
access_token = self.runtime.credentials["telegraph_access_token"] access_token = self.runtime.credentials["telegraph_access_token"]
except KeyError: except KeyError:
raise Exception("Telegraph Access Token 未配置或无效。请在插件设置中提供。") raise Exception("Telegraph Access Token 未配置或无效。请在插件设置中提供。")
# 2. 获取工具输入参数 # 2. 获取工具输入参数
title = tool_parameters.get("p_title", "Untitled") # 使用 .get 提供默认值 title = tool_parameters.get("p_title", "Untitled") # 使用 .get 提供默认值
content = tool_parameters.get("p_content", "") content = tool_parameters.get("p_content", "")
if not content: if not content:
raise Exception("发布内容不能为空。") raise Exception("发布内容不能为空。")
# 3. 调用库执行操作 # 3. 调用库执行操作
try: try:
telegraph = TelegraphAPI(access_token) # 初始化 Telegraph API telegraph = TelegraphAPI(access_token) # 初始化 Telegraph API
ph_link = telegraph.create_page_md(title, content) # 创建页面 ph_link = telegraph.create_page_md(title, content) # 创建页面
except Exception as e: except Exception as e:
# 如果库调用失败,抛出异常 # 如果库调用失败,抛出异常
raise Exception(f"调用 Telegraph API 失败: {e}") raise Exception(f"调用 Telegraph API 失败: {e}")
# 4. 返回结果 # 4. 返回结果
# 使用 create_link_message 生成一个包含链接的输出消息 # 使用 create_link_message 生成一个包含链接的输出消息
yield self.create_link_message(ph_link) yield self.create_link_message(ph_link)
``` ```
- **关键点:**
- **关键点:** - 从 `self.runtime.credentials` 获取凭证。
- 从 `self.runtime.credentials` 获取凭证 - 从 `tool_parameters` 获取工具的输入参数(参数名将在下一步的 YAML 中定义)。使用 `.get()` 是更健壮的方式
- 从 `tool_parameters` 获取工具的输入参数(参数名将在下一步的 YAML 中定义)。使用 `.get()` 是更健壮的方式 - 调用 `ytelegraph` 库执行实际操作
- 用 `ytelegraph` 库执行实际操作 - 使用 `try...except` 捕获可能的错误并抛出异常
- 使用 `try...except` 捕获可能的错误并抛出异常 - 使用 `yield self.create_link_message(url)` 返回一个包含 URL 的结果给 Dify
- 使用 `yield self.create_link_message(url)` 返回一个包含 URL 的结果给 Dify。
### 4.5 配置工具 (Tool) 参数 ### 4.5 配置工具 (Tool) 参数
@@ -307,202 +289,191 @@ print(ph_link)
1. **编辑 Tool YAML 文件:** 打开 `telegraph/tools/telegraph.yaml`。 1. **编辑 Tool YAML 文件:** 打开 `telegraph/tools/telegraph.yaml`。
2. **定义参数:** 将文件内容替换或修改为: 2. **定义参数:** 将文件内容替换或修改为:
```yaml ```yaml
identity: identity:
name: telegraph_publisher # 工具的唯一内部名称 name: telegraph_publisher # 工具的唯一内部名称
author: your-name author: your-name
label: # 在 Dify UI 中显示的工具名称 (多语言) label: # 在 Dify UI 中显示的工具名称 (多语言)
en_US: Publish to Telegraph en_US: Publish to Telegraph
zh_Hans: 发布到 Telegraph zh_Hans: 发布到 Telegraph
# ... (其他语言) # ... (其他语言)
description: description:
human: # 给人类用户看的工具描述 (多语言) human: # 给人类用户看的工具描述 (多语言)
en_US: Publish content to Telegraph as a new page. en_US: Publish content to Telegraph as a new page.
zh_Hans: 将内容作为新页面发布到 Telegraph。 zh_Hans: 将内容作为新页面发布到 Telegraph。
# ... (其他语言) # ... (其他语言)
llm: # 给 LLM 看的工具描述 (用于 Agent 模式) llm: # 给 LLM 看的工具描述 (用于 Agent 模式)
A tool that takes a title and markdown content, then publishes it as a new page on Telegraph, returning the URL of the published page. Use this when the user wants to publish formatted text content publicly via Telegraph. A tool that takes a title and markdown content, then publishes it as a new page on Telegraph, returning the URL of the published page. Use this when the user wants to publish formatted text content publicly via Telegraph.
parameters: # 定义工具的输入参数列表 parameters: # 定义工具的输入参数列表
- name: p_title # 参数的内部名称,与 Python 代码中的 key 对应 - name: p_title # 参数的内部名称,与 Python 代码中的 key 对应
type: string # 参数类型 type: string # 参数类型
required: true # 是否必需 required: true # 是否必需
label: # 在 Dify UI 中显示的参数标签 (多语言) label: # 在 Dify UI 中显示的参数标签 (多语言)
en_US: Post Title en_US: Post Title
zh_Hans: 文章标题 zh_Hans: 文章标题
human_description: # 给人类用户看的参数描述 (多语言) human_description: # 给人类用户看的参数描述 (多语言)
en_US: The title for the Telegraph page. en_US: The title for the Telegraph page.
zh_Hans: Telegraph 页面的标题。 zh_Hans: Telegraph 页面的标题。
llm_description: # 给 LLM 看的参数描述 (指导 Agent 如何填充) llm_description: # 给 LLM 看的参数描述 (指导 Agent 如何填充)
The title of the post. Should be a concise and meaningful plain text string. The title of the post. Should be a concise and meaningful plain text string.
form: llm # 参数表单类型 ('llm' 或 'form') form: llm # 参数表单类型 ('llm' 或 'form')
- name: p_content - name: p_content
type: string type: string
required: true required: true
label: label:
en_US: Content (Markdown) en_US: Content (Markdown)
zh_Hans: 内容 (Markdown) zh_Hans: 内容 (Markdown)
human_description: human_description:
en_US: The main content for the Telegraph page, written in Markdown format. en_US: The main content for the Telegraph page, written in Markdown format.
zh_Hans: Telegraph 页面的主要内容,请使用 Markdown 格式编写。 zh_Hans: Telegraph 页面的主要内容,请使用 Markdown 格式编写。
llm_description: # 强调格式要求对 LLM 很重要 llm_description: # 强调格式要求对 LLM 很重要
The full content to be published on the Telegraph page. Must be provided in Markdown format. Ensure proper Markdown syntax for formatting like headings, lists, links, etc. The full content to be published on the Telegraph page. Must be provided in Markdown format. Ensure proper Markdown syntax for formatting like headings, lists, links, etc.
form: llm form: llm
extra: # 额外配置 extra: # 额外配置
python: python:
source: tools/telegraph.py # 指向实现该工具逻辑的 Python 文件 source: tools/telegraph.py # 指向实现该工具逻辑的 Python 文件
``` ```
- **字段解释:**
- **字段解释:** - `identity`: 工具的基本信息,`name` 是唯一标识。
- `identity`: 工具的基本信息,`name` 是唯一标识。 - `description`: 分为 `human` (给用户看) 和 `llm` (给 Agent 看)。**`llm 描述对于 Agent 能否正确理解和使用工具至关重要。`**
- `description`: 分为 `human` (给用户看) 和 `llm` (给 Agent 看)。**`llm` 描述对于 Agent 能否正确理解和使用工具至关重要。** - `parameters`: 定义每个输入参数。
- `parameters`: 定义每个输入参数 - `name`: 内部名称,需与 Python 代码中 `tool_parameters.get("...")` 的键一致
- `name`: 内部名称,需与 Python 代码中 `tool_parameters.get("...")` 的键一致 - `type`: 数据类型 (如 `string`, `number`, `boolean` 等)
- `type`: 数据类型 (如 `string`, `number`, `boolean` 等) - `required`: 是否必须提供
- `required`: 是否必须提供。 - `label`, `human_description`, `llm_description`: 类似 `identity` 中的描述,但针对具体参数。**`llm_description 应清晰指导 LLM 如何生成或获取该参数的值,包括格式要求(如此处的 Markdown。`**
- `label`, `human_description`, `llm_description`: 类似 `identity` 中的描述,但针对具体参数。**`llm_description` 应清晰指导 LLM 如何生成或获取该参数的值,包括格式要求(如此处的 Markdown。** - `form`: 定义参数如何在 Dify 中呈现和填充。`llm` 表示该参数值可以由用户输入、通过变量传入,或者在 Agent 模式下由 LLM 自主决定;`form` 通常表示需要用户在界面上固定填写的配置项。对于工具输入,`llm` 更常见。
- `form`: 定义参数如何在 Dify 中呈现和填充。`llm` 表示该参数值可以由用户输入、通过变量传入,或者在 Agent 模式下由 LLM 自主决定;`form` 通常表示需要用户在界面上固定填写的配置项。对于工具输入,`llm` 更常见 - `extra.python.source`: 指明实现此工具逻辑的 Python 文件路径(相对于项目根目录)
- `extra.python.source`: 指明实现此工具逻辑的 Python 文件路径(相对于项目根目录)。
### 4.6 实现 Provider 凭证验证 (可选但推荐) ### 4.6 实现 Provider 凭证验证 (可选但推荐)
为了确保用户提供的凭证有效,我们应该实现验证逻辑。 为了确保用户提供的凭证有效,我们应该实现验证逻辑。
1. **编辑 Provider Python 文件:** 打开 `telegraph/provider/telegraph.py`。 1. **编辑 Provider Python 文件:** 打开 `telegraph/provider/telegraph.py`。
2. **实现 `_validate_credentials` 方法:** 将文件内容替换为: 2. **`实现 _validate_credentials 方法:`** 将文件内容替换为:
```python ```python
from typing import Any from typing import Any
from dify_plugin import ToolProvider from dify_plugin import ToolProvider
from dify_plugin.errors.tool import ToolProviderCredentialValidationError from dify_plugin.errors.tool import ToolProviderCredentialValidationError
class TelegraphProvider(ToolProvider): class TelegraphProvider(ToolProvider):
def _validate_credentials(self, credentials: dict[str, Any]) -> None: def _validate_credentials(self, credentials: dict[str, Any]) -> None:
""" """
验证提供的 Telegraph Access Token 是否有效。 验证提供的 Telegraph Access Token 是否有效。
尝试使用该 token 创建一个测试页面。 尝试使用该 token 创建一个测试页面。
如果验证失败,应抛出 ToolProviderCredentialValidationError 异常。 如果验证失败,应抛出 ToolProviderCredentialValidationError 异常。
""" """
access_token = credentials.get("telegraph_access_token") access_token = credentials.get("telegraph_access_token")
if not access_token: if not access_token:
raise ToolProviderCredentialValidationError("Telegraph Access Token 不能为空。") raise ToolProviderCredentialValidationError("Telegraph Access Token 不能为空。")
try: try:
# 尝试执行一个需要凭证的简单操作来验证 # 尝试执行一个需要凭证的简单操作来验证
from ytelegraph import TelegraphAPI from ytelegraph import TelegraphAPI
ph = TelegraphAPI(access_token=access_token) ph = TelegraphAPI(access_token=access_token)
# 尝试创建一个临时的、无害的页面作为验证手段 # 尝试创建一个临时的、无害的页面作为验证手段
# 注意:更好的验证方式可能是调用 API 的 'getAccountInfo' 等只读方法(如果存在) # 注意:更好的验证方式可能是调用 API 的 'getAccountInfo' 等只读方法(如果存在)
test_page = ph.create_page_md("Dify Validation Test", "This is a test page created by Dify plugin validation.") test_page = ph.create_page_md("Dify Validation Test", "This is a test page created by Dify plugin validation.")
# 如果需要,可以考虑立即编辑或删除这个测试页面,但这会增加复杂性 # 如果需要,可以考虑立即编辑或删除这个测试页面,但这会增加复杂性
# print(f"Validation successful. Test page created: {test_page}") # print(f"Validation successful. Test page created: {test_page}")
except Exception as e: except Exception as e:
# 如果 API 调用失败,说明凭证很可能无效 # 如果 API 调用失败,说明凭证很可能无效
raise ToolProviderCredentialValidationError(f"Telegraph 凭证验证失败: {e}") raise ToolProviderCredentialValidationError(f"Telegraph 凭证验证失败: {e}")
``` ```
- **关键点:**
- **关键点:** - 从 `credentials` 字典中获取凭证。
- 从 `credentials` 字典中获取凭证 - 执行一个需要该凭证的 API 调用(最好是只读操作,如获取账户信息;如果没有,创建一个无害的测试页面也可以,但要注意可能产生的副作用)
- 执行一个需要该凭证的 API 调用(最好是只读操作,如获取账户信息;如果没有,创建一个无害的测试页面也可以,但要注意可能产生的副作用) - 如果 API 调用成功,则不抛出异常,表示验证通过
- 如果 API 调用成功,则不抛出异常,表示验证通过 - 如果 API 调用失败,则捕获异常并抛出 `ToolProviderCredentialValidationError`,将原始错误信息包含在内
- 如果 API 调用失败,则捕获异常并抛出 `ToolProviderCredentialValidationError`,将原始错误信息包含在内。
## 5. 本地运行与调试 ## 5. 本地运行与调试
现在可以在本地运行插件,并在 Dify 中进行调试了。 现在可以在本地运行插件,并在 Dify 中进行调试了。
1. **准备 `.env` 文件:** 1. **`准备 .env 文件:`**
- 确保您仍在 `telegraph` 项目目录下。
- 复制环境变量模板文件:
- 确保您仍在 `telegraph` 项目目录下。 ```bash
- 复制环境变量模板文件: cp .env.example .env
```
```bash - **`编辑 .env 文件:`** 打开刚刚创建的 `.env` 文件,填入您的 Dify 环境信息:
cp .env.example .env
```
- **编辑 `.env` 文件:** 打开刚刚创建的 `.env` 文件,填入您的 Dify 环境信息:
```dotenv
DIFY_API_HOST=https://your-dify-host.com # 替换为您的 Dify 实例地址 (例如 https://cloud.dify.ai)
DIFY_API_KEY=your-api-key # 替换为您的 Dify API 密钥
```
- **获取 Host 和 Key:** 登录您的 Dify 环境点击右上角的“插件”图标然后点击调试图标或类似虫子形状。在弹出的窗口中复制“API 密钥 (Key)”和“主机地址 (Host)”。 _(请参考您本地对应的截图 ,它展示了获取密钥和主机地址的界面)_
```dotenv
DIFY_API_HOST=https://your-dify-host.com # 替换为您的 Dify 实例地址 (例如 https://cloud.dify.ai)
DIFY_API_KEY=your-api-key # 替换为您的 Dify API 密钥
```
- **获取 Host 和 Key:** 登录您的 Dify 环境点击右上角的“插件”图标然后点击调试图标或类似虫子形状。在弹出的窗口中复制“API 密钥 (Key)”和“主机地址 (Host)”。 _(请参考您本地对应的截图 ,它展示了获取密钥和主机地址的界面)_
2. **启动本地插件服务:** 2. **启动本地插件服务:**
- 确保您的 Python 虚拟环境已激活。
- 在 `telegraph` 目录下,运行主程序:
- 确保您的 Python 虚拟环境已激活。 ```bash
- 在 `telegraph` 目录下,运行主程序: python -m main
```
```bash - **观察终端输出:** 如果一切正常,您应该会看到类似以下的日志信息,表示插件工具已成功加载并连接到 Dify
python -m main
```
- **观察终端输出:** 如果一切正常,您应该会看到类似以下的日志信息,表示插件工具已成功加载并连接到 Dify
```json
{"event": "log", "data": {"level": "INFO", "message": "Installed tool: telegraph_publisher", "timestamp": 1678886400.123456}}
{"event": "log", "data": {"level": "INFO", "message": "Plugin daemon started, waiting for requests...", "timestamp": 1678886400.123457}}
```
```json
{"event": "log", "data": {"level": "INFO", "message": "Installed tool: telegraph_publisher", "timestamp": 1678886400.123456}}
{"event": "log", "data": {"level": "INFO", "message": "Plugin daemon started, waiting for requests...", "timestamp": 1678886400.123457}}
```
3. **在 Dify 中查看并测试:** 3. **在 Dify 中查看并测试:**
- **刷新 Dify 页面:** 回到您的 Dify 环境(浏览器中),刷新插件管理页面 (通常是 `https://your-dify-host.com/plugins`)。
- **刷新 Dify 页面:** 回到您的 Dify 环境(浏览器中),刷新插件管理页面 (通常是 `https://your-dify-host.com/plugins`) - **查找插件:** 您应该能在列表中看到名为 "Telegraph" (或您在 Provider YAML 中定义的 `label`) 的插件,并且可能带有一个“调试中”的标记
- **查找插件:** 您应该能在列表中看到名为 "Telegraph" (或您在 Provider YAML 中定义的 `label`) 的插件,并且可能带有一个“调试中”的标记。 - **添加凭证:** 点击该插件,系统会提示您输入之前在 `provider/telegraph.yaml` 中定义的 "Telegraph Access Token"。输入有效的 token 并保存。如果您的验证逻辑 (`_validate_credentials`) 实现正确,这里会进行验证。 _(请参考您本地对应的截图 ,它展示了插件出现在列表并请求授权的界面)_
- **添加凭证:** 点击该插件,系统会提示您输入之前在 `provider/telegraph.yaml` 中定义的 "Telegraph Access Token"。输入有效的 token 并保存。如果您的验证逻辑 (`_validate_credentials`) 实现正确,这里会进行验证。 _(请参考您本地对应的截图 ,它展示了插件出现在列表并请求授权的界面)_ - **在应用中使用:** 现在,您可以在 Dify 的应用(如 Chatbot 或 Workflow中添加这个工具节点并尝试调用它了当您在应用中运行并触发该工具时请求会被转发到您本地运行的 `python -m main` 进程进行处理。您可以在本地终端看到相关的日志输出,并进行调试。
- **在应用中使用:** 现在,您可以在 Dify 的应用(如 Chatbot 或 Workflow中添加这个工具节点并尝试调用它了当您在应用中运行并触发该工具时请求会被转发到您本地运行的 `python -m main` 进程进行处理。您可以在本地终端看到相关的日志输出,并进行调试。
4. **停止本地服务:** 在终端中按下 `Ctrl + C` 可以停止本地插件服务。 4. **停止本地服务:** 在终端中按下 `Ctrl + C` 可以停止本地插件服务。
这个运行 -> 测试 -> 停止 -> 修改代码 -> 重新运行 的循环是插件开发的主要流程。 这个运行 -\> 测试 -\> 停止 -\> 修改代码 -\> 重新运行 的循环是插件开发的主要流程。
## 6. 完善插件元信息 ## 6. 完善插件元信息
为了让插件更专业、更易于被发现和理解,我们需要完善一些展示性的信息。 为了让插件更专业、更易于被发现和理解,我们需要完善一些展示性的信息。
1. **图标 (Icon):** 1. **图标 (Icon):**
- 在 `telegraph/_assets` 目录下放置一个代表您插件的图标文件(例如 `icon.png`, `icon.svg`)。推荐使用正方形、清晰的图片。 - 在 `telegraph/_assets` 目录下放置一个代表您插件的图标文件(例如 `icon.png`, `icon.svg`)。推荐使用正方形、清晰的图片。
2. **Provider 信息 (`provider/telegraph.yaml`):** 2. **`Provider 信息 (provider/telegraph.yaml):`**
- 确保 `identity` 部分的 `label` (显示名称), `description` (功能描述), 和 `icon` (填写图标文件名,如 `icon.png`) 已填写并支持多语言。这部分信息主要在 Dify 应用编排界面中展示给\_使用\_插件的用户。
- 确保 `identity` 部分的 `label` (显示名称), `description` (功能描述), 和 `icon` (填写图标文件名,如 `icon.png`) 已填写并支持多语言。这部分信息主要在 Dify 应用编排界面中展示给_使用_插件的用户。 ```yaml
identity:
```yaml author: your-name
identity: name: telegraph # 内部名称,保持不变
author: your-name label:
name: telegraph # 内部名称,保持不变 en_US: Telegraph
label: zh_Hans: Telegraph 发布文章
en_US: Telegraph description:
zh_Hans: Telegraph 发布文章 en_US: A Telegraph plugin that allow you publish your content easily
description: zh_Hans: 一个让您轻松发布内容的Telegraph插件
en_US: A Telegraph plugin that allow you publish your content easily icon: icon.png # 引用 _assets 目录下的图标文件名
zh_Hans: 一个让您轻松发布内容的Telegraph插件 ```
icon: icon.png # 引用 _assets 目录下的图标文件名 3. **`插件清单 (manifest.yaml):`**
``` - 编辑项目根目录下的 `telegraph/manifest.yaml` 文件。这是整个插件的“身份证”,其信息将展示在 Dify 的**插件管理页面**和**插件市场 (Marketplace)** 中。
- 务必更新或确认以下字段:
3. **插件清单 (`manifest.yaml`):** - `label`: 插件的**主要显示名称** (支持多语言)。
- `description`: 对插件功能的**整体简介** (支持多语言),应清晰概括其核心价值。注意市场展示可能有长度限制。
- 编辑项目根目录下的 `telegraph/manifest.yaml` 文件。这是整个插件的“身份证”,其信息将展示在 Dify 的**插件管理页面**和**插件市场 (Marketplace)** 中 - `icon`: 插件的**主图标** (直接填写 `_assets` 目录下的图标文件名,如 `icon.png`)
- 务必更新或确认以下字段: - `tags`: 为插件添加分类标签,有助于用户在市场中筛选。可选值请参考 Dify 提供的枚举或文档说明 (例如 `media`, `tools`, `data-processing` 等)。可参考 [ToolLabelEnum 定义](https://github.com/langgenius/dify-plugin-sdks/blob/main/python/dify_plugin/entities/tool.py)。
- `label`: 插件的**主要显示名称** (支持多语言)。
- `description`: 对插件功能的**整体简介** (支持多语言),应清晰概括其核心价值。注意市场展示可能有长度限制。
- `icon`: 插件的**主图标** (直接填写 `_assets` 目录下的图标文件名,如 `icon.png`)。
- `tags`: 为插件添加分类标签,有助于用户在市场中筛选。可选值请参考 Dify 提供的枚举或文档说明 (例如 `media`, `tools`, `data-processing` 等)。可参考 [ToolLabelEnum 定义](https://github.com/langgenius/dify-plugin-sdks/blob/main/python/dify_plugin/entities/tool.py)。
```yaml
label:
en_US: Telegraph Publisher
zh_Hans: Telegraph 发布助手
description:
en_US: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
zh_Hans: 从 Dify 应用中轻松将内容发布为 Telegraph 页面,支持 Markdown 格式。
icon: icon.png
tags: ['media', 'content-creation'] # 示例标签
# ... (author, name 等其他字段保持不变)
```
```yaml
label:
en_US: Telegraph Publisher
zh_Hans: Telegraph 发布助手
description:
en_US: Easily publish content to Telegraph pages directly from your Dify applications. Supports Markdown formatting.
zh_Hans: 从 Dify 应用中轻松将内容发布为 Telegraph 页面,支持 Markdown 格式。
icon: icon.png
tags: ['media', 'content-creation'] # 示例标签
# ... (author, name 等其他字段保持不变)
```
4. **README 和隐私政策:** 4. **README 和隐私政策:**
- `README.md`: 编辑项目根目录下的 `README.md` 文件。它将作为插件在 **Marketplace** 上的详细介绍页面,应包含更丰富的信息,如功能详述、使用示例、配置指南、常见问题等。可参考 [AWS 插件市场页面](https://marketplace.dify.ai/plugins/langgenius/aws_tools) 的样式。 - `README.md`: 编辑项目根目录下的 `README.md` 文件。它将作为插件在 **Marketplace** 上的详细介绍页面,应包含更丰富的信息,如功能详述、使用示例、配置指南、常见问题等。可参考 [AWS 插件市场页面](https://marketplace.dify.ai/plugins/langgenius/aws_tools) 的样式。
- `PRIVACY.md`: 如果您计划将插件发布到官方 Marketplace需要提供隐私政策说明文件 `PRIVACY.md`,描述插件如何处理数据。
<Info>
README 支持多语言,具体规范请阅读 [多语言 README](/plugin-dev-zh/0411-multilingual-readme)。
</Info>
- `PRIVACY.md`: 如果您计划将插件发布到官方 Marketplace需要提供隐私政策说明文件 `PRIVACY.md`,描述插件如何处理数据。
## 7. 打包插件 ## 7. 打包插件
@@ -510,18 +481,16 @@ print(ph_link)
1. **返回上级目录:** 确保您的终端当前路径在 `telegraph` 文件夹的**上一级**。 1. **返回上级目录:** 确保您的终端当前路径在 `telegraph` 文件夹的**上一级**。
```bash ```bash
cd .. cd ..
``` ```
2. **执行打包命令:** 2. **执行打包命令:**
```bash ```bash
./dify plugin package ./telegraph ./dify plugin package ./telegraph
``` ```
(请将 `./telegraph` 替换为您插件项目的实际路径)
(请将 `./telegraph` 替换为您插件项目的实际路径)
3. **获取打包文件:** 命令执行成功后,将在当前目录下生成一个名为 `telegraph.difypkg` (或 `您的插件名.difypkg`) 的文件。 3. **获取打包文件:** 命令执行成功后,将在当前目录下生成一个名为 `telegraph.difypkg` (或 `您的插件名.difypkg`) 的文件。
这个 `.difypkg` 文件就是一个完整的插件包。您可以: 这个 `.difypkg` 文件就是一个完整的插件包。您可以:

View File

@@ -0,0 +1,51 @@
---
dimensions:
type:
primary: reference
detail: core
level: beginner
standard_title: Multilingual README
language: zh
title: 多语言 README
description: 本文介绍插件多语言 README 的文件规范及其在 Dify Marketplace 中的展示规则。
---
Dify 插件支持多语言 README并将在 [Dify Marketplace](https://marketplace.dify.ai/?language=zh-Hans) 等位置根据用户的首选语言展示对应的 README。
### README 文件规范
| 语种 | 必需 | 文件名 | 存放路径 | 说明 |
| :------- | :-- | :----------------- | :-------------------- | :---------------- |
| **英语** | 是 | `README.md` | 插件根目录下 | / |
| **其他语种** | 否 | `README_<语言标识>.md` | 插件根目录下的 `readme` 文件夹中 | 目前支持日语、葡萄牙语、简体中文。 |
目录结构示例如下:
```bash
...
├── main.py
├── manifest.yaml
├── readme
│   ├── README_ja_JP.md
│   ├── README_pt_BR.md
│   └── README_zh_Hans.md
├── README.md
...
```
### Marketplace 展示规则
当插件提供了用户所用语言的 README 文件时Dify Marketplace 的插件详情页将展示对应语言版本的 README。
![](/images/plugin_details_page_zh.jpg)
{/*
Contributing Section
DO NOT edit this section!
It will be automatically generated by the script.
*/}
---
[编辑此页面](https://github.com/langgenius/dify-docs/edit/main/plugin-dev-zh/0411-multilingual-readme.mdx) | [提交问题](https://github.com/langgenius/dify-docs/issues/new?template=docs.yml)