# Admin APIs Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/admin-apis Requires Dify Enterprise version ≥ v2.2.0 Admin APIs adhere to REST API standards, enabling efficient automation and management within the Dify Enterprise platform. These APIs support querying and modifying information for the following resources: * **Workspaces**: Global workspace management, including querying workspace information and performing management operations. * **Members**: Global team member management, including querying team member details and managing accounts. * **Workspace Member**: Management of members within a specific workspace, including querying member information and managing members. > More features will be supported with future version updates, including enhanced operations and resource management. *** ## API Types To avoid confusion, Dify distinguishes between different levels of API services: * APIs provided by applications are referred to as **Workspace APIs**. * APIs for managing platform-level operations are collectively called **Admin APIs**. *** ## Endpoint URL Admin APIs use the following endpoint address. When making API calls, replace `your-domain` with your Dify Enterprise platform domain name and append the specific request path to form the complete API endpoint. ```bash theme={null} https://your-domain/admin-api/v1 ``` *** ## Authentication API requests require a Secret Key for authentication. To obtain one, navigate to the **Admin APIs** page in the Dify Enterprise admin dashboard to generate and configure the Key. > [!WARNING] > > Modifying data via Admin APIs may impact production data within your organization. Please proceed with caution. *** ![API Documentation](https://assets-docs.dify.ai/2025/02/0431242649acccbcbcf23fa8e4268ce8.png) *** ## Usage Example To facilitate understanding of the Admin APIs, here is an example of how to retrieve the list of workspaces. ### 1. Create an API Key * Log in to the Dify Enterprise admin dashboard. * Navigate to the **Admin APIs**. * Click the **Add** button in the top-right corner and follow the prompts to create a key by entering a name. *** ### 2. Import the API Collection and Configure Variables Click the **Postman Collection** link on the page to download the configuration file. ![Postman Collection Download](https://assets-docs.dify.ai/2025/02/5aa925f58ec5bb12a2838704f1444525.png) Import the configuration file into Postman. Replace the `base_url` and `secret_key` variables in the **Variables**. ![Postman Variables Configuration](https://assets-docs.dify.ai/2025/02/786336845c4d67117fdede872eb7883b.png) *** ### 3. Send the Request Send the request and receive the response. You can view the complete list of workspaces and their corresponding information within the current enterprise version in the response. ```json theme={null} { "data": [ { "id": "a7145b74-****--****---****", # Workspace ID "name": "Workspace A Name", # Workspace Name "status": "normal", # Workspace Status "created_at": "2025-02-08T02:45:33Z", # The Create Time of Workspace "updated_at": "2025-02-08T02:45:33Z" # The Update Time of Workspace }, { "id": "bbffbfdf-****--****---****", "name": "Dify's Workspace", "status": "normal", "created_at": "2025-02-07T16:55:59Z", "updated_at": "2025-02-07T16:55:59Z" }, ], "has_more": true, "limit": 10, "page": 1, "total": 491 } ``` ![API Request and Response](https://assets-docs.dify.ai/2025/02/bd4d300b08ceed74c17c3b428329fa19.png) # Configure Permission Templates Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/admin-console-rbac-help Learn how to configure default workspace roles and resource permission level templates for new workspaces. # Configure Permission Templates Dify Enterprise provides admin-level RBAC templates to help organization administrators define the default permission structure for new workspaces. Admin console templates do not directly change permissions in existing workspaces. They define the initial roles and resource permission levels that will be inherited when a new workspace is created. ## What You Can Configure In the admin console, go to **Roles & Permissions**. You can configure two types of templates: | Template | Purpose | | - | - | | **Workspace Role Templates** | Defines the default workspace roles and their permissions for new workspaces. | | **Resource Permission Set Template** | Defines the default resource permission levels available in new workspaces. | ## Workspace Role Templates Workspace role templates define what members can do in a workspace. When a new workspace is created, it inherits the roles configured in this template. To open the page, go to **Admin Console → Roles & Permissions → Workspace Role Templates**. The page lists all default workspace roles, including: | Column | Description | | - | - | | **Role** | The role name. | | **Type** | Indicates whether the role is a system preset role or an enterprise custom role. | | **Description** | A short explanation of the role. | | **Action** | View, edit, or remove the role, depending on the role type. | ### System Preset Roles System preset roles are built-in roles provided by Dify. They are used to keep permissions stable during upgrades and provide a reliable default role model for new workspaces. Common system preset roles include: | Role | Description | | - | - | | **Owner** | Full control of the workspace, including members, roles, and resources. | | **Admin** | Manages most workspace settings, members, roles, and resources. | | **Editor** | Can create and edit apps, knowledge bases, and other content. | | **Normal** | Can view and use assigned resources, but cannot manage them. | | **Restricted Member** | Has no default access to features or resources. | System preset roles can't be removed or edited. ### Enterprise Custom Roles Enterprise custom roles are roles created by enterprise administrators. They can be used to define permission models that match your organization’s internal responsibilities. You can: * Create a custom role. * Edit the role name, description, and permissions. * Remove the role if it is no longer needed. ### Create a Role 1. Click **Create Role**. 2. Enter a role name. 3. Add a role description. 4. Select the permissions that should be granted to this role. 5. Click **Confirm**. Permissions are grouped by product area, such as **Workspace** and **Application**. You can search for permissions or expand each permission group to select individual permission points. ### Edit a Role 1. Click **Detail** for the role you want to edit. 2. Review the role name, description, and selected permissions. 3. Update the editable fields. 4. Click **Save**. ### Remove a Custom Role Only enterprise custom roles can be removed. 1. Click **Remove** next to the custom role. 2. In the dialog, type the confirmation text and click **Remove**. Removing a role cannot be undone. Before deleting a role, make sure no workspace setup depends on it. ## Resource Permission Set Template Resource permission set templates define reusable resource permission levels for new workspaces. These templates do not decide who can access a resource. Instead, they define what a member can do after they are assigned a permission level on a specific resource. To open the page, go to **Admin Console → Roles & Permissions → Resource Permission Set Template**. The page contains three tabs: | Tab | Purpose | | - | - | | **App permission sets** | Permission levels that can be used for apps. | | **Knowledge base permission sets** | Permission levels that can be used for knowledge bases. | | **Agent permission sets** | Permission levels that can be used for [agents](/en/3.13.x/use/build/new-agent/overview). | New workspaces inherit these permission set templates by default. Workspace administrators can later adjust permission sets inside their own workspace. ### Default App Permission Sets | Permission Set | Description | | - | - | | **Full Control** | Full control of the app. | | **Edit Content** | Can edit app content and settings, but not access control. | | **View Monitoring and Access Points** | Can view the app's monitoring data and its access points. | | **Preview App** | Can only see the app in the list, without opening details. | ### Default Knowledge Base Permission Sets | Permission Set | Description | | - | - | | **Full Control** | Full control of the knowledge base. | | **Edit Content** | Can edit knowledge base content and settings, but not access control. | | **Preview Knowledge Base** | Can only see the knowledge base in the list, without opening details. | ### Default Agent Permission Sets | Permission Set | Description | | - | - | | **Full Control** | Full control of the agent. | | **Edit Content** | Everything on the agent except changing who can access it and deleting it. | | **View Agent Basic Info** | Can only see the agent in the list, without opening details. | | **View Access Points** | Can open the agent's access point page, without changing anything. | ### Create a Permission Set 1. Open the tab for the resource type, then click its create button, such as **Create agent permission set**. 2. Enter a name and a description. 3. Select the resource permissions to include. See [Permission Reference](/en/3.13.x/use/workspace/permission-reference) for what each one allows. 4. Click **Confirm**. Permission sets are designed as reusable shortcuts. For example, an app permission set named **Edit Content** can include permissions such as editing app content and updating app configuration. ### Edit a Permission Set 1. Click the **...** menu next to a permission set. 2. Select **Edit**. 3. Update the name, description, or granted permissions. 4. Click **Confirm**. Editing a permission set template affects how the template is inherited by new workspaces. It does not automatically rewrite permissions that have already been customized inside existing workspaces. ### Delete a Permission Set 1. Click the **...** menu next to a permission set. 2. Select **Delete**. 3. Confirm the deletion. Deleting a permission set cannot be undone. If a permission set is required by your default workspace setup, avoid deleting it. ## Important Notes * Admin console templates apply to new workspaces. * Existing workspaces keep their current role and permission configurations unless they are manually updated. * Workspace roles define what members can do at the workspace level. * Resource permission sets define reusable permission levels for apps, knowledge bases, and agents. * Resource access still needs to be configured on the specific resource when member-level access control is required. ## Recommended Setup Flow 1. Configure **Workspace Role Templates** first. 2. Configure **Resource Permission Set Template** for apps, knowledge bases, and agents. 3. Create a test workspace. 4. Verify that the new workspace inherits the expected roles and permission sets. 5. Assign members to roles and test resource access behavior. # Audit Log Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/audit-log The audit log is used to record key operational behaviors within the system, supporting users in operation tracking, security auditing, and compliance analysis. ## 1. Feature Introduction The audit log feature provides the capability to record and query key behaviors such as resource changes, permission operations, and configuration adjustments in the platform. The log has structured fields, supports precise filtering, querying, and exporting, helping enterprises identify potential risks and meet security compliance requirements. **Typical application scenarios include:** * Operation tracing and responsibility positioning * Security policy audit and risk troubleshooting * Compliance check and external audit support ## 2. Operation Instructions ### 2.1 Access Path Enterprise Admin Dashboard > Audit Log. ### 2.2 Log Structure and Field Description | Field Name | Description | | - | - | | Time | The time when the operation occurred, accurate to the second | | Workspace | The workspace to which the resource belongs (if applicable), including the name and ID | | Operator | The member account, system user account, API Key, operator ID, and IP address of the operator who triggered the operation | | Operation Type | The type of operation behavior (such as create, modify, delete, upload, etc.) | | Resource Type | The resource category of the operated object (such as members, workspaces, applications, configuration items, etc.) | | Resource Name | The specific resource name, which can be accompanied by the parent resource, for example: test.doc (TestDataSet), as well as the ID of the resource and parent resource | ### 2.3 Query Function Description **Optional filter conditions:** * Workspace, search by workspace ID * Resource type, for example: members, applications, authentication configuration * Operation type, for example: create, modify, export DSL * Resource ID, exact match of resource ID * Time range, by default only supports the last 90 days **Query restrictions:** The default query range is **the last 90 days**. If you need to query historical logs, please use the "Download Log" function to obtain complete data. **List display:** Hovering over the resource name will display the resource ID. Clicking the "Details" link in the row of a specific log will display the complete information of that log. ![](https://assets-docs.dify.ai/2025/06/3cd33660fa4e1e4c23b975918bd85e99.png) ![](https://assets-docs.dify.ai/2025/06/702271d2cd90f8eab00711c43239c8ad.png) ## 3. Download Log ### 3.1 Feature Description To ensure query efficiency and system performance, logs older than 90 days will be automatically archived. Users can obtain them by **downloading log files (CSV format)**. ### 3.2 Operation Steps 1. Click "Download Log" in the upper right corner of the page; 2. Select the time range in the pop-up window (supports any historical time period); 3. Click "Download CSV File", and the system will start downloading the CSV file. > * If part of the data in the selected time range is still within the online query range, the system will package and download it together. > * The log file may be large in size, and the download time depends on the selected range and data volume, please be patient. ![](https://assets-docs.dify.ai/2025/07/2fb97a4d140a6072a0730a93d3a24951.png) ### 3.3 Data Analysis Suggestions You can use the following tools to filter and analyze the exported CSV files: * Excel / Numbers: suitable for lightweight filtering and summarizing * Notion / Airtable: suitable for structured visual management * ELK Stack (Elasticsearch + Logstash + Kibana): suitable for large-scale log visualization, search, and alerting > Tip: The downloaded log is a structured CSV file, and the fields are consistent with online queries, which is convenient for subsequent analysis. ## 4. Operation Type Classification Description | Operation Type | Description | | :- | :- | | Create | Creating workspaces, applications, knowledge bases, members, API keys, member groups, system users | | Modify | Modifying configuration items, resource properties, renaming, etc., for example: authentication configuration in the enterprise admin dashboard | | Delete | Deleting members, applications, workspaces, etc. | | Enable | Enabling members | | Disable | Disabling members | | Login | Members logging into the workspace, system users logging into the enterprise admin dashboard | | Export | Exporting files | | Upload | Uploading files | | Publish | Publishing applications | | Import DSL | Importing DSL files of applications | | Export DSL | Exporting DSL files of applications | | Enable web application | Enabling the web application of an application | | Disable web application | Disabling the web application of an application | | Enable backend service API | Enabling the backend service API of an application | | Disable backend service API | Disabling the backend service API of an application | | Modify web application access rights | Modifying the access rights of an application's web application | | Modify access rights | Modifying the access rights of the knowledge base | | Modify configuration | Modifying the synchronization settings of member groups | | Invite | Inviting members from the workspace | | Modify password | Modifying the password of a member or system administrator | | Bind two-factor authentication | System administrator binding two-factor authentication | | Enable two-factor authentication | System administrator enabling two-factor authentication | | Disable two-factor authentication | System administrator disabling two-factor authentication | | Generate backup code | System administrator generating backup code | ## 5. Frequently Asked Questions ### Why can't I view logs from 3 months ago? For system performance considerations, only online queries of data from the last 90 days are provided. Please obtain historical data through the download log function. ### How to analyze after downloading the log? It is recommended to use tools such as Excel, Notion to filter fields, or import into Elasticsearch for full-text search and chart visualization. ### Will the audit log be automatically cleared? The audit log will be archived regularly according to system configuration, but it will not be actively deleted unless the administrator customizes a cleaning strategy. ## 6. Data Security Description The content of the audit log is only accessible to system users in the enterprise admin dashboard or users with corresponding permissions. The system ensures that log data cannot be tampered with and is retained and processed in accordance with enterprise data compliance requirements. *** For further support, please contact technical support or the system administrator. # Enterprise Members Authentication Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/authentication/enterprise-user-auth Enterprise members refer to who have registered in the Dify Enterprise workspace or been added by administrators through the admin console. Our authentication system ensures these users can only access Dify Enterprise resources after proper verification. ## Authentication Scope Overview Dify Enterprise offers tailored authentication methods based on user roles and access requirements: | Access Target | User Role | Authentication Method | Security Level | | - | - | - | - | | **Workspace** | Enterprise Internal Users | Email & Password, Email & Verification Code, SSO | High | | **Web App** | Enterprise Internal Users, Specific Group Users | Email & Password, Email & Verification Code, SSO | Medium | ## Authentication Method System administrators can navigate to **Admin Console** → **Authentication** → **Members** to centrally configure authentication methods for internal users accessing workspaces and Web Apps. ![](https://assets-docs.dify.ai/2025/06/6b8cf5d9a048fc463c59bc8b41665d2a.png) ### Email and Password Authentication **Applicable Scope:** * Workspace * Web App **Features:** * Classic username and password authentication * Configurable password security policies * Suitable for all user types **Configuration Steps:** 1. **Authentication** → **Members** → **Email and Password** 2. Enable the toggle > [tab] Admin Console Configuration > > ![Email and password authentication configuration interface](https://assets-docs.dify.ai/2025/06/6ebe7dbbdc394d94b3f45dbc4b615a1d.png) > > Enable email and password authentication in enterprise admin console > [tab] User Login Interface > > ![User login interface](https://assets-docs.dify.ai/2025/04/14e603662ca00daf80762f57a228e57c.png) > > User login page display **Password Security Recommendations:** * Enforce minimum password length of 8 characters * Include uppercase and lowercase letters, numbers, and special characters * Regularly remind users to update passwords * Prohibit common weak passwords ### Email and Verification Code Authentication **Applicable Scope:** * Workspace * Web App **Features:** * Passwordless login method * Single-use email verification codes * Enhances user experience by eliminating password management **Configuration Steps:** 1. Verify that your email service is properly configured 2. Enable "Email and Verification Code" on **Authentication** → **Members** page 3. Configure verification code parameters: * Verification code validity period (recommended 5-10 minutes) * Sending frequency limits * Verification code length and type > [tab] Admin Console Configuration > > ![Email verification code authentication configuration interface](https://assets-docs.dify.ai/2025/06/7729d5b4e299f11f089c0d73045308e1.png) > > Enable email verification code authentication in enterprise admin console > [tab] User Login Interface > > ![Verification code login interface](https://assets-docs.dify.ai/2025/04/2572a20174e7b9fa85817dca02bba937.png) > > Verification code login page **Prerequisites:** * SMTP email service configured * Email service stable and available * Valid user email addresses ### Single Sign-On (SSO) **Applicable Scope:** * Workspace * Web App **Features:** * Integration with existing enterprise identity systems * Supports OIDC, SAML, OAuth2 protocols * Unified enterprise identity management * Supports automatic user synchronization **Configuration Steps:** 1. Enable "Single Sign-On (SSO)" on **Authentication** → **Members** page 2. Configure identity provider information 3. Set user attribute mapping 4. Test SSO connection > [tab] Admin Console Configuration > > ![SSO authentication configuration interface](https://assets-docs.dify.ai/2025/06/b8e0836b5179a4127d611926f9a1a34d.png) > > Enable SSO authentication in enterprise admin console > [tab] User Login Interface > > ![SSO login interface](https://assets-docs.dify.ai/2025/04/32db3fc352c7ba40eb4343fd5f6229e5.png) > > SSO login page > [!WARNING] > > When setting up SSO, ensure you configure the correct callback URL in your identity provider. **Note that Workspace and Web App require different callback URLs** - please configure them accordingly. For detailed SSO configuration instructions, please refer to [Enterprise SSO Configuration Guide](/en/3.13.x/administer/sso/introduction). ## Access Permission Management ### Workspace System administrators can enable email and password authentication, email and verification code authentication, and Single Sign-On (SSO) authentication methods in **System Settings** → **Authentication** → **Members**. ![](https://assets-docs.dify.ai/2025/06/6b8cf5d9a048fc463c59bc8b41665d2a.png) When users access the Dify Enterprise workspace, they'll see authentication prompts based on your configuration settings and gain access upon successful verification. **User Registration Strategies:** Here are the most common user registration strategies: > [tab] Open Registration Mode > > **Configuration:** > > * Enable "Allow users to register accounts themselves" > * Enable "Allow system to automatically create personal spaces" > > **Features:** > > * Users can self-register and start using the platform immediately > * Personal workspaces are automatically created > * Suitable for open enterprise environments > [tab] Invitation Registration Mode > > **Configuration:** > > * Disable "Allow users to register accounts themselves" > * Enable "Allow system to automatically create personal spaces" > > **Features:** > > * Registration is limited to administrator-invited users > * Personal space automatically created after registration > * Suitable for controlled enterprise environments > [tab] Fully Controlled Mode > > **Configuration:** > > * Disable "Allow users to register accounts themselves" > * Disable "Allow system to automatically create personal spaces" > > **Features:** > > * All user operations require manual administrator approval > * Highest security level > * Suitable for highly sensitive enterprise environments ### Web App When Web App access is set to **All Platform Members** or **Specific Platform Groups**, the authentication methods configured in "Enterprise User Authentication" (email/password, email verification codes, or SSO) will be automatically applied. Users not on the Dify Enterprise member list will receive an access denied message. ## Security Best Practices ### Authentication Strategy Recommendations **Enable Multiple Authentication Methods** * Use SSO as your primary method for centralized identity management * Maintain email/password authentication as a fallback option * Reserve email verification codes for emergency situations ### Session Management **Session Security Configuration:** * **Session Timeout**: Recommended 7-30 days, adjust based on security requirements * **Concurrent Login Limits**: Restrict simultaneous logins per user account * **IP Address Binding**: Implement IP whitelisting for enhanced security environments ### Password Policy **Strong Password Requirements:** * Minimum 8 characters, recommended 12+ characters * Include uppercase and lowercase letters, numbers, and special characters * Block commonly used weak passwords and dictionary attacks * Enforce periodic password changes (every 90-180 days) ## Troubleshooting ### Common Issues > [accordion] When accessing Web App, prompted with no access permission > > **Possible Causes:** > > * SSO configuration not enabled > * Identity provider configuration error > * Network connection issues > > **Solutions:** > Contact your system administrator to verify SSO configuration at **System Settings** → **Authentication** → **Web App External User Verification**. > [accordion] User cannot log in, prompted with 'Authentication method not configured' > > **Root Cause Analysis:** > No authentication methods are currently enabled, or all methods have been disabled by the administrator. > > **Solutions:** > > 1. Check **Authentication** → **Members** configuration > 2. Enable at least one authentication method > 3. Confirm email service configuration is normal (if using email verification code) > 4. Test SSO connection status (if using SSO) > [accordion] Email verification code cannot be sent or received > > **Possible Causes:** > > * SMTP email service configuration error > * Email server connection issues > * Invalid user email address > * Email filtered by spam > > **Solutions:** > > 1. Verify SMTP server settings and connectivity > 2. Confirm email server authentication credentials > 3. Validate user email addresses > 4. Advise users to check their spam/junk folders > 5. Verify service status with your email provider > [accordion] SSO login failure or cannot redirect > > **Possible Causes:** > > * Identity provider configuration error > * Incorrect callback address settings > * User lacks permissions in identity provider > * Network connection issues > > **Solutions:** > > 1. Check identity provider configuration information > 2. Confirm the callback URL is correctly configured > 3. Verify user account status and permissions in your identity provider > 4. Check network connectivity to your identity provider > 5. Review system logs for detailed error messages With proper enterprise user authentication configuration, you can deliver a seamless AI application experience while maintaining security. We recommend selecting authentication strategies that align with your organization's security requirements and user base size. # Introduction Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/authentication/introduction Dify Enterprise delivers secure and reliable identity authentication solutions tailored to different user types. Whether it's internal employees accessing workspaces or external users utilizing Web Apps, our flexible authentication methods ensure secure access. Administrators can configure the most appropriate authentication approach based on their organization's security policies and user requirements. ## User Types Dify Enterprise categorizes users into two types: **Internal Members**: Users within your organization's system, including workspace-registered members or users added through the admin console. These users typically require workspace access to create and manage AI applications. **External Users**: Personnel outside your Dify Enterprise system, including users from other departments, business partners, external customers, or visitors who need to use your AI applications. These users typically only require access to specific Web Apps without workspace entry. ## Authentication Methods Each user type supports different authentication methods depending on their access requirements: | User Type | User Scope | Access Scenario | Supported Authentication Methods | | - | - | - | - | | Internal Users | Regular Members | Workspace | Email and Password, Email and Verification Code, Single Sign-On (SSO) | | Internal Users | Designated Group Members | Web App | Single Sign-On (SSO) | | External Users | External Visitors | Web App | Single Sign-On (SSO) | With proper identity authentication configuration, organizations can deliver seamless user access while maintaining robust data security. We recommend implementing Single Sign-On (SSO) as your primary method to achieve centralized identity management and enhance both user experience and administrative efficiency. ## Configuration Guide Choose the appropriate configuration guide based on your requirements: * [Internal User Authentication](./enterprise-user-auth) - Set up multiple authentication methods for internal team members * [Web App External User Authentication](./webapp-external-user-auth) - Configure secure access for external users to your applications # Web App External User Authentication Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/authentication/webapp-external-user-auth This authentication method is designed for Web Apps with publishing permissions set to "Authenticated External Users". External users can access Web Apps through authentication without needing to register Dify Enterprise accounts. > External users are individuals who are not part of your Dify Enterprise system. This authentication method enables organizations to control application access while monitoring and managing external users through third-party identity providers. **Use Cases** Consider a scenario where IT staff have built AI assistants for company employees, but not everyone has joined the Dify Enterprise system. However, all employees exist in a third-party identity provider. External user authentication allows these users to access applications through SSO without Dify registration. This approach is ideal when providing AI services to customers, partners, or other external stakeholders. ## Authentication Process **1. User Access** User clicks on the web application link **2. Automatic Redirect** System redirects to your configured SSO login page **3. Identity Verification** User authenticates through your identity provider **4. Authorization Callback** Upon successful authentication, user returns to the application **5. Start Using** User accesses the Web App and begins using the service ## Configuration Steps ### Prerequisites Before you begin, verify that: * Dify Enterprise is deployed and running * You have system administrator access * Your SSO identity provider is configured and ready ### Step 1: Configure SSO Identity Provider 1. Access the **Dify Enterprise Admin Console** 2. Go to **Authentication** → **Web App External Users** 3. Click **Configure** in the "SSO Identity Provider" section ![](https://assets-docs.dify.ai/2025/06/a738885cd51b088a2292742d03b6f271.png) Configure based on your specific identity provider. For detailed setup instructions, see [Configure SSO Authentication](/en/3.13.x/administer/sso/introduction). ### Step 2: Enable External User Authentication 1. Once configuration is complete, locate the **Enable SSO** toggle 2. Switch it to **On** > [!NOTE] > > If SSO is configured but not enabled, the **Authenticated External Users** option will be unavailable in Web App publishing permissions. Learn more about this in [Application Access Permission Management](/en/3.13.x/use/publish/webapp/web-app-settings). ### Step 3: Test Authentication Configuration 1. Set Web App permissions to **Authenticated External Users** during publishing 2. Share the Web App URL with external users 3. Verify proper redirection to the SSO login page 4. Test the complete login flow with a test account 5. Confirm successful Web App access ## Common Issues > [accordion] Access denied when accessing Web App > > **Possible Causes:** > > * SSO configuration not enabled > * Identity provider configuration error > * Network connection issues > > **Solutions:** > > 1. Contact your system administrator to verify SSO configuration at **System Settings** → **Authentication** → **Web App External User Verification** > 2. Ensure the user exists in your third-party identity provider's member list > [accordion] Cannot redirect to SSO login page > > **Possible Causes:** > > * SSO configuration not enabled > * Identity provider configuration error > * Network connection issues > > **Solutions:** > > 1. Verify SSO is enabled > 2. Review identity provider configuration > 3. Test network connectivity and DNS resolution > 4. Review system error logs > [accordion] Cannot return to Web App after SSO login > > **Possible Causes:** > > * Incorrect callback address configuration > * Token verification failure > * Insufficient user permissions > > **Solutions:** > > 1. Verify callback URL configuration in your identity provider. Find the correct URL at **Admin Console** → **Authentication** → **Web App External Users** > 2. Confirm the client secret is correct > 3. Check user permissions in your identity provider > [accordion] Some users cannot authenticate through SSO > > **Possible Causes:** > > * User account disabled > * Permission group configuration issues > * Attribute mapping mismatch > > **Solutions:** > > 1. Verify user account status in your identity provider > 2. Review user's organizational structure and permission assignments > 3. Update attribute mapping configuration # Branding Settings Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/branding ## Overview System administrators can configure unified brand identities for the entire Dify Enterprise Edition, including application titles, email notifications, login page logos, and workspace logos. By customizing brand elements, the Dify Enterprise platform will follow your corporate visual identity, providing users with a consistent and professional experience. ## Accessing Branding Settings 1. Log in to the Dify Enterprise Edition admin panel using a system administrator account. 2. Click the **Branding** option in the left navigation menu. 3. Customize the branding configuration options according to your requirements. ## Branding Configuration Options The Enterprise Edition branding settings provide three main configuration options, each targeting different display areas of the platform: ### 1. Application Title This option allows you to set the application name displayed in browser tabs and emails. * **Purpose**: Used in browser tabs and email titles. * **Requirements**: Supports up to 50 characters. ### 2. Login Page Logo This option controls the logo image displayed on the login page. * **Purpose**: This logo appears on the login page. * **Requirements**: For best results, we recommend using a PNG format image with any width × 40px height. Ensure the logo size is reasonable to maintain an aesthetically pleasing page layout. ### 3. Workspace Logo This option controls the logo image displayed within the workspace. * **Purpose**: This logo appears in the upper left corner of the workspace. * **Requirements**: Unified logo format suitable for display in the navigation area. * **Recommendations**: Use an image with a style consistent with the login page logo to maintain brand consistency. We recommend keeping the logo size within a reasonable range to ensure an aesthetically pleasing page layout. # Credential Management Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/credential-management Credential Management centralizes the configuration and control of authentication information (such as API Key, Access Token) required by plugins, supporting multi-level authorization and usage control across Global—Workspace. With unified management, enterprises can balance security compliance and flexibility: IT administrators centrally maintain global credentials in the Admin Dashboard and can optionally allow workspaces to maintain local credentials. ## 1. Feature Overview Credential Management addresses the following common issues: * **Duplicate configuration**: Multiple workspaces need the same credential. If each maintains it separately, it leads to redundancy and inconsistency. * **Security risks**: Decentralized credential management increases the risk of leakage and misuse, not meeting enterprise security requirements. * **Governance challenges**: Without unified policy control, it is hard to clarify which workspaces can use credentials and which plugins are allowed to use self-managed credentials. ### 1.1 Value * **Centralized management**: System administrators configure and maintain credentials in the Admin Dashboard and assign them to specific workspaces. * **Reduced security risk**: Sensitive information is centrally governed to avoid credentials being scattered across workspaces. * **Flexible and controllable**: Support allowing or forbidding workspaces to create their own credentials, with exception mechanisms to balance security and flexibility. * **Unified updates**: When credentials are updated or rotated, modify them once in the Admin Dashboard to take effect globally. ### 1.2 Use Cases * The enterprise IT department centrally manages model vendor API Keys and assigns them to business teams' workspaces as needed. * Production environment plugins (such as databases) require global unified configuration, while test plugins allow workspace-managed credentials. * Different credentials are required for predefined models and custom models, with flexible selection in Application Orchestration or Model Provider pages. ### 1.3 Core Concepts **Plugin types** * Model plugins: e.g., OpenAI, Claude, Gemini * Tool plugins: e.g., database, HTTP caller, Google Maps **Credential types** * Tool Plugin Credential: Authentication information required by tool plugins * Model Plugin Credential (Predefined Model, Custom Model): Authentication information required by model plugins **Credential levels** * Global credential: Created by system administrators in the Admin Dashboard, assigned to multiple workspaces; referenceable in workspaces but not editable * Workspace credential: Created within a workspace by workspace administrators or application orchestrators; visible only to that workspace; whether it is allowed is determined by credential policies ## 2. Instructions ### 2.0 Quick Start A typical Credential Management workflow includes three steps: **Create global credential > Assign to workspace > Reference in workspace**. The following example uses the OpenAI plugin: 1. **Create a credential in the Admin Dashboard** Admin Dashboard > Credential Management > Model Plugin Credential > 【Add Credential】 Select the OpenAI plugin and version, enter the credential name and API Key, then save. 2. **Assign the credential to the target workspace** Find the newly created credential in the list, click 【Assign Credential】, select the target workspace, and click 【Assign】. 3. **Reference the credential in the workspace** Go to the target Workspace > Settings > Model Provider > OpenAI > Configure In the credential dropdown on the configuration page, select the assigned global credential. With these steps, you complete an end-to-end credential configuration and usage flow. For more complex scenarios (such as Tool Plugin Credentials, custom models, Credential Policy Settings), refer to the detailed sections below. ![](https://assets-docs.dify.ai/2025/09/c55a796a868770f82e6b42cf1effe150.png) ### 2.1 Access Paths * **Admin Dashboard**: Admin Dashboard > Credentials You can add credentials, edit, assign credentials, delete, and configure credential policy settings. * **Workspace**: Tools, Workspace > specific application > Orchestration, Settings > Model Provider You can view assigned global credentials, create workspace credentials when policies allow, and choose credentials in Tools, Model Provider, or Orchestration. ### 2.2 Credential List On the Credential Management page of the Admin Dashboard, the list displays all created global credentials grouped by plugin, including: * Plugin version * Credential name * Model (applies to model plugins): indicates whether the credential applies to a predefined model or a custom model * Number of assigned workspaces (hover to view the detailed list) * Created time, updated time * Actions: Details, Assign Credential, Delete Credential ### 2.3 Add Tool Plugin Credential On the Tool Plugin Credential page, you can add credentials for installed tool plugins: 1. Click 【Add Credential】 2. Select the target plugin and version (installed plugins only) 3. Enter a credential name (must be unique within this plugin) 4. Fill in credential parameters as required by the plugin 5. Click 【Save】; the system will validate the credential After saving successfully, no workspaces are assigned by default. You can choose 【Assign Now】 to assign immediately or assign later from the credential list. **Common prompts:** * **Current plugin does not require credentials. Please select another plugin**: The selected plugin does not need a credential * **Credential validation failed**: Parameter error or network issue; check the API Key and network connectivity * **Name already exists**: Duplicate credential name; change it to a unique value ![](https://assets-docs.dify.ai/2025/09/1536da7ca9f5f09deee5a439f9dfdb1d.png) ### 2.4 Add Model Plugin Credential On the Model Plugin Credential page, you can create credentials for predefined models or custom models: 1. Click 【Add Credential】 2. Select the model plugin and version 3. Choose Model Type: * **Predefined Model**: Enter credential name and parameters * **Custom Model**: Select Model Type and enter the model name, then enter credential name and parameters 4. Click 【Save】; the system will validate the credential After saving successfully, no workspaces are assigned by default. You can assign as prompted or assign later. **Common prompts:** * **Credential validation failed**: Check the vendor API Key or network status * **Name already exists**: Duplicate name within the plugin; change it to a unique value ![](https://assets-docs.dify.ai/2025/09/a2f87f646b67a2129b11c46300c09d2f.png) ### 2.5 Edit Credential Click 【Details】 in the credential list to modify the credential name, version, and parameters. * Plugin type cannot be changed * For Model Plugin Credentials, "whether it is a predefined model," "Model Type," and "Model Name" cannot be changed * When switching versions, compatible fields are migrated automatically; incompatible fields must be entered manually ### 2.6 Assign Credential Click 【Assign Credential】 in the credential list to select target workspaces for assignment. Only assigned workspaces can use the credential in Tools, Model Provider, or Orchestration. When removing a workspace on the assignment page, the system detects whether any applications in that workspace are referencing the credential. If so, it lists the affected applications and warns that calls will fail after removal. To ensure normal operation, replace the credential in the workspace first, then remove the assignment. > **Note**: When removing Model Plugin Credentials, the system can only detect whether the workspace is using the credential. Because model credentials take effect at the workspace level, they cannot be traced down to specific applications. The same rule applies to deleting credentials. ![](https://assets-docs.dify.ai/2025/09/1808ca2c662c06e5cb5e97d7c56bd354.png) ### 2.7 Delete Credential Click 【Delete Credential】 to remove a credential permanently. The system checks whether any applications are referencing the credential. If references exist, the system lists the dependencies and warns that related applications will fail to invoke the plugin after deletion. Delete only after completing replacement. ### 2.8 Configure Credential Policies Credential policies control whether workspaces may use custom credentials. Typical scenarios include: * Payment-related plugins (such as PayPal, Alipay) are only allowed to use global credentials configured in the Admin Dashboard. * Forbid workspaces from using custom credentials and enforce reliance on global credentials for specified models. On the Credential Policy Settings page, you can configure whether workspaces are allowed to use custom credentials and set exceptions for specific plugins: * **Allow**: Workspaces can create and use custom credentials * **Forbid**: Workspace custom credential entry is disabled; cannot create or use * **Exception plugins**: Not bound by the global restriction; can be allowed individually When saving policies, the system automatically detects applications currently using custom credentials that conflict with the policy. If conflicts are detected, the system lists the affected applications and supports export as CSV. After confirming and saving, the affected applications will no longer be able to invoke the plugin successfully. > **Note**: For model plugins, the system can only detect whether the workspace is using related credentials. Because model credentials take effect at the workspace level, they cannot be traced down to specific applications. ![](https://assets-docs.dify.ai/2025/09/a9a96739b488b686ae8608cd9869d3aa.png) ### 2.9 Use Credentials in Workspaces Workspace administrators and orchestrators can use credentials in the following places: * **Tools page or Model Provider settings**: Select an assigned global credential * **Create a workspace credential (when policies allow)**: Click 【Add Credential】, fill in parameters, and save * **Orchestrate applications**: Select a credential in node configuration, or create a workspace credential when allowed When the credential policy forbids custom credentials, existing workspace credentials display "Custom credential is currently unavailable," and new ones cannot be added. If a global credential has been deleted, you will see "Credential has been deleted." Switch to another credential or contact an administrator to adjust the configuration. ![](https://assets-docs.dify.ai/2025/09/76e00dbb77e386061983ea6cc8c6e786.png) ## 3. Troubleshooting * **Credential has been deleted**: The global credential was removed in the Admin Dashboard. Switch to another credential or contact the administrator to restore it. * **Credential unavailable**: Possibly due to assignment removal or the disabling of the workspace custom credential policy in the Admin Dashboard. Verify the assignment and contact the administrator to adjust if necessary. * **Credential validation failed**: Invalid API Key, parameter error, or network timeout. Check credential parameters and network, and regenerate the key if necessary. ## 4. FAQ ### Why can't I create a credential in a workspace? Whether a workspace can create credentials depends on the credential policy configured in the Admin Dashboard. If the policy forbids custom credentials for specific plugins, the "Create Credential" entry for those plugins will be hidden in that workspace, and only global credentials can be used. ### What is the difference between global credentials and workspace credentials? Global credentials are maintained centrally in the Admin Dashboard and can be assigned to multiple workspaces. Workspace credentials are visible only within a single workspace, and whether they are allowed depends on the credential policy. ### After forbidding workspace custom credentials for a specific plugin in the policy, what happens to existing custom credentials? Once the policy takes effect, existing custom credentials for that plugin in the workspace will be immediately marked "unavailable," and can no longer be used or created. Related applications must switch to global credentials. ### Why do applications fail after removing a workspace on the credential assignment page? After you remove a workspace from a credential's assignments, that workspace loses the right to use the credential. If applications still reference it, they can no longer invoke the related service and will error. To avoid impact, replace the credential in the applications first, then remove the assignment. ### What is the difference between deleting a credential and removing a workspace on the assignment page? * **Delete credential**: Permanently removes the credential; all references across all workspaces and applications fail immediately. * **Remove workspace on the assignment page**: Only affects the removed workspace; applications in that workspace lose access to the credential, while other workspaces are unaffected. ### After a plugin is uninstalled, do global credentials remain? When a plugin version has been completely uninstalled from all workspaces, the corresponding global credentials are not deleted automatically. Such credentials remain in the system but can no longer be edited. You may switch the credential's plugin version to another installed version of that plugin, or delete the credential directly. ## 5. Best Practices * **Centralize sensitive credentials**: Configure global credentials in the Admin Dashboard to avoid scattering sensitive information. * **Establish a rotation mechanism**: Update credentials regularly—add replacements and assign them, switch usage, then reclaim old credentials. * **Export a dependency list before deleting or removing**: Ensure replacements are completed to avoid service interruption. * **Combine policies and exceptions**: Generally allow workspace-managed credentials; disable them for sensitive plugins, and set exceptions for a small number of plugins when needed. * **Use clear naming**: Credential names should clearly distinguish predefined models from custom models to simplify maintenance and troubleshooting. * **Clear roles and responsibilities**: System administrators handle global policies and sensitive operations; workspace administrators handle in-app replacement and selection. * **Test before production**: Validate credential and plugin version compatibility in a test workspace before enabling in production. # Push Telemetry to Your Observability Stack Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/data-push Stream Dify application metrics, token consumption, and user behavior to your own observability stack over the OpenTelemetry protocol Stream application metrics, token consumption, and user behavior data from Dify to your own monitoring system, BI platform, or data warehouse over the OpenTelemetry (OTel) open standard. Consolidating this data across workspaces supports operations analysis, cost allocation, and compliance reporting. Configure the push in the Enterprise Dashboard, under **Data Push** in the sidebar. For field-level definitions of every exported signal, see the [Data Push Data Dictionary](/en/3.13.x/administer/data-push-data-dictionary). ## Before You Start * An OpenTelemetry Collector reachable from the Dify deployment, with an OTLP receiver enabled for your chosen transport (by convention port `4318` for HTTP, `4317` for gRPC). The connection originates from the platform-managed Dify Enterprise Collector. * Access to the Enterprise Dashboard. ## What Gets Pushed | Signal | Coverage | Answers questions such as | | :- | :- | :- | | **Metrics** | Request count, error rate, token consumption, latency distribution, feedback count, retrieval count, application lifecycle | How is usage growing? Is the failure rate abnormal? Which application has the highest cost? | | **Traces** | `dify.workflow.run`, `dify.node.execution`, `dify.node.execution.draft` | Why did a workflow slow down? Which node is the latency bottleneck? Where exactly did an error occur? | | **Logs** (separate pipeline) | Message runs, tool calls, content moderation, knowledge retrieval, suggested questions, prompt generation details | What were the inputs, outputs, and context for a specific business operation? | > [!NOTE] > > Data Push transmits Metrics and Traces over OTLP. Logs are not pushed: structured event logs are written as JSON to the API/Worker Pod standard output. > > To make them searchable, deploy your own log collector (Promtail, Fluent Bit, or Vector) to ship Pod output to Loki or OpenSearch. That log pipeline is separate from the OTel Collector configured on this page. ## Configure the Connection 1. In the Enterprise Dashboard sidebar, open **Data Push**. 2. Click **Parameter Config** in the top-right corner to open the **Parameter Configuration** dialog. 3. Choose a **Configuration Mode**: **Unified** pushes Metrics and Traces to one endpoint (recommended when you run an OpenTelemetry Collector); **Separate** configures the **Traces** and **Metrics** tabs independently. 4. Fill in the connection fields: * **Endpoint URL**: the OpenTelemetry Collector address, with an `http://`, `https://`, `grpc://`, or `grpcs://` scheme (e.g. `http://otel-collector:4318`). An `https://` or `grpcs://` endpoint enables TLS; the scheme does not select the wire format, so set **Transport Protocol** to match your Collector's receiver. * **Transport Protocol**: `http/protobuf` (recommended), `grpc` (higher throughput; suited to stable internal networks), or `http/json` (debugging only; lower performance). * **Compression**: `gzip` (recommended) or `none`. * **Timeout**: push timeout as a duration in seconds, e.g. `5s`. * **Headers**: key-value pairs for authentication and similar needs (e.g. `Authorization: Bearer `); click **Add Header** to add entries. * **Advanced Settings** (for TLS endpoints): upload the **Certificate File (CA)**, the certificate of the CA that issued your Collector's server certificate (your own CA for self-signed certificates; the issuing public CA's certificate, such as the Let's Encrypt root, otherwise). It may be omitted only when **Skip Certificate Verification** is enabled (skipping verification is not recommended for production). For **Mutual TLS (mTLS)**, also upload the **Client Key File** and **Client Certificate File**. 5. Click **Test Connectivity**. It validates the connection and reports the reason for any failure (unreachable host, invalid certificate, etc.). 6. Click **Save Configuration** and confirm with **Confirm Restart and Apply**. If the service is running, saving restarts the push service and may briefly interrupt data transfer. > [!NOTE] > > For production, use a TLS endpoint and configure authentication headers. ## Start and Stop the Push Service * **Start**: when stopped, click **Connect and Push Data** and confirm. The status changes to **Service Running**. * **Stop**: when running, click **Stop Push Service** and confirm. The status changes to **Service Stopped**; stopping interrupts data transfer. ## Verify the Setup These checks assume your Collector already routes metrics to Prometheus and traces to Jaeger; if a query returns nothing, check that routing first. Prometheus stores OTel metric names in underscore form (`dify.requests.total` becomes `dify_requests_total`). 1. On the **Data Push Configuration** page, confirm the status shows **Service Running**. 2. Run a published workflow and confirm that `dify_requests_total{type="workflow"}` is queryable in Prometheus. 3. Run a multi-node workflow and confirm that complete `dify.workflow.run` and `dify.node.execution` traces are visible in Jaeger. 4. Debug a workflow in Studio (the Dify app-building workspace) and confirm `dify_requests_total{type="draft_node"}` in Prometheus and the `dify.node.execution.draft` span name in Jaeger. 5. Verify that tool call, knowledge retrieval, and content moderation events appear correctly in the log platform (requires the stdout log pipeline described in What Gets Pushed). 6. With content push disabled (the default; see Control Input/Output Content), verify that sensitive fields are replaced with `ref:{id_type}={uuid}`. Gated fields are listed in the [Data Push Data Dictionary](/en/3.13.x/administer/data-push-data-dictionary). > [!NOTE] > > The Operation Name dropdown in a Trace platform only lists Span names that the backend has already received. It does not pre-populate with all Span names the product supports. ## Monitor the Push Service The **Data Push Configuration** page (opened from **Data Push** in the sidebar) shows the real-time service status by default. **Status 1: Service Stopped** * The page shows "Not connected. Please configure parameters and start the connection." * Click **Connect and Push Data** on the right to connect, or click **Parameter Config** in the top-right to begin configuration. **Status 2: Service Running** The page displays: * **Status indicator**: green light + **Service Running**. * **Connection Start Time**: when the current connection began (YYYY-MM-DD HH:mm:ss). * **Data statistics**: **Data Pushed** (real-time, MB/GB) and **UnPushed or Buffered Data** currently held in the buffer. * **Recent Data Push Log**: exception and network error logs reported by OpenTelemetry. **Status 3: Service Error** * **Status indicator**: orange light + **Service Error**. Check the **Recent Data Push Log** and fix the exception to avoid data loss. > [!WARNING] > > Push uses an asynchronous mechanism and **does not affect the main request path**. When a push fails or the connection drops, data is held in a FIFO buffer and forwarded once connectivity is restored. The built-in Span queue holds **2,048 Spans** and flushes batches every 5 seconds. When the buffer is full, the newest data is dropped to prevent user-facing latency. Metrics and structured event logs use separate paths and are not subject to this queue limit. > > The page surfaces the scenarios that may cause data loss: push service errors, buffer overflow from a slow downstream consumer, or a service restart. Review the status and logs here regularly, and configure alerts on your Collector side (e.g. connection drops, backlog exceeding a threshold) for timely response. ## Control Input/Output Content Whether Input/Output content is included is controlled by `ENTERPRISE_INCLUDE_CONTENT`, an environment variable on the Dify API service (default `false`). Changing it takes effect after a redeploy; see the [environment variable reference](/en/3.13.x/deploy/advanced-configuration/environment-variables). * **Disabled (default)**: content fields are replaced with reference strings in the form `ref:{id_type}={uuid}`; metadata such as Message ID, user ID, and application ID is still pushed. Use the UUID to look up the corresponding record (workflow run, message) in the Dify database. * **Enabled**: request inputs and model outputs are included in the exported data. Keep content push disabled in any environment with strict data privacy requirements. ## Plan for Production ### Architecture and Responsibility Boundary The diagram below shows how the Dify Enterprise telemetry engine connects to your observability stack, along with the responsibility boundary: ```text theme={null} Dify API/Worker ↓ OTLP gRPC (async, built-in buffer) Dify Enterprise Collector (platform-managed, receives and forwards) ↓ OTLP (customer-configured endpoint) Customer OTel Collector (customer-managed) ├──► Prometheus (scrapes /metrics) → Grafana └──► Jaeger / Tempo (Traces) Dify API/Worker stdout (JSON event logs) └──► your log collector (Promtail / Fluent Bit / Vector) ──► Loki / OpenSearch ``` 1. **Dify API** generates business metrics, traces, and events. These are written to an internal buffer first and then forwarded asynchronously by the OTel SDK. 2. **Dify Enterprise Collector** receives data over OTLP gRPC, applies batch and aggregation processors, and writes the push service's runtime status (connection time, bytes pushed, etc.) to the Enterprise DB for display in the Enterprise Dashboard. 3. Its **Exporter** sends data to the customer-provided OpenTelemetry Collector. The destination endpoint, protocol, TLS, and authentication are determined by the Data Push configuration. 4. The customer Collector routes data to Prometheus/Thanos (Metrics), Jaeger/Tempo (Traces), and similar backends. Grafana or enterprise BI tools query and visualize data from those backends. > [!WARNING] > > **Responsibility boundary**: you do not need to modify Dify's internal buffer, OTel SDK, Enterprise Collector processors, or Enterprise DB. > > On your side, plan the destination Collector, backend storage, query and visualization, alerting, access control, and data retention policies. ### Size Your Collector Estimate your daily volume first: ```text theme={null} Daily Trace volume ≈ production workflow runs + production node executions + draft node executions Daily business event volume ≈ messages + tool calls + moderation checks + retrievals + suggested question generations + conversation name generations + prompt generations + feedback events ``` The following sizing targets apply to the **customer-side OTel Collector**, not the Dify Enterprise Collector. | Concurrency scale | Recommended customer Collector config | Key concerns | | :- | :- | :- | | POC / small production | 1 replica (2 vCPU, 4 GB) | Validate the destination endpoint, data routing, and dashboard alignment. | | Department-scale production | 2 replicas (4 vCPU, 8 GB) with HA failover | Peak queue depth, export timeouts, reliable recovery during rolling upgrades. | | Enterprise high-concurrency | Horizontally scaled cluster with Kafka/RabbitMQ message buffering | Partition routing, rate limiting, cross-region failover, and durable queues. | In high-concurrency deployments, prefer the `grpc` protocol, and ensure the Collector has sufficient resources: a slow consumer causes platform-side buffer overflow and data loss. The concurrency thresholds vary significantly with Workflow complexity, node count, and message frequency. Treat these specifications as starting points and validate them with load tests using actual peak traffic before procurement. ### Data Retention The following are recommended starting retention values for your observability platform (Dify does not manage storage; plan storage costs on your side): * Metrics: 15–30 days to start; extend to 90 days or longer for trend analysis. * Traces: 3–7 days to start. ## Troubleshooting * **Cannot connect to the OpenTelemetry Collector**: check that the Endpoint URL is correct and the network is reachable. For a TLS endpoint, verify the CA certificate, client key, and client certificate are valid and in the correct format. Use **Test Connectivity** to see the specific error. * **Data push interrupted**: check the **Recent Data Push Log** for network instability or Collector errors. Verify the Collector is running and has not reached its ingestion limit. * **Backlog growing continuously**: the Collector is consuming data more slowly than it is produced, or network latency is high. Backlogged data is held in the buffer and forwarded once connectivity is restored; if the buffer fills up, new data is dropped. Increase the Collector's resources or scale out. * **Configuration save fails**: ensure all required fields are filled in. For a TLS endpoint, confirm that the certificate files have been uploaded successfully. * **Data loss**: can occur during a service error, buffer overflow, or system restart (this is intentional degradation to protect the main request path). If data loss is unacceptable, increase the Collector's processing capacity to avoid sustained backlog. # Data Push Data Dictionary Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/data-push-data-dictionary Field-level reference for all telemetry signals emitted by Dify Enterprise via the Data Push feature Field-level reference for every telemetry signal Dify Enterprise emits through Data Push. For configuring and operating the push service itself, see [Data Push](/en/3.13.x/administer/data-push). ## Getting Started You do not need to read every table. Jump directly to the signal layer that matches your observability goal. ### Scenario-to-Signal Map | Scenario or business need | Preferred signal | Target platform | Example signal or event | | :- | :- | :- | :- | | Total requests, success rate, error rate, token consumption | `Metrics` (Counter) | Prometheus / Grafana | `dify.requests.total`, `dify.tokens.total` | | System throughput, latency distribution (P50/P95/P99) | `Metrics` (Histogram) | Prometheus / Grafana | `dify.workflow.duration`, `dify.message.time_to_first_token` | | Why a workflow slowed down, bottleneck node, error location | `Traces` (Spans) | Jaeger / Tempo | `dify.workflow.run`, `dify.node.execution` | | Detailed inputs/outputs, tool parameters, retrieval results for a specific run | `Structured Logs` | Loki / Elasticsearch | `span_detail`, `dify.tool.execution` | ### Telemetry Data Flow and Routing All telemetry signals exported by Dify comply with the OpenTelemetry specification and can be split and routed by a standard OTel Collector: ```text theme={null} Dify Enterprise Telemetry Engine (OTel Exporter) ├── Metrics ──► Prometheus Exporter ──► Prometheus / Grafana Dashboard ├── Traces ──► OTel / OTLP gRPC ──► Jaeger / Grafana Tempo └── Logs ──► Pod stdout (JSON) ──► your log collector ──► Loki / Elasticsearch ``` *** ## Transmission Rules and Resource Attributes ### Resource Attributes Global environment metadata attached to every exported OTel signal: | Attribute | Type | Example | Description | | :- | :- | :- | :- | | `service.name` | string | `dify` | Name of the service that produced the telemetry data | | `host.name` | string | `dify-api-7f8b` | Host or Pod identifier of the producing instance | ### Common Identity and Correlation Attributes Spans carry the `dify.`-prefixed form; metric labels and the correlation keys on logs (`trace_id`, `span_id`, `tenant_id`, `user_id`) use the bare form. Rows listing two names cover both cases. | Attribute | Type | Description | | :- | :- | :- | | `tenant_id` / `dify.tenant_id` | string | Tenant identifier | | `app_id` / `dify.app_id` | string | Application identifier; the primary dimension for filtering metrics and logs | | `dify.workflow.id` | string | Workflow definition ID | | `dify.workflow.run_id` | string | Unique ID for a single workflow run instance | | `dify.message.id` | string | Unique message ID | | `dify.conversation.id` | string | Conversation context ID (optional) | | `trace_id` / `dify.trace_id` | string | OTel correlation Trace ID (32-character hex string) | | `span_id` | string | OTel Span ID (16-character hex string) | | `user_id` / `gen_ai.user.id` | string | End-user identifier that triggered the request (optional) | | `apprunner.environment_id` | string | Deployed environments: ID of the environment for this run | | `apprunner.deployment_id` | string | Deployed environments: ID of the application deployment for this run | | `apprunner.revision_id` | string | Deployed environments: ID of the deployment revision used for this run | The three `apprunner.*` attributes apply to workflow Spans (`dify.workflow.run`), node Spans (`dify.node.execution`), and their companion logs in deployed environments. They aren't used as metric labels. ### OTel-to-Prometheus Naming Conventions OTel signal names are automatically converted to underscore format when ingested by Prometheus. Counters gain a `_total` suffix; Histograms produce `_bucket`, `_sum`, and `_count` series, plus a unit suffix (`_seconds` for metrics measured in `s`), as the example below shows. The table below shows common examples; all other metrics follow the same rules. | OTel name | Prometheus query name | | :- | :- | | `dify.requests.total` | `dify_requests_total` | | `dify.errors.total` | `dify_errors_total` | | `dify.tokens.total` | `dify_tokens_total` | | `dify.workflow.duration` | `dify_workflow_duration_seconds_bucket` and related Histogram series | ### Null Values and Content-Gated Fields * **Null value behavior**: attributes with no value are omitted from Trace Spans; in structured log JSON output they are explicitly rendered as `null`. * **Content-gating**: attributes that may hold sensitive text (Input/Output/Query/Prompt) are gated by `ENTERPRISE_INCLUDE_CONTENT`. When content push is disabled (the default), the value is replaced by a reference string (e.g. `ref:{id_type}={uuid}`) rather than `null`. * **High-cardinality warning**: `tenant_id`, `app_id`, and `trace_id` are high-cardinality dimensions. Do not store unbounded text fields as Prometheus labels. *** ## Traces and Spans Traces present the complete time sequence and nesting topology of a single call. The OTel `trace_id` is derived deterministically from the business run ID, so every signal of one run shares it; query Jaeger or Tempo by this `trace_id`. The `dify.trace_id` attribute keeps the original business UUID (for example the workflow run ID) for joining with business data. ### dify.workflow\.run | Attribute | Type | Description | | :- | :- | :- | | `dify.trace_id` | string | Business Trace ID (workflow run ID) | | `dify.tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.workflow.id` | string | Workflow definition ID | | `dify.workflow.run_id` | string | Unique ID for this run | | `dify.workflow.status` | string | `succeeded`, `failed`, `stopped`, etc. | | `dify.workflow.error` | string | Error message on failure | | `dify.workflow.elapsed_time` | float | Total execution time (seconds) | | `dify.invoke_from` | string | `api`, `webapp`, `debug` | | `dify.conversation.id` | string | Conversation ID (optional) | | `dify.message.id` | string | Message ID (optional) | | `dify.invoked_by` | string | User ID that triggered the run | | `gen_ai.usage.total_tokens` | int | Total token count across all nodes (optional) | | `gen_ai.user.id` | string | End-user identifier (optional) | | `dify.parent.trace_id` | string | Parent workflow trace ID (optional) | | `dify.parent.workflow.run_id` | string | Parent workflow run ID (optional) | | `dify.parent.node.execution_id` | string | Parent node execution ID (optional) | | `dify.parent.app.id` | string | Parent application ID (optional) | ### dify.node.execution | Attribute | Type | Description | | :- | :- | :- | | `dify.trace_id` | string | Business Trace ID | | `dify.tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.workflow.id` | string | Workflow definition ID | | `dify.workflow.run_id` | string | Workflow run ID | | `dify.message.id` | string | Message ID (optional) | | `dify.conversation.id` | string | Conversation ID (optional) | | `dify.node.execution_id` | string | Unique node execution ID | | `dify.node.id` | string | Node ID in the Workflow graph | | `dify.node.type` | string | Node type (see Appendix) | | `dify.node.title` | string | Display title | | `dify.node.status` | string | `succeeded`, `failed` | | `dify.node.error` | string | Error message on failure | | `dify.node.elapsed_time` | float | Execution time (seconds) | | `dify.node.index` | int | Execution sequence index | | `dify.node.predecessor_node_id` | string | ID of the node that triggered this node | | `dify.node.iteration_id` | string | Iteration ID (optional) | | `dify.node.loop_id` | string | Loop ID (optional) | | `dify.node.parallel_id` | string | Parallel branch ID (optional) | | `dify.node.invoked_by` | string | User ID that triggered execution | | `gen_ai.usage.input_tokens` | int | Prompt token count (LLM nodes only) | | `gen_ai.usage.output_tokens` | int | Completion token count (LLM nodes only) | | `gen_ai.usage.total_tokens` | int | Total token count (LLM nodes only) | | `gen_ai.request.model` | string | LLM model name (LLM nodes only) | | `gen_ai.provider.name` | string | LLM provider name (LLM nodes only) | | `gen_ai.user.id` | string | End-user identifier (optional) | ### dify.node.execution.draft Carries the same attributes as `dify.node.execution`, but is produced only during a single-node test or a draft preview run in the Studio canvas. Use this signal to separate production telemetry from test runs. *** ## Metrics ### Counters All counters are cumulative and are never sampled: the trace sampling rate (`ENTERPRISE_OTEL_SAMPLING_RATE`, see the [environment variable reference](/en/3.13.x/deploy/advanced-configuration/environment-variables)) does not affect them. #### Token Counters | Metric | Unit | Description | | :- | :- | :- | | `dify.tokens.total` | `{token}` | Total tokens consumed | | `dify.tokens.input` | `{token}` | Input (prompt) tokens | | `dify.tokens.output` | `{token}` | Output (completion) tokens | **Labels**: `tenant_id`, `app_id`, `operation_type`, `model_provider`, `model_name`, `node_type` (for `node_execution` only) > [!WARNING] > > The workflow-level `dify.tokens.total` already includes tokens from all `node_execution` operations. Filter by `operation_type` to avoid double-counting. **Token hierarchy and query patterns** Token metrics are emitted at multiple levels. Understanding the hierarchy prevents double-counting: ```text theme={null} App-level total ├── workflow ← sum of all node_execution tokens (do not add together) │ └── node_execution ← per-node breakdown ├── message ← standalone (non-workflow chat apps only) ├── rule_generate ← standalone auxiliary LLM call ├── code_generate ← standalone auxiliary LLM call ├── structured_output ← standalone auxiliary LLM call └── instruction_modify← standalone auxiliary LLM call ``` **Key rule**: `workflow` tokens already include all `node_execution` tokens. Never add both together. * **Available labels on token metrics**: `tenant_id`, `app_id`, `operation_type`, `model_provider`, `model_name`, `node_type`. * **Application name** is carried on the trace side only, as `dify.app.name` on the span companion logs (see Span Companion Logs), never as a metric label. Use `app_id` in metric queries. * **Cost** exists only on the node companion logs (`dify.node.total_price`, see Span Companion Logs); there is no cost metric. #### Request Counter | Metric | Unit | Description | | :- | :- | :- | | `dify.requests.total` | `{request}` | Total operation count | The `type` label identifies the operation (for example `dify_requests_total{type="workflow"}`); additional labels vary by `type`: | Type | Additional labels | | :- | :- | | `workflow` | `tenant_id`, `app_id`, `status`, `invoke_from` | | `node` | `tenant_id`, `app_id`, `node_type`, `model_provider`, `model_name`, `status` | | `draft_node` | `tenant_id`, `app_id`, `node_type`, `model_provider`, `model_name`, `status` | | `message` | `tenant_id`, `app_id`, `model_provider`, `model_name`, `status`, `invoke_from` | | `tool` | `tenant_id`, `app_id`, `tool_name` | | `moderation` | `tenant_id`, `app_id` | | `suggested_question` | `tenant_id`, `app_id`, `model_provider`, `model_name` | | `dataset_retrieval` | `tenant_id`, `app_id` | | `generate_name` | `tenant_id`, `app_id` | | `prompt_generation` | `tenant_id`, `app_id`, `operation_type`, `model_provider`, `model_name`, `status` | #### Error Counter | Metric | Unit | Description | | :- | :- | :- | | `dify.errors.total` | `{error}` | Total failed operation count | The error counter uses the same `type` label; additional labels vary by `type`: | Type | Additional labels | | :- | :- | | `workflow` | `tenant_id`, `app_id` | | `node` | `tenant_id`, `app_id`, `node_type`, `model_provider`, `model_name` | | `draft_node` | `tenant_id`, `app_id`, `node_type`, `model_provider`, `model_name` | | `message` | `tenant_id`, `app_id`, `model_provider`, `model_name` | | `tool` | `tenant_id`, `app_id`, `tool_name` | | `prompt_generation` | `tenant_id`, `app_id`, `operation_type`, `model_provider`, `model_name` | #### Other Counters | Metric | Unit | Labels | | :- | :- | :- | | `dify.feedback.total` | `{feedback}` | `tenant_id`, `app_id`, `rating` | | `dify.dataset.retrievals.total` | `{retrieval}` | `tenant_id`, `app_id`, `dataset_id`, `embedding_model_provider`, `embedding_model`, `rerank_model_provider`, `rerank_model` | | `dify.app.created.total` | `{app}` | `tenant_id`, `app_id`, `mode` | | `dify.app.updated.total` | `{app}` | `tenant_id`, `app_id` | | `dify.app.deleted.total` | `{app}` | `tenant_id`, `app_id` | ### Histograms > [!NOTE] > > Unlike Counters, which can only produce averages (which extreme values can distort), Histograms support **calculations for the P50, P95, and P99 percentiles** that more accurately describe the actual distribution. > > Each Histogram in Prometheus expands into three series: `_bucket`, `_sum`, and `_count`. P95/P99 may return `NaN` in low-traffic time windows; increase the query window if this occurs. When latency is concentrated within 5 seconds, such as for TTFT or tool calls, percentile precision is limited. For higher-precision evaluation, extend the query window or contact the Dify team for bucket configuration details. | Metric | Unit | Labels | | :- | :- | :- | | `dify.workflow.duration` | `s` | `tenant_id`, `app_id`, `status` | | `dify.node.duration` | `s` | `tenant_id`, `app_id`, `node_type`, `model_provider`, `model_name`, `plugin_name` | | `dify.message.duration` | `s` | `tenant_id`, `app_id`, `model_provider`, `model_name` | | `dify.message.time_to_first_token` | `s` | `tenant_id`, `app_id`, `model_provider`, `model_name` | | `dify.tool.duration` | `s` | `tenant_id`, `app_id`, `tool_name` | | `dify.prompt_generation.duration` | `s` | `tenant_id`, `app_id`, `operation_type`, `model_provider`, `model_name` | *** ## Structured Logs Structured logs provide detailed business data. Logs fall into two categories: Span companion logs and standalone business logs. > [!NOTE] > > `ENTERPRISE_OTEL_SAMPLING_RATE` only affects the number of Spans sent to Trace backends such as Jaeger and Tempo. Structured logs (`span_detail` and `metric_only`) are always written to Pod standard output at 100% and are not controlled by the sampling rate. ### Span Companion Logs Signal type: `span_detail`. These logs are tightly coupled to a Trace Span (sharing `trace_id` and `span_id`) and contain content-gated detailed context. #### dify.workflow\.run companion log **Common attributes**: all Span attributes (see Traces section) plus: **Event attributes**: * `dify.event.name`: `dify.workflow.run` * `dify.event.signal`: `span_detail` * `trace_id`, `span_id`, `tenant_id`, `user_id` | Additional attribute | Type | Always present | Description | | :- | :- | :- | :- | | `dify.app.name` | string | No | Application display name | | `dify.workspace.name` | string | No | Workspace display name | | `dify.workflow.version` | string | Yes | Workflow definition version | | `dify.workflow.inputs` | string/JSON | Yes | Input parameters (content-gated) | | `dify.workflow.outputs` | string/JSON | Yes | Output results (content-gated) | | `dify.workflow.query` | string | No | User query text (content-gated) | #### dify.node.execution and dify.node.execution.draft companion logs **Common attributes**: all Span attributes (see Traces section) plus: **Event attributes**: * `dify.event.name`: `dify.node.execution` or `dify.node.execution.draft` * `dify.event.signal`: `span_detail` * `trace_id`, `span_id`, `tenant_id`, `user_id` | Additional attribute | Type | Always present | Description | | :- | :- | :- | :- | | `dify.app.name` | string | No | Application display name | | `dify.workspace.name` | string | No | Workspace display name | | `dify.invoke_from` | string | No | Invocation source | | `gen_ai.tool.name` | string | No | Tool name (tool nodes only) | | `dify.node.total_price` | float | No | Cost (LLM nodes only) | | `dify.node.currency` | string | No | Currency code (LLM nodes only) | | `dify.node.iteration_index` | int | No | Iteration index (iteration nodes) | | `dify.node.loop_index` | int | No | Loop index (loop nodes) | | `dify.plugin.name` | string | No | Plugin name (tool / knowledge nodes) | | `dify.credential.name` | string | No | Credential name (plugin nodes) | | `dify.credential.id` | string | No | Credential ID (plugin nodes) | | `dify.dataset.ids` | JSON array | No | Dataset IDs (knowledge nodes) | | `dify.dataset.names` | JSON array | No | Dataset names (knowledge nodes) | | `dify.node.inputs` | string/JSON | Yes | Node inputs (content-gated) | | `dify.node.outputs` | string/JSON | Yes | Node outputs (content-gated) | | `dify.node.process_data` | string/JSON | No | Processing data (content-gated) | ### Standalone Logs Logs without a structured Span. Their signal type is `metric_only`: the event feeds counters and carries its detail in this log, with no companion span. #### dify.message.run | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.message.run` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID (32-character hex) | | `span_id` | string | OTel Span ID (16-character hex) | | `tenant_id` | string | Tenant identifier | | `user_id` | string | User identifier (optional) | | `dify.app_id` | string | Application identifier | | `dify.message.id` | string | Message identifier | | `dify.conversation.id` | string | Conversation ID (optional) | | `dify.workflow.run_id` | string | Workflow run ID (optional) | | `dify.invoke_from` | string | `service-api`, `web-app`, `debugger`, `explore` | | `gen_ai.provider.name` | string | LLM provider | | `gen_ai.request.model` | string | LLM model | | `gen_ai.usage.input_tokens` | int | Input token count | | `gen_ai.usage.output_tokens` | int | Output token count | | `gen_ai.usage.total_tokens` | int | Total token count | | `dify.message.status` | string | `succeeded`, `failed` | | `dify.message.error` | string | Error message (if failed) | | `dify.message.duration` | float | Duration (seconds) | | `dify.message.time_to_first_token` | float | Time to first token / TTFT (seconds) | | `dify.message.inputs` | string/JSON | Inputs (content-gated) | | `dify.message.outputs` | string/JSON | Outputs (content-gated) | #### dify.tool.execution | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.tool.execution` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID | | `span_id` | string | OTel Span ID | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.message.id` | string | Message identifier | | `dify.tool.name` | string | Tool name | | `dify.tool.duration` | float | Duration (seconds) | | `dify.tool.status` | string | `succeeded`, `failed` | | `dify.tool.error` | string | Error message (if failed) | | `dify.tool.inputs` | string/JSON | Inputs (content-gated) | | `dify.tool.outputs` | string/JSON | Outputs (content-gated) | | `dify.tool.parameters` | string/JSON | Parameters (content-gated) | | `dify.tool.config` | string/JSON | Configuration (content-gated) | #### dify.moderation.check | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.moderation.check` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID | | `span_id` | string | OTel Span ID | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.message.id` | string | Message identifier | | `dify.moderation.type` | string | `input`, `output` | | `dify.moderation.action` | string | `pass`, `block`, `flag` | | `dify.moderation.flagged` | boolean | Whether the content was flagged | | `dify.moderation.categories` | JSON array | Categories that triggered the flag | | `dify.moderation.query` | string | Content (content-gated) | #### dify.suggested\_question.generation | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.suggested_question.generation` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID | | `span_id` | string | OTel Span ID | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.message.id` | string | Message identifier | | `dify.suggested_question.count` | int | Number of questions generated | | `dify.suggested_question.duration` | float | Duration (seconds) | | `dify.suggested_question.status` | string | `succeeded`, `failed` | | `dify.suggested_question.error` | string | Error message (if failed) | | `dify.suggested_question.questions` | JSON array | Generated questions (content-gated) | #### dify.dataset.retrieval | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.dataset.retrieval` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID | | `span_id` | string | OTel Span ID | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.message.id` | string | Message identifier | | `dify.dataset.id` | string | Dataset identifier | | `dify.dataset.name` | string | Dataset name | | `dify.dataset.embedding_providers` | JSON array | Embedding model provider (one per dataset) | | `dify.dataset.embedding_models` | JSON array | Embedding model (one per dataset) | | `dify.retrieval.rerank_provider` | string | Rerank model provider | | `dify.retrieval.rerank_model` | string | Rerank model name | | `dify.retrieval.query` | string | Search query (content-gated) | | `dify.retrieval.document_count` | int | Number of documents retrieved | | `dify.retrieval.duration` | float | Duration (seconds) | | `dify.retrieval.status` | string | `succeeded`, `failed` | | `dify.retrieval.error` | string | Error message (if failed) | | `dify.dataset.documents` | JSON array | Documents (content-gated) | #### dify.generate\_name.execution | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.generate_name.execution` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID | | `span_id` | string | OTel Span ID | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.conversation.id` | string | Conversation identifier | | `dify.generate_name.duration` | float | Duration (seconds) | | `dify.generate_name.status` | string | `succeeded`, `failed` | | `dify.generate_name.error` | string | Error message (if failed) | | `dify.generate_name.inputs` | string/JSON | Inputs (content-gated) | | `dify.generate_name.outputs` | string | Generated name (content-gated) | #### dify.prompt\_generation.execution | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.prompt_generation.execution` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID | | `span_id` | string | OTel Span ID | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.prompt_generation.operation_type` | string | Operation type (see Appendix) | | `gen_ai.provider.name` | string | LLM provider | | `gen_ai.request.model` | string | LLM model | | `gen_ai.usage.input_tokens` | int | Input token count | | `gen_ai.usage.output_tokens` | int | Output token count | | `gen_ai.usage.total_tokens` | int | Total token count | | `dify.prompt_generation.duration` | float | Duration (seconds) | | `dify.prompt_generation.status` | string | `succeeded`, `failed` | | `dify.prompt_generation.error` | string | Error message (if failed) | | `dify.prompt_generation.instruction` | string | Instruction (content-gated) | | `dify.prompt_generation.output` | string/JSON | Output (content-gated) | #### dify.app.created | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.app.created` | | `dify.event.signal` | string | `metric_only` | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.app.mode` | string | `chat`, `completion`, `agent-chat`, `workflow` | | `dify.app.created_at` | string | Timestamp (ISO 8601) | #### dify.app.updated | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.app.updated` | | `dify.event.signal` | string | `metric_only` | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.app.updated_at` | string | Timestamp (ISO 8601) | #### dify.app.deleted | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.app.deleted` | | `dify.event.signal` | string | `metric_only` | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.app.deleted_at` | string | Timestamp (ISO 8601) | #### dify.feedback.created | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.feedback.created` | | `dify.event.signal` | string | `metric_only` | | `trace_id` | string | OTel Trace ID | | `span_id` | string | OTel Span ID | | `tenant_id` | string | Tenant identifier | | `dify.app_id` | string | Application identifier | | `dify.message.id` | string | Message identifier | | `dify.feedback.rating` | string | `like`, `dislike`, `null` | | `dify.feedback.content` | string | Feedback text (content-gated) | | `dify.feedback.created_at` | string | Timestamp (ISO 8601) | #### dify.telemetry.rehydration\_failed A diagnostic event for telemetry pipeline health, emitted when a buffered telemetry payload cannot be reconstructed (rehydrated) for processing. A sustained rate indicates telemetry data loss. | Attribute | Type | Description | | :- | :- | :- | | `dify.event.name` | string | `dify.telemetry.rehydration_failed` | | `dify.event.signal` | string | `metric_only` | | `tenant_id` | string | Tenant identifier | | `dify.telemetry.error` | string | Error message | | `dify.telemetry.payload_type` | string | Payload type (see Appendix) | | `dify.telemetry.correlation_id` | string | Correlation ID | *** ## Content-Gated Attributes The following fields may contain user inputs, model outputs, document content, tool parameters, or feedback text. Raw values are transmitted only when content push is enabled on the deployment: `ENTERPRISE_INCLUDE_CONTENT` (default `false`; see the [environment variable reference](/en/3.13.x/deploy/advanced-configuration/environment-variables)). When disabled, these attributes are replaced with `ref:{id_type}={uuid}`. The `id_type` names the correlating entity (for example `workflow_run_id`, `node_execution_id`, or `message_id`); look up that record in the Dify database to retrieve the original content. | Attribute | Signal | | :- | :- | | `dify.workflow.inputs` | `dify.workflow.run` | | `dify.workflow.outputs` | `dify.workflow.run` | | `dify.workflow.query` | `dify.workflow.run` | | `dify.node.inputs` | `dify.node.execution` | | `dify.node.outputs` | `dify.node.execution` | | `dify.node.process_data` | `dify.node.execution` | | `dify.message.inputs` | `dify.message.run` | | `dify.message.outputs` | `dify.message.run` | | `dify.tool.inputs` | `dify.tool.execution` | | `dify.tool.outputs` | `dify.tool.execution` | | `dify.tool.parameters` | `dify.tool.execution` | | `dify.tool.config` | `dify.tool.execution` | | `dify.moderation.query` | `dify.moderation.check` | | `dify.suggested_question.questions` | `dify.suggested_question.generation` | | `dify.retrieval.query` | `dify.dataset.retrieval` | | `dify.dataset.documents` | `dify.dataset.retrieval` | | `dify.generate_name.inputs` | `dify.generate_name.execution` | | `dify.generate_name.outputs` | `dify.generate_name.execution` | | `dify.prompt_generation.instruction` | `dify.prompt_generation.execution` | | `dify.prompt_generation.output` | `dify.prompt_generation.execution` | | `dify.feedback.content` | `dify.feedback.created` | `dify.node.execution.draft` carries the same gated fields as `dify.node.execution`. > [!WARNING] > > In production, it is recommended to disable content push by default. Enable it in a controlled environment only after confirming data classification, access controls, redaction requirements, retention periods, and audit obligations. *** ## Appendix ### Operation Types `workflow`, `node_execution`, `message`, `rule_generate`, `code_generate`, `structured_output`, `instruction_modify` These values belong to the `operation_type` label on token metrics and to `dify.prompt_generation.operation_type`. The request and error counters use the separate `type` label; its values are listed under Counters. ### Node Types `start`, `end`, `answer`, `llm`, `knowledge-retrieval`, `knowledge-index`, `if-else`, `code`, `template-transform`, `question-classifier`, `http-request`, `tool`, `datasource`, `variable-aggregator`, `loop`, `iteration`, `parameter-extractor`, `assigner`, `document-extractor`, `list-operator`, `agent`, `trigger-webhook`, `trigger-schedule`, `trigger-plugin`, `human-input` ### Workflow Statuses `running`, `succeeded`, `failed`, `stopped`, `partial-succeeded`, `paused` ### Payload Types `workflow`, `node`, `message`, `tool`, `moderation`, `suggested_question`, `dataset_retrieval`, `generate_name`, `prompt_generation`, `app`, `feedback` ### Invoke From Values * Workflow spans (`dify.invoke_from` on `dify.workflow.run`): `api`, `webapp`, `debug` * Message logs (`dify.invoke_from` on `dify.message.run`): `service-api`, `web-app`, `debugger`, `explore` ### Null Value Behavior * **Spans**: attributes with null values are omitted. * **Logs**: attributes with null values are rendered as `null` in the JSON output. * **Content-gated fields**: replaced by a reference string rather than set to `null`. # Environments Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/environments Create and manage application runtime environments, allocate resources, and view application statuses and deployment records Use Environments to create and manage application runtime environments, allocate resources, and view application status and deployment records. Environment management is available only for Kubernetes (Helm) deployments. Docker Compose deployments do not support this feature. ![Environment list card view](https://mintcdn.com/dify-enterprise-docs/Hu0J7U2xWLzt-hdq/images/administer/app-runner-environments.png?fit=max\&auto=format\&n=Hu0J7U2xWLzt-hdq\&q=85\&s=d06f9a8e14f658240ac60a306e4f61b1) ## Resource model and modes The platform's total CPU quota is determined by the license. When creating an environment, set **CPU allocation** using the platform's available quota to create a CPU resource pool for applications in that environment. Regardless of whether applications are deployed in the environment, the quota allocated to an environment counts toward the platform's allocated quota. Environments that have failed or are being deleted don't count. **Both shared and isolated modes use the environment's resource pool; the difference lies in how applications run and how resources in the pool are allocated.** | Comparison | Shared mode | Isolated mode | | - | - | - | | How applications run | All applications run in the same App Runner | Each application runs in an independent App Runner | | How CPU is allocated | All applications share the environment's CPU without per-application quotas | CPU is allocated individually to each application from the environment resource pool, and the total allocation cannot exceed the environment quota | | How memory is configured | Configure maximum memory uniformly for the environment, shared by all applications | Configure maximum memory individually for each application, with no environment-level memory pool | For example, if the platform total quota is 24 vCPU, after creating an environment with a CPU allocation of 4 vCPU, the platform has 20 vCPU remaining to allocate to other environments: * **Shared mode**: All applications in the environment share these 4 vCPU. * **Isolated mode**: After allocating 1 vCPU each to Application A and Application B, 2 vCPU remains available in the environment resource pool. The platform's available quota remains 20 vCPU and is not deducted again for application allocations. CPU allocation represents the allocated resource allowance, not the current actual CPU usage. An empty isolated environment does not launch an App Runner in advance that occupies the entire environment quota. Environment mode cannot be changed after creation. The environment's CPU allocation can be adjusted later, but in isolated mode it cannot be lower than the total CPU already allocated to its applications. Memory is not constrained by the license CPU quota, but it must still meet the minimum displayed in the form, and you must ensure cluster resources are sufficient. ## Create environment Click **Create environment** in the top right corner of the page and fill in the following information: | Configuration | Description | | - | - | | **Name** | Required. Used to identify the environment. | | **Description** | Optional. Used to describe how this environment is used. | | **Mode** | Select shared or isolated mode. Cannot be changed after creation. | | **CPU allocation** | Set the total size of the environment's CPU resource pool. It must be at least 0.1 vCPU and cannot exceed the platform's currently available quota. | | **Maximum memory** | Configured during creation in shared mode only. The minimum changes with the CPU allocation, and the form displays "At least N MiB"; if left blank, the system calculates a default value based on the CPU allocation. In isolated mode, memory is configured individually for each application after deployment via [Edit resources](#adjust-resources-per-application) in the Enterprise Dashboard. | | **Namespace** | Leave blank to use the namespace where Dify Enterprise is deployed. Before specifying a different namespace, you must enable `enterprise.appDeploy.clusterRole.enabled` in Helm values, which defaults to `false`. The namespace must already exist; otherwise the environment fails (`namespace_missing`). | After completing the configuration, click **Create environment**. ![Create a shared environment and configure resources](https://mintcdn.com/dify-enterprise-docs/Hu0J7U2xWLzt-hdq/images/administer/app-runner-create-environment.png?fit=max\&auto=format\&n=Hu0J7U2xWLzt-hdq\&q=85\&s=4ae63d0580d4ca9983d7670d532e3b08) The environment shows **Creating** until it can accept deployments, then **Ready**. From then on, members with the **Deploy app** permission can deploy apps to it. If an error occurs during initialization, the environment transitions to **Failed**. Hover over the status badge to view the reason. Failed environments do not support retries; troubleshoot the issue, then delete and recreate the environment. ## Environment status The environment list supports two views, **Cards** and **Table**, displaying resource allocations and runtime metrics for the last 24 hours: * **24h calls** and **Error rate**: Error rate is the ratio of failed calls to total calls. When there are no calls in the last 24 hours, the error rate shows `—`. * **CPU allocation**: Isolated mode displays "allocated / quota" to show how much of the resource pool has been allocated; shared mode displays only the quota. * **24h failed deploys**: Click the number to open those deployments and their failure reasons in [Deployments](#deployments). Click an environment to enter its details page. The **Apps** tab lists the **Runtime state**, **Current version**, and **24h calls here** by application. When a notice next to **Current version** indicates "N versions behind the latest published version", it means the currently deployed version lags behind the latest published version and must be redeployed to update. ![Applications and runtime states in a shared environment](https://mintcdn.com/dify-enterprise-docs/Hu0J7U2xWLzt-hdq/images/administer/app-runner-environment-apps.png?fit=max\&auto=format\&n=Hu0J7U2xWLzt-hdq\&q=85\&s=0f46c95a297754e17206524c48a1679f) Call count and error rate are aggregate metrics. To view the status, duration, token usage, and error messages of individual calls, open [Invocation Logs](/en/3.13.x/administer/invocation-logs) and filter by environment. ## Deployments Open the **Deployments** tab on the environment details page to filter by application, time range (default **Last 7 days**), operation type, and status. ![Environment deployment records and filters](https://mintcdn.com/dify-enterprise-docs/Hu0J7U2xWLzt-hdq/images/administer/app-runner-deployment-history.png?fit=max\&auto=format\&n=Hu0J7U2xWLzt-hdq\&q=85\&s=5f14e9c3e14aa5ba5abb9e5322527177) Expand a failed record to view and copy the **Failure reason**, including the error code and error message. **Operator** displays the user who initiated the deployment. Insufficient resources in an isolated environment can cause deployment failures: applications deployed to an isolated environment are allocated 0.5 vCPU by default, and deployment will fail if less than 0.5 vCPU remains in the resource pool. Increase the environment's **CPU allocation**, or reduce the CPU of other applications via [Adjust resources per application](#adjust-resources-per-application), then redeploy the application. ## Edit environment Select **Edit** from the **…** menu on an environment card, at the end of a table row, or in the top right corner of the details page. You can modify the name, description, and resource configuration. Mode and namespace cannot be changed after creation; if changes are required, recreate the environment. Resource configurations supported by each mode are as follows: * **Shared mode**: You can modify **CPU allocation** and **Maximum memory**, following the same rules as during creation. Increasing CPU raises the minimum memory requirement; if the currently configured maximum memory is below the new minimum, the form prompts you to increase memory first. * **Isolated mode**: Supports modifying only the **CPU allocation**, which is the resource pool size. When decreasing it, the allocation cannot be lower than the amount already held by applications. To release quota, first decrease application CPU allocations or undeploy applications. Adjusting the resource pool size does not restart applications in the environment. ## Adjust resources per application Isolated mode supports configuring CPU and memory individually for each application. On the **Apps** tab of the environment details page, click the **…** menu at the end of the target application row and select **Edit resources**. Shared mode does not support adjusting resources per application; modify environment resources via [Edit environment](#edit-environment). ![Edit resources entry point for an application in isolated mode](https://mintcdn.com/dify-enterprise-docs/Hu0J7U2xWLzt-hdq/images/administer/app-runner-isolated-app-actions.png?fit=max\&auto=format\&n=Hu0J7U2xWLzt-hdq\&q=85\&s=9e5f5088c3f124eb2197b215bbc539a7) * **CPU**: At least 0.1 vCPU, and cannot exceed the environment quota minus the CPU allocated to other applications. Applications are allocated 0.5 vCPU by default upon deployment. Selecting a CPU quota during deployment is not supported; adjust it via **Edit resources**. * **Maximum memory**: Cannot be lower than the minimum displayed in the form, which is determined by the application's current CPU allocation; if left blank, the system derives a default value based on CPU. Increasing CPU raises the minimum requirement; if the currently configured maximum memory is below the new minimum, the form prompts you to increase memory first. Saving restarts the app, so it's briefly unavailable. ## Undeploy applications In the details page **Apps** tab, select **Undeploy** from the **…** menu at the end of the row. The resources used by the application will be released, and its endpoints will immediately stop serving traffic. Undeployment runs in the background, and you can view progress and results in **Deployments**. Undeploying cannot be undone; restoring service requires redeploying the application. Confirm the business impact before proceeding. ## Delete environment Deleting an environment deletes its API keys, web app and API settings, and conversation records. This operation cannot be undone. To switch modes or namespaces, create a new environment and redeploy applications before deleting the old environment. Select **Delete** from the **…** menu on an environment card, at the end of a table row, or in the top right corner of the details page. An environment cannot be deleted while deployed applications exist; you must first [undeploy applications](#undeploy-applications) one by one. If an undeploy operation is in progress, wait for it to complete. Once the environment is deleted, its vCPU returns to the platform's available quota. # FAQ Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/faq ## 1. How to Enable Access Control for WebApps? ### Get the WebApp Frontend Code You can refer to the following code repositories to customize the WebApp's authentication page. * [Text Generation App Code](https://github.com/langgenius/webapp-text-generator) * [Chat App Code](https://github.com/langgenius/webapp-conversation) ### Get the WebApp Backend API You can develop a custom access control system using the WebApp API. Visit any Dify application and click "Access API" to get the complete API documentation. ![](https://assets-docs.dify.ai/2025/05/7a59eb35efedbd0106aa7597c10ff308.png) ## 2. How to Adjust Member Permissions in a Workspace? Scenario: Member A is added to a workspace with Normal permission role. How can you change Member A's permission to Admin? Currently, it's not possible to switch member permissions within [System Settings](/en/3.13.x/administer/members-management). To adjust permissions, you need to remove Member A and then re-add them with the Admin role. If you need to continue adding members to the workspace, it's recommended to have the workspace administrator directly invite members to join the space. For detailed instructions, please refer to [Team Member Management](/en/3.13.x/use/workspace/team-members-management). ## 3. My account is locked. How can I unlock it? Account locking typically occurs in two situations: 1. Automatic locking: Due to consecutive failed login or password reset attempts, the account is locked for 24 hours. This lock will be automatically lifted after the locking period ends. 2. Manual ban by administrator: Please contact your system administrator to lift the ban. ## 4. What should I do if I'm not receiving verification codes? 1. **Check your inbox**: Make sure the verification code email hasn't been categorized as spam. 2. **Wait time**: Only one verification code can be sent per minute. Please wait at least 1 minute before trying again. 3. **Contact administrator**: If you still can't receive codes, contact your system administrator to verify that your email configuration is correct. For more information about security restrictions, please read the [Security Measures](/en/3.13.x/administer/password-policy). ## 5. How can I enhance my account security? 1. **Use SSO**: If your organization supports SSO, we recommend configuring and using it. For detailed information, please refer to [Enterprise SSO Authentication](/en/3.13.x/administer/sso/introduction). 2. **Stay vigilant**: Be careful to protect your login credentials and avoid saving passwords in public places. ## 6. How to resolve issues when using Azure SAML SSO login? **Issue Details**: After configuring Azure SAML SSO and enabling forced login, you encounter an `account not found` error. **Solution**: 1. Please refer to [Authentication - User Account Creation Methods](/en/3.13.x/administer/loginsettings) and enable the following two account creation methods: * Allow users to self-register * Allow auto-create personal workspace for new users 2. If the above switches are confirmed to be enabled but the error still occurs, please refer to [Edit Attributes and Claims](/en/3.13.x/administer/sso/azure/saml#advanced-configuration%3A-edit-attributes-and-claims) and change the **source attribute** for the **Unique User Identifier (Name ID)** to `user.mail`. # Invocation Logs Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/invocation-logs Query application invocation logs across workspaces and environments, and view invocation status, duration, and failure reasons Use Invocation Logs to view application invocations across workspaces and environments in the organization, including their status, duration, token usage, and failure reasons. Each run of a Workflow application and each conversation message of a Chatflow application corresponds to an individual log record. In the built-in environment, messages from Chatbot, Agent, and Text Generator apps are recorded too. Access path: Enterprise Dashboard > **Invocation Logs**. The application **Logs** page within a workspace displays records only for a single application, whereas Invocation Logs in the Enterprise Dashboard aggregates records for all applications across the organization. ## Log scope **Environment** indicates where an application runs, and **Source** indicates how the invocation was initiated. Invocation logs cover the platform's **built-in environment** as well as **deployed environments** created in Environments: | Environment type | Description | | - | - | | **Built-in environment** | The application runtime environment built into the Dify platform, including invocations initiated while debugging in the studio. | | **Deployed environment** | Environments created, configured with resources, and used to deploy applications in [Environments](/en/3.13.x/administer/environments). | In the built-in environment, test runs in Studio show **Debugging** as the **Source**. Deployed environments carry only **Web app** and **Service API** calls. Docker Compose deployments display invocation logs only for the built-in environment. ## Query logs The page displays records from the **Last 24 hours** by default. The summary line above the table displays "N records · M failed", and the statistics update according to the active filters. ![Invocation log list and error details](https://mintcdn.com/dify-enterprise-docs/Hu0J7U2xWLzt-hdq/images/administer/app-runner-invocation-logs.png?fit=max\&auto=format\&n=Hu0J7U2xWLzt-hdq\&q=85\&s=68ac9a5ed60d40f0422364ae932667c0) You can find target invocations using the following filters: * **Time range**: Switch to **Last 7 days**, **Last 30 days**, or **Custom range**. * **Environment, workspace, status, and source**: Can be combined. Set the status to **Failure** to view only failed invocations. * **Search app name**: Matches application names containing the search term, case-insensitive. ## Invocation details The list displays the Time, Status, App, Environment, Version, Duration, Tokens, Operator, and Source for each invocation. * **Version**: Shows the version name, or its number (`# N`) or **Untitled version** when it has none. `—` means the record has no version. * **Operator**: Shows the member's name for calls made by a workspace member, the session ID (`session_id`) for web app end users, and the `user` value sent with Service API calls in deployed environments. Expand a record containing error details to view and copy the **Error message**. ## Log retention Records from deployed environments are kept for 30 days by default, and a daily cleanup deletes older ones. Built-in records stay in Dify but are hidden once they're older than the retention period. The period applies to every time range, including **Custom range**. To change the retention period, set `enterprise.appRunnerLog.retentionDays` (`APP_RUNNER_LOG_RETENTION_DAYS`, minimum `1`). Lowering it deletes older deployed-environment records at the next daily cleanup. See [Deployed Environments (App Runner)](/en/3.13.x/deploy/advanced-configuration/environment-variables#app-runner) for the setting. # Login Settings Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/loginsettings ## 1. Function Overview Dify Enterprise provides two login methods for the admin console: **Email + Password** and **Single Sign-On (SSO)**. System administrators can enable or disable either method as needed in "Login Settings" and complete SSO identity provider configuration in one place. Configuration takes effect immediately, and the admin console login page only displays currently available entry points, meeting different enterprise security and experience strategies. ## 2. Configuration Instructions ### 2.1 Access Path `Dashboard > Settings > Login Settings` ![](https://assets-docs.dify.ai/2025/10/707778a6980f061cfcdef16c8ccccd73.jpg) ### 2.2 Login Behavior Description | Login Method | Condition | Behavior | | - | - | - | | Local Login | Email and Password login enabled | Email password login | | SSO Login | SSO login enabled and identity provider configured | Login page displays "Login with SSO" entry | | First-time SSO Login | When automatic system user creation is enabled | Automatically create and login to system | > Note: Both methods can be fully enabled, or either login method can be disabled, but at least one must remain enabled. ## 2.3 SSO Identity Provider Configuration Instructions Supports integration with existing enterprise identity systems through SAML, OIDC, and OAuth2 protocols. Administrators can select the protocol type based on the enterprise's actual identity system and fill in the corresponding fields (such as Client ID, Issuer URL, certificates, etc.). Configuration methods for the three protocols can be found in the SSO configuration in the `Authentication` module: * Okta * [Configure OIDC with Okta](/en/3.13.x/administer/sso/okta/oidc) * [Configure SAML with Okta](/en/3.13.x/administer/sso/okta/saml) * [Configure OAuth2 with Okta](/en/3.13.x/administer/sso/okta/oauth2) * Azure * [Configure SAML with Azure](/en/3.13.x/administer/sso/azure/saml) * GitHub * [Configure OAuth2 with GitHub](/en/3.13.x/administer/sso/github/oauth2) Note: Different forms have different callback addresses at the bottom. Please refer to the callback address information at the bottom of the form on the `Login Settings` page and configure it in your identity provider platform. ### 2.4 Automatic System User Creation When this option is enabled, users logging in via SSO for the first time will **automatically create system users**, without the need to manually add accounts in the system beforehand. * Created users will have complete system administration privileges; * The current system has no role management mechanism, all users have the same permissions. ## 3. Precautions * Do not enable the SSO switch before the identity provider configuration is successful. * The system currently does not support permission differentiation after user login, and all system users default to super administrator privileges. *** ## 4. Frequently Asked Questions (FAQ) ### Q1: What is the difference between SSO in `Settings > Login Settings` and SSO in `Authentication > Members`? The single sign-on functionalities are targeted at different user groups and applicable to different login scenarios: * **Admin Dashboard SSO** (`Admin Dashboard > Settings > Login Settings`) Used to configure the authentication method for system administrators (System Users) accessing the **Admin Dashboard**, typically aimed at enterprise technical personnel or platform operators with system management permissions. * **Member Authentication SSO** (`Authentication > Members`) Used to configure identity authentication for workspace members or Web application end users, applicable to business end users, customers, employees, etc., accessing the **business workspace or Web product front-end** login scenarios. ### Q2: What are the differences in configuration at the enterprise IdP (identity provider) end for these two SSO functionalities? To distinguish between the identity authentication of the Admin Dashboard and business applications, it is recommended to configure two separate applications in the enterprise IdP: * **Backend SSO Configuration**: Used for identity authentication of the Admin Dashboard, assigned to users with system management permissions (such as administrators, DevOps, platform operators); * **Member SSO Configuration**: Used for identity authentication of workspace or Web application users, aimed at ordinary members, internal employees, customer users, etc. Each application should use an independent callback address (Redirect URI) and trust settings to ensure permission isolation and authentication accuracy. # Member Management Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/members-management System administrators can view and manage all organization members from the Members page, including their groups, permissions in each workspace, member status, creation date, and last active date. ## Managing Members ### Manual Management #### Add New Members to Your Team If your team doesn't use SSO authentication, members can log in with username and password. Click the **Add** button in the top right corner, then enter the username and email. The system displays the default login password when adding a member for the first time. To add administrators to your team, see [System Administrator Settings](/en/3.13.x/administer/systems/users). ![](https://assets-docs.dify.ai/2025/05/3e4c5dad9b527e2bada27aa0ecaed5a6.png) #### Add New Members to Workspaces To add members to a specific workspace, check out [Workspace Management](/en/3.13.x/administer/workspace-management). #### Disable Members Disabling members is better than deleting them—it preserves their data while denying access. Click the menu button next to a member and switch their **Status** to "banned" to disable them. ![](https://assets-docs.dify.ai/2025/05/7f2bc586e6d322d2a5883c643822522b.png) #### Reset Member Passwords When members forget their passwords, system administrators need to send password reset emails manually. Click the menu button next to a member and select **Reset Password**. ![](https://assets-docs.dify.ai/2025/05/f394f56556a5675710a86efc8bebd24a.png) #### Delete Member In the member list, click the dropdown menu on the right side of the member and select **Delete** to remove that member. The deleted member will no longer be able to log in to the workspace, and any resources they previously created (such as apps/knowledge bases) will be automatically transferred to the workspace owner. ![](https://assets-docs.dify.ai/2025/05/2a40fc714d72bfff8af6571b3b395fa5.png) > **Note:** If the member is an owner of one or more workspaces, they cannot be deleted directly. Please go to the edit page of the respective workspace, assign a new owner, and then proceed with the deletion. #### Search for Members Administrators can search for users by workspace ID or email address, and filter by user status. ![](https://assets-docs.dify.ai/2025/05/6122923b1662f51431d246ab659e101e.png) ### Automatic Management > [!NOTE] > > Automatic member sync requires Dify Enterprise Edition version ≥v2.7.0. Dify Enterprise Edition supports automatic synchronization of your existing department and personnel structure through the [SCIM](https://scim.cloud/) (System for Cross-domain Identity Management) standard, making it easier to manage large-scale organizations. > [card] [Automatic Member Sync](/en/3.13.x/administer/members/synchronization/sync-team-members) > > Automatically sync organization members through the SCIM standard. ## Permission Management Each member has permissions at both the team level and workspace level. Team administrators can add regular members, invite new system administrators, and assign workspace permissions to members. ![](https://assets-docs.dify.ai/2025/06/8c01fffb2b555ab60c481cf6b8af9aa5.png) ### Team-Level Permissions * **Team Members** Users added from the Members page have regular member permissions by default. ![](https://assets-docs.dify.ai/2025/05/f067bb3150ee71948ee73f3149064dc0.png) These members can: * Log in and use Dify Enterprise Edition * **System Administrators** Users added from the Settings page have system administrator permissions by default. For more about system administrator operations, see [System Settings](/en/3.13.x/administer/systems/users). ![](https://assets-docs.dify.ai/2025/05/1bbffcce17bc31b5550cf842421772fa.png) These members can: * Access the enterprise management dashboard * Add, delete, or disable team members * Add members to workspaces and assign permissions ### Workspace-Level Permissions A member's workspace role decides what they can do inside a workspace, and each app, knowledge base, and agent's access settings decide which resources they reach. See [Roles and Permissions](/en/3.13.x/use/workspace/roles-and-permissions) for the system roles and their defaults, and [Configure Permission Templates](/en/3.13.x/administer/admin-console-rbac-help) for the role and permission-set templates that new workspaces inherit. ## Group Management > [!NOTE] > > This feature requires Dify Enterprise Edition version ≥v2.6.0. In Dify Enterprise Edition, **group management** controls member access to different resources within your organization. By organizing members into different groups, you can effectively control which users access which Web Apps, preventing resource misuse or potential data leaks while ensuring information security. ### Manual Sync Groups #### Create Groups Click **Group Management** in the top right corner of the Members page, enter a group name to create it. Group names must be unique. ![](https://assets-docs.dify.ai/2025/04/cb14986e1d2346aff6c5e321ced7cff7.png) #### Edit Groups Groups support renaming and reordering by dragging. Click the **Edit** button next to a group name to rename it. Names cannot duplicate existing groups. #### Assign Users to Groups Click the **menu** button next to a member → **Edit Groups**, then select the groups they should join. Each user can belong to multiple groups. ![](https://assets-docs.dify.ai/2025/04/2e20d0adc2cbeb1267b6b1639c1ec677.png) After assigning users to groups, see [Application Publishing: Access Permission Management](/en/3.13.x/use/publish/webapp/web-app-access) to learn how to control Web App access permissions. ### Automatic Sync Group > [!NOTE] > > Automatic department synchronization requires Dify Enterprise Edition version ≥v2.7.0. Through the SCIM standard, Dify Enterprise Edition supports automatic synchronization of existing user groups from your IdP. For detailed configuration instructions, see: > [card] [Azure](/en/3.13.x/administer/members/synchronization/azure#6-sync-user-groups) > > Automatically sync user groups through Azure. > [card] [Okta](/en/3.13.x/administer/members/synchronization/okta#5-assign-users-and-groups) > > Automatically sync user groups through Okta. # Azure Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/members/synchronization/azure Set up automatic member sync with Azure AD using SCIM. Version ≥ v2.7.0 This guide shows you how to connect Azure Entra ID to Dify Enterprise Edition's SCIM service for automatic member synchronization. ## Set Up Your Azure Application ### 1. Create a New Application In the Azure admin portal, go to Applications and click **New application**. ![](https://assets-docs.dify.ai/2024/11/4f52715ff661e6c9430af09b4b2a4736.png) Select **Create your own application**, give it a name (e.g., "dify"), choose **Integrate any other application you don't find in the gallery (Non-gallery)**, then click **Create**. ![](https://assets-docs.dify.ai/2024/11/b823ecfaa94d18ba0ac794cc0290dc7f.png) ### 2. Assign Users and Groups From the application's left menu, select **Users and groups**, then click **Add user/group**. ![](https://assets-docs.dify.ai/2024/11/ed3c6f5de21c75e2261bf05d055ffb9e.png) ### 3. Set Up Provisioning 1. In the left menu, go to **Provision → Get started → Connect your application**. ![](https://assets-docs.dify.ai/2025/05/f890065efeb5390dcb43e7e7d1c1f5b8.png) 2. Under Admin credentials, enter: * **Tenant URL**: Your SCIM endpoint URL * **Secret token**: Your SCIM authentication token > Get these values from [Sync Members](/en/3.13.x/administer/members/synchronization/sync-team-members). ![](https://assets-docs.dify.ai/2025/05/03f1e586bc428538d80b6f5316a293df.png) 3. Click **Test Connection** to verify your setup. 4. If the test passes, click **Save**. ### 4. Configure Attribute Mappings 1. On the provisioning page, click **Mappings**. You'll see two default mappings: * `Provision Microsoft Entra ID Users` - for syncing users * `Provision Microsoft Entra ID Groups` - for syncing groups 2. Click each mapping and keep only these attributes: * **Provision Microsoft Entra ID Users** | customappsso Attribute | Microsoft Entra ID Attribute | | - | - | | userName | userPrincipalName | | active | Switch(\[IsSoftDeleted], , "False", "True", "True", "False") | | displayName | displayName | * **Provision Microsoft Entra ID Groups** | customappsso Attribute | Microsoft Entra ID Attribute | | - | - | | displayName | displayName | | members | members | ### 5. Start Provisioning 1. Return to the main **Provisioning** page 2. Under **Settings**, choose your sync scope: * "Sync only assigned users and groups" (best for selective sync) * "Sync all users and groups" (for organization-wide sync) ![](https://assets-docs.dify.ai/2025/05/489e8b8f4091d53ab699ec33199d57a4.png) 3. Click **Save** 4. Click **Start provisioning** > [!NOTE] > > First-time sync can take 20 minutes to several hours, depending on your directory size. ### 6. Sync User Groups To include groups in the sync: 1. Create a group in Azure Entra ID 2. In your Dify application, click **Users and groups** 3. Add the groups you want to sync ![](https://assets-docs.dify.ai/2025/05/af19820dfd75bd6bc00c602009574a77.png) ## Enable SCIM in Dify Once Azure is configured: 1. Go to the Dify admin dashboard 2. Navigate to **Members** → click the menu button → **Automatic synchronization** → **Enable** ![](https://assets-docs.dify.ai/2025/05/08d3b05fc5dfaa1eb0a6b8bd523ea5f9.png) > Sync isn't instant. Azure controls the sync schedule. Check your provisioning logs in Azure for sync history. # Okta Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/members/synchronization/okta Set up automatic member sync with Okta using SCIM. Version ≥ v2.7.0 This guide shows you how to connect Okta to Dify Enterprise Edition's SCIM service for automatic member synchronization. ## Create and Configure Your Okta Application ### 1. Log into Okta Admin Console Go to your Okta admin portal and navigate to **Applications** → **Create App Integration**. ![](https://assets-docs.dify.ai/2025/05/c5f569eb091dfd55d6cc131fb74192f4.png) ### 2. Create the App Integration 1. Click **Create App Integration** 2. Configure the app: * Platform: **Web Application** * Sign-on method: **SAML 2.0** * Click **Create** 3. Enable SCIM: * In the General tab, find App Settings * Click **Edit** * Update the Application label if needed * Enable SCIM provisioning * Click **Save** ![](https://assets-docs.dify.ai/2025/05/5e5031051743b7ad391b38030d5a7abd.png) ### 3. Set Up SCIM Connection 1. Go to the **Provisioning** tab 2. Click **Configure API Integration** 3. Check **Enable API integration** 4. Enter your SCIM details: * **SCIM 2.0 base URL**: Your SCIM endpoint URL * **OAuth Bearer Token**: Your SCIM authentication token * Enable **Import User** and **Import Group** based on your needs 5. Click **Test API Credentials** 6. After a successful test, click **Save** ![](https://assets-docs.dify.ai/2025/05/1dcde7b1f9fc3a26769ef91170f2be58.png) ### 4. Configure Provisioning Options 1. In the **Provisioning** tab, find the "To App" section and click **Edit** 2. Enable these features as needed: * **Create Users**: Adds new Dify users when assigned in Okta * **Update User Attributes**: Keeps user info synchronized * **Deactivate Users**: Sets user status to "disabled" in Dify when deactivated in Okta 3. Click **Save** ![](https://assets-docs.dify.ai/2025/05/3f660720b6a51f9858e547ffc10e8bde.png) ### 5. Assign Users and Groups **To assign users:** 1. Go to the **Assignments** tab 2. Click **Assign** and choose users or groups to sync with Dify Enterprise 3. Click **Save** **To sync groups:** 1. Click **Push Groups** 2. Select the groups you want to sync to Dify Enterprise 3. Click **Save** ![](https://assets-docs.dify.ai/2025/05/cbc2fdde9886807eed30c1e5d208f8cd.png) ## Enable SCIM in Dify Once Okta is configured: 1. Go to the Dify admin dashboard 2. Navigate to **Members** → click the menu button → **Automatic synchronization** → **Enable** ![](https://assets-docs.dify.ai/2025/05/08d3b05fc5dfaa1eb0a6b8bd523ea5f9.png) > Sync isn't instant. Okta controls the sync schedule. Check your provisioning logs in Okta for sync history. # Sync Members Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/members/synchronization/sync-team-members Automatically sync organization members through SCIM protocol. Version ≥ v2.7.0 ## Overview Dify Enterprise Edition supports automatic synchronization of your organization's existing structure through the [SCIM](https://scim.cloud/) (System for Cross-domain Identity Management) protocol, making it easier for admins to manage large teams efficiently. * Standard SCIM 2.0 protocol support * Automatic user and organization structure sync * Works with major identity providers * Real-time member updates ## Before You Start To enable automatic synchronization, make sure you have: 1. Dify EE system administrator permissions 2. Access to your organization's identity provider backend 3. Understanding of your current identity provider type ## Setup Guide ### 1. Get Your SCIM Configuration **1. Open Sync Settings** In the enterprise dashboard, go to **Members** → **Sync Settings** from the left sidebar. ![Sync Settings Interface](https://assets-docs.dify.ai/2025/05/764e71213cadcaa45c62c56a2dc38cbf.png) **2. Copy the SCIM Endpoint** Find and copy the `SCIM 2.0 Base URL` shown on the page. You'll need this for your identity provider setup. **3. Create an Authentication Token** * Click **Get Token** * The system generates an OAuth Bearer Token > [!WARNING] > > This token appears only once. Copy and save it immediately in a secure location. If you lose it, you'll need to generate a new one. **4. Save Your Configuration** Keep these items safe for the next steps: * SCIM Base URL * OAuth Bearer Token ### 2. Connect Your Identity Provider Select your identity provider below for specific setup instructions: > [card] [Azure Active Directory](./azure) > > Set up member sync with Azure AD > [card] [Okta](./okta) > > Set up member sync with Okta ## How SCIM Maps to Dify Here's how SCIM resources work with Dify features: | SCIM Resource Type | Maps to Dify | What You Can Do | Notes | | - | - | - | - | | User | Member (email, username, status) | Create, Update, Deactivate | Deactivating changes user status to "Disabled" but keeps their data | | Group | Group (name, members) | Create, Update, Delete | Deleting a group removes it permanently along with member relationships | ## Key Things to Know > [!NOTE] > > Once you enable SCIM sync, your identity provider becomes the single source of truth for user and group management. To learn about API limitations, check out the [Admin APIs](/en/3.13.x/administer/admin-apis) documentation. ### What Changes When SCIM is Active **With SCIM enabled:** * All user and group management happens through your identity provider * Admin APIs become read-only * Self-registration is disabled **With SCIM disabled:** * Full Admin API access returns * All user management features work normally ### If You Need to Make Manual Changes Sometimes you might need to use Admin APIs directly: 1. Temporarily turn off SCIM 2. Make your API changes 3. Turn SCIM back on and check sync status > [!WARNING] > > This can cause sync conflicts. Use with caution. For more details about Admin APIs, please check the [Admin APIs](/en/3.13.x/administer/admin-apis) documentation. # Password Policy Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/password-policy ## 1. Overview To meet enterprise compliance requirements for admin passwords, the Admin Console supports a flexible, configurable password policy that covers password complexity, expiration, and expiration reminders, balancing security, maintainability, and user experience. Administrators can configure the following in the UI: * Password complexity (length, character classes, consecutive character restrictions) * Password expiration and expiration reminders The system provides a default policy and enforces non-reducible boundaries on certain items to ensure compliance and security. *** ## 2. Configuration ### 2.1 Navigation `Admin Console > Settings > Password Policy` ### 2.2 Password Complexity Policy | Item | Default | | - | - | | Minimum password length | Cannot be set below 8 | | Must include uppercase | true | | Must include lowercase | true | | Must include numbers | true | | Must include special chars | false | | Disallow repeated chars | false | | Disallow ascending chars | false | Notes: * After the configuration is updated, the complexity rules take effect immediately. * Administrators who are currently signed out can still sign in with their existing password/SSO: * If the current password does not meet the new rules, they must change it after signing in. * If the current password meets the new rules, they are not affected. * Administrators who are already signed in are not affected until their next sign-in. * On their first SSO sign-in after the policy update, administrators will be required to update their local password to complete the compliance check. ### 2.3 Password Expiration and Reminders | Item | Default | Notes | | - | - | - | | Enable expiration | false | Takes effect immediately when enabled | | Expiration period (days) | 90 | Minimum 1 day, maximum 3650 days | * After a successful password change, you must sign in again. ### 2.4 Force Password Change on First Sign-in for New Users * New users created in the Admin Console or users whose password has been reset will be required to change their password upon first sign-in until the new password satisfies the current password complexity policy. *** ## 4. Notes * The minimum password length cannot be less than 8; the maximum length is fixed at 64. * The allowed special character set is fixed: `!@#$%^&*()-_+=[]{}|;:,.?/`. * Weak-password dictionary blocking is enabled by default and cannot be turned off. * Policy changes do not immediately affect administrators who are already signed in; they take effect on next sign-in. * Administrators who use SSO only may be required to set/update a local password after a policy update to complete compliance checks. * The current version does not provide role/permission-specific password policies; the policy is uniform for all system users. *** ## 5. FAQ **Q1: Why can’t the minimum password length be set below 8?** To meet compliance and security requirements, the system enforces a minimum of 8. **Q2: Is preventing reuse of recent passwords (e.g., last 5) supported?** This capability is not available in the current version. Future Enterprise Edition releases will evaluate differentiated and more advanced compliance modules. **Q3: Are administrators who only use SSO affected by the password policy?** Yes. After the policy is updated, on their first SSO sign-in, they will be required to update their local password to complete the compliance check. # Plugin installation strategy Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/plugins-management System administrators can manage the installation policies of plugins for all workspaces within the current Enterprise Edition globally through the Plugins page in the Enterprise Edition management backend. By controlling plugin types and sources, they can ensure enterprise data security and application stability. ## Managing Plugin Installation In the Enterprise Edition management backend, click **Plugins** in the left-hand menu to enter the plugin management page, and find **Plugin Installation Policy**. On this page, you can: * View current plugin policy configurations * Control allowed plugin types for installation * Restrict plugin installation sources * Keep one plugin version installed in every workspace, including workspaces created later ## Install a Plugin in Every Workspace 1. In **Plugins**, find the row for the plugin version you want and click **Install Manage**. If the version isn't listed yet, install it first with **Install Plugin**, from the Marketplace or a local package. 2. In the **Install Management** dialog, check **Install in every workspace** and click **Confirm**. While the option is on, that version is installed in every current workspace and in each new workspace after it's created. Follow progress in **Installation Logs** on the **Plugins** page. To stop installing the plugin in new workspaces, uncheck **Install in every workspace**. > [!NOTE] > > Turning the option off leaves the plugin in every workspace that already has it. To uninstall it from those workspaces, remove them from the **Installed Workspace List** in the same dialog. ## Allow Specific Plugin Types Administrators can select allowed plugin types for installation through the "Allowed Plugins" dropdown menu: | Plugin Type | Description | | - | - | | All | Allow installation of all plugin types, including official plugins, partner plugins, and third-party developed plugins | | Official + Partner | Only allow installation of Dify official plugins and certified partner plugins, providing a good balance of security and stability | | Official | Only allow installation of plugins developed and maintained by Dify officially, providing high-level security and stability assurance | | None | Prohibit installation of any plugins, suitable for environments with extremely high security requirements | **Plugin Source Description:** In the plugin marketplace, you can identify different types of plugins through tags and author names: ![](https://assets-docs.dify.ai/2025/06/c2bfdfbb2132848e589073600e55ffab.png) ## Control Plugin Installation Sources ### Marketplace Installation Restrictions The "Restrict to Marketplace Installations" toggle controls plugin installation sources, helping administrators balance functional requirements and security risks: | Setting Status | Allowed Installation Channels | Security Level | | - | - | - | | Enable Restriction | Dify official plugin marketplace only | High | | Disable Restriction | Marketplace, local files, GitHub, etc. | Low | **Plugin Installation Source Channels Overview:** | Installation Method | Security Review | Version Management | Documentation | | - | - | - | - | | Official Plugin Marketplace | Security reviewed | Automatic version management and updates | Detailed usage documentation | | Local File Installation | Requires self-assessment | Manual management required | Depends on developer | | GitHub Installation | Requires code security verification | Timely version updates but manual | Depends on project maintenance | ### Signature Installation Restrictions In addition to restricting plugins to marketplace-only installation in the management console, you can also control plugin installation by modifying environment file variable values in the deployment. Plugin signatures can be considered as trusted source verification for plugins, and verification will be performed during plugin installation. When deploying the enterprise edition, the `FORCE_VERIFYING_SIGNATURE` in the environment variable file controls plugin signature verification. If plugin signature restrictions are enabled in environment variables, it will affect plugin installation. * For information on how to control signature installation restrictions through environment variables during deployment, please refer to the deployment manual. ```yaml theme={null} FORCE_VERIFYING_SIGNATURE=false # Disable forced signature verification FORCE_VERIFYING_SIGNATURE=true # Enable forced signature verification ``` **Relationship Overview between Signature Verification and Marketplace Installation Restrictions:** ### Enable Marketplace Installation Restrictions | Environment Variable Configuration | Marketplace Installation | GitHub Online Installation (with signature) | GitHub Online Installation (without signature) | Manual Installation (with signature) | Manual Installation (without signature) | | - | - | - | - | - | - | | Verify signature | ✅ Allow installation | ❌ Not allowed | ❌ Not allowed | ❌ Not allowed | ❌ Not allowed | | Don't verify signature | ✅ Allow installation | ❌ Not allowed | ❌ Not allowed | ❌ Not allowed | ❌ Not allowed | ### Disable Marketplace Installation Restrictions | Environment Variable Configuration | Marketplace Installation | GitHub Online Installation (with signature) | GitHub Online Installation (without signature) | Manual Installation (with signature) | Manual Installation (without signature) | | - | - | - | - | - | - | | Verify signature | ✅ Allow installation | ✅ Allow installation | ❌ Not allowed | ✅ Allow installation | ❌ Not allowed | | Don't verify signature | ✅ Allow installation | ✅ Allow installation | ✅ Allow installation | ✅ Allow installation | ✅ Allow installation | > **Note**: All plugins provided on Dify Marketplace include Dify signatures. # Configuring SAML with Azure Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/sso/azure/saml This document will use Azure Entra ID as the SSO identity provider to demonstrate how to enable SAML authentication protocol for Dify Enterprise. By enabling this feature, the enterprise login page will use a unified identity authentication entry to enhance security. For enterprise internal users, there's no need to enter complex passwords - they can log in using organizational accounts to pass verification, simplifying the login process. ## 1. Create a New Application in Azure Access the Azure administrator backend page, navigate to the Applications page, and click New application. ![](https://assets-docs.dify.ai/2024/11/4f52715ff661e6c9430af09b4b2a4736.png) Select **Create your own application**, enter an application name such as "dify", then select **Integrate any other application you don't find in the gallery (Non-gallery)**, then click Create. ![](https://assets-docs.dify.ai/2024/11/b823ecfaa94d18ba0ac794cc0290dc7f.png) Next, you need to assign visible members to this application. Only authorized Azure members will be allowed to log in to Dify Enterprise. Select **Users and groups** on the left side of the application, then click **Add user/group**. ![](https://assets-docs.dify.ai/2024/11/ed3c6f5de21c75e2261bf05d055ffb9e.png) ## 2. Configure the Application Click the Single sign-on option under Manage on the left side of the application, then select the SAML option. ![](https://assets-docs.dify.ai/2024/11/7a5f653e751bf20c01c7eb53cc79ddde.png) Edit the SAML configuration and fill in the Dify Enterprise ACS URL in the **Entity ID** and **Reply URL** fields. ![Image 1](https://assets-docs.dify.ai/2024/11/639bb89e402f8f20078d6c7a14ca0297.png) ![Image 2](https://assets-docs.dify.ai/2024/11/236a4995e4fe338d12b41993fc237611.png) > [tab] Workspace > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-dify-enterprise-url]/console/api/enterprise/sso/saml/acs > ``` > [tab] Web App Members (For Internal Users) > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/members/saml/acs > ``` > [tab] WebApp External Users (For External Users) > > Click **Admin Backend** → **Authentication** → **Web App** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/saml/acs > ``` After obtaining the ACS URL, switch back to the Azure application page, download the Certificate in the SAML Certificates tab; also copy the Login URL from the setup page. Next, you need to fill these two parameters into the Dify Enterprise admin backend. ![](https://assets-docs.dify.ai/2024/11/ab7e3bd7067858ec4627d1d863244e81.png) ### Advanced Configuration: Edit Attributes and Claims 1. Click **Unique User Identifier (Name ID)** under **Required claim**. ![](https://assets-docs.dify.ai/2024/11/97a46bf1b5264ef72ad4b202fdf2a772.png) 2. Change the source attribute to `user.mail`. ![](https://assets-docs.dify.ai/2024/11/183dd293f17f87081ac4c2390b583fb0.png) ## 3. Complete Dify Enterprise Backend Configuration System administrator clicks on the Authentication page of Dify Enterprise, click **"+ New Identity Provider → New SAML Provider"**, > [tab] Workspace > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > * Fill in the Login URL from the Azure application in the IdP SSO URL field; > * Fill in the content from the downloaded Certificate file in the X509 Signing Certificate field; > > ![](https://assets-docs.dify.ai/2025/06/a45a2d156196ae163e7944cdad7ec2da.png) > > It usually follows this format: > > ```bash theme={null} > https://[your-dify-enterprise-url]/console/api/enterprise/sso/saml/acs > ``` > [tab] WebApp Members (For Internal Users) > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > * Fill in the Login URL from the Azure application in the IdP SSO URL field; > * Fill in the content from the downloaded Certificate file in the X509 Signing Certificate field; > > ![](https://assets-docs.dify.ai/2025/06/a45a2d156196ae163e7944cdad7ec2da.png) > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/members/saml/acs > ``` > [tab] WebApp External Users (For External Users) > > Click **Admin Backend** → **Authentication** → **Web App External User Authentication** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > * Fill in the Login URL from the Azure application in the IdP SSO URL field; > * Fill in the content from the downloaded Certificate file in the X509 Signing Certificate field; > > ![](https://assets-docs.dify.ai/2025/06/a8451628cb9a659f55164fa10307ca12.png) > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/saml/acs > ``` ## 4. Enable SSO Authentication After completing the basic SSO configuration, system administrators can enable SSO authentication for internal members and external users separately to unify identity authentication processes. ### For Internal Users If you want only members who have passed enterprise identity authentication to access the Dify workspace and Web App, click **Authentication** → **Members** and enable the SSO authentication toggle. * **Workspace**: Requires authorization when logging into the Dify Enterprise workspace. * **Web App**: Requires verification when using applications created by the current Dify Enterprise. ### For External Users If you want to enable authentication for external users of Web Apps (such as customers and partners) to ensure that only trusted users can access applications, click **Authentication** → **Web App** and enable the SSO authentication toggle. * Fill in the Login URL from the Azure application in the IdP SSO URL field; * Fill in the content from the downloaded Certificate file in the X509 Signing Certificate field; ![](https://assets-docs.dify.ai/2024/11/556e3d68efbc742711e4313534a2e95c.png) # Configuring OAuth2 with GitHub Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/sso/github/oauth2 This document will use GitHub as the SSO identity provider to demonstrate how to enable OAuth2 authorization protocol for Dify Enterprise. By enabling this feature, the enterprise login page will use a unified identity authentication entry to enhance security. For enterprise internal users, there's no need to enter complex passwords - they can log in using organizational accounts to pass verification, simplifying the login process. > [!NOTE] > > This document will mention internal users and external users. The following distinctions are made: > > * Internal members: Members registered within the Dify Enterprise workspace or added through the admin backend. > * External users: Members not within Dify Enterprise ## 1. Create an OAuth App in GitHub 1. Access the GitHub administrator backend page, navigate to the Settings page, select OAuth Apps and create a new OAuth application. ![](https://assets-docs.dify.ai/2025/02/5d51e9ba8b3018f1a02a87aa3832acb2.png) 2. Follow the page prompts to fill in the following content and complete application creation: * Application name (Required): Application name, can be customized. * Homepage URL (Required): Homepage link, recommended to fill in the Dify Enterprise platform URL. * Application description (Optional): Application description. * Authorization Callback URL (Required): Callback link, please refer to [the section below](#2-obtaining-callback-url) for how to obtain it. > For more information about creating GitHub OAuth2 applications, please refer to [GitHub Documentation](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app). ## 2. Obtaining Callback URL According to the required SSO scope to be enabled, **Callback URLs differ**. System administrators need to fill the Dify Enterprise Callback URL into the corresponding GitHub OAuth2 application to complete the creation process. > [tab] Workspace > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New OAuth2 Provider**, and view the Workspace Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-dify-enterprise-url]/console/api/enterprise/sso/oauth2/callback > ``` > [tab] WebApp Members (For Internal Users) > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New OAuth2 Provider**, and view the Workspace Callback URL at the bottom. > > ![](https://assets-docs.dify.ai/2025/06/5570530b7133b8d847ae3281304f26cb.png) > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/members/oauth2/callback > ``` > [tab] WebApp External Users (For External Users) > > Click **Admin Backend** → **Authentication** → **Web App** → **SSO Identity Provider** → **New Identity Provider** → **New OAuth2 Provider**, and view the Web App Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/oauth2/callback > ``` 2. Paste it into the **Authorization callback URL** field in the OAuth2 App. ## 3. Enable OAuth2 Authentication Access the Dify Enterprise Authentication page, click **"+ New Identity Provider → New OAuth2 Provider"**, and fill in the information according to the prompts to complete the configuration. Go to the OAuth application to obtain the following information: * Client ID * Client Secrets The basic information of different OAuth2 providers varies, please refer to the official documentation of each provider. The following information is for reference only and can be adjusted according to actual needs. * Authorization Endpoint: `https://github.com/login/oauth/authorize` * Token Endpoint: `https://github.com/login/oauth/access_token` * User Info Endpoint: `https://api.github.com/user` * Scopes: `openid,profile,email` ## 4. Enable SSO Mandatory Authentication (Optional) System administrators can enable SSO Enforcement options for the following two scenarios to enable mandatory authentication: * **Workspace**: Requires authorization when logging into Dify Enterprise Workspace. * **WebApp**: Requires verification when using applications created by the current Dify Enterprise. After enabling, accessing the corresponding scenarios will prompt for access authorization. ![](https://assets-docs.dify.ai/2025/02/28a707cfe144c090d0379834bc41ad7e.png) # SSO Authentication Introduction Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/sso/introduction Dify Enterprise supports enforcing Single Sign-On (SSO) for organization members. Once enabled, team members must log in to the Dify Enterprise platform through identity providers (such as Microsoft Entra ID, Okta, and GitHub authentication providers). System administrators only need to select the corresponding protocol and configure parameters on the Authentication page to enable a more secure identity authentication system for Dify Enterprise, supporting OpenID Connect (OIDC), SAML, and OAuth2 protocols. ## SSO Application Scope Based on the user scope, Dify Enterprise's SSO authentication system provides the following two different scope Single Sign-On (SSO) configuration options: ### Internal Users > Internal users refer to members who have registered in the Dify Enterprise workspace or have been added in the admin backend. **Workspace** * Controls how users access the Dify Enterprise workspace. * Once enabled, all users need to authenticate through your designated identity provider (IDP) before entering any workspace. **Web App** * Controls internal user access to Web Apps created on the Dify Enterprise platform. * Once enabled, internal users need to authenticate through the identity provider (IdP) before accessing any Web applications created by the Dify Enterprise platform. This setting is a global option and cannot individually control the enabling/disabling of permissions for a single WebApp. To enable personnel permission grouping for individual Webapps, please refer to [Application Access Permission Management](/en/3.13.x/use/publish/webapp/web-app-settings). > The Callback URLs for Workspace and Webapp SSO are different, please note the distinction. ### External Users > External users refer to members who have not joined the Dify Enterprise system. **Web App** * After SSO authentication, external users can access Web applications created on the Dify Enterprise platform. * Once enabled, users need to authenticate through the identity provider (IdP) before accessing any Web applications created by Dify Enterprise. > The Web App Callback URL for this permission scope is different from the Web App for internal users, please note the distinction. **⚠️ Important Notes** For security reasons, some identity providers (IDP) disable SSO authentication in iframe pages. This may affect situations where WebApps are embedded in other web pages. You need to check the identity provider's (IDP) CSP: frame-ancestors configuration to ensure this feature works properly. For detailed instructions, please refer to [this documentation](/en/3.13.x/administer/faq). Here are the different security policies provided by various IDP vendors: * Azure EntraID explicitly does not allow SSO login pages to be embedded in iframe pages due to security issues. * Okta configures SSO login pages to allow embedding. For detailed instructions, please refer to [Okta Official Documentation](https://developer.okta.com/docs/guides/build-sso-integration/saml2/main/). ## Configure SSO Authentication Administrators can easily integrate Dify Enterprise with various identity providers, such as Okta, OneLogin, or Azure Active Directory (Azure AD). Dify Enterprise supports any identity provider that meets OIDC requirements or SAML standards. You can refer to the following SSO provider configuration guides: * Okta * [Configure OIDC with Okta](/en/3.13.x/administer/sso/okta/oidc) * [Configure SAML with Okta](/en/3.13.x/administer/sso/okta/saml) * Azure * Configure SAML with Azure * GitHub * [Configure OAuth2 with GitHub](/en/3.13.x/administer/sso/github/oauth2) ## Set Session Timeout Limits This option is used to set the session duration for organization members. After this time, the system will prompt members to re-authenticate with the identity provider to regain access to Dify Enterprise resources. The default value is 7 days. ## Enable SSO Authentication Click the blue button in the SSO Enforcement section to enable SSO authentication. Administrators can choose to enable login authentication for Workspace or Web App. ## Common Issues For detailed instructions, please refer to [FAQ](/en/3.13.x/administer/faq). # MCP User-Identity Forwarding Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/sso/mcp-identity-forwarding Forward the SSO identity of the user who is **currently running a workflow** to the downstream [MCP server](/en/3.13.x/use/workspace/tools) that workflow calls. The MCP server can then act on behalf of the real end user — per-user authorization, auditing, and data scoping — instead of seeing every Dify request as the same fixed account. > [!NOTE] > > This is an enterprise feature that builds on [SSO Authentication](/en/3.13.x/administer/sso/introduction) and [MCP tools](/en/3.13.x/use/workspace/tools). It treats your identity provider (IdP) and your MCP server as black boxes — this page lists only what they must provide. ## How it works When a workflow invokes a tool on an MCP server, Dify normally calls that server with a single, **fixed workspace-level credential** configured on the MCP provider. Every caller looks the same to the MCP server. With identity forwarding enabled, Dify additionally sends a **per-user token** — one your IdP already issued for the running user — on each outbound request. Dify never signs a token of its own; it only relays a token the IdP issued, scoped to your MCP server, and the MCP server verifies it against the **same IdP**. The token rides in a dedicated HTTP header, so it never disturbs any credential already configured on the provider: ``` X-Dify-SSO-Token: ``` ``` Running user (SSO-authenticated) │ identity ▼ Dify workflow ──[ user's IdP token ]──▶ MCP server │ └─ verifies the token against the same IdP ``` The core idea: **the MCP server and Dify trust the same IdP.** ### Where it applies | Caller | Forwarding | | - | - | | Workspace user running a workflow in the console | Supported | | Workspace user via an app (including chat apps) | Supported | | End user of a published Web App | Supported | | Service API call | Not supported | | Scheduled / Cron trigger | Not supported | | Users who signed in via SAML SSO | Not supported | | Community (non-Enterprise) deployments | Not available | > [!NOTE] > > Identity forwarding applies only to the supported callers above. It is **not supported** for Service API calls or scheduled (Cron) runs, which have no interactive user — don't rely on it for those execution paths. ## Requirements for your identity provider You already have an IdP wired into Dify SSO. For forwarding to work, that **same** IdP must satisfy the following — no new IdP and no extra services are required. 1. **Shared issuer.** The IdP that authenticates Dify users must be the same IdP your MCP server trusts. Both sides verify tokens against its issuer. 2. **Protocol is OIDC or OAuth2.** SAML is not supported. 3. **The IdP returns a refresh token at login.** This is the one capability forwarding depends on. How you enable it depends on the IdP: | IdP family | What to enable | | - | - | | Standard OIDC / OAuth2 (Microsoft Entra ID, Okta, Auth0, Keycloak, Ping, OneLogin, …) | Allow the `offline_access` scope on the client and enable the refresh-token grant. | | IdPs that don't issue refresh tokens via the `offline_access` scope (for example, Google) | No admin action — Dify handles these automatically. | | OAuth2-mode clients | Include a refresh-granting scope in the configured scope list (`offline_access`, or Salesforce's `refresh_token`). | 4. **Audience agreement.** Dify asks your IdP to scope each per-user token (its `aud`) to your MCP server. Many IdPs don't do this by default and instead set the audience to the SSO client's identifier. Either is fine, as long as **both ends agree on the expected value**. Pick one: * Configure your IdP to bind the audience to the MCP server, or * *(simplest)* have the MCP server accept the SSO **client identifier** as its expected audience. > [!WARNING] > > Whichever you choose, the MCP server **must** verify the audience — otherwise any token the IdP trusts could call it. Everything else (redirect URIs, user provisioning, and so on) is your existing SSO setup and is unchanged. ## Requirements for your MCP server Your MCP server is treated as a black box. To consume the forwarded identity it must do the following — nothing else about how Dify calls it changes. 1. **Read the forwarded header.** When present, treat `X-Dify-SSO-Token` as the bearer of the end-user token. 2. **Validate the token against the IdP** — verify its signature using the IdP (for example, the IdP's published signing keys, or token introspection). 3. **Verify the issuer** equals your IdP. 4. **Verify the audience**, matching whichever option you chose above. Never skip this check. 5. **Derive the user** from the standard token claims (`sub`, `email`, …) as your application needs. 6. **Reject unauthenticated requests** — do not fall back to anonymous access when a valid token is absent. ## Enable identity forwarding Once your IdP and MCP server meet the requirements above, turn the feature on. **1. Configure OIDC or OAuth2 SSO** In the admin console, configure workspace SSO as OIDC or OAuth2 (not SAML). See [Configure SSO Authentication](/en/3.13.x/administer/sso/introduction). SSO configuration changes take effect immediately — no restart needed. **2. Apply the database migration** Apply the database migration shipped with this release. Existing MCP providers are unaffected — forwarding is off by default. **3. Have each user sign in via SSO once** Each user must sign in through SSO at least once, so Dify can later obtain per-call tokens on their behalf. Console/workspace users and published-Web-App end users are both handled automatically. **4. Turn on forwarding per MCP provider** Go to **Tools → MCP**, select the provider, click **Edit**, enable the **Forward user identity** toggle, and save. The toggle is shown only when SSO is enforced for sign-in (it is hidden on community editions and when SSO is not configured). The switch is **per provider**, so an admin controls in one place which MCP servers receive caller identity. **5. Verify** Run any workflow that calls the provider and confirm the MCP server receives the forwarded token and that it represents the running user. ## Troubleshooting If forwarding doesn't work for a supported caller, check the following: | Situation | What to do | | - | - | | The running user has never signed in via SSO, or their session can no longer be refreshed | Ask the user to (re-)sign in via SSO | | SSO is not configured or disabled | Configure SSO in the admin console | ## Pre-flight checklist * Workspace SSO is OIDC or OAuth2 (not SAML). * The IdP client allows refresh tokens (`offline_access` scope / refresh grant; Google-likes are automatic). * You decided how the audience is bound (the IdP binds it, or the MCP server accepts the SSO client identifier). * The MCP server validates the IdP token (signature, issuer, audience) and rejects anonymous requests. * The database migration has been applied. * Users have signed in via SSO at least once. * **Forward user identity** is enabled on the target MCP provider. # Configuring OAuth2 with Okta Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/sso/okta/oauth2 This document will use Okta as the SSO identity provider to demonstrate how to enable OAuth2 authorization protocol for Dify Enterprise. By enabling this feature, the enterprise login page will use a unified identity authentication entry to enhance security. For enterprise internal users, there's no need to enter complex passwords - they can log in using organizational accounts to pass verification, simplifying the login process. > This document will mention internal users and external users. The following distinctions are made: > Internal members: Members registered within the Dify Enterprise workspace or added through the admin backend. > External users: Members not within Dify Enterprise ## 1. Create a New Application in Okta 1. Access the Okta administrator backend page, navigate to the Applications page. Click the Create App Integration button, select OIDC login method and Web Application application type. ![](https://assets-docs.dify.ai/2025/02/21c12f61141314a3a942f3423086e5ef.png) 2. Fill in the application name according to the page prompts and define the authorization scope according to requirements. * The `Sign-in redirect URIs` field needs to be filled with the Dify Enterprise Callback URL. Please refer to [the section below](#2-obtaining-callback-url) for how to obtain it. * Leave the `Sign-out redirect URIs` field empty. ## 2. Obtaining Callback URL According to the required SSO scope to be enabled, **Callback URLs differ**. System administrators need to fill the Dify Enterprise Callback URL into the corresponding Okta application to complete the creation process. > [tab] Workspace > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New OAuth2 Provider**, and view the Workspace Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-dify-enterprise-url]/console/api/enterprise/sso/oauth2/callback > ``` > [tab] WebApp Members (For Internal Users) > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New OAuth2 Provider**, and view the Workspace Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/members/oauth2/callback > ``` > [tab] WebApp External Users (For External Users) > > Click **Admin Backend** → **Authentication** → **Web App** → **SSO Identity Provider** → **New Identity Provider** → **New OAuth2 Provider**, and view the Web App Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/oauth2/callback > ``` 2. Paste it into the **Sign-in redirect URIs** field in the Okta App and save the application. ## 3. Enable OAuth2 Authentication ### 3.1 Obtain Key Information from Okta Application 1. Go to the "General" page of the Okta application and copy the information from the following fields for subsequent configuration: * Client ID * Client secret ![](https://assets-docs.dify.ai/2025/10/a5128a58f2f96f185ad74ecf267a2d73.jpg) 2. (Optional) Check **Proof Key for Code Exchange (PKCE) → Require PKCE as additional verification** then click **Save**. After checking this option, Okta will enforce verification of the `code_verifier` when exchanging authorization codes for tokens, reducing the risk of authorization code interception attacks. 3. Switch to the "Sign On" page and set the **Issuer** to a fixed link. ![](https://assets-docs.dify.ai/2025/02/0cf3c5b1c3b662e48d65827ae3b34ca4.png) ### 3.2 Configure OAuth2 Authentication Access the Dify Enterprise Authentication page, click **+ New Identity Provider → New OAuth2 Provider**, and fill in the following information according to the prompts: * **Client ID** * **Client Secrets** * If PKCE verification is enabled in the Okta application, you need to enable the **PKCE Additional Verification** switch in the window The basic information of different OAuth2 providers varies, please refer to the official documentation of each provider. The following information is for reference only and can be adjusted according to actual needs. * **Authorization Endpoint**: `https://your-okta-issuer-url/v1/authorize` * **Token Endpoint**: `https://your-okta-issuer-url/v1/token` * **User Info Endpoint**: `https://your-okta-issuer-url/v1/userinfo` * **Scopes**: `openid,profile,email` > How to obtain `your-okta-issuer-url`: **Security → API → Authorization Servers → Issuer URI**. For more information on how to obtain more field information through Okta App, please refer to [Use of the Issuer](https://support.okta.com/help/s/article/What-is-theIssuerlocated-under-the-OpenID-Connect-ID-Token-app-settings-used-for?language=en_US). ## 4. Enable SSO Mandatory Authentication (Optional) System administrators can enable **SSO Enforcement** options for the following two scenarios to enable mandatory authentication: * **Workspace**: Requires authorization when logging into Dify Enterprise Workspace. * **WebApp**: Requires verification when using applications created by the current Dify Enterprise. After enabling, accessing the corresponding scenarios will prompt for access authorization. ![](https://assets-docs.dify.ai/2025/02/87bf868d0058723607311265a57888c5.png) # Configuring OIDC with Okta Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/sso/okta/oidc This document will use Okta as the SSO identity provider to demonstrate how to enable OIDC authentication protocol for Dify Enterprise. By enabling this feature, the enterprise login page will use a unified identity authentication entry to enhance security. For enterprise internal users, there's no need to enter complex passwords - they can log in using organizational accounts to pass verification, simplifying the login process. > This document will mention internal users and external users. The following distinctions are made: > Internal members: Members registered within the Dify Enterprise workspace or added through the admin backend. > External users: Members not within Dify Enterprise ## 1. Create a New Application in Okta 1. Access the Okta administrator backend page, navigate to the Applications page. Click the Create App Integration button, select OIDC login method and Web Application application type. ![](https://assets-docs.dify.ai/2025/02/21c12f61141314a3a942f3423086e5ef.png) 2. Fill in the application name according to the page prompts and define the authorization scope according to requirements. * The `Sign-in redirect URIs` field needs to be filled with the Dify Enterprise Callback URL. Please refer to [the section below](#2-configuring-okta-application) for how to obtain it. * Leave the `Sign-out redirect URIs` field empty. ## 2. Configuring Okta Application According to the required SSO scope to be enabled, **Callback URLs differ**. System administrators need to fill the Dify Enterprise Callback URL into the corresponding Okta OAuth2 application to complete the creation process. > [tab] Workspace > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New OIDC Provider**, and get the Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-dify-enterprise-url]/console/api/enterprise/sso/oidc/callback > ``` > [tab] WebApp Members (For Internal Users) > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New OIDC Provider**, and get the Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/members/oidc/callback > ``` > [tab] WebApp External Users (For External Users) > > Click **Admin Backend** → **Authentication** → **Web App** → **SSO Identity Provider** → **New Identity Provider** → **New OIDC Provider**, and get the Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/oidc/callback > ``` 2. Paste it into the **Sign-in redirect URIs** field in the Okta App and save the application. ## 3. Enable OIDC Authentication ### 3.1 Obtain Key Information from Okta Application 1. Go to the "General" page of the Okta application and find the following fields: * Client ID * Client secret ![](https://assets-docs.dify.ai/2025/10/a5128a58f2f96f185ad74ecf267a2d73.jpg) 2. (Optional) Check **Proof Key for Code Exchange (PKCE) → Require PKCE as additional verification** then click **Save**. After checking this option, Okta will enforce verification of the `code_verifier` when exchanging authorization codes for tokens, reducing the risk of authorization code interception attacks. 3. Switch to the "Sign On" page and find the Issuer field, set the **Issuer** to a fixed link and copy the information. ![](https://assets-docs.dify.ai/2025/02/0cf3c5b1c3b662e48d65827ae3b34ca4.png) ### 3.2 Configure OIDC Authentication Access the Dify Enterprise Authentication page, click **+ New Identity Provider → New OIDC Provider**, and fill in the following information according to the prompts: * **Issuer URL** * **Client ID** * **Client Secrets** * If PKCE verification is enabled in the Okta application, you need to enable the **PKCE Additional Verification** switch in the window ## 4. Enable SSO Mandatory Authentication (Optional) System administrators can enable **SSO Enforcement** options for the following two scenarios to enable mandatory authentication: * **Workspace**: Requires authorization when logging into Dify Enterprise Workspace. * **WebApp**: Requires verification when using applications created by the current Dify Enterprise. After enabling, accessing the corresponding scenarios will prompt for access authorization. ![](https://assets-docs.dify.ai/2025/02/87bf868d0058723607311265a57888c5.png) # Configuring SAML with Okta Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/sso/okta/saml This document will use Okta as the SSO identity provider to demonstrate how to enable SAML authentication protocol for Dify Enterprise. By enabling this feature, the enterprise login page will use a unified identity authentication entry to enhance security. For enterprise internal users, there's no need to enter complex passwords - they can log in using organizational accounts to pass verification, simplifying the login process. ## 1. Create a New Application in Okta 1. Access the Okta administrator backend page, navigate to the Applications page, and click the Create App Integration button. ![](https://assets-docs.dify.ai/2025/05/49d2eb9547c644a90a50e7ac1972b90c.png) 2. Select "SAML 2.0" application type. ![](https://assets-docs.dify.ai/2025/05/409f64e068449c2f9dc9c3e471a36946.png) 3. After clicking Next, you will be navigated to the Configure SAML page, where you need to fill in some parameters. Please wait a moment and open a new browser tab, follow the instructions below to get the necessary information, then continue filling. ## 2. Configure Okta Application System administrators need to fill the Dify Enterprise Callback URL into the Okta application. > [tab] Workspace > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > ![](https://assets-docs.dify.ai/2025/06/a45a2d156196ae163e7944cdad7ec2da.png) > > It usually follows this format: > > ```bash theme={null} > https://[your-dify-enterprise-url]/console/api/enterprise/sso/saml/acs > ``` > [tab] WebApp Members (For Internal Users) > > Click **Admin Backend** → **Authentication** → **Members** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > ![](https://assets-docs.dify.ai/2025/06/a45a2d156196ae163e7944cdad7ec2da.png) > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/members/saml/acs > ``` > [tab] WebApp External Users (For External Users) > > Click **Admin Backend** → **Authentication** → **Web App** → **SSO Identity Provider** → **New Identity Provider** → **New SAML Provider**, and get the Callback URL at the bottom. > > It usually follows this format: > > ```bash theme={null} > https://[your-app-url]/api/enterprise/sso/saml/acs > ``` Paste it into the Single sign-on URL and Audience URI (SP Entity ID) fields on the Configure SAML page. ![](https://assets-docs.dify.ai/2025/05/e6c1a1521306919ab325030adafb2d2b.png) After filling in the URL, continue to complete the following settings: * Set Name ID format to EmailAddress * Under "Show Advanced Settings", verify that response and assertion signatures are set to Signed 4. Click the "Next" button to complete the setup. ## 3. Complete Configuration on Dify 1. First go to the "Sign On" page of the Okta application and find the following information: * Sign-on URL * Signing certificate ![](https://assets-docs.dify.ai/2025/05/edd232ff0c1e0a28243fdce755f8ea1b.png) 2. Then go to the "Assignments" page to assign members who are allowed to use SSO login. ![](https://assets-docs.dify.ai/2025/05/7ce55440e9bce1965712e167ab8e8567.png) 3. Finally, return to the Authentication page of Dify Enterprise, click **"+ New Identity Provider → New SAML Provider"**, then fill in the information obtained above to complete the configuration. When filling in the X509 Signing Certificate, please refer to the following format: ``` -----BEGIN CERTIFICATE----- {certificate} -----END CERTIFICATE----- ``` ![](https://assets-docs.dify.ai/2025/05/1548ea93cfa68352384295fef8b038e3.png) ## 4. Enable SSO Mandatory Authentication (Optional) System administrators can enable **SSO Enforcement** options for the following two scenarios to enable mandatory authentication: * **Workspace**: Requires authorization when logging into Dify Enterprise Workspace. * **WebApp**: Requires verification when using applications created by the current Dify Enterprise. After enabling, accessing the corresponding scenarios will prompt for access authorization. # Two-Factor Verification Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/systems/2sv ## Introduction The enterprise backend contains a large amount of sensitive user information. Two-factor verification can provide deeper security protection for Dify Enterprise system administrator accounts. After enabling this feature, even if the original password is accidentally leaked, unauthorized access operations can still be prevented, ensuring the security of system administrator accounts and enterprise backend data. This mechanism requires users to enter a real-time verification code generated by an authenticator application after entering the correct password to complete login. This "two-factor" verification significantly improves account security. ## Implementation Prerequisites Before configuring two-factor verification, please ensure the following conditions are met: 1. **System Administrator Permissions** - Only system administrators can configure two-factor verification. 2. **Authenticator Application** - Install a compatible authenticator application on your mobile device. > [!NOTE] > > Authenticator applications (such as [Google Authenticator](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2)) are based on the TOTP (Time-based One-Time Password) standard and generate a new verification code every 30 seconds. ## Enable Two-Factor Verification Before enabling global two-factor verification for the team, ensure that two-factor verification has been configured for personal accounts. ### Personal Account Steps to configure personal two-factor verification: **1. Access Admin Backend** Log in to the Dify Enterprise admin backend. **2. Open Two-Factor Verification Settings** In the sidebar menu, click the "Two-Factor Verification" option. **3. Configure Authenticator** Find the authenticator section and click the "Configure" button on the right. **4. Scan QR Code** Use your authenticator application to scan the displayed QR code. **5. Enter Verification Code** Enter the six-digit verification code displayed by the authenticator application in the verification box to complete setup. If you cannot scan the QR code, hover over **Setup Key** to view the key text. Enter it into the authenticator to generate a six-digit verification code, and fill in this verification code in the verification box. ![](https://assets-docs.dify.ai/2025/04/fd6b474384081f4079aa453c45c07562.png) After enabling two-factor verification, backup codes will be generated simultaneously. To avoid being unable to obtain online verification codes due to loss of the device with the authenticator, it is recommended to handwrite or print backup codes in a safe place. ![](https://assets-docs.dify.ai/2025/04/2c88c1492bf9a079df9ad4a25e1923ac.png) Backup codes are one-time use only; used backup codes will become invalid. If you need more backup codes, click "Regenerate". ![](https://assets-docs.dify.ai/2025/04/8313cf497c66cfef7dee2a4ae816c32b.png) ### Enterprise Global > All system administrators have the permission to enable enterprise global two-factor verification; personal two-factor verification must be enabled before allowing enterprise global verification to be enabled. Go to **Settings** → **Authentication** to enable enterprise global two-factor verification. Once enabled, each system administrator will be required to provide an additional verification code when logging in to the enterprise admin backend. If any system administrator has not yet set up two-factor verification, please refer to [Common Issues](#how-do-administrators-who-have-not-enabled-personal-account-two-factor-verification-log-in-after-global-mandatory-two-factor-verification-is-enabled). ![](https://assets-docs.dify.ai/2025/04/1271b3b0e39558465dbb79b17d1a9721.png) ## Modify Two-Factor Verification Access the enterprise admin backend, click "Two-Factor Verification", click the "Edit" button in the menu options on the right side of the authenticator. In the pop-up verification page, enter the new six-digit verification code displayed by the authenticator to confirm identity and complete the modification. ## Disable Two-Factor Verification > [!WARNING] > > Disabling two-factor verification removes the additional security layer, making accounts rely only on password protection, significantly increasing the risk of unauthorized access. ### Personal Account > If the enterprise backend has enabled global mandatory two-factor verification, personal account two-factor verification cannot be disabled. Access the enterprise admin backend, click "Two-Factor Verification" → "Disable Two-Factor Verification". ### Enterprise Global Access the enterprise admin backend, click **"Settings" → "Authentication"** to turn off the two-factor verification button. > [!NOTE] > > When enabling, modifying, or disabling two-factor verification, system administrators will receive corresponding notifications in their email. ## Common Issues ### I lost the device with the authenticator, how should I log in? If you forget or lose the original device, use the following methods to log in: 1. **Use backup codes to log in**: Select the "Use backup code" option on the login page and enter a previously saved backup code. Note that each backup code can only be used once. 2. **Contact other system administrators**: If you don't have backup codes, please contact other system administrators in the team to request temporary access or assistance in resetting two-factor verification settings. ### Two-factor verification code is correct but system shows error, how to resolve? Verification code errors usually have the following causes: 1. **Time not synchronized**: Authenticators generate verification codes based on time, ensure your device time is synchronized with standard time. Most smartphones automatically sync time, but if you have disabled automatic sync, please enable it in device settings. 2. **Verification code expired**: Authenticator verification codes usually update every 30 seconds. If you enter the code when it's about to expire, it may become invalid. Please wait for a new verification code to be generated before trying again. 3. **Device and account mismatch**: Confirm you are using the correct authenticator and correct account to generate the verification code. ### How to migrate authenticator after changing phones? There are two methods to migrate the application: 1. **Use in-app migration feature**: Some authenticators (such as the latest version of Google Authenticator) provide account export/import functions, which can be used to migrate authenticator information to new devices. 2. **Reset two-factor verification**: * Use backup codes to log in to the system. * Refer to [Modify Two-Factor Verification](#modify-two-factor-verification), go to personal two-factor verification settings page, click "Edit". * Complete verification using verification codes generated by the new device. ### How do administrators who have not enabled personal account two-factor verification log in after global mandatory two-factor verification is enabled? When global mandatory two-factor verification is enabled, the login process for administrators who have not enabled two-factor verification is: 1. New administrators log in to the system using email and password (or SSO). 2. The system will automatically detect that the administrator has not configured two-factor verification and provide two-factor verification operation guidance on the enterprise login page. 3. New administrators need to download an authenticator application and complete two-factor verification setup according to the page prompts. 4. After setup is complete, entering the six-digit verification code will allow new administrators to continue logging in to the enterprise backend. # System Administrators Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/systems/users System administrators can manage system administrator users for the current enterprise edition on the Settings page, with the following permissions: * Log in to the enterprise admin backend * Add / Delete / Disable team members * Add Owners to Workspaces * Add new members to Workspaces and assign permissions ## Managing System Administrators ### Adding System Administrators The creator of the enterprise backend is the first system administrator by default. Any system administrator can invite others to become system administrators. Click the blue Add button in the upper right corner of the Settings page, enter the user's name and email to complete the addition. ![](https://assets-docs.dify.ai/2025/05/cb2bad848e40760140e7aa6e25eb2a42.png) If a system administrator's email is not added to the "Members" list, they do not have permission to create and use workspaces. If you want the system administrator to also be able to create or join a Workspace, please refer to [Adding Members to Workspace](/en/3.13.x/administer/members-management). ### Modifying System Administrator Information Select a system administrator, click the menu button on the right, click Edit, and modify the system administrator's name or email in the pop-up tab. ![](https://assets-docs.dify.ai/2025/05/174d265a01cca44c60ae34dc9c0ff4a5.png) ### Resetting System Administrator Password If a member has lost their password, a system administrator needs to manually send a password reset email. Click the menu button on the right side of the member, click Reset Password. ![](https://assets-docs.dify.ai/2025/05/aa143894091c9e4990c5993163df637a.png) ### Disabling System Administrator Select a system administrator, click the menu button on the right, click Edit, and switch the member's Status to banned. Disabled administrators will not be able to access the enterprise backend. ![](https://assets-docs.dify.ai/2025/05/3ee32101ff701db88b8b16e7a6db4587.png) ### Deleting Administrator ⚠️ Dangerous operation, please handle with caution Click the menu button on the right side of the system administrator, click Delete. ### Searching Administrators You can search for system administrators by entering their email in the search box. ![](https://assets-docs.dify.ai/2025/05/487f328e311a0242d7216a4a8ce15ba7.png) ## Security Recommendations ### Two-Factor Authentication (2FA) **Applicable to:** System administrator users only **Features:** * Additional security verification layer * Based on TOTP (Time-based One-Time Password) * Supports multiple authenticator applications * Mandatory or optional configuration **Configuration Steps:** 1. System administrator logs in to the admin backend 2. Go to **System Settings** → **Security Settings** 3. Enable two-factor verification 4. Scan QR code to bind authenticator 5. Enter verification code to complete binding For detailed configuration instructions, please refer to [Two-Factor Verification](/en/3.13.x/administer/systems/2sv). # Workspace Management Source: https://enterprise-docs.dify.ai/en/3.13.x/administer/workspace-management A Workspace is a space where team members create and manage various AI applications. Administrators can view and manage all workspaces on the Workspaces page in the Enterprise Admin Panel. ## Create New Workspace Click the blue **Add** button in the top right corner of the workspace page, enter a name, and specify the email of a team member to create a new workspace within the team. Each workspace needs to be assigned an Owner. For details on member permissions within a workspace, please refer to [Member Management](/en/3.13.x/administer/members-management). ## Manage Workspace To rename a workspace or change its status, click the menu button on the right side of the workspace and select **Edit**. To hand a workspace to a different owner, select **Transfer Owner** instead and pick the new owner. The previous owner keeps their other roles, or becomes a Restricted Member if they have none. The new owner's existing roles are replaced by Owner. ![](https://assets-docs.dify.ai/2025/05/fb8b7bcd82da8ca91625fdb73cd516df.png) ## View Members in Workspace Administrators can view the Owner and members of any workspace. Select any workspace, click the menu button on the right, and select **Show Member**. ![](https://assets-docs.dify.ai/2025/05/02345b2cf02627d22f6ceb18d2e37325.png) ## Add Members to Workspace To add a member to a workspace, click the menu button on the right side of the workspace, select **Join Member**, choose a role for the new member, and enter the member's email. See [Roles and Permissions](/en/3.13.x/use/workspace/roles-and-permissions) for what each role allows. Once members are added to a workspace, they can only be removed through the workspace's **Members** settings. ## Adjust Workspace Status Workspaces contain the following two states: * **Normal** The current workspace is running normally, and members can use or create applications in the workspace normally. * **Archive** The current workspace has been archived, and members can no longer use or create applications in the workspace. ## Delete Workspace ⚠️ This operation is dangerous, please proceed with caution. Click the menu button on the right side of the workspace and click "Delete" to complete the deletion. After deleting a workspace, the AI applications within it will no longer be available. ## Search Workspace Administrators can query all workspaces in the Enterprise Edition through the workspace ID and name in the search box. Clicking "Reset" will reset all search conditions. ![](https://assets-docs.dify.ai/2025/04/9060f34d41d5c8b86deef885b8598a64.png) ## Workspace Permission Configuration Administrators can select a specific workspace and click **Permission Settings** to configure: * Whether to allow workspace administrators to invite and add new members to the workspace. * Whether to allow the workspace owner to transfer workspace ownership to others. ## Set Default Workspace Administrators can select a specific workspace as the default workspace. All new members entering the enterprise system thereafter will automatically join this workspace with the role of **Member**. After canceling the default workspace, members who have already joined the workspace will not be affected. # Agent Sandbox Deployment Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/agent-sandbox Install the agent-sandbox controller, configure the Helm values, and choose between dedicated-Pod and shared sandbox modes While executing tasks, an Agent runs commands and reads/writes files inside an isolated sandbox environment. In a Kubernetes deployment, this capability consists of the following components: * `agent-backend`: the Agent runtime service, deployed by the Helm Chart. * `sandbox-gateway`: the sandbox control plane responsible for sandbox allocation and reclamation, deployed by the Helm Chart. * `agent-sandbox` controller: the official Kubernetes community project [kubernetes-sigs/agent-sandbox](https://github.com/kubernetes-sigs/agent-sandbox), which provides the sandbox CRDs and controller. It must be installed in the cluster in advance. Each Agent session gets a dedicated sandbox Pod. A warm pool keeps allocation fast, and Pods are automatically reclaimed when the session ends or idles out. If your cluster does not allow installing third-party CRDs and controllers, use the [shared sandbox mode](#alternative-without-agent-sandbox-shared-sandbox-mode) instead, which requires no cluster-level changes. ## Install the agent-sandbox controller Installation requires cluster admin privileges and is performed once per cluster: ```bash theme={null} export VERSION="v0.5.2" kubectl apply -f https://github.com/kubernetes-sigs/agent-sandbox/releases/download/${VERSION}/sandbox-with-extensions.yaml ``` Confirm the CRDs are ready: ```bash theme={null} kubectl get crd | grep agents.x-k8s.io ``` The following 4 CRDs should be present: * `sandboxes.agents.x-k8s.io` * `sandboxclaims.extensions.agents.x-k8s.io` * `sandboxtemplates.extensions.agents.x-k8s.io` * `sandboxwarmpools.extensions.agents.x-k8s.io` For air-gapped environments, download the manifest above and import it into your internal network, sync the controller image to your private registry, and replace the image references accordingly. ## Helm Chart configuration Both `agentBackend.enabled` and `sandboxGateway.enabled` default to `true`, so a standard deployment enables the sandbox capability out of the box, provided the controller installation above has been completed. Run `helm show values dify/dify` to see all available options. Below is an example of the Agent Sandbox related configuration: ```yaml theme={null} agentBackend: enabled: true serverSecretKey: "#REPLACE_ME#" sandboxGateway: enabled: true provision: warmPoolReplicas: 1 requestsCpu: "250m" requestsMemory: "256Mi" limitsCpu: "1" limitsMemory: "1Gi" agentRuntime: image: repository: langgenius/dify-ee-agent-runtime tag: "3.13.0" ``` * `agentBackend.enabled` * Whether to deploy agent-backend. When disabled, the Agent app is not available in the console. * `agentBackend.serverSecretKey` * Encryption key for Agent tool callback tokens: a base64url-encoded 32-byte random value. The default value must be replaced in production. Generate one with: ```bash theme={null} python3 -c "import secrets; print(secrets.token_urlsafe(32))" ``` * `sandboxGateway.enabled` * Whether to enable the dedicated-Pod sandbox mode. When disabled, the deployment automatically falls back to the [shared sandbox mode](#alternative-without-agent-sandbox-shared-sandbox-mode) with no extra configuration. * `agentRuntime.image` * The sandbox runtime image, shared by both the dedicated-Pod mode and the shared sandbox mode. The sandbox ships with Python 3.12, Node.js 22, pnpm, uv, git, and other common tools. See [Customize the sandbox image](#customize-the-sandbox-image) below for customization. * `sandboxGateway.provision.warmPoolReplicas` * Warm pool size, i.e. the number of idle sandboxes kept on standby. Adjust according to Agent concurrency. * `sandboxGateway.provision.requestsCpu` / `requestsMemory` / `limitsCpu` / `limitsMemory` * Resource configuration for a single sandbox Pod. For capacity planning, running N concurrent Agent sessions requires headroom for roughly N + `warmPoolReplicas` sandbox Pods. Other optional settings: * `sandboxGateway.namespace`: namespace for sandbox Pods, defaults to the release namespace. * `sandboxGateway.provision.sandboxTtl`: maximum lifetime of a single sandbox, default `1800s`. * `sandboxGateway.inactiveTtl`: idle reclamation time for sandboxes, default `360s`. * `sandboxGateway.execTimeout`: execution timeout for a single command, default `300s`. * `sandboxGateway.provision.extraEnv`: extra environment variables injected into sandbox Pods, e.g. egress proxy settings. * `sandboxGateway.provision.volumeClaimTemplates`: persistent volumes mounted into sandbox Pods; each entry creates a PVC. * `sandboxGateway.provision.securityContext` / `podSecurityContext`: security contexts for sandbox Pods, configure as needed when the cluster enforces Pod Security Standards. * The global `imagePullSecrets` is automatically propagated to sandbox Pods; no extra configuration is needed for private registries. ## Sandbox network policy Egress traffic from sandbox pods is controlled by two layers, both enabled by default: **SSRF proxy**: the chart deploys a dedicated squid proxy for sandboxes (`agent-sandbox-ssrf-proxy`) and injects `HTTP_PROXY` / `HTTPS_PROXY` into sandbox pods, forcing all outbound HTTP(S) traffic through it. By default the proxy blocks requests to private (RFC1918 and similar) address ranges, providing SSRF protection. The proxy itself is configured via `sandboxGateway.ssrfProxy` (`replicas` / `image` / `resources` / `squidConf`). **NetworkPolicy**: `sandboxGateway.provision.networkPolicy` defaults to `enabled: true` and only allows the following egress: DNS (kube-dns/coredns in kube-system), agent-backend (port 5050), the SSRF proxy (port 3128), and the external internet (`allowExternalEgress: true`, excluding private ranges). Sandboxes cannot reach dify-api directly. If sandboxes need to reach other in-cluster services or internal addresses, both layers must be opened: 1. Add allow rules for the target addresses via `networkPolicy.extraEgressRules`; 2. Override `sandboxGateway.ssrfProxy.squidConf` and insert allow rules for the targets before the default `deny private_dst` rule. When opening additional egress destinations, weigh the [Security Notice: Agent Environment Variable Exfiltration Risk](/en/3.13.x/use/build/new-agent/overview): an agent that can reach the network can encode and transmit sensitive values despite output masking. Other options: * With `networkPolicy.enabled: false`, the agent-sandbox controller's secure defaults take over: only the public internet is reachable and **all private (RFC1918) addresses are blocked**. * `networkPolicy.management: "Unmanaged"` skips NetworkPolicy provisioning entirely, leaving it to the cluster to manage. ## Home Snapshot Home Snapshot captures a sandbox's home directory into object storage and restores it into the next sandbox, carrying the agent's [persistent files](/en/3.13.x/use/build/new-agent/build#file-system) across sessions. Archives go to the bucket configured under `persistence`, so there is nothing extra to configure. Every object-storage `persistence.type` is supported, in both managed-identity and account-key modes. > [!NOTE] > > Home Snapshot requires object storage: `persistence.type: local` (the chart default) is not supported. Tune it under `sandboxGateway.homeSnapshot`: * `enabled`: default `true`. Turns snapshot capture and restore off entirely. * `keyPrefix`: default `"home-snapshots/"`. Key prefix for snapshot archives inside the bucket. * `maxSizeBytes`: default `67108864` (64 MiB). Largest archive the gateway accepts from a sandbox. * `maxConcurrent`: default `4`. How many saves and restores the gateway runs at once, across all sandboxes; requests past the limit are rejected with `429 snapshot_busy` rather than queued. * `snapshotTimeout`: default `"30s"`. Deadline for the sandbox runtime call; object-storage reads and writes happen outside it and are not covered. * `runtimePort`: default `5004`. Port the sandbox runtime's HTTP server listens on. * `excludes`: default empty. Home entries to leave out of snapshot archives, as gitignore patterns matched at any depth: `"*.log"`, `"**/node_modules"`, `"/build"` to anchor at the home root, `"cache/"` for directories only, `"!keep"` to re-include. > [!WARNING] > > The gateway buffers each archive entirely in memory and ships with no resource limits. To avoid OOM under concurrent snapshots, size `sandboxGateway.resources` against `maxConcurrent × maxSizeBytes × 3` (the buffer grows geometrically, so a 64 MiB archive peaks near 192 MiB). ## Deploy and verify Apply the updated values with an upgrade: ```bash theme={null} helm upgrade dify dify/dify -n dify -f values.yaml ``` Helm automatically creates the `SandboxTemplate` and `SandboxWarmPool` resources in the namespace (`sandboxGateway.provision.managedByHelm` defaults to `true`); no manual creation is needed. Verify the deployment: ```bash theme={null} # Services ready kubectl get pods -n dify | grep -E 'agent-backend|sandbox-gateway' # Warm pool sandboxes created kubectl get sandboxwarmpools,sandboxes -n dify ``` Log in to the Dify console, create an Agent app, and run a task that executes commands. During execution you should see new sandbox Pods appear in the namespace, which are automatically reclaimed when the session ends or idles out. ## RBAC permissions Enabling this feature introduces the following cluster permission changes, for security review reference: * The `agent-sandbox` controller is a cluster-scoped component responsible for creating and deleting sandbox Pods based on the CRDs. * sandbox-gateway uses a namespace-scoped Role (created by the Chart, controlled by `sandboxGateway.rbac.create`) containing only: * read/write on `sandboxclaims` (sandbox lifecycle management); * read-only on `sandboxtemplates` / `sandboxwarmpools` (the resources themselves are created by Helm); * read-only on `sandboxes` (status queries). * sandbox-gateway has no permissions on native resources such as Pods, Secrets, or ConfigMaps, and no cluster-scoped permissions. To use a centrally managed ServiceAccount, set `sandboxGateway.rbac.create: false` and specify it via `sandboxGateway.serviceAccountName`. ## Alternative without agent-sandbox (shared sandbox mode) If your cluster does not allow installing third-party CRDs and controllers, simply set `sandboxGateway.enabled` to `false`. The Chart then automatically deploys a long-running agent-runtime service, and all Agent sessions share a single sandbox container instead of getting dedicated Pods: ```yaml theme={null} agentBackend: enabled: true serverSecretKey: "#REPLACE_ME#" sandboxGateway: enabled: false agentRuntime: image: repository: langgenius/dify-ee-agent-runtime tag: "3.13.0" ``` * This mode installs no CRDs and introduces no additional RBAC permissions. * All sessions share one container, so isolation is weaker than the dedicated-Pod mode, and only a single replica is supported. Recommended only as a fallback for restricted environments. * Adjust resources via `agentRuntime.resources`. ## Customize the sandbox image To provide additional tools, SDKs, or internal CA certificates inside the sandbox, build on top of the official image: ```dockerfile theme={null} FROM langgenius/dify-ee-agent-runtime:3.13.0 USER root RUN apt-get update \ && apt-get install -y --no-install-recommends \ && rm -rf /var/lib/apt/lists/* USER dify ``` Observe the following constraints, or the sandbox will not work: 1. Do not override the image's default `CMD` / `ENTRYPOINT`; the sandbox service must listen on port 5004. 2. Do not remove the `shellctl*` and `dify-agent` binaries under `/usr/local/bin`. 3. Switch to `USER root` to install system packages, and always switch back to `USER dify` afterwards. 4. Keep the `/home/dify` and `/mnt/drive` directories and their ownership. After building and pushing the image, update `agentRuntime.image` in your values and run `helm upgrade`. In dedicated-Pod mode the warm pool rolls over to the new image automatically; in shared sandbox mode the agent-runtime deployment restarts on rollout. ## FAQ * **No Agent app entry in the console** * Confirm `agentBackend.enabled` is `true`. * **sandbox-gateway fails to start with CRD-not-found errors** * The agent-sandbox controller is not installed. Complete the installation steps above, or switch to the shared sandbox mode if installation is not possible. * **Sandbox Pods stuck in Pending or ImagePullBackOff** * Check node resource headroom; when using a private registry, confirm the global `imagePullSecrets` is configured. * **Sandbox cannot reach in-cluster services or internal addresses** * Egress goes through the SSRF proxy by default and only DNS, agent-backend, and the external internet are allowed. Open both layers: add the targets to `networkPolicy.extraEgressRules` and allow them in `sandboxGateway.ssrfProxy.squidConf`; see [Sandbox network policy](#sandbox-network-policy). * **Agent command execution times out** * A single command is limited to 300 seconds by default; adjust via `sandboxGateway.execTimeout`. * **Sandbox reclaimed while a session is in progress** * The sandbox idled longer than `inactiveTtl` (default 360s) or lived longer than `sandboxTtl` (default 1800s); increase them as needed. # Custom CA Certificate Configuration Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/ca This guide explains how to configure custom Certificate Authority (CA) certificates for Dify Enterprise in Helm Chart deployments. This feature is essential for environments that use self-signed certificates or private PKI infrastructure. ## Overview When enabled, Dify will trust both system-wide CA certificates and your custom CA certificate for all outbound HTTPS connections. This is particularly useful when: * Your organization uses an internal PKI (Public Key Infrastructure). * You are deploying in air-gapped environments with self-signed certificates. * External services (Redis, databases, S3, vector databases, etc.) use certificates signed by a private CA. * You need to establish trust with internal HTTPS endpoints. ## How It Works The custom CA implementation uses the following approach: 1. **Initialization**: An init container runs before each Dify pod starts. 2. **CA Bundle Creation**: The init container combines system CA certificates (from the base image) with your custom CA certificate (from a Kubernetes Secret). 3. **Environment Setup**: Environment variables are configured to point Python, Node.js, curl, and AWS CLI to the combined CA bundle. 4. **Runtime Trust**: All Dify components use the combined CA bundle for SSL/TLS verification. ## Prerequisites * Kubernetes cluster with Dify Helm chart installed (or ready to install). * Your custom CA certificate in PEM format. * `kubectl` access to your cluster. * Basic understanding of Kubernetes Secrets. *** ## Configuration Steps ### 1. Prepare Your CA Certificate Your CA certificate must be in **PEM format** (Base64-encoded, enclosed in `BEGIN CERTIFICATE` and `END CERTIFICATE` markers). Verify your certificate format: ```bash theme={null} # Your certificate should look like this: cat your-ca.crt # -----BEGIN CERTIFICATE----- # MIIDXTCCAkWgAwIBAgIJAKJ... (Base64 content) # ... # -----END CERTIFICATE----- ``` If you have a DER-encoded certificate, convert it to PEM: ```bash theme={null} openssl x509 -inform der -in your-ca.der -out your-ca.crt ``` ### 2. Create a Kubernetes Secret Create a Kubernetes Secret containing your CA certificate. ```bash theme={null} kubectl create secret generic dify-custom-ca \ --from-file=ca.crt=your-ca.crt \ --namespace= ``` > **Note**: > > * **Secret name**: `dify-custom-ca` (you can choose any name). > * **Key name**: `ca.crt` (default, can be customized in `values.yaml`). > * **Namespace**: Must be in the same namespace as your Dify deployment. Verify the secret was created: ```bash theme={null} kubectl get secret dify-custom-ca -n kubectl describe secret dify-custom-ca -n ``` ### 3. Configure values.yaml Edit your Helm `values.yaml` file to enable custom CA. ```yaml theme={null} global: customCA: # Enable custom CA certificate support enabled: true # Name of the Kubernetes secret containing your CA certificate existingSecret: "dify-custom-ca" # Key name in the secret (must match the key you used in Step 2) key: ca.crt # Mount path for the combined CA bundle inside containers # (Advanced: usually no need to change this) mountPath: /etc/dify/custom-ca # Init container image used to combine system CAs with custom CA # For air-gapped environments, replace with your private registry initImage: alpine:3.20 ``` **Minimal configuration (using defaults):** ```yaml theme={null} global: customCA: enabled: true existingSecret: "dify-custom-ca" ``` ### 4. Deploy or Update Dify **For new installations:** ```bash theme={null} helm install dify dify/dify \ --namespace dify \ --values values.yaml ``` **For existing installations:** ```bash theme={null} helm upgrade dify dify/dify \ --namespace dify \ --values values.yaml ``` > **Note**: Changes to the custom CA configuration require a pod restart to take effect. The CA bundle is generated once during pod initialization. *** ## Verification After deployment, verify that the custom CA is properly configured. ### 1. Check Init Containers Check if the init containers ran successfully. ```bash theme={null} # List pods kubectl get pods -n dify # Check init container logs for a specific pod (e.g., api pod) kubectl logs -n dify -c init-custom-ca ``` You should see output indicating the CA bundle was created successfully. ### 2. Verify Environment Variables Exec into a running pod and check the environment variables. ```bash theme={null} # Exec into a running pod kubectl exec -it -n dify -- sh # Check environment variables env | grep -E 'SSL_CERT_FILE|REQUESTS_CA_BUNDLE|CURL_CA_BUNDLE|NODE_EXTRA_CA_CERTS|AWS_CA_BUNDLE' ``` **Expected output:** ```bash theme={null} SSL_CERT_FILE=/etc/dify/custom-ca/ca-bundle.crt REQUESTS_CA_BUNDLE=/etc/dify/custom-ca/ca-bundle.crt CURL_CA_BUNDLE=/etc/dify/custom-ca/ca-bundle.crt NODE_EXTRA_CA_CERTS=/etc/dify/custom-ca/ca-bundle.crt AWS_CA_BUNDLE=/etc/dify/custom-ca/ca-bundle.crt ``` ### 3. Verify CA Bundle Content Inside the pod, verify the bundle contains your certificate. ```bash theme={null} # Inside the pod cat /etc/dify/custom-ca/ca-bundle.crt | grep -A 5 "BEGIN CERTIFICATE" | tail -10 # Count certificates in the bundle grep -c "BEGIN CERTIFICATE" /etc/dify/custom-ca/ca-bundle.crt ``` The bundle should contain multiple certificates (system CAs + your custom CA). *** ## Environment Variables Reference The custom CA feature sets the following environment variables to ensure broad compatibility. All variables point to the same combined CA bundle: `/etc/dify/custom-ca/ca-bundle.crt` (or your custom `mountPath`). | Variable | Purpose | Used By | | :- | :- | :- | | `SSL_CERT_FILE` | OpenSSL/LibreSSL | General SSL libraries, Python requests | | `REQUESTS_CA_BUNDLE` | Python requests library | Python HTTP clients | | `CURL_CA_BUNDLE` | curl command | Shell scripts, curl-based tools | | `NODE_EXTRA_CA_CERTS` | Node.js | Node.js HTTPS client | | `AWS_CA_BUNDLE` | AWS SDK | S3, AWS service connections | *** ## Affected Components When custom CA is enabled, the following Dify components automatically use the custom CA bundle: * API Server (`api-deployment`) * Worker (`worker-deployment`) * Worker Beat (`worker-beat-deployment`) * Trigger Worker (`trigger-worker-deployment`) * Enterprise Service (`enterprise-deployment`) * Enterprise Audit (`enterprise-audit-deployment`) * Sandbox (`sandbox-deployment`) * Gateway (`caddy-deploy`) * SSRF Proxy (`ssrf-proxy-deployment`) * Unstructured (`unstructured-deployment`) * Plugin Daemon (`plugin-daemon`) * Plugin Manager (`plugin-manager`) * Plugin Controller (`plugin-controller`) *** ## Troubleshooting ### Pods stuck in Init:0/1 **Cause**: Init container `init-custom-ca` is failing. **Solution**: ```bash theme={null} # Check init container logs kubectl logs -n dify -c init-custom-ca ``` Common causes: 1. `initImage` cannot be pulled (air-gapped environment). 2. Secret not found or wrong namespace. 3. Wrong key name in secret. ### SSL verification errors after enabling custom CA **Cause**: Your custom CA certificate might not be properly formatted or is incomplete. **Solution**: 1. Verify certificate is valid PEM format: ```bash theme={null} openssl x509 -in your-ca.crt -text -noout ``` 2. Check if it's a full chain (if your CA requires intermediate certificates). Concatenate multiple certificates if needed: ```bash theme={null} cat intermediate-ca.crt root-ca.crt > combined-ca.crt ``` 3. Update the secret and restart pods: ```bash theme={null} kubectl delete secret dify-custom-ca -n dify kubectl create secret generic dify-custom-ca \ --from-file=ca.crt=combined-ca.crt -n dify kubectl rollout restart deployment -n dify ``` ### Changes to custom CA secret not taking effect **Cause**: The CA bundle is created during pod initialization. Updating the secret doesn't automatically update running pods. **Solution**: You must restart pods after updating the secret. ```bash theme={null} kubectl rollout restart deployment -n dify ``` ### Init container cannot pull alpine:3.20 image **Cause**: Air-gapped environment or restricted registry access. **Solution**: Use your private registry in `values.yaml`. ```yaml theme={null} global: customCA: enabled: true existingSecret: "dify-custom-ca" initImage: your-registry.company.com/alpine:3.20 ``` **Supported alternatives**: * Alpine-based: `alpine:3.20`, `alpine:3.19` * Debian-based: `ubuntu:22.04`, `debian:12` * Any image containing `/etc/ssl/certs/ca-certificates.crt` (Debian/Ubuntu) or `/etc/ssl/cert.pem` (Alpine). *** ## Advanced Configuration ### Using a Different Secret Key Name If your secret uses a different key name: ```yaml theme={null} global: customCA: enabled: true existingSecret: "my-ca-secret" key: custom-ca.pem # Different key name ``` ### Custom Mount Path If you need to change where the CA bundle is mounted: ```yaml theme={null} global: customCA: enabled: true existingSecret: "dify-custom-ca" mountPath: /custom/path/to/ca ``` > **Note**: Changing `mountPath` updates all environment variables automatically. ### Multiple CA Certificates If you need to trust multiple custom CAs, concatenate them into a single file: ```bash theme={null} cat ca1.crt ca2.crt ca3.crt > combined-ca.crt kubectl create secret generic dify-custom-ca \ --from-file=ca.crt=combined-ca.crt -n dify ``` ### Air-Gapped Environments For completely air-gapped deployments: 1. **Mirror the init image** to your private registry: ```bash theme={null} docker pull alpine:3.20 docker tag alpine:3.20 your-registry.company.com/alpine:3.20 docker push your-registry.company.com/alpine:3.20 ``` 2. **Update values.yaml**: ```yaml theme={null} global: customCA: enabled: true existingSecret: "dify-custom-ca" initImage: your-registry.company.com/alpine:3.20 ``` *** ## FAQ ### Can I disable custom CA after enabling it? Yes, set `global.customCA.enabled: false` and upgrade the Helm release. Pods will restart without the custom CA configuration. ### Does this affect TLS between Dify components? No, this only affects outbound HTTPS connections from Dify to external services (databases, S3, APIs, etc.). Internal component communication is not affected. ### What if my database also requires a custom CA? The custom CA feature covers database connections too. Ensure your database server's certificate is signed by the CA you've configured. ### Can I use intermediate certificates? Yes, concatenate the full chain (intermediate + root CA) into a single file before creating the secret. ### How do I update the CA certificate without downtime? Kubernetes Secrets can be updated, but pods must be restarted. For zero-downtime updates: 1. Update the secret. 2. Use `kubectl rollout restart` with rolling update strategy (default). 3. Pods will restart one by one, maintaining service availability. # Workflow Collaboration Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/collaboration Workflow collaboration enables real-time multiplayer editing of workflow drafts: multiple editors can open the same workflow, see each other's cursors and presence, and changes are synchronized live over Socket.IO. > [!NOTE] > > Requires Dify Enterprise 3.11.1 or later. ## Enable Collaboration Set the switch in your Helm chart values: ```yaml theme={null} collaboration: enabled: true ``` Then apply: ```bash theme={null} helm upgrade -i dify -f values.yaml dify/dify ``` This single switch drives everything required — no `extraEnv` wiring is needed: * Deploys a dedicated Socket.IO service (`-api-websocket`) that handles all realtime collaboration traffic. * Routes `/socket.io` on the gateway to that service. * Sets `ENABLE_COLLABORATION_MODE` on both the API and Web ConfigMaps. * Derives `NEXT_PUBLIC_SOCKET_URL` for the Web frontend from `global.consoleApiDomain` and `global.useTLS` (`wss://` when TLS is enabled). Once enabled, workspace members can edit workflows together and comment on the canvas. See [Collaborate with Teammates](/en/3.13.x/use/build/workflow-collaboration) for details. ## How It Works Collaboration traffic uses the Socket.IO protocol (WebSocket with HTTP long-polling fallback) on the `/socket.io` path of the console API domain. The chart runs it in a dedicated deployment separate from the main API pods: | Component | Value | | - | - | | Deployment | `-api-websocket` | | Service | `-api-websocket-svc`, port `5001` | | Gateway route | `/socket.io` and `/socket.io/*` on the console API vhost | The websocket deployment is intentionally fixed at **1 replica with 1 gunicorn worker** and uses the `Recreate` update strategy. Socket.IO authentication sessions live in process memory, so all socket traffic must share a single process. Do not scale this deployment; room events are fanned out through the existing Redis configuration, so the main API and worker deployments scale independently as usual. ## Resource Configuration Override resources for the websocket pod under `collaboration.websocket`: ```yaml theme={null} collaboration: enabled: true websocket: resources: requests: cpu: 250m memory: 512Mi limits: cpu: "1" memory: 1Gi ``` ## Prerequisites * `global.consoleApiDomain` must be reachable from editors' browsers; the frontend connects to `wss:///socket.io` (or `ws://` without TLS). * Any load balancer or ingress in front of the gateway must allow WebSocket upgrades on the console API domain. ## Upgrading from Manual Configuration If you previously enabled collaboration by injecting `ENABLE_COLLABORATION_MODE` / `NEXT_PUBLIC_SOCKET_URL` through `extraEnv`, remove those entries and set `collaboration.enabled: true` instead. Leaving the old `extraEnv` entries in place is harmless but redundant — container-level `extraEnv` values take precedence over the ConfigMap values the chart now generates. # Container Registry Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/container-registry ## Display Helm Chart Values ```bash theme={null} helm show values dify/dify ``` To customize the image repository and tag, modify the values file as shown below: ```yaml theme={null} api: image: repository: langgenius/dify-api tag: "x.x.x" ... ... ``` ## Syncing Images to a Private Registry Dify images support both AMD64 and ARM64 architectures. You can use the following script to sync them to your private container registry. 1. Save the following script as `sync.sh`. ```bash theme={null} #!/bin/bash # Set the following environment variables REGISTRY_URL="xxxx" NAMESPACE="xxx" BASE_IMAGE=langgenius/$IMAGE:$VERSION echo "BASE_IMAGE: $BASE_IMAGE" # Ensure script receives required parameters if [ -z "$1" ] || [ -z "$2" ]; then echo "Usage: $0 " exit 1 fi IMAGE=$1 VERSION=$2 TARGET_IMAGE_FOR_AMD64=$REGISTRY_URL/$NAMESPACE/$IMAGE:$VERSION-amd64 echo "TARGET_IMAGE_FOR_AMD64: $TARGET_IMAGE_FOR_AMD64" TARGET_IMAGE_FOR_ARM64=$REGISTRY_URL/$NAMESPACE/$IMAGE:$VERSION-arm64 echo "TARGET_IMAGE_FOR_ARM64: $TARGET_IMAGE_FOR_ARM64" TARGET_IMAGE=$REGISTRY_URL/$NAMESPACE/$IMAGE:$VERSION echo "TARGET_IMAGE: $TARGET_IMAGE" docker pull --platform linux/amd64 $BASE_IMAGE docker tag $BASE_IMAGE $TARGET_IMAGE_FOR_AMD64 docker push $TARGET_IMAGE_FOR_AMD64 docker pull --platform linux/arm64 $BASE_IMAGE docker tag $BASE_IMAGE $TARGET_IMAGE_FOR_ARM64 docker push $TARGET_IMAGE_FOR_ARM64 docker manifest create $TARGET_IMAGE --amend $TARGET_IMAGE_FOR_AMD64 --amend $TARGET_IMAGE_FOR_ARM64 docker manifest push $TARGET_IMAGE ``` 2. Set Script Variables. Edit the `sync.sh` file and set the following variables: * `REGISTRY_URL`: The URL of your private registry. * `NAMESPACE`: The namespace of your private registry. * `BASE_IMAGE` (Optional): The base image to sync, default is `langgenius/$IMAGE:$VERSION`. 3. Set Execution Permission. ```bash theme={null} chmod +x ./sync.sh ``` 4. Execute script to sync images. ```bash theme={null} # ./sync.sh ./sync.sh dify-api x.x.x ``` # Container Registry (Plugins) Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/container-registry-for-plugins ## Supported Container Registries * AWS ECR(with AK/SK or IRSA)/ Azure ACR / Aliyun ACR (with AK/SK) / Tencent TCR (with AK/SK) / Dockerhub / Google Artifact Registry ## Why Container Registry is Required * Dify Enterprise requires a container registry to store and manage plugin images. * The package of plugin is not a Docker image, but a compressed file that contains the plugin code and metadata. * When run on Kubernetes cluster, the package of plugin will be built into a Docker image, which is why a container registry is required. ## Display Helm Chart Values ```bash theme={null} helm show values dify/dify ``` This is an example of the Container Registry configuration in the Helm chart values. ```yaml theme={null} plugin_connector: insecureImageRepo: false imageRepoSecret: "image-repo-secret" imageRepoPrefix: "docker.io/your-image-repo-prefix" imageRepoType: docker ecrRegion: "us-east-1" ``` ## How to Configure Container Registry 1. `imageRepoSecret` (Required): This is a Kubernetes secret that contains the credentials for accessing the container registry. * 1.1 **Warning**: The value of `imageRepoSecret` is fixed as `image-repo-secret`, which is the name of the Kubernetes secret that will be created during the deployment. * 1.2 Save the following script as `generate-image-repo-secret.sh`. ```bash theme={null} #!/bin/bash if [ "$#" -lt 3 ]; then echo "How to use: $0 " echo "Example: $0 myuser mypass default https://index.docker.io/v1/" exit 1 fi USERNAME="$1" PASSWORD="$2" NAMESPACE="$3" REGISTRY="${4:-https://index.docker.io/v1/}" OUTPUT_FILE="./config.json" AUTH=$(echo -n "$USERNAME:$PASSWORD" | base64 | tr -d '\n') cat > "$OUTPUT_FILE" < . ./generate-image-repo-secret.sh myuser mypass default https://index.docker.io/v1/ ``` * `imageRepoPrefix` (Required): The prefix for the image repository, which is used to push the plugin images to the container registry. * `imageRepoType` (Required): The type of the container registry. * `docker` (Default): For Docker Hub or other Docker-compatible registries. * `ecr`: For AWS ECR. * `ecrRegion` (Optional): The region of the AWS ECR registry, if applicable. * `insecureImageRepo` (Optional): If your image repo is `not` using `https` protocol, set this to true. ## Scheduling of Kubernetes for plugin pods ```yaml theme={null} plugin_connector: nodeSelector: {} affinity: {} tolerations: [] labels: {} ``` * The plugin pods of (nodeSelector、affinity、tolerations、labels) are extended from the `plugin_connector` service. ## How to configure if your country has network restrictions If your network failed to access `docker.io`, you can use a custom image repository. ```yaml theme={null} plugin_connector: gatewayImage: "nginx:1.29.4-alpine" shaderImage: "gcr.io/kaniko-project/executor:latest" busyBoxImage: "busybox:latest" awsCliImage: "amazon/aws-cli:latest" generatorConf: | generator: repo: langgenius python: pipMirror: "" preCompile: true versions: python3.14: langgenius: docker.io/langgenius/dify-ee-plugin-build-base-python-3.14:3.11.0 python3.13: langgenius: docker.io/langgenius/dify-ee-plugin-build-base-python-3.13:3.11.0 python3.12: langgenius: docker.io/langgenius/dify-ee-plugin-build-base-python-3.12:3.11.0 ``` 1. The list of images that need to be replaced: * `gatewayImage`: The image for the plugin gateway service. * `shaderImage`: The shader image used during plugin build. * `busyBoxImage`: The busybox image used during plugin runtime. * `awsCliImage`: The image for the AWS CLI. If you are not using AWS, ignore this image. * `python3.xx`: The base image for the plugin build. 2. [Syncing images to your private registry.](/en/3.13.x/deploy/advanced-configuration/container-registry#syncing-images-to-a-private-registry) # Data Push Configuration Guide Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/data-push-configuration ## Helm Values This update introduces the following configurations: `global.otel` configuration involves services responsible for generating telemetry data, specifically including `dify-api` and `dify-worker`. `enterpriseCollector` is a new service designed to interact with your custom OpenTelemetry (OTEL) system. In most cases, keeping the default configuration values is sufficient. ```yaml theme={null} global: otel: # Requires enterpriseCollector.enabled to be true enabled: true # Sampling rate (0.0 to 1.0, empty means default) samplingRate: "0.2" # Batch export schedule delay in milliseconds batchExportScheduleDelay: "5000" # Maximum queue size for batching maxQueueSize: "2048" # Maximum export batch size maxExportBatchSize: "512" # Metric export interval in milliseconds metricExportInterval: "60000" # Batch export timeout in milliseconds batchExportTimeout: "30000" # Metric export timeout in milliseconds metricExportTimeout: "30000" sender: otlp: # Custom headers for OTLP requests (key=value,key2=value2) headers: "" # Service name reported to OTEL collector serviceName: "dify-api-otel" # Include input/output content in traces (privacy toggle) includeContent: false enterpriseCollector: enabled: true # https://github.com/langgenius/dify-enterprise/releases/tag/0.14.4 image: repository: langgenius/dify-enterprise-collector tag: "0.14.4" replicas: 1 resources: {} nodeSelector: {} affinity: {} tolerations: [] extraEnv: # Apply your own Environment Variables if necessary. Below is demo. # extraEnv: # - name: ENV_FROM_COMMUNITY1 # value: env123 # - name: ENV_FROM_COMMUNITY2 # value: env123 serviceAccountName: "" # readinessProbe: # tcpSocket: # port: 8080 # initialDelaySeconds: 30 # periodSeconds: 10 # successThreshold: 1 # timeoutSeconds: 3 # livenessProbe: # tcpSocket: # port: 8080 # initialDelaySeconds: 20 # periodSeconds: 10 # successThreshold: 1 # timeoutSeconds: 3 extraConfig: | # yaml config for otel collector # you can use this to fully customize the otel collector # see https://opentelemetry.io/docs/collector/configuration/ # The size of the sending queues are related to the memory limit and the batch size # the default value assumes 512 MiB memory limit and 512 batch size # adjust correspondingly when you configure different memory limits and batch sizes sendingQueues: trace: size: 64 metric: size: 256 ``` ## ServiceMonitor Integration Although the architecture of `enterpriseCollector` is designed to transmit telemetry data to user systems, pulling data remains a common method for collecting metrics. Therefore, it also exposes a metrics endpoint on port 8889, which can be seamlessly integrated with Prometheus `ServiceMonitor`. Below is an example. ```yaml theme={null} apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: dify-enterprise-collector namespace: monitoring spec: endpoints: - interval: 5s path: /metrics port: http-metrics scheme: http namespaceSelector: matchNames: - {dify's namespace} selector: matchLabels: app: {dify's release name}-enterprise-collector ``` # External Database Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/database # 3.9.0 configuration ## Show Helm Chart values ```bash theme={null} helm show values dify/dify ``` ## Connect to an external database You can use PostgreSQL, MySQL, or TiDB as an external database. Below is a generic example of external database settings in Helm chart values: ```yaml theme={null} ################################### # External database (Postgres/MySQL/TiDB) ################################### externalDatabase: enabled: false # postgres | mysql | tidb engine: "postgres" host: "localhost" # Default ports: postgres=5432, mysql=3306, tidb=4000 # Note: when switching engine, remember to update port accordingly port: 5432 user: "postgres" password: "#REPLACE_ME#" timezone: "UTC" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" enterprise: "enterprise" audit: "audit" dialectOptions: postgres: sslMode: "require" uriScheme: "postgresql" # extras: "options=-c search_path=your-schema -c your-other-option=xxx" extras: "" mysql: # MySQL/TiDB params, e.g. charset=utf8mb4&parseTime=true&loc=UTC params: "charset=utf8mb4&parseTime=true&loc=UTC" tls: false ``` > **Note** > > Before starting Dify, you must create the required databases manually. ### PostgreSQL ```sql theme={null} CREATE DATABASE dify; CREATE DATABASE enterprise; CREATE DATABASE audit; -- dify_plugin_daemon is created automatically on first startup of the plugin daemon ``` ### MySQL / TiDB ```sql theme={null} CREATE DATABASE IF NOT EXISTS dify; CREATE DATABASE IF NOT EXISTS enterprise; CREATE DATABASE IF NOT EXISTS audit; -- dify_plugin_daemon is created automatically on first startup of the plugin daemon ``` ## Configuration reference | Field | Description | | - | - | | `engine` | Database engine: `postgres`, `mysql`, or `tidb` | | `databases` | Mapping of database names used by each component | | `dialectOptions.postgres` | PostgreSQL-specific options (e.g. `sslMode`, `uriScheme`, `extras`) | | `dialectOptions.mysql` | MySQL/TiDB-specific options (e.g. `params`, `tls`) | ### Default ports | Engine | Default port | | - | - | | postgres | 5432 | | mysql | 3306 | | tidb | 4000 | ## Configuration examples ### External PostgreSQL ```yaml theme={null} externalDatabase: enabled: true engine: "postgres" host: "postgres.example.com" port: 5432 user: "postgres" password: "******" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" extras: "" dialectOptions: postgres: sslMode: "require" ``` ### External MySQL ```yaml theme={null} externalDatabase: enabled: true engine: "mysql" host: "mysql.example.com" port: 3306 user: "root" password: "******" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" dialectOptions: mysql: params: "charset=utf8mb4&parseTime=true&loc=UTC" ``` ### External TiDB ```yaml theme={null} externalDatabase: enabled: true engine: "tidb" host: "tidb.example.com" port: 4000 user: "root" password: "******" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" dialectOptions: mysql: params: "charset=utf8mb4&parseTime=true&loc=UTC" ``` # 3.9.1 configuration ## View Helm Chart default values ```bash theme={null} helm show values dify/dify ``` *** ## Connect to an external database You can use **PostgreSQL, MySQL, or TiDB** as an external database. Below is a generic configuration example for the external database in the updated Helm chart: ```yaml theme={null} ################################### # External database (Postgres/MySQL/TiDB) ################################### externalDatabase: enabled: false # postgres | mysql | tidb engine: "postgres" host: "localhost" # Default ports: postgres=5432, mysql=3306, tidb=4000 # Note: when switching engine, remember to update port accordingly port: 5432 # Global database credentials (used by default) user: "postgres" password: "#REPLACE_ME#" timezone: "UTC" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" enterprise: "enterprise" audit: "audit" ################################### # Per-database credentials (optional) ################################### # Configure username and password independently for each database # These take precedence over the global user/password # If empty, fallback to the global credentials databaseCredentials: dify: user: "" password: "" enterprise: user: "" password: "" audit: user: "" password: "" plugin_daemon: user: "" password: "" dialectOptions: postgres: sslMode: "require" uriScheme: "postgresql" # extras: "options=-c search_path=your-schema -c your-other-option=xxx" extras: "" mysql: # MySQL/TiDB params, e.g. charset=utf8mb4&parseTime=true&loc=UTC params: "charset=utf8mb4&parseTime=true&loc=UTC" tls: false ``` *** ## ⚠️ Important Before starting Dify, create the required databases manually: *** ## Database initialization ### PostgreSQL ```sql theme={null} CREATE DATABASE dify; CREATE DATABASE enterprise; CREATE DATABASE audit; -- dify_plugin_daemon is created automatically on first startup of the plugin daemon ``` *** ### MySQL / TiDB ```sql theme={null} CREATE DATABASE IF NOT EXISTS dify; CREATE DATABASE IF NOT EXISTS enterprise; CREATE DATABASE IF NOT EXISTS audit; -- dify_plugin_daemon is created automatically on first startup of the plugin daemon ``` *** ## Configuration reference | Field | Description | | - | - | | engine | Database engine: `postgres` / `mysql` / `tidb` | | databases | Mapping of database names used by each component | | databaseCredentials | (New) Per-database credentials; takes precedence over global credentials | | dialectOptions.postgres | PostgreSQL-specific options (e.g. `sslMode`, `uriScheme`, `extras`) | | dialectOptions.mysql | MySQL/TiDB-specific options (e.g. `params`, `tls`) | *** ## Per-database credentials behavior Precedence: ``` databaseCredentials[db] > global user/password ``` * If a database has its own credentials configured → use those credentials * If empty → fall back to global `user/password` *** ## Default ports | Engine | Default port | | - | - | | postgres | 5432 | | mysql | 3306 | | tidb | 4000 | *** ## Configuration examples *** ### External PostgreSQL ```yaml theme={null} externalDatabase: enabled: true engine: "postgres" host: "postgres.example.com" port: 5432 user: "postgres" password: "******" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" enterprise: "enterprise" audit: "audit" databaseCredentials: dify: user: "" password: "" enterprise: user: "" password: "" audit: user: "" password: "" plugin_daemon: user: "" password: "" dialectOptions: postgres: sslMode: "require" ``` *** ### External MySQL ```yaml theme={null} externalDatabase: enabled: true engine: "mysql" host: "mysql.example.com" port: 3306 user: "root" password: "******" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" enterprise: "enterprise" audit: "audit" databaseCredentials: dify: user: "" password: "" enterprise: user: "" password: "" audit: user: "" password: "" plugin_daemon: user: "" password: "" dialectOptions: mysql: params: "charset=utf8mb4&parseTime=true&loc=UTC" ``` *** ### External TiDB ```yaml theme={null} externalDatabase: enabled: true engine: "tidb" host: "tidb.example.com" port: 4000 user: "root" password: "******" databases: dify: "dify" plugin_daemon: "dify_plugin_daemon" enterprise: "enterprise" audit: "audit" databaseCredentials: dify: user: "" password: "" enterprise: user: "" password: "" audit: user: "" password: "" plugin_daemon: user: "" password: "" dialectOptions: mysql: params: "charset=utf8mb4&parseTime=true&loc=UTC" ``` # Database Configuration Guide Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/database-configuration This guide explains how to configure the database for Dify Enterprise. Dify Enterprise supports both Docker Compose and Helm Chart deployment methods and is compatible with PostgreSQL, MySQL, and TiDB database engines. ## Architecture Overview Dify Enterprise uses a **single-instance, multi-database** architecture. All community and enterprise services connect to the same database server, but each service uses its own independent database: | Database | Default Name | Components Used | | :- | :- | :- | | Dify Core | `dify` | Community API / Worker / Plugin Daemon, Enterprise Services | | Enterprise | `enterprise` | dify-enterprise, dify-audit, dify-plugin-manager | | Audit Log | `audit` | dify-audit | | Plugin | `dify_plugin` | Plugin Daemon, dify-plugin-manager | > **Note**: Community services and enterprise services use different environment variable naming conventions, but they must point to the **same database instance**. *** ## Docker Compose Configuration In a Docker Compose deployment, configure the database by modifying the `.env` file. ### 1. Environment Variable Reference #### Community Services (Dify API / Worker) | Variable Name | Description | PostgreSQL Default | MySQL Default | | :- | :- | :- | :- | | `DB_TYPE` | Database type | `postgresql` | `mysql` | | `DB_USERNAME` | Database username | `postgres` | `root` | | `DB_PASSWORD` | Database password | `difyai123456` | `difyai123456` | | `DB_HOST` | Database host | `db_postgres` | `db_mysql` | | `DB_PORT` | Database port | `5432` | `3306` | | `DB_DATABASE` | Dify core database name | `dify` | `dify` | #### Enterprise Services | Variable Name | Description | PostgreSQL Default | MySQL/TiDB Default | | :- | :- | :- | :- | | `DB_ENGINE` | Database engine | `postgres` | `mysql` | | `DB_HOST` | Database host | `db_postgres` | `db_mysql` | | `DB_PORT` | Database port | `5432` | `3306` / `4000` (TiDB) | | `DB_USER` | Database username | `postgres` | `root` | | `DB_PASS` | Database password | `difyai123456` | `difyai123456` | | `DIFY_DB_NAME` | Dify core database name | `dify` | `dify` | | `ENTERPRISE_DB_NAME` | Enterprise database name | `enterprise` | `enterprise` | | `AUDIT_DB_NAME` | Audit log database name | `audit` | `audit` | ### 2. External Database Mode If using an external database (such as AWS RDS, Alibaba Cloud RDS, or TiDB Cloud), follow these steps: 1. **Modify `.env` environment variables**: Point the variables above to your external database address. 2. **Adjust `COMPOSE_PROFILES`** (Optional): Remove the database type (e.g., `postgresql`) from `COMPOSE_PROFILES` to prevent the built-in database container from starting. ```bash theme={null} # Example: Keep only vector database and unstructured data processing services COMPOSE_PROFILES="weaviate,unstructured" ``` 3. **Manually create databases**: Before starting Dify, you must manually create the required databases in the external instance (see the [Database Initialization](#database-initialization) section below). *** ## Helm Chart Configuration In a Helm deployment, configure the database via `values.yaml`. ### 1. Internal Database Mode (PostgreSQL) By default, Helm will start a built-in PostgreSQL container. ```yaml theme={null} postgresql: enabled: true global: postgresql: auth: postgresPassword: "your_password" database: "dify" ``` ### 2. External Database Mode (Recommended for Production) Connect to an external PostgreSQL, MySQL, or TiDB. ```yaml theme={null} postgresql: enabled: false externalDatabase: enabled: true # Options: postgres | mysql | tidb engine: "postgres" host: "your-db-host" port: 5432 user: "your-user" password: "your-password" databases: dify: "dify" enterprise: "enterprise" audit: "audit" plugin_daemon: "dify_plugin" dialectOptions: postgres: sslMode: "require" mysql: params: "charset=utf8mb4&parseTime=true&loc=UTC" tls: false ``` *** ## Database Initialization ### 1. Built-in Database Mode When using the built-in database for Docker Compose or Helm, the system automatically executes initialization scripts (such as `dify-postgresql-init.sql`) to create the `enterprise` and `audit` databases. ### 2. External Database Mode (Manual Creation) **When using an external database, you must manually create the following databases before starting Dify:** #### PostgreSQL ```sql theme={null} CREATE DATABASE dify; CREATE DATABASE enterprise; CREATE DATABASE audit; -- dify_plugin will be automatically created by the plugin service upon first startup ``` #### MySQL / TiDB ```sql theme={null} CREATE DATABASE IF NOT EXISTS dify; CREATE DATABASE IF NOT EXISTS enterprise; CREATE DATABASE IF NOT EXISTS audit; -- dify_plugin will be automatically created by the plugin service upon first startup ``` *** ## FAQ ### Why are there two sets of database variables? Community services (Python) and enterprise services (Go) use different configuration standards. When configuring, ensure both sets of variables point to the same database instance. ### Which engine should I choose for TiDB? TiDB is compatible with the MySQL protocol. When configuring, set both `DB_TYPE` and `DB_ENGINE` to `mysql`, and point the port to TiDB's service port (default `4000`). ### How do I enable SSL/TLS connections? * **Docker Compose**: Set `DB_SSL_MODE="require"`. For MySQL/TiDB, also set `DB_TLS="true"`. * **Helm**: Configure the corresponding `sslMode` or `tls` fields under `dialectOptions`. # Dify Helm Chart Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/dify-helm-chart ## Requirements * Release Log: [https://langgenius.github.io/dify-helm](https://langgenius.github.io/dify-helm) * Kubernetes 1.24+ * Helm 3.14+ * `Warning`: If you are using a restricted environment (like OpenShift), make sure pods are allowed to run as `root`. ## Quick Start ### Get Helm Repository Info ```bash theme={null} helm repo add dify https://langgenius.github.io/dify-helm helm repo update ``` See [helm repo](https://helm.sh/docs/helm/helm_repo/) for command documentation. ### Check Available Versions * If you want to check the versions between the community and the enterprise, you can use the following command. * The `APP VERSION` is the version of the Dify community, and the `CHART VERSION` is the version of the Dify enterprise. ```bash theme={null} helm repo update helm search repo dify/dify --versions ``` See [helm search repo](https://helm.sh/docs/helm/helm_search_repo/) for command documentation. ### Installation or Upgrade For the first time installation or upgrade Dify, you can use the following command: > [!WARNING] > > Before upgrade, please make sure to backup your database. If failed to upgrade, you can rollback version and restore the database quickly. ```bash theme={null} helm repo update helm search repo dify/dify helm upgrade -i dify -f values.yaml dify/dify # If you want to upgrade to target version, you can use the following command: # helm upgrade -i dify -f values.yaml dify/dify --version x.x.x ``` See [helm upgrade](https://helm.sh/docs/helm/helm_upgrade/) for command documentation. ## Advanced Usage ### Uninstallation To uninstall Dify, you can use the following command: > [!WARNING] > > * If you want to re-install Dify, please make sure to clean up the database of `dify_plugin_daemon` first. > * For more details, please refer to the [Postgresql Database](/en/3.13.x/deploy/advanced-configuration/database-configuration). ```bash theme={null} helm uninstall dify ``` See [helm uninstall](https://helm.sh/docs/helm/helm_uninstall/) for command documentation. ### Display Helm Chart Values For more information about the Helm chart values, you can use the following command: ```bash theme={null} helm show values dify/dify ``` See [helm show values](https://helm.sh/docs/helm/helm_show_values/) for command documentation. ### Use Helm Template to Generate Kubernetes YAML You can use the following command to generate the Kubernetes YAML files: ```bash theme={null} helm template dify -f values.yaml dify/dify > dify-k8s-template.yaml ``` See [helm template](https://helm.sh/docs/helm/helm_template/) for command documentation. ### Download the Helm Chart locally You can use the following command to download the Helm chart: ```bash theme={null} helm pull dify/dify # helm pull dify/dify --version x.x.x ``` ### Allow Environments in Other Namespaces To let administrators create [environments](/en/3.13.x/administer/environments) outside the Dify Enterprise release namespace, enable the cluster role in `values.yaml`: ```yaml theme={null} enterprise: appDeploy: clusterRole: enabled: true ``` With it enabled, the Enterprise service account gets cluster-wide permissions on Deployments, Services, and ConfigMaps, and read-write access to Secrets in every namespace. Create each target namespace in advance, and add the image pull Secrets listed in `imagePullSecrets` to it. > [!WARNING] > > Before turning the switch off, delete every environment outside the release namespace in the Enterprise Dashboard. # Domain and SSL Certificate Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/domain-and-ssl-certificate ## Domain Requirements Dify Enterprise requires 6 domains to be set up. The domains are: * Console: console.dify.local * Services API: api.dify.local * APP: app.dify.local * Files: upload.dify.local * Enterprise: enterprise.dify.local * Trigger: trigger.dify.local ## Find the Domain Configuration in the Helm Chart Values ### Display Helm Chart Values ```bash theme={null} helm show values dify/dify ``` This is an example of the domain configuration in the Helm chart values. ```yaml theme={null} global: consoleApiDomain: "console.dify.local" consoleWebDomain: "console.dify.local" serviceApiDomain: "api.dify.local" appApiDomain: "app.dify.local" appWebDomain: "app.dify.local" filesDomain: "upload.dify.local" enterpriseDomain: "enterprise.dify.local" triggerDomain: "trigger.dify.local" ... ... ``` ## How to configure SSL Certificate ### Generate SSL Certificate ```bash theme={null} kubectl create secret tls example-tls --key example.key --cert example.crt ``` ### Update Helm values #### Set `useTLS` to `true` ```yaml theme={null} global: useTLS: true ``` #### Update Ingress values If you only have one certificate, you can set it like this ```yaml theme={null} ingress: tls: - hosts: - console.dify.local - app.dify.local - api.dify.local - upload.dify.local - enterprise.dify.local - trigger.dify.local secretName: example-tls ``` If you have multiple certificates, you can set it like this ```yaml theme={null} ingress: tls: - hosts: - console.dify.local secretName: example-tls - hosts: - app.dify.local secretName: example-tls-2 - hosts: - api.dify.local secretName: example-tls-3 - hosts: - upload.dify.local secretName: example-tls-4 - hosts: - enterprise.dify.local secretName: example-tls-5 - hosts: - trigger.dify.local secretName: example-tls-6 ``` ## The cache error of Http/Https After configuring the SSL certificate, if you encounter http/https cache errors in your browser, you can restart the Dify service to clear the cache. ```bash theme={null} kubectl rollout restart deployment dify-api kubectl rollout restart deployment dify-web kubectl rollout restart deployment dify-enterprise-frontend ``` # Email Provider Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/email-provider ## Display Helm Chart Values ```bash theme={null} helm show values dify/dify ``` This is an example of the email provider configuration in the Helm chart values. ```yaml theme={null} mail: type: '' defaultSender: 'YOUR EMAIL FROM (eg: no-reply )' resend: apiKey: '' apiUrl: https://api.resend.com smtp: server: '' port: 587 username: '' password: '' useTLS: false ... ... ``` ## The options for the `mail.type` field * `resend`: Use the Resend service to send emails * `smtp`: Use the SMTP service to send emails # Environment Variables Source: https://enterprise-docs.dify.ai/en/3.13.x/deploy/advanced-configuration/environment-variables Reference for environment variables used by Dify Enterprise Helm deployments Dify Enterprise deploys with Helm. Most variables are configured through your `values.yaml` file. The Helm chart writes a fixed set of variables into the API, web, worker, and enterprise ConfigMaps (with defaults drawn from `values.yaml`), and exposes the rest of the Dify application's variables through the `extraEnv` field on each service. > [!NOTE] > > The variables listed here are for reference. The Dify application reads many more variables than the Helm chart sets directly. For the complete application-level list, see the upstream [`.env.example`](https://github.com/langgenius/dify/blob/main/docker/.env.example). Any variable that is not set in `values.yaml` can be added through `extraEnv` (see [FAQs](#faqs)). If you cannot find a variable in `values.yaml`, set it through `extraEnv`. > [!TIP] > > A default value listed as **(Helm default)** is the value the chart writes into the ConfigMap from `values.yaml`. All other defaults are the Dify application's built-in defaults, which apply when the variable is not set through `extraEnv`. ## Common Variables These URL variables configure the public addresses of Dify's services. The Helm chart derives them from the domain settings in `values.yaml` (`global.consoleApiDomain`, `global.consoleWebDomain`, and so on), so you normally set the domains rather than the variables directly. ### CONSOLE\_API\_URL Default: derived from `global.consoleApiDomain` The public URL of Dify's backend API. Used to construct OAuth authorization callbacks (GitHub, Google login), Notion integration, and any plugin that requires OAuth. Also determines whether secure (HTTPS-only) cookies are used. Example: `https://api.console.dify.ai` ### CONSOLE\_WEB\_URL Default: derived from `global.consoleWebDomain` The public URL of Dify's console frontend. Used to build links in all system emails (invitations, password resets, notifications) and to redirect users back to the console after OAuth login. Also serves as the default CORS allowed origin if `CONSOLE_CORS_ALLOW_ORIGINS` is not set. Example: `https://console.dify.ai` ### SERVICE\_API\_URL Default: derived from `global.serviceApiDomain` The API Base URL shown to developers in the Dify console: the URL they copy into their code to call the Dify API. Set this to ensure a consistent URL when your server is reachable through multiple addresses. Example: `https://api.dify.ai` ### APP\_API\_URL Default: derived from `global.appApiDomain` The backend API URL for the WebApp frontend (published apps). This variable is used by the web frontend container, not the Python backend. Example: `https://api.app.dify.ai` ### APP\_WEB\_URL Default: derived from `global.appWebDomain` The public URL where published WebApps are accessible. Required for the Human Input node in workflows: form links in email notifications are built as `{APP_WEB_URL}/form/{token}`. If empty, Human Input email delivery will not include valid form links. Example: `https://app.dify.ai` ### TRIGGER\_URL Default: derived from `global.triggerDomain` The publicly accessible URL for webhook and integration trigger endpoints. External systems use this address to invoke your workflows. Dify builds trigger callback URLs like `{TRIGGER_URL}/triggers/webhook/{id}` and displays them in the console. For triggers to work, this must point to a public domain or IP that external systems can reach. ### FILES\_URL Default: derived from `global.filesDomain` The base URL for file preview and download links. Dify generates signed, time-limited URLs for all files (uploaded documents, tool outputs, workspace logos) and serves them to the frontend and multi-modal models. To prevent forgery, file URLs are signed and expire (see `FILES_ACCESS_TIMEOUT`). Example: `https://upload.example.com` ### INTERNAL\_FILES\_URL Default: (empty; falls back to `FILES_URL`) The file access URL used for communication between services inside the cluster (for example, the plugin daemon and document extractors). Internal services may not be able to reach the external `FILES_URL` if it routes through an ingress or public domain. Set this through `extraEnv` when internal services can't reach the external URL. Example: `http://dify-api-svc:5001` ### FILES\_ACCESS\_TIMEOUT Default: `300` (5 minutes) How long signed file URLs remain valid, in seconds. After this time, the URL is rejected and the file must be re-requested. Increase for long-running processes; decrease for tighter security. *** ## Server Configuration ### Logging | Variable | Default | Description | | :- | :- | :- | | `LOG_LEVEL` | `INFO` (Helm default) | Minimum log severity. Levels from least to most severe: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`. For production, `ERROR` reduces noise. | | `LOG_OUTPUT_FORMAT` | `json` (Helm default) | `json` produces structured logs for aggregation tools (ELK, Datadog). `text` produces human-readable lines. The chart defaults to `json`; the application's own default is `text`. | | `LOG_FILE` | `/app/logs/server.log` | Log file path. When set, enables file-based logging with automatic rotation. When empty, logs only go to console. | | `LOG_FILE_MAX_SIZE` | `20` | Maximum log file size in MB before rotation. | | `LOG_FILE_BACKUP_COUNT` | `5` | Number of rotated log files to keep. | | `LOG_DATEFORMAT` | `%Y-%m-%d %H:%M:%S` | Timestamp format for text-format logs (strftime codes). | | `LOG_TZ` | `UTC` | Timezone for log timestamps. Also sets Celery's task scheduling timezone. | ### General | Variable | Default | Description | | :- | :- | :- | | `MODE` | `api` / `worker` / `beat` (Helm default) | Service role. The chart sets this per ConfigMap; do not override. | | `DEBUG` | `false` | Enables verbose logging: node inputs/outputs, tool execution details, full LLM prompts and responses. Not recommended for production. | | `FLASK_DEBUG` | `false` | Standard Flask debug flag. Not actively used by Dify; `DEBUG` is the primary control. | | `ENABLE_REQUEST_LOGGING` | `false` | Logs a compact access line for every HTTP request. With `LOG_LEVEL=DEBUG`, additionally logs full request and response bodies. | | `DEPLOY_ENV` | `PRODUCTION` (Helm default) | Tags monitoring data in Sentry and OpenTelemetry so you can filter by environment. Also sent as the `X-Env` response header. | | `MIGRATION_ENABLED` | `true` (API), `false` (worker/beat) (Helm default) | When `true`, runs database schema migrations automatically on container startup. The chart enables it for the API service only. | | `CHECK_UPDATE_URL` | `https://updates.dify.ai` (Helm default) | The console checks this URL for newer Dify versions. Set to empty for air-gapped environments. | | `OPENAI_API_BASE` | `https://api.openai.com/v1` | Legacy variable. Not actively used by Dify's own code. | ### SECRET\_KEY Default: set by the chart (see your deployment's secret configuration) Used for session cookie signing, JWT authentication tokens, file URL signatures (HMAC-SHA256), and encrypting third-party OAuth credentials (AES-256). The Helm chart manages this through a secret. > [!WARNING] > > Changing this key after deployment will immediately log out all users, invalidate all file URLs, and break any plugin integrations that use OAuth, since their encrypted credentials become unrecoverable. ### KEY\_PROVIDER\_TYPE Default: `local` Choose where Dify keeps the keys used to encrypt workspace credentials, such as model-provider and tool secrets: * `local`: stores each workspace's RSA private key in the configured `STORAGE_TYPE` backend. * `azure-keyvault`: keeps workspace RSA keys in Azure Key Vault. The private key stays in the vault; authentication uses Azure `DefaultAzureCredential`. > [!WARNING] > > Choose the provider before creating credentials. Changing providers on an existing installation makes existing credentials unreadable with the new provider; it does not migrate them. Keep `KEY_PROVIDER_TYPE` and, for Azure, `AZURE_KEYVAULT_VAULT_URL` consistent across the Dify application services and `plugin_manager`. Set them through `api.extraEnv`, `worker.extraEnv`, `workerBeat.extraEnv`, and `plugin_manager.extraEnv`. For each entry in `additionalWorkers`, also set these variables in its own `extraEnv`; it does not inherit `worker.extraEnv`. For `azure-keyvault`, configure these variables: | Variable | Default | Description | | :- | :- | :- | | `AZURE_KEYVAULT_VAULT_URL` | (unset) | Required vault URL, for example `https://your-vault-name.vault.azure.net`. | | `AZURE_KEYVAULT_KEY_SIZE` | `2048` | RSA key size in bits for new workspace keys. Keep the default unless your organization requires a different key size. | | `AZURE_KEYVAULT_ROTATION_INTERVAL_DAYS` | (unset) | Auto-rotation interval in days for workspace keys created by the Dify application. Minimum: `7`. Keep old key versions available so Dify can decrypt credentials encrypted with them. | ### Token & Request Limits | Variable | Default | Description | | :- | :- | :- | | `ACCESS_TOKEN_EXPIRE_MINUTES` | `60` | How long a login session's access token stays valid (in minutes). The browser silently refreshes it using the refresh token. | | `REFRESH_TOKEN_EXPIRE_DAYS` | `30` | How long a user can stay logged in without re-entering credentials (in days). | | `APP_MAX_EXECUTION_TIME` | `3600` | Maximum time (in seconds) an app execution can run before being terminated. Works alongside `WORKFLOW_MAX_EXECUTION_TIME`. Set through `api.appMaxExecutionTimeSeconds`. | | `APP_DEFAULT_ACTIVE_REQUESTS` | `0` | Default concurrent request limit per app when no custom limit is set. `0` means unlimited. | | `APP_MAX_ACTIVE_REQUESTS` | `0` | Global ceiling for concurrent requests per app. `0` means unlimited. | | `WEBSOCKET_MAX_HTTP_BUFFER_SIZE` | `10485760` (Helm default) | Maximum incoming message size in bytes (10 MiB) for workflow-editor collaboration. Messages over this limit are rejected and the editor connection is closed. Increase it if large workflow graphs exceed the limit. Set through `collaboration.websocket.maxHttpBufferSize`. | ### Worker Configuration The Helm chart manages worker counts through `values.yaml` rather than environment variables. `serverWorkerAmount` controls API Gunicorn workers, and `celeryWorkerAmount` controls Celery workers per worker deployment. Set them in `values.yaml`. | Variable | Default | Description | | :- | :- | :- | | `SERVER_WORKER_AMOUNT` | `1` (Helm default) | Number of Gunicorn worker processes. With gevent (default), 1 is usually sufficient. Set through `api.serverWorkerAmount` in `values.yaml`. | | `GUNICORN_TIMEOUT` | `360` (Helm default) | If a worker doesn't respond within this many seconds, Gunicorn restarts it. 360 supports long-lived SSE streaming connections. | | `CELERY_WORKER_AMOUNT` | `1` (Helm default) | Number of Celery worker processes per worker deployment. Set through `worker.celeryWorkerAmount` in `values.yaml`. | | `SERVER_WORKER_CLASS` | `gevent` | Gunicorn worker type. Keep the default; other values break psycopg2 and gRPC patching. | | `SERVER_WORKER_CONNECTIONS` | `10` | Maximum concurrent connections per worker. Only applies to async (gevent) workers. | | `CELERY_WORKER_CLASS` | (empty; defaults to gevent) | Celery worker type. Strongly discouraged to change. | ### API Tool Configuration | Variable | Default | Description | | :- | :- | :- | | `API_TOOL_DEFAULT_CONNECT_TIMEOUT` | `10` | Maximum time (in seconds) to wait for establishing a TCP connection when API Tool nodes call external APIs. | | `API_TOOL_DEFAULT_READ_TIMEOUT` | `60` | Maximum time (in seconds) to wait for receiving response data from external APIs called by API Tool nodes. | ### Database Configuration The Helm chart configures the main database connection (host, port, credentials, database name) through `values.yaml` and the shared database ConfigMap, not through individual `DB_*` variables. The variables below tune the application's connection pool and can be set through `extraEnv`. | Variable | Default | Description | | :- | :- | :- | | `SQLALCHEMY_POOL_SIZE` | `250` (Helm default) | Number of persistent connections kept in the pool. The chart default is 250 (the application default is 30). Set through `api.db.poolSize` / `worker.db.poolSize`. | | `SQLALCHEMY_POOL_RECYCLE` | `3600` (Helm default) | Recycle connections after this many seconds to prevent stale connections. | | `SQLALCHEMY_MAX_OVERFLOW` | `10` | Additional temporary connections allowed when the pool is full. | | `SQLALCHEMY_POOL_TIMEOUT` | `30` | How long to wait for a connection when the pool is exhausted. | | `SQLALCHEMY_POOL_RESET_ON_RETURN` | `rollback` | Action when a connection returns to the pool. `rollback` clears uncommitted transaction state; `commit` commits it. | | `SQLALCHEMY_POOL_PRE_PING` | `false` | Test each connection with a lightweight query before use. Prevents "connection lost" errors but adds slight latency. | | `SQLALCHEMY_POOL_USE_LIFO` | `false` | Reuse the most recently returned connection (LIFO) instead of rotating evenly (FIFO). | | `SQLALCHEMY_ECHO` | `false` | Print all SQL statements to logs. Useful for debugging query issues. | ### Redis Configuration The Helm chart configures Redis connectivity through `values.yaml` (the shared Redis configuration). The application supports standalone, Sentinel, and Cluster modes. The variables below are the application-level knobs; in a Helm deployment, prefer the chart's Redis settings, and use `extraEnv` for tuning. | Variable | Default | Description | | :- | :- | :- | | `REDIS_KEY_PREFIX` | (empty) | Optional global prefix applied to all Redis keys, pub/sub channels, Streams names, and Celery broker queues. Useful when multiple Dify instances share one Redis deployment. Turning the prefix on for an existing deployment strands keys written under the previous prefix. | | `REDIS_USE_SSL` | `false` | Enable SSL/TLS for the Redis connection. Does not automatically apply to the Sentinel protocol. | | `REDIS_MAX_CONNECTIONS` | (empty) | Maximum connections in the Redis pool. Leave unset for the library default. | #### Redis SSL Configuration Only applies when `REDIS_USE_SSL=true`. | Variable | Default | Description | | :- | :- | :- | | `REDIS_SSL_CERT_REQS` | `CERT_NONE` | Certificate verification level: `CERT_NONE`, `CERT_OPTIONAL`, or `CERT_REQUIRED`. | | `REDIS_SSL_CA_CERTS` | (empty) | Path to CA certificate file for verifying the Redis server. | | `REDIS_SSL_CERTFILE` | (empty) | Path to client certificate for mutual TLS. | | `REDIS_SSL_KEYFILE` | (empty) | Path to client private key for mutual TLS. | #### Redis Connection Resilience | Variable | Default | Description | | :- | :- | :- | | `REDIS_RETRY_RETRIES` | `3` | Maximum retries per Redis command on transient failures. Set to `0` to disable. Uses exponential backoff with jitter. | | `REDIS_RETRY_BACKOFF_BASE` | `1.0` | Base delay in seconds for exponential backoff between retries. | | `REDIS_RETRY_BACKOFF_CAP` | `10.0` | Maximum backoff delay in seconds between retries. | | `REDIS_SOCKET_TIMEOUT` | `5.0` | Socket timeout in seconds for Redis read/write operations. | | `REDIS_SOCKET_CONNECT_TIMEOUT` | `5.0` | Socket timeout in seconds for establishing a Redis connection. | | `REDIS_HEALTH_CHECK_INTERVAL` | `30` | Interval in seconds between client-side health checks on idle connections. Set to `0` to disable. Not applied in Cluster mode. | ### Celery Configuration The Helm chart manages the Celery broker connection through `values.yaml` and the shared Celery secret. The variables below are application-level tuning knobs. | Variable | Default | Description | | :- | :- | :- | | `CELERY_BACKEND` | `redis` | Where Celery stores task results. Options: `redis` (fast, in-memory) or `database`. | | `BROKER_USE_SSL` | `false` | Auto-enabled when the broker URL uses the `rediss://` scheme. | | `CELERY_USE_SENTINEL` | `false` | Enable Redis Sentinel mode for the Celery broker. | | `CELERY_SENTINEL_MASTER_NAME` | (empty) | Sentinel service name (Master Name). | | `CELERY_SENTINEL_PASSWORD` | (empty) | Password for Sentinel authentication. | | `CELERY_SENTINEL_SOCKET_TIMEOUT` | `0.1` | Timeout for connecting to Sentinel in seconds. | | `CELERY_TASK_ANNOTATIONS` | `null` | Apply runtime settings to specific tasks (for example, rate limits). Format: JSON dictionary. Most users don't need this. | ### CORS Configuration Controls cross-domain access policies for the frontend. The chart writes these only when set in `values.yaml`. | Variable | Default | Description | | :- | :- | :- | | `WEB_API_CORS_ALLOW_ORIGINS` | `*` | Allowed origins for cross-origin requests to the Web API. Example: `https://dify.app` | | `CONSOLE_CORS_ALLOW_ORIGINS` | `*` | Allowed origins for cross-origin requests to the console API. If not set, falls back to `CONSOLE_WEB_URL`. | | `COOKIE_DOMAIN` | (empty) | Set to the shared top-level domain (for example, `example.com`) when frontend and backend run on different subdomains, so authentication cookies can be shared across subdomains. | ### File Storage Configuration Configure where Dify stores uploaded files, dataset documents, and encryption keys. Each storage type has its own credential variables; configure only the one you use. In Helm deployments, set these through `extraEnv` unless the chart already exposes them. ### STORAGE\_TYPE Default: `opendal` Selects the file storage backend. Supported values: `opendal`, `s3`, `azure-blob`, `aliyun-oss`, `google-storage`, `huawei-obs`, `volcengine-tos`, `tencent-cos`, `baidu-obs`, `oci-storage`, `supabase`, `clickzetta-volume`, `local` (deprecated; internally uses OpenDAL with the filesystem scheme). > [accordion] OpenDAL (Default) > > Default storage backend using [Apache OpenDAL](https://opendal.apache.org/), a unified interface supporting many storage services. Dify automatically scans environment variables matching `OPENDAL__*` and passes them to OpenDAL. For example, with `OPENDAL_SCHEME=s3`, set `OPENDAL_S3_ACCESS_KEY_ID`, `OPENDAL_S3_SECRET_ACCESS_KEY`, etc. > > | Variable | Default | Description | > | :- | :- | :- | > | `OPENDAL_SCHEME` | `fs` | Storage service to use. Examples: `fs` (local filesystem), `s3`, `gcs`, `azblob`. | > | `OPENDAL_FS_ROOT` | `storage` | Root directory for local filesystem storage (used with the `fs` scheme). | > > For all available schemes and their configuration options, see the [OpenDAL services documentation](https://github.com/apache/opendal/tree/main/core/services). > [accordion] S3 > > | Variable | Default | Description | > | :- | :- | :- | > | `S3_ENDPOINT` | (empty) | S3 endpoint address. Required for non-AWS S3-compatible services (MinIO, etc.). | > | `S3_REGION` | `us-east-1` | S3 region. | > | `S3_BUCKET_NAME` | `difyai` | S3 bucket name. | > | `S3_ACCESS_KEY` | (empty) | S3 Access Key. Not needed when using IAM roles. | > | `S3_SECRET_KEY` | (empty) | S3 Secret Key. Not needed when using IAM roles. | > | `S3_ADDRESS_STYLE` | `auto` | S3 addressing style: `auto`, `path`, or `virtual`. Only applies when `S3_USE_AWS_MANAGED_IAM` is `false`. | > | `S3_USE_AWS_MANAGED_IAM` | `false` | Use AWS IAM roles (EC2 instance profile, EKS service account) instead of explicit keys. Credentials are auto-discovered from instance metadata. | > [accordion] Azure Blob > > | Variable | Default | Description | > | :- | :- | :- | > | `AZURE_BLOB_ACCOUNT_NAME` | `difyai` | Azure storage account name. | > | `AZURE_BLOB_ACCOUNT_KEY` | `difyai` | Azure storage account key. | > | `AZURE_BLOB_CONTAINER_NAME` | `difyai-container` | Azure Blob container name. | > | `AZURE_BLOB_ACCOUNT_URL` | `https://.blob.core.windows.net` | Azure Blob account URL. | > [accordion] Google Cloud Storage > > | Variable | Default | Description | > | :- | :- | :- | > | `GOOGLE_STORAGE_BUCKET_NAME` | (empty) | Google Cloud Storage bucket name. | > | `GOOGLE_STORAGE_SERVICE_ACCOUNT_JSON_BASE64` | (empty) | Base64-encoded service account JSON key. | > [accordion] Alibaba Cloud OSS > > | Variable | Default | Description | > | :- | :- | :- | > | `ALIYUN_OSS_BUCKET_NAME` | (empty) | OSS bucket name. | > | `ALIYUN_OSS_ACCESS_KEY` | (empty) | OSS access key. | > | `ALIYUN_OSS_SECRET_KEY` | (empty) | OSS secret key. | > | `ALIYUN_OSS_ENDPOINT` | `https://oss-ap-southeast-1-internal.aliyuncs.com` | OSS endpoint. [Regions and endpoints reference](https://www.alibabacloud.com/help/en/oss/user-guide/regions-and-endpoints). | > | `ALIYUN_OSS_REGION` | `ap-southeast-1` | OSS region. | > | `ALIYUN_OSS_AUTH_VERSION` | `v4` | OSS authentication version. | > | `ALIYUN_OSS_PATH` | (empty) | Object path prefix. Don't start with `/`. [Reference](https://www.alibabacloud.com/help/en/oss/support/0016-00000005). | > | `ALIYUN_CLOUDBOX_ID` | (empty) | CloudBox ID for CloudBox-based OSS deployments. | > [accordion] Tencent Cloud COS > > | Variable | Default | Description | > | :- | :- | :- | > | `TENCENT_COS_BUCKET_NAME` | (empty) | COS bucket name. | > | `TENCENT_COS_SECRET_KEY` | (empty) | COS secret key. | > | `TENCENT_COS_SECRET_ID` | (empty) | COS secret ID. | > | `TENCENT_COS_REGION` | (empty) | COS region, for example, `ap-guangzhou`. [Reference](https://cloud.tencent.com/document/product/436/6224). | > | `TENCENT_COS_SCHEME` | (empty) | Protocol to access COS (`http` or `https`). | > | `TENCENT_COS_CUSTOM_DOMAIN` | (empty) | Custom domain for COS access. | > [accordion] OCI Object Storage > > | Variable | Default | Description | > | :- | :- | :- | > | `OCI_ENDPOINT` | (empty) | OCI endpoint URL. | > | `OCI_BUCKET_NAME` | (empty) | OCI bucket name. | > | `OCI_ACCESS_KEY` | (empty) | OCI access key. | > | `OCI_SECRET_KEY` | (empty) | OCI secret key. | > | `OCI_REGION` | `us-ashburn-1` | OCI region. | > [accordion] Huawei OBS > > | Variable | Default | Description | > | :- | :- | :- | > | `HUAWEI_OBS_BUCKET_NAME` | (empty) | OBS bucket name. | > | `HUAWEI_OBS_ACCESS_KEY` | (empty) | OBS access key. | > | `HUAWEI_OBS_SECRET_KEY` | (empty) | OBS secret key. | > | `HUAWEI_OBS_SERVER` | (empty) | OBS server URL. [Reference](https://support.huaweicloud.com/sdk-python-devg-obs/obs_22_0500.html). | > | `HUAWEI_OBS_PATH_STYLE` | `false` | Use path-style URLs instead of virtual-hosted-style. | > [accordion] Volcengine TOS > > | Variable | Default | Description | > | :- | :- | :- | > | `VOLCENGINE_TOS_BUCKET_NAME` | (empty) | TOS bucket name. | > | `VOLCENGINE_TOS_ACCESS_KEY` | (empty) | TOS access key. | > | `VOLCENGINE_TOS_SECRET_KEY` | (empty) | TOS secret key. | > | `VOLCENGINE_TOS_ENDPOINT` | (empty) | TOS endpoint URL. [Reference](https://www.volcengine.com/docs/6349/107356). | > | `VOLCENGINE_TOS_REGION` | (empty) | TOS region, for example, `cn-guangzhou`. | > [accordion] Baidu OBS > > | Variable | Default | Description | > | :- | :- | :- | > | `BAIDU_OBS_BUCKET_NAME` | (empty) | Baidu OBS bucket name. | > | `BAIDU_OBS_ACCESS_KEY` | (empty) | Baidu OBS access key. | > | `BAIDU_OBS_SECRET_KEY` | (empty) | Baidu OBS secret key. | > | `BAIDU_OBS_ENDPOINT` | (empty) | Baidu OBS server URL. | > [accordion] Supabase > > | Variable | Default | Description | > | :- | :- | :- | > | `SUPABASE_BUCKET_NAME` | (empty) | Supabase storage bucket name. | > | `SUPABASE_API_KEY` | (empty) | Supabase API key. | > | `SUPABASE_URL` | (empty) | Supabase server URL. | > [accordion] ClickZetta Volume > > | Variable | Default | Description | > | :- | :- | :- | > | `CLICKZETTA_VOLUME_TYPE` | `user` | Volume type. Options: `user`, `table`, `external`. | > | `CLICKZETTA_VOLUME_NAME` | (empty) | External volume name (required only when `TYPE=external`). | > | `CLICKZETTA_VOLUME_TABLE_PREFIX` | `dataset_` | Table volume table prefix (used only when `TYPE=table`). | > | `CLICKZETTA_VOLUME_DIFY_PREFIX` | `dify_km` | Dify file directory prefix for isolation from other apps. | > > ClickZetta Volume reuses the `CLICKZETTA_*` connection parameters configured in the Vector Database section. #### Archive Storage Separate S3-compatible storage for archiving workflow run logs. Used to archive workflow runs older than the retention period to JSONL format. | Variable | Default | Description | | :- | :- | :- | | `ARCHIVE_STORAGE_ENABLED` | `false` | Enable archive storage for workflow log archival. | | `ARCHIVE_STORAGE_ENDPOINT` | (empty) | S3-compatible endpoint URL. | | `ARCHIVE_STORAGE_ARCHIVE_BUCKET` | (empty) | Bucket for archived workflow run logs. | | `ARCHIVE_STORAGE_EXPORT_BUCKET` | (empty) | Bucket for workflow run exports. | | `ARCHIVE_STORAGE_ACCESS_KEY` | (empty) | Access key. | | `ARCHIVE_STORAGE_SECRET_KEY` | (empty) | Secret key. | | `ARCHIVE_STORAGE_REGION` | `auto` | Storage region. | | `ARCHIVE_STORAGE_ADDRESS_STYLE` | `path` | S3 addressing style for archive storage. Use `path` for path-style URLs, `virtual` for virtual-hosted URLs, or `auto` to let the S3 client choose. | ### Vector Database Configuration Configure the vector database used for knowledge base embedding storage and similarity search. Each provider has its own set of credential variables; configure only the one you use. ### VECTOR\_STORE Default: `weaviate` Selects the vector database backend. If a dataset already has an index, the dataset's stored type takes precedence over this setting. Supported values: `weaviate`, `oceanbase`, `seekdb`, `qdrant`, `milvus`, `myscale`, `relyt`, `pgvector`, `pgvecto-rs`, `chroma`, `opensearch`, `oracle`, `tencent`, `elasticsearch`, `elasticsearch-ja`, `analyticdb`, `couchbase`, `vikingdb`, `opengauss`, `tablestore`, `vastbase`, `tidb`, `tidb_on_qdrant`, `baidu`, `lindorm`, `huawei_cloud`, `upstash`, `matrixone`, `clickzetta`, `alibabacloud_mysql`, `iris`, `hologres`. | Variable | Default | Description | | :- | :- | :- | | `VECTOR_INDEX_NAME_PREFIX` | `Vector_index` | Prefix added to collection names in the vector database. Change this if you share a vector database instance across multiple Dify deployments. | > [accordion] Weaviate > > | Variable | Default | Description | > | :- | :- | :- | > | `WEAVIATE_ENDPOINT` | `http://weaviate:8080` | Weaviate REST API endpoint. | > | `WEAVIATE_API_KEY` | (empty) | API key for Weaviate authentication. | > | `WEAVIATE_GRPC_ENDPOINT` | `grpc://weaviate:50051` | Separate gRPC endpoint for high-performance binary protocol. Falls back to inferring from the HTTP endpoint if not set. | > | `WEAVIATE_TOKENIZATION` | `word` | Tokenization method. Options: `word`, `whitespace`, `character` (better for CJK languages). | > [accordion] OceanBase / seekdb > > seekdb is the lite version of OceanBase and shares the same connection configuration. > > | Variable | Default | Description | > | :- | :- | :- | > | `OCEANBASE_VECTOR_HOST` | `oceanbase` | Hostname or IP address. | > | `OCEANBASE_VECTOR_PORT` | `2881` | Port number. | > | `OCEANBASE_VECTOR_USER` | `root@test` | Database username. | > | `OCEANBASE_VECTOR_PASSWORD` | `difyai123456` | Database password. | > | `OCEANBASE_VECTOR_DATABASE` | `test` | Database name. | > | `OCEANBASE_ENABLE_HYBRID_SEARCH` | `false` | Enable fulltext index for BM25 queries alongside vector search. Requires OceanBase >= 4.3.5.1. Collections must be recreated after enabling. | > | `OCEANBASE_FULLTEXT_PARSER` | `ik` | Fulltext parser. Built-in: `ngram`, `beng`, `space`, `ngram2`, `ik`. | > [accordion] Qdrant > > | Variable | Default | Description | > | :- | :- | :- | > | `QDRANT_URL` | `http://qdrant:6333` | Qdrant endpoint address. | > | `QDRANT_API_KEY` | `difyai123456` | API key for Qdrant. | > | `QDRANT_CLIENT_TIMEOUT` | `20` | Client timeout in seconds. | > | `QDRANT_GRPC_ENABLED` | `false` | Enable gRPC communication. | > | `QDRANT_GRPC_PORT` | `6334` | gRPC port. | > | `QDRANT_REPLICATION_FACTOR` | `1` | Number of replicas per shard. | > [accordion] Milvus > > | Variable | Default | Description | > | :- | :- | :- | > | `MILVUS_URI` | `http://host.docker.internal:19530` | Milvus URI. For [Zilliz Cloud](https://docs.zilliz.com/docs/free-trials), use the Public Endpoint. | > | `MILVUS_DATABASE` | (empty) | Database name. | > | `MILVUS_TOKEN` | (empty) | Authentication token. For Zilliz Cloud, use the API Key. | > | `MILVUS_USER` | (empty) | Username. | > | `MILVUS_PASSWORD` | (empty) | Password. | > | `MILVUS_ENABLE_HYBRID_SEARCH` | `false` | Enable BM25 sparse index for full-text search. Requires Milvus >= 2.5.0. | > | `MILVUS_ANALYZER_PARAMS` | (empty) | Analyzer parameters for text fields. | > | `MILVUS_SECURE` | `false` | Enable one-way TLS for the Milvus connection; the client connects over gRPC with TLS and verifies the server certificate. | > | `MILVUS_SERVER_PEM_PATH` | (empty) | Path inside the container to the Milvus server certificate (PEM), used to verify the server when `MILVUS_SECURE` is on. | > | `MILVUS_SERVER_NAME` | (empty) | TLS SNI server name to verify against (matches the certificate CN/SAN). Required when `MILVUS_SERVER_PEM_PATH` is set. | > [accordion] MyScale > > | Variable | Default | Description | > | :- | :- | :- | > | `MYSCALE_HOST` | `myscale` | MyScale host. | > | `MYSCALE_PORT` | `8123` | MyScale port. | > | `MYSCALE_USER` | `default` | Username. | > | `MYSCALE_PASSWORD` | (empty) | Password. | > | `MYSCALE_DATABASE` | `dify` | Database name. | > | `MYSCALE_FTS_PARAMS` | (empty) | Full-text search params. [Reference](https://myscale.com/docs/en/text-search/#understanding-fts-index-parameters). | > [accordion] Couchbase > > | Variable | Default | Description | > | :- | :- | :- | > | `COUCHBASE_CONNECTION_STRING` | `couchbase://couchbase-server` | Connection string for the Couchbase cluster. | > | `COUCHBASE_USER` | `Administrator` | Username. | > | `COUCHBASE_PASSWORD` | `password` | Password. | > | `COUCHBASE_BUCKET_NAME` | `Embeddings` | Bucket name. | > | `COUCHBASE_SCOPE_NAME` | `_default` | Scope name. | > [accordion] Hologres > > | Variable | Default | Description | > | :- | :- | :- | > | `HOLOGRES_HOST` | (empty) | Hostname. | > | `HOLOGRES_PORT` | `80` | Port number. | > | `HOLOGRES_DATABASE` | (empty) | Database name. | > | `HOLOGRES_ACCESS_KEY_ID` | (empty) | Access key ID (used as PG username). | > | `HOLOGRES_ACCESS_KEY_SECRET` | (empty) | Access key secret (used as PG password). | > | `HOLOGRES_SCHEMA` | `public` | Schema name. | > | `HOLOGRES_TOKENIZER` | `jieba` | Tokenizer for text fields. | > | `HOLOGRES_DISTANCE_METHOD` | `Cosine` | Distance method. | > | `HOLOGRES_BASE_QUANTIZATION_TYPE` | `rabitq` | Quantization type. | > | `HOLOGRES_MAX_DEGREE` | `64` | HNSW max degree. | > | `HOLOGRES_EF_CONSTRUCTION` | `400` | HNSW ef\_construction parameter. | > [accordion] PGVector > > | Variable | Default | Description | > | :- | :- | :- | > | `PGVECTOR_HOST` | `pgvector` | Hostname. | > | `PGVECTOR_PORT` | `5432` | Port number. | > | `PGVECTOR_USER` | `postgres` | Username. | > | `PGVECTOR_PASSWORD` | `difyai123456` | Password. | > | `PGVECTOR_DATABASE` | `dify` | Database name. | > | `PGVECTOR_MIN_CONNECTION` | `1` | Minimum pool connections. | > | `PGVECTOR_MAX_CONNECTION` | `5` | Maximum pool connections. | > | `PGVECTOR_PG_BIGM` | `false` | Enable pg\_bigm extension for full-text search. | > [accordion] Vastbase > > | Variable | Default | Description | > | :- | :- | :- | > | `VASTBASE_HOST` | `vastbase` | Hostname. | > | `VASTBASE_PORT` | `5432` | Port number. | > | `VASTBASE_USER` | `dify` | Username. | > | `VASTBASE_PASSWORD` | `Difyai123456` | Password. | > | `VASTBASE_DATABASE` | `dify` | Database name. | > | `VASTBASE_MIN_CONNECTION` | `1` | Minimum pool connections. | > | `VASTBASE_MAX_CONNECTION` | `5` | Maximum pool connections. | > [accordion] PGVecto.RS > > | Variable | Default | Description | > | :- | :- | :- | > | `PGVECTO_RS_HOST` | `pgvecto-rs` | Hostname. | > | `PGVECTO_RS_PORT` | `5432` | Port number. | > | `PGVECTO_RS_USER` | `postgres` | Username. | > | `PGVECTO_RS_PASSWORD` | `difyai123456` | Password. | > | `PGVECTO_RS_DATABASE` | `dify` | Database name. | > [accordion] AnalyticDB > > | Variable | Default | Description | > | :- | :- | :- | > | `ANALYTICDB_KEY_ID` | (empty) | Aliyun access key ID. [Create AccessKey](https://help.aliyun.com/zh/analyticdb/analyticdb-for-postgresql/support/create-an-accesskey-pair). | > | `ANALYTICDB_KEY_SECRET` | (empty) | Aliyun access key secret. | > | `ANALYTICDB_REGION_ID` | `cn-hangzhou` | Region identifier. | > | `ANALYTICDB_INSTANCE_ID` | (empty) | Instance ID, for example, `gp-xxxxxx`. [Create instance](https://help.aliyun.com/zh/analyticdb/analyticdb-for-postgresql/getting-started/create-an-instance-1). | > | `ANALYTICDB_ACCOUNT` | (empty) | Account name. [Create account](https://help.aliyun.com/zh/analyticdb/analyticdb-for-postgresql/getting-started/createa-a-privileged-account). | > | `ANALYTICDB_PASSWORD` | (empty) | Account password. | > | `ANALYTICDB_NAMESPACE` | `dify` | Namespace (schema). Created automatically if it does not exist. | > | `ANALYTICDB_NAMESPACE_PASSWORD` | (empty) | Namespace password. | > | `ANALYTICDB_HOST` | (empty) | Direct connection host (alternative to API-based access). | > | `ANALYTICDB_PORT` | `5432` | Direct connection port. | > | `ANALYTICDB_MIN_CONNECTION` | `1` | Minimum pool connections. | > | `ANALYTICDB_MAX_CONNECTION` | `5` | Maximum pool connections. | > [accordion] TiDB Vector > > | Variable | Default | Description | > | :- | :- | :- | > | `TIDB_VECTOR_HOST` | `tidb` | Hostname. | > | `TIDB_VECTOR_PORT` | `4000` | Port number. | > | `TIDB_VECTOR_USER` | (empty) | Username. | > | `TIDB_VECTOR_PASSWORD` | (empty) | Password. | > | `TIDB_VECTOR_DATABASE` | `dify` | Database name. | > [accordion] MatrixOne > > | Variable | Default | Description | > | :- | :- | :- | > | `MATRIXONE_HOST` | `matrixone` | Hostname. | > | `MATRIXONE_PORT` | `6001` | Port number. | > | `MATRIXONE_USER` | `dump` | Username. | > | `MATRIXONE_PASSWORD` | `111` | Password. | > | `MATRIXONE_DATABASE` | `dify` | Database name. | > [accordion] Chroma > > | Variable | Default | Description | > | :- | :- | :- | > | `CHROMA_HOST` | `127.0.0.1` | Chroma server host. | > | `CHROMA_PORT` | `8000` | Chroma server port. | > | `CHROMA_TENANT` | `default_tenant` | Tenant name. | > | `CHROMA_DATABASE` | `default_database` | Database name. | > | `CHROMA_AUTH_PROVIDER` | `chromadb.auth.token_authn.TokenAuthClientProvider` | Auth provider class. | > | `CHROMA_AUTH_CREDENTIALS` | (empty) | Auth credentials. | > [accordion] Oracle > > | Variable | Default | Description | > | :- | :- | :- | > | `ORACLE_USER` | `dify` | Oracle username. | > | `ORACLE_PASSWORD` | `dify` | Oracle password. | > | `ORACLE_DSN` | `oracle:1521/FREEPDB1` | Data source name. | > | `ORACLE_CONFIG_DIR` | `/app/api/storage/wallet` | Oracle configuration directory. | > | `ORACLE_WALLET_LOCATION` | `/app/api/storage/wallet` | Wallet location for Autonomous DB. | > | `ORACLE_WALLET_PASSWORD` | `dify` | Wallet password. | > | `ORACLE_IS_AUTONOMOUS` | `false` | Whether using Oracle Autonomous Database. | > [accordion] AlibabaCloud MySQL > > | Variable | Default | Description | > | :- | :- | :- | > | `ALIBABACLOUD_MYSQL_HOST` | `127.0.0.1` | Hostname. | > | `ALIBABACLOUD_MYSQL_PORT` | `3306` | Port number. | > | `ALIBABACLOUD_MYSQL_USER` | `root` | Username. | > | `ALIBABACLOUD_MYSQL_PASSWORD` | `difyai123456` | Password. | > | `ALIBABACLOUD_MYSQL_DATABASE` | `dify` | Database name. | > | `ALIBABACLOUD_MYSQL_MAX_CONNECTION` | `5` | Maximum pool connections. | > | `ALIBABACLOUD_MYSQL_HNSW_M` | `6` | HNSW M parameter. | > [accordion] Relyt > > | Variable | Default | Description | > | :- | :- | :- | > | `RELYT_HOST` | `db` | Hostname. | > | `RELYT_PORT` | `5432` | Port number. | > | `RELYT_USER` | `postgres` | Username. | > | `RELYT_PASSWORD` | `difyai123456` | Password. | > | `RELYT_DATABASE` | `postgres` | Database name. | > [accordion] OpenSearch > > | Variable | Default | Description | > | :- | :- | :- | > | `OPENSEARCH_HOST` | `opensearch` | Hostname. | > | `OPENSEARCH_PORT` | `9200` | Port number. | > | `OPENSEARCH_SECURE` | `true` | Use HTTPS. | > | `OPENSEARCH_VERIFY_CERTS` | `true` | Verify SSL certificates. | > | `OPENSEARCH_AUTH_METHOD` | `basic` | `basic` uses username/password. `aws_managed_iam` uses AWS SigV4 request signing via Boto3 credentials. | > | `OPENSEARCH_USER` | `admin` | Username. Only used with `basic` auth. | > | `OPENSEARCH_PASSWORD` | `admin` | Password. Only used with `basic` auth. | > | `OPENSEARCH_AWS_REGION` | `ap-southeast-1` | AWS region. Only used with `aws_managed_iam` auth. | > | `OPENSEARCH_AWS_SERVICE` | `aoss` | AWS service type: `es` (Managed Cluster) or `aoss` (OpenSearch Serverless). | > [accordion] Tencent Cloud VectorDB > > | Variable | Default | Description | > | :- | :- | :- | > | `TENCENT_VECTOR_DB_URL` | `http://127.0.0.1` | Access address. [Console](https://console.cloud.tencent.com/vdb). | > | `TENCENT_VECTOR_DB_API_KEY` | `dify` | API key. [Key Management](https://cloud.tencent.com/document/product/1709/95108). | > | `TENCENT_VECTOR_DB_TIMEOUT` | `30` | Request timeout in seconds. | > | `TENCENT_VECTOR_DB_USERNAME` | `dify` | Account name. [Account Management](https://cloud.tencent.com/document/product/1709/115833). | > | `TENCENT_VECTOR_DB_DATABASE` | `dify` | Database name. [Create Database](https://cloud.tencent.com/document/product/1709/95822). | > | `TENCENT_VECTOR_DB_SHARD` | `1` | Number of shards. | > | `TENCENT_VECTOR_DB_REPLICAS` | `2` | Number of replicas. | > | `TENCENT_VECTOR_DB_ENABLE_HYBRID_SEARCH` | `false` | Enable hybrid search. [Sparse Vector docs](https://cloud.tencent.com/document/product/1709/110110). | > [accordion] Elasticsearch > > | Variable | Default | Description | > | :- | :- | :- | > | `ELASTICSEARCH_HOST` | `0.0.0.0` | Hostname. | > | `ELASTICSEARCH_PORT` | `9200` | Port number. | > | `ELASTICSEARCH_USERNAME` | `elastic` | Username. | > | `ELASTICSEARCH_PASSWORD` | `elastic` | Password. | > | `ELASTICSEARCH_USE_CLOUD` | `false` | Switch to Elastic Cloud mode. When `true`, uses `ELASTICSEARCH_CLOUD_URL` and `ELASTICSEARCH_API_KEY` instead of host/port/username/password. | > | `ELASTICSEARCH_CLOUD_URL` | (empty) | Elastic Cloud endpoint URL. Required when `ELASTICSEARCH_USE_CLOUD=true`. | > | `ELASTICSEARCH_API_KEY` | (empty) | Elastic Cloud API key. Required when `ELASTICSEARCH_USE_CLOUD=true`. | > | `ELASTICSEARCH_VERIFY_CERTS` | `false` | Verify SSL certificates. | > | `ELASTICSEARCH_CA_CERTS` | (empty) | Path to CA certificates. | > | `ELASTICSEARCH_REQUEST_TIMEOUT` | `100000` | Request timeout in milliseconds. | > | `ELASTICSEARCH_RETRY_ON_TIMEOUT` | `true` | Retry on timeout. | > | `ELASTICSEARCH_MAX_RETRIES` | `10` | Maximum retry attempts. | > [accordion] Baidu Vector DB > > | Variable | Default | Description | > | :- | :- | :- | > | `BAIDU_VECTOR_DB_ENDPOINT` | `http://127.0.0.1:5287` | Endpoint URL. | > | `BAIDU_VECTOR_DB_CONNECTION_TIMEOUT_MS` | `30000` | Connection timeout in milliseconds. | > | `BAIDU_VECTOR_DB_ACCOUNT` | `root` | Account name. | > | `BAIDU_VECTOR_DB_API_KEY` | `dify` | API key. | > | `BAIDU_VECTOR_DB_DATABASE` | `dify` | Database name. | > | `BAIDU_VECTOR_DB_SHARD` | `1` | Number of shards. | > | `BAIDU_VECTOR_DB_REPLICAS` | `3` | Number of replicas. | > | `BAIDU_VECTOR_DB_INVERTED_INDEX_ANALYZER` | `DEFAULT_ANALYZER` | Inverted index analyzer. | > | `BAIDU_VECTOR_DB_INVERTED_INDEX_PARSER_MODE` | `COARSE_MODE` | Inverted index parser mode. | > | `BAIDU_VECTOR_DB_AUTO_BUILD_ROW_COUNT_INCREMENT` | `500` | Absolute row-count increment that triggers an automatic index rebuild. Works alongside `_RATIO`; whichever threshold is crossed first wins. | > | `BAIDU_VECTOR_DB_AUTO_BUILD_ROW_COUNT_INCREMENT_RATIO` | `0.05` | Relative growth that triggers an automatic index rebuild. Whichever threshold is crossed first wins. | > | `BAIDU_VECTOR_DB_REBUILD_INDEX_TIMEOUT_IN_SECONDS` | `300` | Maximum time the client waits for an index rebuild to complete. | > [accordion] VikingDB > > | Variable | Default | Description | > | :- | :- | :- | > | `VIKINGDB_ACCESS_KEY` | (empty) | Access key. | > | `VIKINGDB_SECRET_KEY` | (empty) | Secret key. | > | `VIKINGDB_REGION` | `cn-shanghai` | Region. | > | `VIKINGDB_HOST` | `api-vikingdb.xxx.volces.com` | API host. Replace with your region-specific endpoint. | > | `VIKINGDB_SCHEME` | `http` | Protocol scheme (`http` or `https`). | > | `VIKINGDB_CONNECTION_TIMEOUT` | `30` | Connection timeout in seconds. | > | `VIKINGDB_SOCKET_TIMEOUT` | `30` | Socket timeout in seconds. | > [accordion] Lindorm > > | Variable | Default | Description | > | :- | :- | :- | > | `LINDORM_URL` | `http://localhost:30070` | Lindorm search engine URL. [Console](https://lindorm.console.aliyun.com/). | > | `LINDORM_USERNAME` | `admin` | Username. | > | `LINDORM_PASSWORD` | `admin` | Password. | > | `LINDORM_USING_UGC` | `true` | Use UGC mode. | > | `LINDORM_QUERY_TIMEOUT` | `1` | Query timeout in seconds. | > [accordion] OpenGauss > > | Variable | Default | Description | > | :- | :- | :- | > | `OPENGAUSS_HOST` | `opengauss` | Hostname. | > | `OPENGAUSS_PORT` | `6600` | Port number. | > | `OPENGAUSS_USER` | `postgres` | Username. | > | `OPENGAUSS_PASSWORD` | `Dify@123` | Password. | > | `OPENGAUSS_DATABASE` | `dify` | Database name. | > | `OPENGAUSS_MIN_CONNECTION` | `1` | Minimum pool connections. | > | `OPENGAUSS_MAX_CONNECTION` | `5` | Maximum pool connections. | > | `OPENGAUSS_ENABLE_PQ` | `false` | Enable PQ acceleration. | > [accordion] Huawei Cloud Search > > | Variable | Default | Description | > | :- | :- | :- | > | `HUAWEI_CLOUD_HOSTS` | `https://127.0.0.1:9200` | Cluster endpoint URL. | > | `HUAWEI_CLOUD_USER` | `admin` | Username. | > | `HUAWEI_CLOUD_PASSWORD` | `admin` | Password. | > [accordion] Upstash Vector > > | Variable | Default | Description | > | :- | :- | :- | > | `UPSTASH_VECTOR_URL` | (empty) | Upstash Vector endpoint URL. | > | `UPSTASH_VECTOR_TOKEN` | (empty) | Upstash Vector API token. | > [accordion] TableStore > > | Variable | Default | Description | > | :- | :- | :- | > | `TABLESTORE_ENDPOINT` | `https://instance-name.cn-hangzhou.ots.aliyuncs.com` | Endpoint address. Replace `instance-name` with your instance. | > | `TABLESTORE_INSTANCE_NAME` | (empty) | Instance name. | > | `TABLESTORE_ACCESS_KEY_ID` | (empty) | Access key ID. | > | `TABLESTORE_ACCESS_KEY_SECRET` | (empty) | Access key secret. | > | `TABLESTORE_NORMALIZE_FULLTEXT_BM25_SCORE` | `false` | Normalize fulltext BM25 scores. | > [accordion] ClickZetta > > | Variable | Default | Description | > | :- | :- | :- | > | `CLICKZETTA_USERNAME` | (empty) | Username. | > | `CLICKZETTA_PASSWORD` | (empty) | Password. | > | `CLICKZETTA_INSTANCE` | (empty) | Instance name. | > | `CLICKZETTA_SERVICE` | `api.clickzetta.com` | Service endpoint. | > | `CLICKZETTA_WORKSPACE` | `quick_start` | Workspace name. | > | `CLICKZETTA_VCLUSTER` | `default_ap` | Virtual cluster. | > | `CLICKZETTA_SCHEMA` | `dify` | Schema name. | > | `CLICKZETTA_BATCH_SIZE` | `100` | Batch size for operations. | > | `CLICKZETTA_ENABLE_INVERTED_INDEX` | `true` | Enable inverted index. | > | `CLICKZETTA_ANALYZER_TYPE` | `chinese` | Analyzer type. | > | `CLICKZETTA_ANALYZER_MODE` | `smart` | Analyzer mode. | > | `CLICKZETTA_VECTOR_DISTANCE_FUNCTION` | `cosine_distance` | Distance function. | > [accordion] InterSystems IRIS > > | Variable | Default | Description | > | :- | :- | :- | > | `IRIS_HOST` | `iris` | Hostname. | > | `IRIS_SUPER_SERVER_PORT` | `1972` | Super server port. | > | `IRIS_USER` | `_SYSTEM` | Username. | > | `IRIS_PASSWORD` | `Dify@1234` | Password. | > | `IRIS_DATABASE` | `USER` | Database name. | > | `IRIS_SCHEMA` | `dify` | Schema name. | > | `IRIS_CONNECTION_URL` | (empty) | Full connection URL (overrides individual settings). | > | `IRIS_MIN_CONNECTION` | `1` | Minimum pool connections. | > | `IRIS_MAX_CONNECTION` | `3` | Maximum pool connections. | > | `IRIS_TEXT_INDEX` | `true` | Enable text indexing. | > | `IRIS_TEXT_INDEX_LANGUAGE` | `en` | Text index language. | ### Knowledge Configuration | Variable | Default | Description | | :- | :- | :- | | `UPLOAD_FILE_SIZE_LIMIT` | `15` (Helm default) | Maximum file size in MB for document uploads (PDFs, Word docs, etc.). Users see a "file too large" error when exceeded. Set through `api.limits.uploadFileSize` in `values.yaml`. | | `UPLOAD_FILE_BATCH_LIMIT` | `5` (Helm default) | Maximum number of files allowed per upload batch. Set through `api.limits.uploadFileBatchCount`. | | `UPLOAD_FILE_EXTENSION_BLACKLIST` | (empty) | Security blocklist of file extensions that cannot be uploaded. Comma-separated, lowercase, no dots. Example: `exe,bat,cmd,com,scr,vbs,ps1,msi,dll`. | | `SINGLE_CHUNK_ATTACHMENT_LIMIT` | `10` | Maximum number of images that can be embedded in a single knowledge base segment (chunk). | | `IMAGE_FILE_BATCH_LIMIT` | `10` | Maximum number of image files per upload batch. | | `ATTACHMENT_IMAGE_FILE_SIZE_LIMIT` | `2` | Maximum size in MB for images fetched from external URLs during knowledge base indexing. Different from `UPLOAD_IMAGE_FILE_SIZE_LIMIT`, which applies to direct uploads. | | `ATTACHMENT_IMAGE_DOWNLOAD_TIMEOUT` | `60` | Timeout in seconds when downloading images from external URLs during knowledge base indexing. | | `ETL_TYPE` | `dify` (Helm default) | Document extraction library. `dify` supports txt, md, pdf, html, xlsx, docx, csv. `Unstructured` adds doc, msg, eml, ppt, pptx, xml, epub. The chart sets `Unstructured` and wires `UNSTRUCTURED_API_URL` automatically when `global.rag.etlType` is `Unstructured`. | | `UNSTRUCTURED_API_URL` | (empty; set by the chart when `etlType=Unstructured`) | Unstructured.io API endpoint. Required when `ETL_TYPE` is `Unstructured`. | | `UNSTRUCTURED_API_KEY` | (empty) | API key for Unstructured.io authentication. | | `SCARF_NO_ANALYTICS` | `true` | Disable the Unstructured library's telemetry collection. | | `TOP_K_MAX_VALUE` | `10` (Helm default) | Maximum value users can set for the `top_k` parameter in knowledge base retrieval. Set through `global.rag.topKMaxValue`. | | `DATASET_MAX_SEGMENTS_PER_REQUEST` | `0` | Maximum number of segments per dataset API request. `0` means unlimited. | #### Annotation Import | Variable | Default | Description | | :- | :- | :- | | `ANNOTATION_IMPORT_FILE_SIZE_LIMIT` | `2` | Maximum CSV file size in MB for annotation import. Returns HTTP 413 when exceeded. | | `ANNOTATION_IMPORT_MAX_RECORDS` | `10000` | Maximum number of records per annotation import. | | `ANNOTATION_IMPORT_MIN_RECORDS` | `1` | Minimum number of valid records required per annotation import. | | `ANNOTATION_IMPORT_RATE_LIMIT_PER_MINUTE` | `5` | Maximum annotation import requests per minute per workspace. Returns HTTP 429 when exceeded. | | `ANNOTATION_IMPORT_RATE_LIMIT_PER_HOUR` | `20` | Maximum annotation import requests per hour per workspace. | | `ANNOTATION_IMPORT_MAX_CONCURRENT` | `5` | Maximum concurrent annotation import tasks per workspace. | ### Model Configuration | Variable | Default | Description | | :- | :- | :- | | `PLUGIN_BASED_TOKEN_COUNTING_ENABLED` | `false` | Use plugin-based token counting for accurate usage tracking. When disabled, token counting returns 0 (faster but cost tracking is less accurate). | ### Multi-modal Configuration | Variable | Default | Description | | :- | :- | :- | | `MULTIMODAL_SEND_FORMAT` | `base64` | How files are sent to multi-modal LLMs. `base64` embeds file data in the request (more compatible). `url` sends a signed URL for the model to fetch (faster, smaller requests, but the model must reach `FILES_URL`). | | `UPLOAD_IMAGE_FILE_SIZE_LIMIT` | `5` (Helm default) | Maximum image file size in MB for direct uploads (jpg, png, webp, gif, svg). The chart default is 5 (the application default is 10). Set through `api.limits.uploadImageFileSize`. | | `UPLOAD_VIDEO_FILE_SIZE_LIMIT` | `100` | Maximum video file size in MB for direct uploads (mp4, mov, mpeg, webm). | | `UPLOAD_AUDIO_FILE_SIZE_LIMIT` | `50` | Maximum audio file size in MB for direct uploads (mp3, m4a, wav, amr, mpga). | ### Sentry Configuration Sentry provides error tracking and performance monitoring. In Helm deployments, enable Sentry per service through `values.yaml` (`api.sentry`, `worker.sentry`, `web.sentry`). | Variable | Default | Description | | :- | :- | :- | | `SENTRY_DSN` | (empty) | Sentry DSN. The chart sets this per service when Sentry is enabled. | | `SENTRY_TRACES_SAMPLE_RATE` | `1.0` | Fraction of requests to include in performance tracing (0.01 = 1%). | | `SENTRY_PROFILES_SAMPLE_RATE` | `1.0` | Fraction of requests to include in CPU/memory profiling. | | `PLUGIN_SENTRY_ENABLED` | `false` | Enable Sentry for the plugin daemon service. | | `PLUGIN_SENTRY_DSN` | (empty) | Sentry DSN for the plugin daemon. | ### Notion Integration Configuration Connect Dify to Notion as a knowledge base data source. Get integration credentials at [https://www.notion.so/my-integrations](https://www.notion.so/my-integrations). | Variable | Default | Description | | :- | :- | :- | | `NOTION_INTEGRATION_TYPE` | `internal` (Helm default) | `public` uses standard OAuth 2.0 (requires an HTTPS redirect URL, plus CLIENT\_ID and CLIENT\_SECRET). `internal` uses a direct integration token (works with HTTP). From Dify Enterprise 3.13.1, set it through `global.integrations.notion.integrationType`. On 3.13.0, Dify uses OAuth (`public`) whatever `integrationType` is set to. With `integrationType` left at `internal`, Notion won't connect. Upgrading to 3.13.1 fixes this. | | `NOTION_CLIENT_SECRET` | (empty) | OAuth client secret. Required for `public` integration. | | `NOTION_CLIENT_ID` | (empty) | OAuth client ID. Required for `public` integration. | | `NOTION_INTERNAL_SECRET` | (empty) | Direct integration token from Notion. Required for `internal` integration. | ### Mail Configuration Dify sends emails for account invitations, password resets, login codes, and Human Input node notifications. Configure one of the three supported providers. Email links require `CONSOLE_WEB_URL` to be set (see [Common Variables](#console_web_url)). | Variable | Default | Description | | :- | :- | :- | | `MAIL_TYPE` | `resend` | Mail provider: `resend`, `smtp`, or `sendgrid`. | | `MAIL_DEFAULT_SEND_FROM` | (empty) | Default "From" address for all outgoing emails. Required. | > [accordion] Resend > > | Variable | Default | Description | > | :- | :- | :- | > | `RESEND_API_URL` | `https://api.resend.com` | Resend API endpoint. Override for self-hosted Resend or a proxy. | > | `RESEND_API_KEY` | (empty) | Resend API key. Required when `MAIL_TYPE=resend`. | > [accordion] SMTP > > Three TLS modes: implicit TLS (`SMTP_USE_TLS=true`, `SMTP_OPPORTUNISTIC_TLS=false`, port 465), STARTTLS (`SMTP_USE_TLS=true`, `SMTP_OPPORTUNISTIC_TLS=true`, port 587), or plain (`SMTP_USE_TLS=false`, port 25). > > | Variable | Default | Description | > | :- | :- | :- | > | `SMTP_SERVER` | (empty) | SMTP server address. | > | `SMTP_PORT` | `465` | SMTP server port. Use `587` for STARTTLS mode. | > | `SMTP_USERNAME` | (empty) | SMTP username. Can be empty for IP-whitelisted servers. | > | `SMTP_PASSWORD` | (empty) | SMTP password. Can be empty for IP-whitelisted servers. | > | `SMTP_USE_TLS` | `true` | Enable TLS. With `SMTP_OPPORTUNISTIC_TLS=false`, uses implicit TLS. | > | `SMTP_OPPORTUNISTIC_TLS` | `false` | Use STARTTLS (explicit TLS) instead of implicit TLS. Must be used with `SMTP_USE_TLS=true`. | > | `SMTP_LOCAL_HOSTNAME` | (empty) | Override the hostname sent in SMTP HELO/EHLO. Required when your SMTP server rejects container hostnames (common with Google Workspace, Microsoft 365). | > [accordion] SendGrid > > | Variable | Default | Description | > | :- | :- | :- | > | `SENDGRID_API_KEY` | (empty) | SendGrid API key. Required when `MAIL_TYPE=sendgrid`. | > > For more details, see the [SendGrid documentation](https://www.twilio.com/docs/sendgrid/for-developers/sending-email/api-getting-started). ### Others Configuration #### Indexing | Variable | Default | Description | | :- | :- | :- | | `INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH` | `4000` (Helm default) | Maximum token length per text segment when chunking documents for the knowledge base. Larger values retain more context per chunk; smaller values provide finer granularity. Set through `global.rag.indexingMaxSegmentationTokensLength`. | #### Token & Invitation All token expiry variables control how long a one-time-use token stored in Redis remains valid. After expiry, the user must request a new token. | Variable | Default | Description | | :- | :- | :- | | `INVITE_EXPIRY_HOURS` | `72` | How long a workspace invitation link stays valid (in hours). | | `RESET_PASSWORD_TOKEN_EXPIRY_MINUTES` | `5` | Password reset token validity in minutes. | | `EMAIL_REGISTER_TOKEN_EXPIRY_MINUTES` | `5` | Email registration token validity in minutes. | | `OWNER_TRANSFER_TOKEN_EXPIRY_MINUTES` | `5` | Workspace owner transfer token validity in minutes. | #### Code Execution Sandbox The sandbox is a separate service that runs Python, JavaScript, and Jinja2 code nodes in isolation. The chart sets `CODE_EXECUTION_ENDPOINT` automatically to the in-cluster sandbox service. | Variable | Default | Description | | :- | :- | :- | | `CODE_EXECUTION_ENDPOINT` | in-cluster sandbox service (Helm default) | Sandbox service endpoint. The chart points this at the bundled sandbox service. | | `CODE_EXECUTION_API_KEY` | `dify-sandbox` | API key for sandbox authentication. Must match `SANDBOX_API_KEY` in the sandbox service. | | `CODE_EXECUTION_SSL_VERIFY` | `true` | Verify SSL for sandbox connections. | | `CODE_EXECUTION_CONNECT_TIMEOUT` | `10` | Connection timeout in seconds. | | `CODE_EXECUTION_READ_TIMEOUT` | `60` | Read timeout in seconds. | | `CODE_EXECUTION_WRITE_TIMEOUT` | `10` | Write timeout in seconds. | | `CODE_EXECUTION_POOL_MAX_CONNECTIONS` | `100` | Maximum concurrent HTTP connections to the sandbox service. | | `CODE_EXECUTION_POOL_MAX_KEEPALIVE_CONNECTIONS` | `20` | Maximum idle connections kept alive in the sandbox pool. | | `CODE_EXECUTION_POOL_KEEPALIVE_EXPIRY` | `5.0` | Seconds before idle sandbox connections are closed. | | `CODE_MAX_NUMBER` | `9223372036854775807` | Maximum numeric value allowed in code node output. | | `CODE_MIN_NUMBER` | `-9223372036854775808` | Minimum numeric value allowed in code node output. | | `CODE_MAX_STRING_LENGTH` | `400000` | Maximum string length in code node output. | | `CODE_MAX_DEPTH` | `5` | Maximum nesting depth for output data structures. | | `CODE_MAX_PRECISION` | `20` | Maximum decimal places for floating-point numbers in output. | | `CODE_MAX_STRING_ARRAY_LENGTH` | `30` | Maximum number of elements in a string array output. | | `CODE_MAX_OBJECT_ARRAY_LENGTH` | `30` | Maximum number of elements in an object array output. | | `CODE_MAX_NUMBER_ARRAY_LENGTH` | `1000` | Maximum number of elements in a number array output. | | `TEMPLATE_TRANSFORM_MAX_LENGTH` | `400000` | Maximum character length for Template Transform node output. | #### Workflow Runtime | Variable | Default | Description | | :- | :- | :- | | `WORKFLOW_MAX_EXECUTION_STEPS` | `500` | Maximum number of node executions for a run in Studio or an app's built-in environment. Runs in deployed environments use a separate limit. See [Deployed Environments (App Runner)](#app-runner) for how to change it. | | `WORKFLOW_MAX_EXECUTION_TIME` | `3600` | Maximum time in seconds for a run in Studio or an app's built-in environment. Set through `api.workflowMaxExecutionTimeSeconds`. Runs in deployed environments use a separate limit, set through `enterprise.workflowMaxExecutionTimeSeconds` (default: `1200` seconds). | | `WORKFLOW_CALL_MAX_DEPTH` | `5` | Maximum depth for nested workflow-calls-workflow. Prevents infinite recursion. | | `MAX_VARIABLE_SIZE` | `204800` | Maximum size in bytes (200 KB) for a single workflow variable. | | `WORKFLOW_FILE_UPLOAD_LIMIT` | `10` | Maximum number of files that can be uploaded in a single workflow execution. | | `WORKFLOW_NODE_EXECUTION_STORAGE` | `rdbms` | Where workflow node execution records are stored. `rdbms` stores everything in the database. `hybrid` stores new data in object storage and reads from both. | | `DSL_EXPORT_ENCRYPT_DATASET_ID` | `true` | Encrypt dataset IDs when exporting DSL files. Set to `false` to export plain IDs for easier cross-environment import. | #### Workflow Tracing These settings apply to workflow tracing integrations in the API and workers, separately from OpenTelemetry instrumentation. | Variable | Default | Description | | :- | :- | :- | | `OPS_TRACE_UNIFIED_ENABLED` | `false` (Helm default) | Set to `true` to use unified workflow tracing with LangSmith or Arize Phoenix. Leave `false` to keep the existing tracing behavior. Other providers keep their existing implementation. Set through `api.opsTrace.unifiedEnabled`. | | `OPS_TRACE_PARENT_CONTEXT_TTL_SECONDS` | `3900` (Helm default) | Seconds to retain parent trace context for linking child workflow traces to their parent. Set `api.opsTrace.parentContextTtlSeconds` to a positive integer. | | `OPS_TRACE_RETRYABLE_DISPATCH_MAX_RETRIES` | `780` (Helm default) | Maximum retries for transient failures sending trace data to a provider. Does not change workflow execution retries. Set `api.opsTrace.retryableDispatchMaxRetries` to a positive integer. | With unified tracing enabled, keep `OPS_TRACE_PARENT_CONTEXT_TTL_SECONDS` at least `OPS_TRACE_RETRYABLE_DISPATCH_MAX_RETRIES` multiplied by `OPS_TRACE_RETRYABLE_DISPATCH_DELAY_SECONDS`. A lower value fails application configuration validation. The retry delay defaults to `5` seconds and can be changed through `extraEnv`. With the default retry count and delay, the minimum parent-context TTL is `780 × 5 = 3900` seconds. #### Workflow Storage Repository These select which backend implementation handles workflow execution data. The default SQLAlchemy repositories store everything in the database. | Variable | Default | Description | | :- | :- | :- | | `CORE_WORKFLOW_EXECUTION_REPOSITORY` | `core.repositories.sqlalchemy_workflow_execution_repository.SQLAlchemyWorkflowExecutionRepository` | Repository implementation for workflow execution records. | | `CORE_WORKFLOW_NODE_EXECUTION_REPOSITORY` | `core.repositories.sqlalchemy_workflow_node_execution_repository.SQLAlchemyWorkflowNodeExecutionRepository` | Repository implementation for workflow node execution records. | | `API_WORKFLOW_RUN_REPOSITORY` | `repositories.sqlalchemy_api_workflow_run_repository.DifyAPISQLAlchemyWorkflowRunRepository` | Service-layer repository for workflow run API operations. | | `API_WORKFLOW_NODE_EXECUTION_REPOSITORY` | `repositories.sqlalchemy_api_workflow_node_execution_repository.DifyAPISQLAlchemyWorkflowNodeExecutionRepository` | Service-layer repository for workflow node execution API operations. | | `LOOP_NODE_MAX_COUNT` | `100` | Maximum iterations for Loop nodes. Prevents infinite loops. | | `MAX_PARALLEL_LIMIT` | `10` | Maximum number of parallel branches in a workflow. | #### GraphEngine Worker Pool | Variable | Default | Description | | :- | :- | :- | | `GRAPH_ENGINE_MIN_WORKERS` | `3` | Minimum workers per GraphEngine instance. | | `GRAPH_ENGINE_MAX_WORKERS` | `10` | Maximum workers per GraphEngine instance. | | `GRAPH_ENGINE_SCALE_UP_THRESHOLD` | `0` (Helm default) | Queue depth that triggers spawning additional workers. Set through `api.graphEngineScaleUpThreshold`. | | `GRAPH_ENGINE_SCALE_DOWN_IDLE_TIME` | `5.0` | Seconds of idle time before excess workers are removed. | #### Workflow Log Cleanup The chart enables this through `workerBeat.enableWorkflowLogCleanup`, which sets `WORKFLOW_LOG_CLEANUP_ENABLED` on the beat ConfigMap. The chart does not set the remaining variables; configure them through `extraEnv` on the worker and beat services. | Variable | Default | Description | | :- | :- | :- | | `WORKFLOW_LOG_CLEANUP_ENABLED` | `false` (Helm default) | Enables automatic cleanup of workflow execution logs at 2:00 AM daily. Set through `workerBeat.enableWorkflowLogCleanup`. | | `WORKFLOW_LOG_RETENTION_DAYS` | `30` | Number of days to retain workflow logs before cleanup. | | `WORKFLOW_LOG_CLEANUP_BATCH_SIZE` | `100` | Number of log entries processed per cleanup batch. | | `WORKFLOW_LOG_CLEANUP_SPECIFIC_WORKFLOW_IDS` | (empty) | Comma-separated list of workflow IDs to limit cleanup to. When empty, all workflow logs are cleaned. | #### HTTP Request Node These configure the HTTP Request node used in workflows to call external APIs. | Variable | Default | Description | | :- | :- | :- | | `HTTP_REQUEST_NODE_MAX_TEXT_SIZE` | `1048576` | Maximum text response size in bytes (1 MB). Responses larger than this are truncated. | | `HTTP_REQUEST_NODE_MAX_BINARY_SIZE` | `10485760` | Maximum binary response size in bytes (10 MB). | | `HTTP_REQUEST_NODE_SSL_VERIFY` | `true` | Verify SSL certificates. Disable for testing with self-signed certificates. | | `HTTP_REQUEST_MAX_CONNECT_TIMEOUT` | `10` | Maximum connect timeout users can set in the workflow editor (in seconds). | | `HTTP_REQUEST_MAX_READ_TIMEOUT` | `600` | Maximum read timeout ceiling (in seconds). | | `HTTP_REQUEST_MAX_WRITE_TIMEOUT` | `600` | Maximum write timeout ceiling (in seconds). | #### Webhook | Variable | Default | Description | | :- | :- | :- | | `WEBHOOK_REQUEST_BODY_MAX_SIZE` | `10485760` | Maximum webhook payload size in bytes (10 MB). Larger payloads are rejected with a 413 error. | #### SSRF Protection All outbound HTTP requests from Dify (HTTP nodes, image downloads, etc.) are routed through a proxy that blocks requests to internal/private IP ranges, preventing Server-Side Request Forgery (SSRF) attacks. The chart sets `SSRF_PROXY_HTTP_URL` and `SSRF_PROXY_HTTPS_URL` automatically when the SSRF proxy is enabled. | Variable | Default | Description | | :- | :- | :- | | `SSRF_PROXY_HTTP_URL` | in-cluster SSRF proxy (Helm default) | SSRF proxy URL for HTTP requests. | | `SSRF_PROXY_HTTPS_URL` | in-cluster SSRF proxy (Helm default) | SSRF proxy URL for HTTPS requests. | | `SSRF_POOL_MAX_CONNECTIONS` | `100` | Maximum concurrent connections in the SSRF HTTP client pool. | | `SSRF_POOL_MAX_KEEPALIVE_CONNECTIONS` | `20` | Maximum idle connections kept alive in the SSRF pool. | | `SSRF_POOL_KEEPALIVE_EXPIRY` | `5.0` | Seconds before idle SSRF connections are closed. | | `SSRF_PROXY_ALLOW_PRIVATE_IPS` | (empty; Docker Compose default) | Docker Compose only. Comma- or space-separated private IPs or CIDR ranges to allow through the SSRF proxy. | | `SSRF_PROXY_ALLOW_PRIVATE_DOMAINS` | (empty; Docker Compose default) | Docker Compose only. Comma- or space-separated internal domains to allow through the SSRF proxy. | | `RESPECT_XFORWARD_HEADERS_ENABLED` | `false` | Trust X-Forwarded-For/Proto/Port headers from reverse proxies. Only enable behind a single trusted reverse proxy. | For Helm deployments, configure SSRF proxy policies in `values.yaml`: * Use `ssrfProxy.squidConf` for Code node sandboxes. API and worker requests routed through the same proxy share this policy. * Use `sandboxGateway.ssrfProxy.squidConf` for the separate policy applied to Agent sandboxes managed through Sandbox Gateway. Adding the two Docker Compose allowlist variables to `ssrfProxy.extraEnv` does not change the proxy policy. #### Agent Configuration | Variable | Default | Description | | :- | :- | :- | | `MAX_TOOLS_NUM` | `10` | Maximum number of tools an agent can use simultaneously. | | `MAX_ITERATIONS_NUM` | `99` | Maximum reasoning iterations per agent execution. | #### UPLOAD\_SKILL\_FILE\_SIZE\_LIMIT Default: `50` Maximum size in MiB for a `.zip` or `.skill` package imported into the skill library or uploaded to an agent as an embedded skill. Set it through `api.limits.uploadSkillFileSize`. #### Dify CLI and Programmatic API | Variable | Default | Description | | :- | :- | :- | | `OPENAPI_ENABLED` | `false` | Enables the `/openapi/v1/*` endpoint group used by `difyctl` and other programmatic clients. When `false`, the chart also suppresses the gateway route. Set through `api.openapi.enabled`. | | `ENABLE_OAUTH_BEARER` | `true` | OAuth bearer middleware: validates device-flow tokens and bearer authentication on the Service API. The CLI sign-in flow requires it. Set through `api.enableOauthBearer`. | ## Web Frontend Service These variables are used by the Next.js web frontend container only, and do not affect the Python backend. | Variable | Default | Description | | :- | :- | :- | | `TEXT_GENERATION_TIMEOUT_MS` | `60000` | Frontend timeout for streaming text generation UI. If a stream stalls for longer than this, the UI pauses rendering. | | `ALLOW_INLINE_STYLES` | `false` | Allow inline `style` attributes and ` {html_content} """ # Create temp directory if it doesn't exist temp_dir = tempfile.gettempdir() if not os.path.exists(temp_dir): os.makedirs(temp_dir) # Output file path file_path = os.path.join(temp_dir, f"{document_name}.pdf") # Configure fonts font_config = FontConfiguration() # Render PDF HTML(string=styled_html).write_pdf( file_path, stylesheets=[], font_config=font_config ) return file_path ``` ## Step 8: Create the Tool Implementations First, create the Word export tool in `tools/word_export.py`: ```python tools/word_export.py theme={null} import os import base64 from collections.abc import Generator from typing import Any from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage from utils.docx_utils import convert_markdown_to_docx class WordExportTool(Tool): def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]: # Extract parameters markdown_content = tool_parameters.get("markdown_content", "") document_name = tool_parameters.get("document_name", "exported_document") if not markdown_content: yield self.create_text_message("Error: No content provided for export.") return try: # Convert markdown to Word file_path = convert_markdown_to_docx(markdown_content, document_name) # Read the file as binary with open(file_path, 'rb') as file: file_content = file.read() # Encode as base64 file_base64 = base64.b64encode(file_content).decode('utf-8') # Return success message and file yield self.create_text_message( f"Document exported successfully as Word (.docx) format." ) yield self.create_file_message( file_name=f"{document_name}.docx", file_content=file_base64, mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) except Exception as e: yield self.create_text_message(f"Error exporting to Word: {str(e)}") return ``` Next, create the PDF export tool in `tools/pdf_export.py`: ```python tools/pdf_export.py theme={null} import os import base64 from collections.abc import Generator from typing import Any from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage from utils.pdf_utils import convert_markdown_to_pdf class PDFExportTool(Tool): def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]: # Extract parameters markdown_content = tool_parameters.get("markdown_content", "") document_name = tool_parameters.get("document_name", "exported_document") if not markdown_content: yield self.create_text_message("Error: No content provided for export.") return try: # Convert markdown to PDF file_path = convert_markdown_to_pdf(markdown_content, document_name) # Read the file as binary with open(file_path, 'rb') as file: file_content = file.read() # Encode as base64 file_base64 = base64.b64encode(file_content).decode('utf-8') # Return success message and file yield self.create_text_message( f"Document exported successfully as PDF format." ) yield self.create_file_message( file_name=f"{document_name}.pdf", file_content=file_base64, mime_type="application/pdf" ) except Exception as e: yield self.create_text_message(f"Error exporting to PDF: {str(e)}") return ``` ## Step 9: Create the Entrypoint Create a `main.py` file at the root of your project: ```python main.py theme={null} from dify_plugin import PluginRunner from tools.word_export import WordExportTool from tools.pdf_export import PDFExportTool plugin = PluginRunner( tools=[ WordExportTool(), PDFExportTool(), ], providers=[] # No credential providers needed ) ``` ## Step 10: Test Your Plugin **1. Set up your debug environment** First, create your `.env` file from the template: ```bash theme={null} cp .env.example .env ``` Configure it with your Dify environment details: ```dotenv theme={null} INSTALL_METHOD=remote REMOTE_INSTALL_URL=debug-plugin.dify.dev:5003 REMOTE_INSTALL_KEY=your_debug_key ``` **2. Install dependencies** ```bash theme={null} pip install -r requirements.txt ``` **3. Start the plugin in debug mode** ```bash theme={null} python -m main ``` ## Step 11: Package for Distribution When you're ready to share your plugin: ```bash theme={null} dify plugin package ./ ``` This creates a `plugin.difypkg` file for distribution. ## Creative Use Cases > [card] Report generation > > Use this plugin to convert analysis summaries into professional reports for clients > [card] Session documentation > > Export coaching or consulting session notes as formatted documents ## Beyond the Basics Here are some interesting ways to extend this plugin: * **Custom templates**: Add company branding or personalized styles. * **Multi-format support**: Expand to export as HTML, Markdown, or other formats. * **Image handling**: Process and include images from conversations. * **Table support**: Implement proper formatting for data tables. * **Collaborative editing**: Add integration with Google Docs or similar platforms. > [accordion] Technical Insights > > The core challenge in document conversion is maintaining formatting and structure. This plugin first converts markdown to HTML as an intermediate format, then processes that HTML into the target format. > > The two-step process provides flexibility: you can support additional formats by adding new output modules that work with the HTML representation. > > For PDF generation, the plugin uses WeasyPrint because it offers high-quality PDF rendering with CSS support. For Word documents, python-docx provides granular control over document structure. ## Summary You've built a practical plugin that lets users export conversations in professional document formats, bridging the gap between AI conversations and traditional document workflows. > [card] Documentation > > Write your README.md in English (en\_US) describing functionality, setup, and usage examples > [card] Localization > > Create additional README files like `readme/README_zh_Hans.md` for other languages Add a privacy policy (PRIVACY.md) if publishing your plugin Include comprehensive examples in documentation Test thoroughly with various document sizes and formats # Multimodal Tool Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/develop-multimodal-data-processing-tool Configure a tool plugin to emit images, audio, or video so the Knowledge Base node can embed multimodal outputs alongside text In knowledge pipelines, the Knowledge Base node supports input in two multimodal data formats: `multimodal-Parent-Child` and `multimodal-General`. For the Knowledge Base node to recognize and embed a tool plugin's multimodal output (such as text, images, audio, or video), complete two configurations: * **In the tool code file**: Call the tool session interface to upload files and construct the `files` object. * **In the tool provider YAML file**: Declare the `output_schema` as either `multimodal-Parent-Child` or `multimodal-General`. ## Upload Files and Construct File Objects When processing multimodal data such as images, first upload the file through Dify's tool session to obtain the file metadata. The following example, taken from the official **Dify Extractor** plugin, shows how to upload a file and construct a `files` object. ```python theme={null} # Upload the file using the tool session file_res = self._tool.session.file.upload( file_name, # filename file_blob, # file binary data mime_type, # MIME type, e.g., "image/png" ) # Generate a Markdown image reference using the file preview URL image_url = f"![image]({file_res.preview_url})" ``` The upload interface returns an `UploadFileResponse` object containing the file information: ```python theme={null} from enum import Enum from pydantic import BaseModel class UploadFileResponse(BaseModel): class Type(str, Enum): DOCUMENT = "document" IMAGE = "image" VIDEO = "video" AUDIO = "audio" @classmethod def from_mime_type(cls, mime_type: str): if mime_type.startswith("image/"): return cls.IMAGE if mime_type.startswith("video/"): return cls.VIDEO if mime_type.startswith("audio/"): return cls.AUDIO return cls.DOCUMENT id: str name: str size: int extension: str mime_type: str type: Type | None = None preview_url: str | None = None ``` Map the file information (`name`, `size`, `extension`, `mime_type`, and so on) to the `files` field in the multimodal output structure. ```json multimodal_parent_child_structure highlight={22-62} expandable theme={null} { "$id": "https://dify.ai/schemas/v1/multimodal_parent_child_structure.json", "$schema": "http://json-schema.org/draft-07/schema#", "version": "1.0.0", "type": "object", "title": "Multimodal Parent-Child Structure", "description": "Schema for multimodal parent-child structure (v1)", "properties": { "parent_mode": { "type": "string", "description": "The mode of parent-child relationship" }, "parent_child_chunks": { "type": "array", "items": { "type": "object", "properties": { "parent_content": { "type": "string", "description": "The parent content" }, "files": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string", "description": "file name" }, "size": { "type": "number", "description": "file size" }, "extension": { "type": "string", "description": "file extension" }, "type": { "type": "string", "description": "file type" }, "mime_type": { "type": "string", "description": "file mime type" }, "transfer_method": { "type": "string", "description": "file transfer method" }, "url": { "type": "string", "description": "file url" }, "related_id": { "type": "string", "description": "file related id" } }, "required": ["name", "size", "extension", "type", "mime_type", "transfer_method", "url", "related_id"] }, "description": "List of files" }, "child_contents": { "type": "array", "items": { "type": "string" }, "description": "List of child contents" } }, "required": ["parent_content", "child_contents"] }, "description": "List of parent-child chunk pairs" } }, "required": ["parent_mode", "parent_child_chunks"] } ``` ```json multimodal_general_structure highlight={18-56} expandable theme={null} { "$id": "https://dify.ai/schemas/v1/multimodal_general_structure.json", "$schema": "http://json-schema.org/draft-07/schema#", "version": "1.0.0", "type": "array", "title": "Multimodal General Structure", "description": "Schema for multimodal general structure (v1) - array of objects", "properties": { "general_chunks": { "type": "array", "items": { "type": "object", "properties": { "content": { "type": "string", "description": "The content" }, "files": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string", "description": "file name" }, "size": { "type": "number", "description": "file size" }, "extension": { "type": "string", "description": "file extension" }, "type": { "type": "string", "description": "file type" }, "mime_type": { "type": "string", "description": "file mime type" }, "transfer_method": { "type": "string", "description": "file transfer method" }, "url": { "type": "string", "description": "file url" }, "related_id": { "type": "string", "description": "file related id" } }, "description": "List of files" } } }, "required": ["content"] }, "description": "List of content and files" } } } ``` ## Declare Multimodal Output Structure Dify's official JSON schemas define the structure of multimodal data. To let the Knowledge Base node recognize the plugin's multimodal output type, point the `result` field under `output_schema` in the plugin's provider YAML file to the corresponding official schema URL. ```yaml theme={null} output_schema: type: object properties: result: # multimodal-Parent-Child $ref: "https://dify.ai/schemas/v1/multimodal_parent_child_structure.json" # multimodal-General # $ref: "https://dify.ai/schemas/v1/multimodal_general_structure.json" ``` For example, a complete YAML configuration using `multimodal-Parent-Child` looks like this: ```yaml expandable theme={null} identity: name: multimodal_tool author: langgenius label: en_US: multimodal tool zh_Hans: 多模态提取器 pt_BR: multimodal tool description: human: en_US: Process documents into multimodal-Parent-Child chunk structures zh_Hans: 将文档处理为多模态父子分块结构 pt_BR: Processar documentos em estruturas de divisão pai-filho llm: Processes documents into hierarchical multimodal-Parent-Child chunk structures parameters: - name: input_text human_description: en_US: The text you want to chunk. zh_Hans: 输入文本 pt_BR: Conteúdo de Entrada label: en_US: Input Content zh_Hans: 输入文本 pt_BR: Conteúdo de Entrada llm_description: The text you want to chunk. required: true type: string form: llm output_schema: type: object properties: result: $ref: "https://dify.ai/schemas/v1/multimodal_parent_child_structure.json" extra: python: source: tools/parent_child_chunk.py ``` # Endpoint Plugin Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/endpoint Define, configure, and implement HTTP Endpoints in a Dify plugin, using the Neko Cat project as an example Endpoints are HTTP interfaces exposed by a plugin for integration with external systems. This guide explains their structure using the [Neko Cat](https://github.com/langgenius/dify-plugin-sdks/tree/739b16ebd300e0b0c5e8c977f70d9c43094b1af7/python/examples/neko) project as an example. > [!NOTE] > > The example was removed from the SDK repository, so the link opens the last revision that carried it. For maintained plugin samples, see the [official plugin examples](https://github.com/langgenius/dify-official-plugins). ## Group Definition An Endpoint group is a collection of multiple Endpoints. When you create a new Endpoint in a Dify plugin, you may need to fill in the following configuration. ![Endpoint Group Configuration Form](https://assets-docs.dify.ai/2024/11/763dbf86e4319591415dc5a1b6948ccb.png) Besides the **Endpoint Name**, you can add form items by writing the group's configuration. After saving, you can see the multiple interfaces the group contains, all sharing the same configuration. ![Endpoint Group Interface List](https://assets-docs.dify.ai/2024/11/b778b7093b7df0dc80a476c65ddcbe58.png) ### Structure * **`settings`** (map\[string] [ProviderConfig](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications#providerconfig)): Endpoint configuration definition. * **`endpoints`** (list\[string], required): Points to the specific `endpoint` interface definitions. ```yaml theme={null} settings: api_key: type: secret-input required: true label: en_US: API key zh_Hans: API key ja_Jp: API key pt_BR: API key placeholder: en_US: Please input your API key zh_Hans: 请输入你的 API key ja_Jp: あなたの API key を入れてください pt_BR: Por favor, insira sua chave API endpoints: - endpoints/duck.yaml - endpoints/neko.yaml ``` ## Interface Definition * **`path`** (string): Follows the Werkzeug interface standard. * **`method`** (string): Interface method; supports only `HEAD`, `GET`, `POST`, `PUT`, `DELETE`, and `OPTIONS`. * **`extra`** (object): Configuration information beyond the basic details. * **`python`** (object) * **`source`** (string): The source code that implements this interface. ```yaml theme={null} path: "/duck/" method: "GET" extra: python: source: "endpoints/duck.py" ``` ## Interface Implementation Implement a subclass of `dify_plugin.Endpoint` and its `_invoke` method. * **Input parameters** * **`r`** (Request): The `Request` object from `werkzeug`. * **`values`** (Mapping): Path parameters parsed from the path. * **`settings`** (Mapping): Configuration information for this Endpoint. * **Return** * A `Response` object from `werkzeug`; streaming responses are supported. * Returning a string directly is not supported. Example code: ```python theme={null} import json from typing import Mapping from werkzeug import Request, Response from dify_plugin import Endpoint class Duck(Endpoint): def _invoke(self, r: Request, values: Mapping, settings: Mapping) -> Response: """ Invokes the endpoint with the given request. """ app_id = values["app_id"] def generator(): yield f"{app_id}
" return Response(generator(), status=200, content_type="text/html") ``` ## Notes * Endpoints are only instantiated when the plugin is called; they are not long-running services. * Pay attention to security when developing Endpoints, and avoid executing dangerous operations. * Endpoints can handle webhook callbacks or provide interfaces for other systems to connect to. If you're new to plugin development, start with [Getting Started with Plugin Development](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin) and the [Developer Cheatsheet](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/cheatsheet). ## Related Resources * [Basic Concepts of Plugin Development](/en/3.13.x/develop/plugins/getting-started/getting-started-dify-plugin): The overall architecture of plugin development. * [Neko Cat Example](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/endpoint): An example of extension plugin development. * [General Specifications Definition](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications): Common structures like ProviderConfig. * [Develop a Slack Bot Plugin Example](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/develop-a-slack-bot-plugin): Another plugin development example. * [Getting Started with Plugin Development](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin): Develop a plugin from scratch. * [Reverse Invocation of Dify Services](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-app): Use the reverse invocation feature. # Tool OAuth Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-oauth Replace manual API-key entry with an OAuth authorization flow so users grant access to third-party services with one click ![OAuth Authorize Example](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/oauth-authorize-example.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=22dd6606b5c9b9ba72b9d51c014bf5dd) This guide teaches you how to build [OAuth](https://oauth.net/2/) support into your tool plugin. OAuth is a better way to authorize tool plugins that need to access user data from third-party services, like Gmail or GitHub. Instead of requiring the user to manually enter API keys, OAuth lets the tool act on behalf of the user with their explicit consent. ## Background OAuth in Dify involves **two separate flows** that developers should understand and design for. ```mermaid theme={null} sequenceDiagram autonumber participant Admin as Admin / Developer participant Service as Third-party Service participant Dify participant User rect rgb(235, 245, 255) Note over Admin,Dify: Flow 1: One-time OAuth client setup Admin->>Service: Register OAuth app Service-->>Admin: client_id + client_secret Admin->>Dify: Configure plugin OAuth client end rect rgb(245, 255, 235) Note over User,Service: Flow 2: Per-user authorization User->>Dify: Click "Authorize" Dify->>Service: Redirect to consent screen User->>Service: Approve Service-->>Dify: Authorization code Dify->>Service: Exchange for access token Service-->>Dify: Access + refresh tokens Dify-->>User: Tool ready to use end ``` ### Flow 1: OAuth Client Setup (Admin / Developer Flow) > [!NOTE] > > On Dify Cloud, the Dify team creates OAuth apps for popular tool plugins and sets up OAuth clients, so users don't need to configure this themselves. > > Admins of self-hosted Dify instances must go through this setup flow. Admins or developers of a Dify instance first register an OAuth app with the third-party service as a trusted application. This provides the credentials needed to configure the Dify tool provider as an OAuth client. As an example, here are the steps to set up an OAuth client for Dify's Gmail tool provider: > [accordion] Create a Google Cloud Project > > 1. Go to [Google Cloud Console](https://console.cloud.google.com) and create a new project, or select an existing one. > 2. Enable the required APIs (e.g., Gmail API). > [accordion] Configure the OAuth Consent Screen > > 1. Navigate to **APIs & Services** > **OAuth consent screen**. > 2. Choose the **External** user type for public plugins. > 3. Fill in the application name, user support email, and developer contact. > 4. Add authorized domains if needed. > 5. For testing, add test users in the **Test users** section. > [accordion] Create OAuth 2.0 Credentials > > 1. Go to **APIs & Services** > **Credentials**. > 2. Click **Create Credentials** > **OAuth 2.0 Client IDs**. > 3. Choose the **Web application** type. > 4. A `client_id` and a `client_secret` will be generated. Save these as the credentials. > [accordion] Enter Credentials in Dify > > Enter the `client_id` and `client_secret` in the OAuth Client configuration popup to set up the tool provider as a client. > > ![OAuth Client Settings Dialog](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/oauth-client-settings-dialog.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=ec6bfed094b4dc8c0e379528ecaad809) > [accordion] Authorize Redirect URI > > Register the redirect URI generated by Dify on the Google OAuth Client's page: > > ![OAuth Google Redirect URI](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/oauth-google-redirect-uri.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=c8ae5860f74fe7f5b1a7a5240a6bc861) > > > [!NOTE] > > > > Dify displays the `redirect_uri` in the OAuth Client configuration popup. It usually follows the format: > > > > ```bash theme={null} > > https://{your-dify-domain}/console/api/oauth/plugin/{plugin-id}/{provider-name}/{tool-name}/callback > > ``` > > > > For self-hosted Dify, `your-dify-domain` should match `CONSOLE_WEB_URL`. > [!TIP] > > Each service has unique requirements, so always consult the specific OAuth documentation for the services you're integrating with. ### Flow 2: User Authorization (Dify User Flow) After configuring OAuth clients, individual Dify users can now authorize your plugin to access their personal accounts. ![OAuth User Authorization](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/oauth-user-authorization.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=75bbbea84b91b8e442abc1bd155ef25e) ## Implementation ### 1. Define OAuth Schema in Provider Manifest The `oauth_schema` section of the provider manifest tells Dify what credentials your plugin's OAuth setup needs and what the OAuth flow produces. Setting up OAuth requires two schemas: #### client\_schema Defines the input for OAuth client setup: ```yaml gmail.yaml theme={null} oauth_schema: client_schema: - name: "client_id" type: "secret-input" required: true url: "https://developers.google.com/identity/protocols/oauth2" - name: "client_secret" type: "secret-input" required: true ``` > [!NOTE] > > The `url` field links to the third-party service's help documentation, giving admins and developers a reference during setup. #### credentials\_schema Specifies what the user authorization flow produces (Dify manages these automatically): ```yaml theme={null} # also under oauth_schema credentials_schema: - name: "access_token" type: "secret-input" - name: "refresh_token" type: "secret-input" - name: "expires_at" type: "secret-input" ``` > [!NOTE] > > Include `oauth_schema` and `credentials_for_provider` together to offer both OAuth and API key authentication options. ### 2. Complete Required OAuth Methods in Tool Provider Add these imports where your `ToolProvider` is implemented: ```python theme={null} from dify_plugin.entities.oauth import ToolOAuthCredentials from dify_plugin.errors.tool import ToolProviderCredentialValidationError, ToolProviderOAuthError ``` Your `ToolProvider` class must implement these three OAuth methods (using `GmailProvider` as an example): > [!WARNING] > > Never return the `client_secret` in the credentials of `ToolOAuthCredentials`; doing so could lead to security issues. ```python _oauth_get_authorization_url expandable theme={null} def _oauth_get_authorization_url(self, redirect_uri: str, system_credentials: Mapping[str, Any]) -> str: """ Generate the authorization URL using credentials from OAuth Client Setup Flow. This URL is where users grant permissions. """ # Generate random state for CSRF protection (recommended for all OAuth flows) state = secrets.token_urlsafe(16) # Define Gmail-specific scopes - request minimal necessary permissions scope = "read:user read:data" # Replace with your required scopes # Assemble Gmail-specific payload params = { "client_id": system_credentials["client_id"], # From OAuth Client Setup "redirect_uri": redirect_uri, # Dify generates this - DON'T modify "scope": scope, "response_type": "code", # Standard OAuth authorization code flow "access_type": "offline", # Critical: gets refresh token (if supported) "prompt": "consent", # Forces reauth when scopes change (if supported) "state": state, # CSRF protection } return f"{self._AUTH_URL}?{urllib.parse.urlencode(params)}" ``` ```python _oauth_get_credentials expandable theme={null} def _oauth_get_credentials( self, redirect_uri: str, system_credentials: Mapping[str, Any], request: Request ) -> ToolOAuthCredentials: """ Exchange authorization code for access token and refresh token. This is called to create ONE credential set for one account connection. """ # Extract authorization code from OAuth callback code = request.args.get("code") if not code: raise ToolProviderOAuthError("Authorization code not provided") # Check for authorization errors from OAuth provider error = request.args.get("error") if error: error_description = request.args.get("error_description", "") raise ToolProviderOAuthError(f"OAuth authorization failed: {error} - {error_description}") # Exchange authorization code for tokens using OAuth Client Setup credentials # Assemble Gmail-specific payload data = { "client_id": system_credentials["client_id"], # From OAuth Client Setup "client_secret": system_credentials["client_secret"], # From OAuth Client Setup "code": code, # From user's authorization "grant_type": "authorization_code", # Standard OAuth flow type "redirect_uri": redirect_uri, # Must exactly match authorization URL } headers = {"Content-Type": "application/x-www-form-urlencoded"} try: response = requests.post( self._TOKEN_URL, data=data, headers=headers, timeout=10 ) response.raise_for_status() token_data = response.json() # Handle OAuth provider errors in response if "error" in token_data: error_desc = token_data.get('error_description', token_data['error']) raise ToolProviderOAuthError(f"Token exchange failed: {error_desc}") access_token = token_data.get("access_token") if not access_token: raise ToolProviderOAuthError("No access token received from provider") # Build credentials dict matching your credentials_schema credentials = { "access_token": access_token, "token_type": token_data.get("token_type", "Bearer"), } # Include refresh token if provided (critical for long-term access) refresh_token = token_data.get("refresh_token") if refresh_token: credentials["refresh_token"] = refresh_token # Handle token expiration - some providers don't provide expires_in expires_in = token_data.get("expires_in", 3600) # Default to 1 hour expires_at = int(time.time()) + expires_in return ToolOAuthCredentials(credentials=credentials, expires_at=expires_at) except requests.RequestException as e: raise ToolProviderOAuthError(f"Network error during token exchange: {str(e)}") except Exception as e: raise ToolProviderOAuthError(f"Failed to exchange authorization code: {str(e)}") ``` ```python _oauth_refresh_credentials theme={null} def _oauth_refresh_credentials( self, redirect_uri: str, system_credentials: Mapping[str, Any], credentials: Mapping[str, Any] ) -> ToolOAuthCredentials: """ Refresh the credentials using the refresh token. Dify calls this automatically when tokens expire. """ refresh_token = credentials.get("refresh_token") if not refresh_token: raise ToolProviderOAuthError("No refresh token available") # Standard OAuth refresh token flow data = { "client_id": system_credentials["client_id"], # From OAuth Client Setup "client_secret": system_credentials["client_secret"], # From OAuth Client Setup "refresh_token": refresh_token, # From previous authorization "grant_type": "refresh_token", # OAuth refresh flow } headers = {"Content-Type": "application/x-www-form-urlencoded"} try: response = requests.post( self._TOKEN_URL, data=data, headers=headers, timeout=10 ) response.raise_for_status() token_data = response.json() # Handle refresh errors if "error" in token_data: error_desc = token_data.get('error_description', token_data['error']) raise ToolProviderOAuthError(f"Token refresh failed: {error_desc}") access_token = token_data.get("access_token") if not access_token: raise ToolProviderOAuthError("No access token received from provider") # Build new credentials, preserving existing refresh token new_credentials = { "access_token": access_token, "token_type": token_data.get("token_type", "Bearer"), "refresh_token": refresh_token, # Keep existing refresh token } # Handle token expiration expires_in = token_data.get("expires_in", 3600) # update refresh token if new one provided new_refresh_token = token_data.get("refresh_token") if new_refresh_token: new_credentials["refresh_token"] = new_refresh_token # Calculate new expiration timestamp for Dify's token management expires_at = int(time.time()) + expires_in return ToolOAuthCredentials(credentials=new_credentials, expires_at=expires_at) except requests.RequestException as e: raise ToolProviderOAuthError(f"Network error during token refresh: {str(e)}") except Exception as e: raise ToolProviderOAuthError(f"Failed to refresh credentials: {str(e)}") ``` ### 3. Access Tokens in Your Tools Use OAuth credentials to make authenticated API calls in your `Tool` implementation: ```python theme={null} class YourTool(BuiltinTool): def _invoke(self, user_id: str, tool_parameters: dict[str, Any]) -> ToolInvokeMessage: if self.runtime.credential_type == CredentialType.OAUTH: access_token = self.runtime.credentials["access_token"] response = requests.get("https://api.service.com/data", headers={"Authorization": f"Bearer {access_token}"}) return self.create_text_message(response.text) ``` `self.runtime.credentials` automatically provides the current user's tokens. Dify handles refresh automatically. For plugins that support both OAuth and `API_KEY` authentication, use `self.runtime.credential_type` to differentiate between the two authentication types. ### 4. Specify the Correct Versions OAuth requires a recent SDK and Dify version. Pin the plugin SDK in `requirements.txt`: ```text theme={null} dify_plugin>=0.5.0 ``` In `manifest.yaml`, add the minimum Dify version: ```yaml theme={null} meta: version: 0.0.1 arch: - amd64 - arm64 runner: language: python version: "3.12" entrypoint: main minimum_dify_version: 1.7.1 ``` # Tool Plugin Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin Develop a Dify tool plugin from initialization to packaging, using Google Search as a worked example Tools are third-party services that Chatflow, Workflow, and Agent applications can call. They extend Dify applications with capabilities such as online search and image generation. ![Tool Plugin Example](https://assets-docs.dify.ai/2024/12/7e7bcf1f9e3acf72c6917ea9de4e4613.png) In this guide, a *tool plugin* is a complete project that includes tool provider files, functional code, and supporting structures. A tool provider can bundle multiple tools, each offering a distinct capability: ```text theme={null} - Tool Provider - Tool A - Tool B ``` ![Tool Plugin Structure](https://assets-docs.dify.ai/2025/02/60c4c86a317d865133aa460592eac079.png) This guide uses Google Search as an example to walk through tool plugin development. ## Prerequisites * Dify plugin scaffolding tool * Python environment (version 3.12) To set up the scaffolding tool, see [Initializing Development Tools](/en/3.13.x/develop/plugins/getting-started/cli). ## Create a New Project Run the scaffolding command line tool to create a new Dify plugin project. ```bash theme={null} ./dify-plugin-darwin-arm64 plugin init ``` If you have renamed the binary file to `dify` and copied it to the `/usr/local/bin` path, you can run the following command to create a new plugin project: ```bash theme={null} dify plugin init ``` > [!NOTE] > > The following examples use `dify` as the command. If you run into issues, replace `dify` with the path to your command-line tool. ## Choose Plugin Type and Template Each template in the scaffolding tool is a complete code project. For this example, select the `Tool` plugin. > [!TIP] > > If you are already familiar with plugin development and don't need a template, see the [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) guide to build any plugin type. ![Plugin Type: Tool](https://assets-docs.dify.ai/2024/12/dd3c0f9a66454e15868eabced7b74fd6.png) ### Configure Plugin Permissions The plugin also needs permissions to read from the Dify platform. Grant this example plugin the following permissions: * Tools * Apps * Enable persistent storage, with the default storage size * Allow registering Endpoints > [!TIP] > > In the terminal, use the arrow keys to select permissions and the Tab key to grant them. After checking all permission items, press Enter to complete the plugin creation. The system generates the plugin project code automatically. ![Plugin Permissions](https://assets-docs.dify.ai/2024/12/9cf92c2e74dce55e6e9e331d031e5a9f.png) ## Develop the Tool Plugin ### 1. Create the Tool Provider File The tool provider file is a YAML file that serves as the plugin's base configuration, supplying the authorization information the tool needs. In the plugin template project, go to the `/provider` directory and rename the YAML file to `google.yaml`. This file describes the tool provider: name, icon, author, and other details shown when the plugin is installed. Example code: ```yaml theme={null} identity: # Basic information about the tool provider author: Your-name # Author name: google # Unique name; must not duplicate another provider's name label: # Label shown in the frontend en_US: Google # English label zh_Hans: Google # Chinese label description: # Description shown in the frontend en_US: Google # English description zh_Hans: Google # Chinese description icon: icon.svg # Tool icon; must be placed in the _assets folder tags: # Tags shown in the frontend - search ``` Make sure the file path is in the `/tools` directory, with the complete path as follows: ```yaml theme={null} plugins: tools: - 'google.yaml' ``` `google.yaml` must be referenced by its absolute path within the plugin project; in this example, it sits in the project root directory. In the YAML file, `identity` holds the tool provider's basic information: author, name, label, description, and icon. * The icon must be an attachment resource placed in the `_assets` folder in the project root directory. * Tags help users find plugins by category. These are all the currently supported tags: ```python theme={null} class ToolLabelEnum(Enum): SEARCH = 'search' IMAGE = 'image' VIDEOS = 'videos' WEATHER = 'weather' FINANCE = 'finance' DESIGN = 'design' TRAVEL = 'travel' SOCIAL = 'social' NEWS = 'news' MEDICAL = 'medical' PRODUCTIVITY = 'productivity' EDUCATION = 'education' BUSINESS = 'business' ENTERTAINMENT = 'entertainment' UTILITIES = 'utilities' OTHER = 'other' ``` ### 2. Add Third-Party Service Credentials For convenience, this example uses the Google Search API provided by the third-party service SerpApi. SerpApi requires an API key, so add a `credentials_for_provider` field to the YAML file. The complete code: ```yaml theme={null} identity: author: Dify name: google label: en_US: Google zh_Hans: Google pt_BR: Google description: en_US: Google zh_Hans: GoogleSearch pt_BR: Google icon: icon.svg tags: - search credentials_for_provider: # Add the credentials_for_provider field serpapi_api_key: type: secret-input required: true label: en_US: SerpApi API key zh_Hans: SerpApi API key placeholder: en_US: Please input your SerpApi API key zh_Hans: Please enter your SerpApi API key help: en_US: Get your SerpApi API key from SerpApi zh_Hans: Get your SerpApi API key from SerpApi url: https://serpapi.com/manage-api-key tools: - tools/google_search.yaml extra: python: source: google.py ``` * The sub-level structure of `credentials_for_provider` must meet the requirements in [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications). * Specify which tools the provider includes. This example includes only one file, `tools/google_search.yaml`. * Besides its basic information, a provider needs code logic, so specify its implementation file. This example uses `google.py`, but leave it unimplemented for now and write the `google_search` tool code first. ### 3. Fill in the Tool YAML File A tool plugin can contain multiple tools, each described by its own YAML file covering basic information, parameters, and output. Continuing with the `GoogleSearch` tool, create a new `google_search.yaml` file in the `/tools` folder. ```yaml theme={null} identity: name: google_search author: Dify label: en_US: GoogleSearch zh_Hans: Google Search pt_BR: GoogleSearch description: human: en_US: A tool for performing a Google SERP search and extracting snippets and webpages. Input should be a search query. zh_Hans: A tool for performing a Google SERP search and extracting snippets and webpages. Input should be a search query. pt_BR: A tool for performing a Google SERP search and extracting snippets and webpages. Input should be a search query. llm: A tool for performing a Google SERP search and extracting snippets and webpages. Input should be a search query. parameters: - name: query type: string required: true label: en_US: Query string zh_Hans: Query string pt_BR: Query string human_description: en_US: used for searching zh_Hans: used for searching web content pt_BR: used for searching llm_description: key words for searching form: llm extra: python: source: tools/google_search.py ``` * **`identity`**: Basic information about the tool, including name, author, label, and description. * **`parameters`**: The parameter list. * **`name`** (required): Parameter name; must be unique among the tool's parameters. * **`type`** (required): Parameter type. One of `string`, `number`, `boolean`, `select`, or `secret-input`, rendered as a string, number, boolean, dropdown, or encrypted input box. Use `secret-input` for sensitive information. * **`label`** (required): Parameter label, shown in the frontend. * **`form`** (required): Form type, either `llm` or `form`. * In Agent applications, `llm` means the LLM infers the parameter itself, while `form` means the parameter can be preset before using the tool. * In Workflow applications, both `llm` and `form` parameters are filled in via the frontend, but `llm` parameters are used as input variables for the tool node. * **`required`** (optional): Whether the parameter is required. * In `llm` mode, a required parameter must be inferred by the Agent. * In `form` mode, a required parameter must be filled in on the frontend before the conversation begins. * **`options`** (optional): Parameter options. * In `llm` mode, Dify passes all options to the LLM, which can infer based on them. * In `form` mode, the frontend displays the options when `type` is `select`. * **`default`** (optional): Default value. * **`min`** (optional): Minimum value; applies when the parameter type is `number`. * **`max`** (optional): Maximum value; applies when the parameter type is `number`. * **`human_description`** (optional): Description shown in the frontend; supports multiple languages. * **`placeholder`** (optional): Hint text for the input field; applies when the form type is `form` and the parameter type is `string`, `number`, or `secret-input`. Supports multiple languages. * **`llm_description`** (optional): Description passed to the LLM. Write it in as much detail as possible so the LLM understands the parameter. ### 4. Write the Tool Code With the tool configuration in place, write the code that implements the tool's logic. Create `google_search.py` in the `/tools` directory with the following content: ```python theme={null} from collections.abc import Generator from typing import Any import requests from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage SERP_API_URL = "https://serpapi.com/search" class GoogleSearchTool(Tool): def _parse_response(self, response: dict) -> dict: result = {} if "knowledge_graph" in response: result["title"] = response["knowledge_graph"].get("title", "") result["description"] = response["knowledge_graph"].get("description", "") if "organic_results" in response: result["organic_results"] = [ { "title": item.get("title", ""), "link": item.get("link", ""), "snippet": item.get("snippet", ""), } for item in response["organic_results"] ] return result def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]: params = { "api_key": self.runtime.credentials["serpapi_api_key"], "q": tool_parameters["query"], "engine": "google", "google_domain": "google.com", "gl": "us", "hl": "en", } response = requests.get(url=SERP_API_URL, params=params, timeout=5) response.raise_for_status() valuable_res = self._parse_response(response.json()) yield self.create_json_message(valuable_res) ``` This code sends a request to `serpapi` and uses `self.create_json_message` to return formatted JSON data. To learn more about return data types, see [Remote Debugging Plugins](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin) and [Persistent Storage KV](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/persistent-storage-kv). ### 5. Complete the Tool Provider Code Finally, implement the provider's credential validation logic. If validation fails, the code raises a `ToolProviderCredentialValidationError` exception; once validation succeeds, the `google_search` tool service is requested correctly. Create a `google.py` file in the `/provider` directory with the following content: ```python theme={null} from typing import Any from dify_plugin import ToolProvider from dify_plugin.errors.tool import ToolProviderCredentialValidationError from tools.google_search import GoogleSearchTool class GoogleProvider(ToolProvider): def _validate_credentials(self, credentials: dict[str, Any]) -> None: try: for _ in GoogleSearchTool.from_credentials(credentials).invoke( tool_parameters={"query": "test", "result_type": "link"}, ): pass except Exception as e: raise ToolProviderCredentialValidationError(str(e)) ``` ## Debug the Plugin After development, test whether the plugin works correctly. Dify provides remote debugging so you can quickly verify the plugin's functionality in a test environment. Go to the [Plugin Management](https://cloud.dify.ai/plugins) page to get the remote server address and debug key. ![Remote Debug Key](https://assets-docs.dify.ai/2024/12/053415ef127f1f4d6dd85dd3ae79626a.png) Back in the plugin project, copy the `.env.example` file, rename it to `.env`, and fill in the remote server address and debug key. `.env` file: ```bash theme={null} INSTALL_METHOD=remote REMOTE_INSTALL_URL=debug.dify.ai:5003 REMOTE_INSTALL_KEY=********-****-****-****-************ ``` Run `python -m main` to start the plugin. On the **Plugins** page, you can see the plugin installed in the workspace, where other team members can also access it. ![Run the Python -M Main Command to Start the Plugin](https://assets-docs.dify.ai/2024/11/0fe19a8386b1234755395018bc2e0e35.png) ## Package the Plugin (Optional) Once the plugin runs correctly, package and name it with the following command. It produces a `google.difypkg` file in the current folder—the final plugin package. ```bash theme={null} # Replace ./google with the actual path of the plugin project dify plugin package ./google ``` Congratulations—you've developed, debugged, and packaged a tool plugin! ## Publish the Plugin (Optional) To publish the plugin to Dify Marketplace, make sure it meets the [Marketplace preparation and validation requirements](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace#prepare-the-package). After review, the package is merged into the main branch and released through the Marketplace pipeline. For the full process, see the [Publishing Overview](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview). ## Explore More ### Quick Start * [Developing Extension Plugins](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/endpoint) * [Developing Model Plugins](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/creating-new-model-provider) * [Bundle Plugins: Packaging Multiple Plugins](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/bundle) ### Plugin Interface Documentation * [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications): Manifest structure and tool specifications. * [Endpoint](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/endpoint): Detailed Endpoint definition. * [Reverse Invocation](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation): Reverse invocation of Dify capabilities. * [Model Schema](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/model-schema): Models. * [Agent Plugins](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation): Extending Agent strategies. ## Next Steps * [Remote Debugging Plugins](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin): Learn more advanced debugging techniques. * [Persistent Storage](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/persistent-storage-kv): Use data storage in plugins. * [Slack Bot Plugin Development Example](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/develop-a-slack-bot-plugin): A more complex plugin development case. * [Tool Plugin](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/tool): Advanced features of tool plugins. # Trigger Plugin Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/trigger-plugin Build a Dify 1.10.0+ trigger plugin that turns third-party webhook events into workflow start signals ## What Is a Trigger Plugin? Triggers were introduced in Dify v1.10.0 as a new type of start node. Unlike functional nodes such as Code, Tool, or Knowledge Retrieval, a trigger **converts third-party events into an input format that Dify can recognize and process**. ![Trigger Plugin Intro](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/trigger-plugin-intro.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=62db42a30ad484a628dbc3283675e3f3) For example, if you configure Dify as the `new email` event receiver in Gmail, Gmail automatically sends an event to Dify every time you receive a new email, and that event can trigger a workflow. However: * Gmail's original event format is not compatible with Dify's input format. * There are thousands of platforms worldwide, each with its own unique event format. Trigger plugins close this gap: they define and parse events from different platforms and unify them into an input format that Dify can accept. ## Technical Overview Dify triggers are built on webhooks, a widely adopted mechanism across the web. Mainstream SaaS platforms such as GitHub, Slack, and Linear support webhooks and document them thoroughly. A webhook is an HTTP-based event dispatcher: once you configure an event-receiving address, the platform automatically pushes event data to that address whenever a subscribed event occurs. To handle webhook events from different platforms in a unified way, Dify defines two core concepts: **Subscription** and **Event**. * **Subscription**: The configuration that registers Dify's network address as the target server in a third-party platform's developer console. * **Event**: A platform may send multiple types of events (such as *email received*, *email deleted*, or *email marked as read*), all pushed to the registered address. A trigger plugin can handle multiple event types, and each event corresponds to an Integration Trigger node in a Dify workflow. ## Plugin Development Developing a trigger plugin follows the same process as other plugin types (Tool, Data Source, Model, and so on). Create a development template with the `dify plugin init` command. The generated file structure follows the standard plugin format specification. ```text theme={null} ├── _assets │   └── icon.svg ├── events │   └── star │   ├── star_created.py │   └── star_created.yaml ├── main.py ├── manifest.yaml ├── provider │   ├── github.py │   └── github.yaml ├── README.md ├── PRIVACY.md └── requirements.txt ``` * `manifest.yaml`: Describes the plugin's basic metadata. * `provider` directory: Contains the provider's metadata, the code for creating subscriptions, and the code for classifying events after receiving webhook requests. * `events` directory: Contains the code for event handling and filtering, which supports local event filtering at the node level. You can create subdirectories to group related events. > [!NOTE] > > For trigger plugins, set the minimum required Dify version to `1.10.0` and the SDK version to `>= 0.6.0`. The following sections use GitHub as an example to walk through the development process. ### Create a Subscription Webhook configuration methods vary significantly across mainstream SaaS platforms: * Some platforms (such as GitHub) support API-based webhook configuration. For these platforms, once OAuth authentication is completed, Dify can automatically set up the webhook. * Other platforms (such as Notion) do not provide a webhook configuration API and may require users to perform manual authentication. To accommodate these differences, we divide the subscription process into two parts: the **Subscription Constructor** and the **Subscription** itself. For platforms like Notion, creating a subscription requires the user to manually copy the callback URL provided by Dify and paste it into their Notion workspace to complete the webhook setup. This process corresponds to the **Paste URL to create a new subscription** option in the Dify interface. ![Paste URL to Create a New Subscription](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/trigger-plugin-manual-webhook-setup.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=29246991df63fec64393f0b07f850ed5) To support subscription creation via manual URL pasting, modify two files: `github.yaml` and `github.py`. > [tab] github.yaml > > GitHub webhooks use an encryption mechanism, so a secret key is required to decrypt and validate incoming requests. Declare `webhook_secret` in `github.yaml`. > > ```yaml theme={null} > subscription_schema: > - name: "webhook_secret" > type: "secret-input" > required: false > label: > zh_Hans: "Webhook Secret" > en_US: "Webhook Secret" > ja_JP: "Webhookシークレット" > help: > en_US: "Optional webhook secret for validating GitHub webhook requests" > ja_JP: "GitHub Webhookリクエストの検証用のオプションのWebhookシークレット" > zh_Hans: "可选的用于验证 GitHub webhook 请求的 webhook 密钥" > ``` > [tab] github.py > > First, implement the `dispatch_event` interface. All requests sent to the callback URL are processed by this interface, and the processed events appear in the **Request Logs** section for debugging and verification. > > ![Manual Setup](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/trigger-plugin-manual-webhook-setup-config.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=f9a0334bbecd3a1b7b5cba40860c36e0) > > In the code, you can retrieve the `webhook_secret` declared in `github.yaml` via `subscription.properties`. > > The `dispatch_event` method determines the event type from the request content. In the example below, the `_dispatch_trigger_event` method handles this extraction. > > > [!TIP] > > > > For the complete code sample, see [Dify's GitHub trigger plugin](https://github.com/langgenius/dify-official-plugins/tree/main/triggers/github_trigger). > > ```python theme={null} > class GithubTrigger(Trigger): > """Handle GitHub webhook event dispatch.""" > > def _dispatch_event(self, subscription: Subscription, request: Request) -> EventDispatch: > webhook_secret = subscription.properties.get("webhook_secret") > if webhook_secret: > self._validate_signature(request=request, webhook_secret=webhook_secret) > > event_type: str | None = request.headers.get("X-GitHub-Event") > if not event_type: > raise TriggerDispatchError("Missing GitHub event type header") > > payload: Mapping[str, Any] = self._validate_payload(request) > response = Response(response='{"status": "ok"}', status=200, mimetype="application/json") > event: str = self._dispatch_trigger_event(event_type=event_type, payload=payload) > return EventDispatch(events=[event] if event else [], response=response) > ``` ### Handle Events Once an event is extracted, the corresponding implementation must filter the original HTTP request and transform it into an input format that Dify workflows can accept. Taking the Issue event as an example, define the event in `events/issues/issues.yaml` and its implementation in `events/issues/issues.py`. Define the event's output in the `output_schema` section of `issues.yaml`, which follows the same JSON Schema specification as tool plugins. > [tab] issues.yaml > > ```yaml theme={null} > identity: > name: issues > author: langgenius > label: > en_US: Issues > zh_Hans: 议题 > ja_JP: イシュー > description: > en_US: Unified issues event with actions filter > zh_Hans: 带 actions 过滤的统一 issues 事件 > ja_JP: アクションフィルタ付きの統合イシューイベント > output_schema: > type: object > properties: > action: > type: string > issue: > type: object > description: The issue itself > extra: > python: > source: events/issues/issues.py > ``` > [tab] issues.py > > ```python theme={null} > from collections.abc import Mapping > from typing import Any > > from werkzeug import Request > > from dify_plugin.entities.trigger import Variables > from dify_plugin.errors.trigger import EventIgnoreError > from dify_plugin.interfaces.trigger import Event > > class IssuesUnifiedEvent(Event): > """Unified Issues event. Filters by actions and common issue attributes.""" > > def _on_event(self, request: Request, parameters: Mapping[str, Any], payload: Mapping[str, Any]) -> Variables: > payload = request.get_json() > if not payload: > raise ValueError("No payload received") > > allowed_actions = parameters.get("actions") or [] > action = payload.get("action") > if allowed_actions and action not in allowed_actions: > raise EventIgnoreError() > > issue = payload.get("issue") > if not isinstance(issue, Mapping): > raise ValueError("No issue in payload") > > return Variables(variables={**payload}) > ``` ### Filter Events To filter out certain events (for example, to focus only on Issue events with a specific label), add `parameters` to the event definition in `issues.yaml`. Then, in the `_on_event` method, raise an `EventIgnoreError` exception for events that don't meet the configured criteria. > [tab] issues.yaml > > ```yaml theme={null} > parameters: > - name: added_label > label: > en_US: Added Label > zh_Hans: 添加的标签 > ja_JP: 追加されたラベル > type: string > required: false > description: > en_US: "Only trigger if these specific labels were added (e.g., critical, priority-high, security, comma-separated). Leave empty to trigger for any label addition." > zh_Hans: "仅当添加了这些特定标签时触发(例如:critical, priority-high, security,逗号分隔)。留空则对任何标签添加触发。" > ja_JP: "これらの特定のラベルが追加された場合のみトリガー(例: critical, priority-high, security,カンマ区切り)。空の場合は任意のラベル追加でトリガー。" > ``` > [tab] issues.py > > ```python theme={null} > def _check_added_label(self, payload: Mapping[str, Any], added_label_param: str | None) -> None: > """Check if the added label matches the allowed labels""" > if not added_label_param: > return > > allowed_labels = [label.strip() for label in added_label_param.split(",") if label.strip()] > if not allowed_labels: > return > > # The payload contains the label that was added > label = payload.get("label", {}) > label_name = label.get("name", "") > > if label_name not in allowed_labels: > raise EventIgnoreError() > > def _on_event(self, request: Request, parameters: Mapping[str, Any], payload: Mapping[str, Any]) -> Variables: > # ... > # Apply all filters > self._check_added_label(payload, parameters.get("added_label")) > > return Variables(variables={**payload}) > ``` ### Create Subscriptions via OAuth or API Key To enable automatic subscription creation via OAuth or API key, modify the `github.yaml` and `github.py` files. > [tab] github.yaml > > In `github.yaml`, add the following fields. > > ```yaml theme={null} > subscription_constructor: > parameters: > - name: "repository" > label: > en_US: "Repository" > zh_Hans: "仓库" > ja_JP: "リポジトリ" > type: "dynamic-select" > required: true > placeholder: > en_US: "owner/repo" > zh_Hans: "owner/repo" > ja_JP: "owner/repo" > help: > en_US: "GitHub repository in format owner/repo (e.g., microsoft/vscode)" > zh_Hans: "GitHub 仓库,格式为 owner/repo(例如:microsoft/vscode)" > ja_JP: "GitHubリポジトリは owner/repo 形式で入力してください(例: microsoft/vscode)" > credentials_schema: > access_tokens: > help: > en_US: Get your Access Tokens from GitHub > ja_JP: GitHub からアクセストークンを取得してください > zh_Hans: 从 GitHub 获取您的 Access Tokens > label: > en_US: Access Tokens > ja_JP: アクセストークン > zh_Hans: Access Tokens > placeholder: > en_US: Please input your GitHub Access Tokens > ja_JP: GitHub のアクセストークンを入力してください > zh_Hans: 请输入你的 GitHub Access Tokens > required: true > type: secret-input > url: https://github.com/settings/tokens?type=beta > extra: > python: > source: provider/github.py > ``` > > `subscription_constructor` is a concept abstracted by Dify to define how a subscription is constructed. It includes the following fields: > > * `parameters` (optional): Defines the parameters required to create a subscription, such as the event types to subscribe to or the target GitHub repository. > * `credentials_schema` (optional): Declares the credentials required to create a subscription with an API key or access token, such as `access_tokens` for GitHub. > * `oauth_schema` (optional): Required for subscription creation via OAuth. For details on how to define it, see [Add OAuth Support to Your Tool Plugin](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-oauth). > [tab] github.py > > In `github.py`, create a `Constructor` class to implement the automatic subscription logic. > > ```python theme={null} > class GithubSubscriptionConstructor(TriggerSubscriptionConstructor): > """Manage GitHub trigger subscriptions.""" > def _validate_api_key(self, credentials: Mapping[str, Any]) -> None: > # ... > > def _create_subscription( > self, > endpoint: str, > parameters: Mapping[str, Any], > credentials: Mapping[str, Any], > credential_type: CredentialType, > ) -> Subscription: > repository = parameters.get("repository") > if not repository: > raise ValueError("repository is required (format: owner/repo)") > > try: > owner, repo = repository.split("/") > except ValueError: > raise ValueError("repository must be in format 'owner/repo'") from None > > events: list[str] = parameters.get("events", []) > webhook_secret = uuid.uuid4().hex > url = f"https://api.github.com/repos/{owner}/{repo}/hooks" > headers = { > "Authorization": f"Bearer {credentials.get('access_tokens')}", > "Accept": "application/vnd.github+json", > } > > webhook_data = { > "name": "web", > "active": True, > "events": events, > "config": {"url": endpoint, "content_type": "json", "insecure_ssl": "0", "secret": webhook_secret}, > } > > try: > response = requests.post(url, json=webhook_data, headers=headers, timeout=10) > except requests.RequestException as exc: > raise SubscriptionError(f"Network error while creating webhook: {exc}", error_code="NETWORK_ERROR") from exc > > if response.status_code == 201: > webhook = response.json() > return Subscription( > expires_at=int(time.time()) + self._WEBHOOK_TTL, > endpoint=endpoint, > parameters=parameters, > properties={ > "external_id": str(webhook["id"]), > "repository": repository, > "events": events, > "webhook_secret": webhook_secret, > "active": webhook.get("active", True), > }, > ) > > response_data: dict[str, Any] = response.json() if response.content else {} > error_msg = response_data.get("message", "Unknown error") > error_details = response_data.get("errors", []) > detailed_error = f"Failed to create GitHub webhook: {error_msg}" > if error_details: > detailed_error += f" Details: {error_details}" > > raise SubscriptionError( > detailed_error, > error_code="WEBHOOK_CREATION_FAILED", > external_response=response_data, > ) > ``` *** Once you have modified these two files, you'll see the **Create with API Key** option in the Dify interface. The same `Constructor` class also supports automatic subscription creation via OAuth: add an `oauth_schema` field under `subscription_constructor` to enable OAuth authentication. ![OAuth & API Key Options](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/dev-guide/trigger-plugin-oauth-apikey.png?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=d2473bde9716f214a9b9127e8de94e19) ## Explore More The interface definitions for the core classes in trigger plugin development are as follows. ### Trigger ```python theme={null} class Trigger(ABC): @abstractmethod def _dispatch_event(self, subscription: Subscription, request: Request) -> EventDispatch: """ Internal method to implement event dispatch logic. Subclasses must override this method to handle incoming webhook events. Implementation checklist: 1. Validate the webhook request: - Check the signature/HMAC using the properties stored in subscription.properties when the subscription was created - Verify the request is from the expected source 2. Extract event information: - Parse event type from headers or body - Extract relevant payload data 3. Return EventDispatch with: - events: List of Event names to invoke (can be single or multiple) - response: Appropriate HTTP response for the webhook Args: subscription: The Subscription object with endpoint and properties fields request: Incoming webhook HTTP request Returns: EventDispatch: Event dispatch routing information Raises: TriggerValidationError: For security validation failures TriggerDispatchError: For parsing or routing errors """ raise NotImplementedError("This plugin should implement `_dispatch_event` method to enable event dispatch") ``` ### TriggerSubscriptionConstructor ```python theme={null} class TriggerSubscriptionConstructor(ABC, OAuthProviderProtocol): # OPTIONAL def _validate_api_key(self, credentials: Mapping[str, Any]) -> None: raise NotImplementedError( "This plugin should implement `_validate_api_key` method to enable credentials validation" ) # OPTIONAL def _oauth_get_authorization_url(self, redirect_uri: str, system_credentials: Mapping[str, Any]) -> str: raise NotImplementedError( "The trigger you are using does not support OAuth, please implement `_oauth_get_authorization_url` method" ) # OPTIONAL def _oauth_get_credentials( self, redirect_uri: str, system_credentials: Mapping[str, Any], request: Request ) -> TriggerOAuthCredentials: raise NotImplementedError( "The trigger you are using does not support OAuth, please implement `_oauth_get_credentials` method" ) # OPTIONAL def _oauth_refresh_credentials( self, redirect_uri: str, system_credentials: Mapping[str, Any], credentials: Mapping[str, Any] ) -> OAuthCredentials: raise NotImplementedError( "The trigger you are using does not support OAuth, please implement `_oauth_refresh_credentials` method" ) @abstractmethod def _create_subscription( self, endpoint: str, parameters: Mapping[str, Any], credentials: Mapping[str, Any], credential_type: CredentialType, ) -> Subscription: """ Internal method to implement subscription logic. Subclasses must override this method to handle subscription creation. Implementation checklist: 1. Use the endpoint parameter provided by Dify 2. Register webhook with external service using their API 3. Store all necessary information in Subscription.properties for future operations (e.g., dispatch_event) 4. Return Subscription with: - expires_at: Set appropriate expiration time - endpoint: The webhook endpoint URL allocated by Dify for receiving events, same as the endpoint parameter - parameters: The parameters of the subscription - properties: All configuration and external IDs Args: endpoint: The webhook endpoint URL allocated by Dify for receiving events parameters: Subscription creation parameters credentials: Authentication credentials credential_type: The type of the credentials, e.g., "api-key", "oauth2", "unauthorized" Returns: Subscription: Subscription details with metadata for future operations Raises: SubscriptionError: For operational failures (API errors, invalid credentials) ValueError: For programming errors (missing required params) """ raise NotImplementedError( "This plugin should implement `_create_subscription` method to enable event subscription" ) @abstractmethod def _delete_subscription( self, subscription: Subscription, credentials: Mapping[str, Any], credential_type: CredentialType ) -> UnsubscribeResult: """ Internal method to implement unsubscription logic. Subclasses must override this method to handle subscription removal. Implementation guidelines: 1. Extract necessary IDs from subscription.properties (e.g., external_id) 2. Use credentials and credential_type to call external service API to delete the webhook 3. Handle common errors (not found, unauthorized, etc.) 4. Always return UnsubscribeResult with detailed status 5. Never raise exceptions for operational failures - use UnsubscribeResult.success=False Args: subscription: The Subscription object with endpoint and properties fields Returns: UnsubscribeResult: Always returns result, never raises for operational failures """ raise NotImplementedError( "This plugin should implement `_delete_subscription` method to enable event unsubscription" ) @abstractmethod def _refresh_subscription( self, subscription: Subscription, credentials: Mapping[str, Any], credential_type: CredentialType ) -> Subscription: """ Internal method to implement subscription refresh logic. Subclasses must override this method to handle simple expiration extension. Implementation patterns: 1. For webhooks without expiration (e.g., GitHub): - Update the Subscription.expires_at=-1 then Dify will never call this method again 2. For lease-based subscriptions (e.g., Microsoft Graph): - Use the information in Subscription.properties to call service's lease renewal API if available - Handle renewal limits (some services limit renewal count) - Update Subscription.properties and Subscription.expires_at for the next renewal if needed Args: subscription: Current subscription with properties credential_type: The type of the credentials, e.g., "api-key", "oauth2", "unauthorized" credentials: Current authentication credentials from credentials_schema. For API key auth, according to `credentials_schema` defined in the YAML. For OAuth auth, according to `oauth_schema.credentials_schema` defined in the YAML. For unauthorized auth, there is no credentials. Returns: Subscription: Same subscription with extended expiration or new properties and expires_at for the next renewal Raises: SubscriptionError: For operational failures (API errors, invalid credentials) """ raise NotImplementedError("This plugin should implement `_refresh` method to enable subscription refresh") # OPTIONAL def _fetch_parameter_options( self, parameter: str, credentials: Mapping[str, Any], credential_type: CredentialType ) -> list[ParameterOption]: """ Fetch the parameter options of the trigger. Implementation guidelines: When you need to fetch parameter options from an external service, use the credentials and credential_type to call the external service API, then return the options to Dify for user selection. Args: parameter: The parameter name for which to fetch options credentials: Authentication credentials for the external service credential_type: The type of credentials (e.g., "api-key", "oauth2", "unauthorized") Returns: list[ParameterOption]: A list of available options for the parameter Examples: GitHub Repositories: >>> result = provider.fetch_parameter_options(parameter="repository") >>> print(result) # [ParameterOption(label="owner/repo", value="owner/repo")] Slack Channels: >>> result = provider.fetch_parameter_options(parameter="channel") >>> print(result) ``` ### Event ```python theme={null} class Event(ABC): @abstractmethod def _on_event(self, request: Request, parameters: Mapping[str, Any], payload: Mapping[str, Any]) -> Variables: """ Transform the incoming webhook request into structured Variables. This method should: 1. Parse the webhook payload from the request 2. Apply filtering logic based on parameters 3. Extract relevant data matching the output_schema 4. Return a structured Variables object Args: request: The incoming webhook HTTP request containing the raw payload. Use request.get_json() to parse JSON body. parameters: User-configured parameters for filtering and transformation (e.g., label filters, regex patterns, threshold values). These come from the subscription configuration. payload: The decoded payload from previous step `Trigger.dispatch_event`. It will be delivered into `_on_event` method. Returns: Variables: Structured variables matching the output_schema defined in the event's YAML configuration. Raises: EventIgnoreError: When the event should be filtered out based on parameters ValueError: When the payload is invalid or missing required fields Example: >>> def _on_event(self, request, parameters): ... payload = request.get_json() ... ... # Apply filters ... if not self._matches_filters(payload, parameters): ... raise EventIgnoreError() ... ... # Transform data ... return Variables(variables={ ... "title": payload["issue"]["title"], ... "author": payload["issue"]["user"]["login"], ... "url": payload["issue"]["html_url"], ... }) """ def _fetch_parameter_options(self, parameter: str) -> list[ParameterOption]: """ Fetch the parameter options of the trigger. To be implemented by subclasses. Implementing it is optional, which is why it's not an abstract method. """ raise NotImplementedError( "This plugin should implement `_fetch_parameter_options` method to enable dynamic select parameter" ) ``` # Bundle Plugin Package Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/advanced-development/bundle Package multiple plugins into a Bundle with Marketplace, GitHub, and Package dependencies A Bundle plugin package is a collection of multiple plugins packaged together, so users can install them all in one step. Use the Dify Plugin CLI to package multiple plugins into a Bundle. Bundle dependencies come in three types: * **`Marketplace`**: Stores the plugin's ID and version. During import, Dify downloads the plugin package from the Dify Marketplace. * **`GitHub`**: Stores the GitHub repository address, release version number, and asset filename. During import, Dify downloads the plugin package from the corresponding GitHub repository. * **`Package`**: Stores the plugin package directly within the Bundle. No reference source is stored, but this can make the Bundle file larger. ## Prerequisites * Dify plugin scaffolding tool * Python environment (version 3.12) To set up the plugin development scaffolding tool, see [Initialize Development Tools](/en/3.13.x/develop/plugins/getting-started/cli). ## Create a Bundle Project In the current directory, run the scaffolding command-line tool to create a new plugin package project: ```bash theme={null} ./dify-plugin-darwin-arm64 bundle init ``` If you have renamed the binary to `dify` and copied it to `/usr/local/bin`, run: ```bash theme={null} dify bundle init ``` ### 1. Fill in Plugin Information Follow the prompts to configure the plugin name, author information, and plugin description. If you are collaborating as a team, you can also enter the organization name as the author. > [!NOTE] > > The name must be 1–128 characters long and can only contain letters, numbers, hyphens, and underscores. ![Bundle Basic Information](https://assets-docs.dify.ai/2024/12/03a1c4cdc72213f09523eb1b40832279.png) Press Enter, and the Bundle plugin project directory is created automatically. ![Bundle Plugin Project Directory](https://assets-docs.dify.ai/2024/12/356d1a8201fac3759bf01ee64e79a52b.png) ### 2. Add Dependencies #### Marketplace ```bash theme={null} dify-plugin bundle append marketplace . --marketplace_pattern=langgenius/openai:0.0.1 ``` `marketplace_pattern` is the reference to the plugin in the Marketplace, in the format `organization_name/plugin_name:version_number`. #### GitHub ```bash theme={null} dify-plugin bundle append github . --repo_pattern=langgenius/openai:0.0.1/openai.difypkg ``` `repo_pattern` is the reference to the plugin on GitHub, in the format `organization_name/repository_name:release/asset_name`. #### Package ```bash theme={null} dify-plugin bundle append package . --package_path=./openai.difypkg ``` `package_path` is the path to the plugin package. ## Package the Bundle Project Run the following command to package the Bundle plugin: ```bash theme={null} dify-plugin bundle package ./bundle ``` This creates a `bundle.difybndl` file in the current directory—the final packaged result. # Integrate Custom Models Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/advanced-development/customizable-model Integrate a custom model into Dify, using Xinference as an example A **custom model** is an LLM that you deploy or configure yourself. This guide uses [Xinference](https://inference.readthedocs.io/en/latest/) as an example to show how to integrate a custom model into your **model plugin**. By default, a custom model automatically includes two parameters, its **model type** and **model name**, so the provider YAML file needs no additional definitions. You do not need to implement `validate_provider_credential` in your provider configuration file. At runtime, Dify calls the corresponding model layer's `validate_credentials` method based on the model type and model name the user selects. ## Integrate a Custom Model Plugin Integrating a custom model takes four steps: 1. **Create a model provider file**: Identify the model types your custom model will include. 2. **Create code files by model type**: Create separate code files for each model type (e.g., `llm` or `text_embedding`). Keeping each model type in its own logical layer simplifies maintenance and future expansion. 3. **Develop the model invocation logic**: Within each model-type module, create a Python file named for that model type (for example, `llm.py`). Define a class in the file that implements the model logic, conforming to the system's model interface specifications. 4. **Debug the plugin**: Write unit and integration tests for the new provider functionality, ensuring that all components work as intended. ### 1. Create the Model Provider File In your plugin’s `/provider` directory, create a `xinference.yaml` file. The `Xinference` family of models supports **LLM**, **Text Embedding**, and **Rerank** model types, so your `xinference.yaml` must include all three. **Example**: ```yaml theme={null} provider: xinference # Identifies the provider label: # Display name; can set both en_US (English) and zh_Hans (Chinese). If zh_Hans is not set, en_US is used by default. en_US: Xorbits Inference icon_small: # Small icon; store in the _assets folder of this provider’s directory. The same multi-language logic applies as with label. en_US: icon_s_en.svg icon_large: # Large icon en_US: icon_l_en.svg help: # Help information title: en_US: How to deploy Xinference zh_Hans: 如何部署 Xinference url: en_US: https://github.com/xorbitsai/inference supported_model_types: # Model types Xinference supports: LLM/Text Embedding/Rerank - llm - text-embedding - rerank configurate_methods: # Xinference is locally deployed and does not offer predefined models. Refer to its documentation to learn which model to use. Thus, we choose a customizable-model approach. - customizable-model provider_credential_schema: credential_form_schemas: ``` Next, define the `provider_credential_schema`. Since `Xinference` supports text-generation, embeddings, and reranking models, you can configure it as follows: ```yaml theme={null} provider_credential_schema: credential_form_schemas: - variable: model_type type: select label: en_US: Model type zh_Hans: 模型类型 required: true options: - value: text-generation label: en_US: Language Model zh_Hans: 语言模型 - value: embeddings label: en_US: Text Embedding - value: reranking label: en_US: Rerank ``` Every model in Xinference requires a `model_name`: ```yaml theme={null} - variable: model_name type: text-input label: en_US: Model name zh_Hans: 模型名称 required: true placeholder: zh_Hans: 填写模型名称 en_US: Input model name ``` Because Xinference is locally deployed, users must also supply the server address (`server_url`) and model UID: ```yaml theme={null} - variable: server_url label: zh_Hans: 服务器 URL en_US: Server url type: text-input required: true placeholder: zh_Hans: 在此输入 Xinference 的服务器地址,如 https://example.com/xxx en_US: Enter the url of your Xinference, for example https://example.com/xxx - variable: model_uid label: zh_Hans: 模型 UID en_US: Model uid type: text-input required: true placeholder: zh_Hans: 在此输入你的 Model UID en_US: Enter the model uid ``` This completes the YAML configuration for your custom model provider. Next, create the code files for each model defined in the configuration. ### 2. Develop the Model Code Xinference supports `llm`, `rerank`, `speech2text`, and `tts`, so create a corresponding directory under `/models` for each type, each containing its feature code. Below is an example for an `llm` type model. Create a file named `llm.py`, then define a class such as `XinferenceAILargeLanguageModel` that extends `__base.large_language_model.LargeLanguageModel`. The class must implement the following methods. #### LLM Invocation The core method for invoking the LLM, supporting both streaming and synchronous responses: ```python theme={null} def _invoke( self, model: str, credentials: dict, prompt_messages: list[PromptMessage], model_parameters: dict, tools: Optional[list[PromptMessageTool]] = None, stop: Optional[list[str]] = None, stream: bool = True, user: Optional[str] = None ) -> Union[LLMResult, Generator]: """ Invoke the large language model. :param model: model name :param credentials: model credentials :param prompt_messages: prompt messages :param model_parameters: model parameters :param tools: tools for tool calling :param stop: stop words :param stream: determines if response is streamed :param user: unique user id :return: full response or a chunk generator """ ``` Implement streaming and synchronous responses as separate functions. Python treats any function containing `yield` as a generator that returns `Generator`, so splitting them keeps the return types clean: ```python theme={null} def _invoke(self, stream: bool, **kwargs) -> Union[LLMResult, Generator]: if stream: return self._handle_stream_response(**kwargs) return self._handle_sync_response(**kwargs) def _handle_stream_response(self, **kwargs) -> Generator: for chunk in response: yield chunk def _handle_sync_response(self, **kwargs) -> LLMResult: return LLMResult(**response) ``` #### Pre-calculate Input Tokens If your model doesn't provide a token-counting interface, return `0`: ```python theme={null} def get_num_tokens( self, model: str, credentials: dict, prompt_messages: list[PromptMessage], tools: Optional[list[PromptMessageTool]] = None ) -> int: """ Get the number of tokens for the given prompt messages. """ return 0 ``` Alternatively, you can call `self._get_num_tokens_by_gpt2(text: str)` from the `AIModel` base class, which uses a GPT-2 tokenizer. Remember this is an approximation and may not match your model exactly. #### Validate Model Credentials Similar to provider-level credential checks, but scoped to a single model: ```python theme={null} def validate_credentials(self, model: str, credentials: dict) -> None: """ Validate model credentials. """ ``` #### Dynamic Model Parameters Schema Unlike [predefined models](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/model-schema), no YAML file defines which parameters a model supports, so you must generate the parameter schema dynamically. For example, Xinference supports `max_tokens`, `temperature`, and `top_p`. Other providers (e.g., `OpenLLM`) may support parameters like `top_k` only for certain models, so the schema must adapt to each model's capabilities: ```python theme={null} def get_customizable_model_schema(self, model: str, credentials: dict) -> AIModelEntity | None: """ used to define customizable model schema """ rules = [ ParameterRule( name='temperature', type=ParameterType.FLOAT, use_template='temperature', label=I18nObject( zh_Hans='温度', en_US='Temperature' ) ), ParameterRule( name='top_p', type=ParameterType.FLOAT, use_template='top_p', label=I18nObject( zh_Hans='Top P', en_US='Top P' ) ), ParameterRule( name='max_tokens', type=ParameterType.INT, use_template='max_tokens', min=1, default=512, label=I18nObject( zh_Hans='最大生成长度', en_US='Max Tokens' ) ) ] # if model is A, add top_k to rules if model == 'A': rules.append( ParameterRule( name='top_k', type=ParameterType.INT, use_template='top_k', min=1, default=50, label=I18nObject( zh_Hans='Top K', en_US='Top K' ) ) ) # ... additional ParameterRule entries omitted for brevity ... entity = AIModelEntity( model=model, label=I18nObject( en_US=model ), fetch_from=FetchFrom.CUSTOMIZABLE_MODEL, model_type=model_type, model_properties={ ModelPropertyKey.MODE: ModelType.LLM, }, parameter_rules=rules ) return entity ``` #### Error Mapping When an error occurs during model invocation, map it to one of the runtime's `InvokeError` types so Dify can handle different errors consistently: * `InvokeConnectionError` * `InvokeServerUnavailableError` * `InvokeRateLimitError` * `InvokeAuthorizationError` * `InvokeBadRequestError` ```python theme={null} @property def _invoke_error_mapping(self) -> dict[type[InvokeError], list[type[Exception]]]: """ Map model invocation errors to unified error types. The key is the error type thrown to the caller. The value is the error type thrown by the model, which needs to be mapped to a unified Dify error for consistent handling. """ # return { # InvokeConnectionError: [requests.exceptions.ConnectionError], # ... # } ``` For more details on interface methods, see the [Model Documentation](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/model-schema). For the complete code files discussed in this guide, see the [GitHub repository](https://github.com/langgenius/dify-official-plugins/tree/main/models/xinference). ### 3. Debug the Plugin After development, test the plugin to make sure it runs correctly. For details, see: > [card] [Debug Plugin](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/cheatsheet) ### 4. Publish the Plugin To list the plugin on the Dify Marketplace, see Publish to Dify Marketplace. ## Explore More **Quick Start**: * [Develop Extension Plugin](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) * [Develop Tool Plugin](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin) * [Bundle Plugins: Package Multiple Plugins](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/bundle) **Plugins Endpoint Docs**: * [Manifest](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/plugin-info-by-manifest) Structure * [Endpoint](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/endpoint) Definitions * [Reverse-Invocation of the Dify Service](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation) * [Tools](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/tool) * [Models](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/model-schema) # Reverse Invocation of Dify Services Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation Call App, Model, Tool, and Node services in the Dify platform from your plugin Through reverse invocation, plugins can call services within the main Dify platform to extend their capabilities. ## Callable Dify Modules * **[App](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-app)**: Access data from Apps within the Dify platform. * **[Model](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-model)**: Invoke LLM capabilities within the Dify platform, including all model types and functions such as TTS and Rerank. * **[Tool](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-tool)**: Call other tool-type plugins within the Dify platform. * **[Node](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-node)**: Call nodes within a specific Chatflow/Workflow application in the Dify platform. ## Related Resources * [Develop Extension Plugins](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/endpoint) - Learn how to develop plugins that integrate with external systems * [Develop a Slack Bot Plugin](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/develop-a-slack-bot-plugin) - An example of using reverse invocation to integrate with the Slack platform * [Bundle Type Plugins](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/bundle) - Learn how to package multiple plugins that use reverse invocation * [Using Persistent Storage](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/persistent-storage-kv) - Enhance plugin capabilities through KV storage # App Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-app Call the Chat, Workflow, and Completion interfaces of Dify Apps from your plugin A plugin can reverse invoke an App within Dify to access its data, with both streaming and non-streaming calls. If you are unfamiliar with the basics of reverse invocation, first read [Reverse Invocation of Dify Services](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation). **Interface Types**: * **Chat Interface**: `Chatbot`, `Agent`, and `Chatflow` applications are all chat-based and share the same input and output parameter types, so they share this interface. * **Workflow Interface**: Used by Workflow applications. * **Completion Interface**: Used by Completion (text generation) applications. Plugins can only access Apps within the Workspace where the plugin resides. ## Call the Chat Interface ### Entry Point ```python theme={null} self.session.app.chat ``` ### Interface Specification ```python theme={null} def invoke( self, app_id: str, query: str, inputs: dict, response_mode: Literal["streaming", "blocking"] = "streaming", conversation_id: str | None = None, user: str | None = None, ) -> Generator[dict, None, None] | dict: pass ``` When `response_mode` is `streaming`, this interface returns `Generator[dict]`; otherwise it returns `dict`. For the specific interface fields, see the return results of `ServiceApi`. ### Use Case This example calls a Chat type App within an `Endpoint` and returns the result directly: ```python theme={null} import json from typing import Mapping from werkzeug import Request, Response from dify_plugin import Endpoint class Duck(Endpoint): def _invoke(self, r: Request, values: Mapping, settings: Mapping) -> Response: """ Invokes the endpoint with the given request. """ app_id = values["app_id"] def generator(): response = self.session.app.chat.invoke( app_id=app_id, query="Hello from the plugin", inputs={}, response_mode="streaming", conversation_id="some-conversation-id", ) for data in response: yield f"{json.dumps(data)}
" return Response(generator(), status=200, content_type="text/html") ``` ## Call the Workflow Interface ### Entry Point ```python theme={null} self.session.app.workflow ``` ### Interface Specification ```python theme={null} def invoke( self, app_id: str, inputs: dict, response_mode: Literal["streaming", "blocking"] = "blocking", user: str | None = None, ) -> Generator[dict, None, None] | dict: pass ``` ## Call the Completion Interface ### Entry Point ```python theme={null} self.session.app.completion ``` ### Interface Specification ```python theme={null} def invoke( self, app_id: str, inputs: dict, response_mode: Literal["streaming", "blocking"] = "blocking", user: str | None = None, ) -> Generator[dict, None, None] | dict: pass ``` ## Related Resources * [Reverse Invocation of Dify Services](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation) - Understand the fundamental concepts of reverse invocation * [Reverse Invocation Model](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-model) - Learn how to call model capabilities within the platform * [Reverse Invocation Tool](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-tool) - Learn how to call other plugins * [Develop a Slack Bot Plugin](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/develop-a-slack-bot-plugin) - A practical application case using reverse invocation * [Develop Extension Plugins](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/endpoint) - Learn how to develop extension plugins # Reverse Invocation Model Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-model Invoke LLM, embedding, rerank, TTS, speech-to-text, and moderation models from your plugin A plugin can reverse invoke Dify's internal LLM capabilities, including all model types and functions within the platform, such as TTS and Rerank. If you are unfamiliar with the basics of reverse invocation, first read [Reverse Invocation of Dify Services](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation). Every model invocation takes a `ModelConfig` type parameter. Its structure is defined in the [General Specifications Definition](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) and varies slightly by model type. For example, `LLM` type models also require `completion_params` and `mode` parameters. You can construct this structure manually or use `model-selector` type parameters or configurations. ## Invoke LLM ### Entry Point ```python theme={null} self.session.model.llm ``` ### Interface ```python theme={null} def invoke( self, model_config: LLMModelConfig, prompt_messages: list[PromptMessage], tools: list[PromptMessageTool] | None = None, stop: list[str] | None = None, stream: bool = True, ) -> Generator[LLMResultChunk, None, None] | LLMResult: pass ``` If the model you are invoking does not have `tool_call` capability, the `tools` passed here will not take effect. ### Use Case This example invokes OpenAI's `gpt-4o-mini` model within a `Tool`: ```python theme={null} from collections.abc import Generator from typing import Any from dify_plugin import Tool from dify_plugin.entities.model.llm import LLMModelConfig from dify_plugin.entities.tool import ToolInvokeMessage from dify_plugin.entities.model.message import SystemPromptMessage, UserPromptMessage class LLMTool(Tool): def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]: response = self.session.model.llm.invoke( model_config=LLMModelConfig( provider='openai', model='gpt-4o-mini', mode='chat', completion_params={} ), prompt_messages=[ SystemPromptMessage( content='you are a helpful assistant' ), UserPromptMessage( content=tool_parameters.get('query') ) ], stream=True ) for chunk in response: if chunk.delta.message: assert isinstance(chunk.delta.message.content, str) yield self.create_text_message(text=chunk.delta.message.content) ``` Note that the code passes the `query` parameter from `tool_parameters`. ### Best Practice Avoid constructing `LLMModelConfig` manually. Instead, let users select the model they want in the UI by adding a `model` parameter to the tool's parameter list: ```yaml theme={null} identity: name: llm author: Dify label: en_US: LLM zh_Hans: LLM pt_BR: LLM description: human: en_US: A tool for invoking a large language model zh_Hans: 用于调用大型语言模型的工具 pt_BR: A tool for invoking a large language model llm: A tool for invoking a large language model parameters: - name: prompt type: string required: true label: en_US: Prompt string zh_Hans: 提示字符串 pt_BR: Prompt string human_description: en_US: used for searching zh_Hans: 用于搜索网页内容 pt_BR: used for searching llm_description: key words for searching form: llm - name: model type: model-selector scope: llm required: true label: en_US: Model zh_Hans: 使用的模型 pt_BR: Model human_description: en_US: Model zh_Hans: 使用的模型 pt_BR: Model llm_description: which Model to invoke form: form extra: python: source: tools/llm.py ``` Because the `scope` of the `model` parameter is `llm`, users can only select `llm` type models. The previous use case then becomes: ```python theme={null} from collections.abc import Generator from typing import Any from dify_plugin import Tool from dify_plugin.entities.model.llm import LLMModelConfig from dify_plugin.entities.tool import ToolInvokeMessage from dify_plugin.entities.model.message import SystemPromptMessage, UserPromptMessage class LLMTool(Tool): def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]: response = self.session.model.llm.invoke( model_config=tool_parameters.get('model'), prompt_messages=[ SystemPromptMessage( content='you are a helpful assistant' ), UserPromptMessage( content=tool_parameters.get('prompt') ) ], stream=True ) for chunk in response: if chunk.delta.message: assert isinstance(chunk.delta.message.content, str) yield self.create_text_message(text=chunk.delta.message.content) ``` ## Invoke Summary This interface summarizes a piece of text using the system model within your current workspace. ### Entry Point ```python theme={null} self.session.model.summary ``` ### Interface ```python theme={null} def invoke( self, text: str, instruction: str, ) -> str: ``` * **`text`**: The text to summarize. * **`instruction`**: Additional instructions, letting you control the style of the summary. ## Invoke TextEmbedding ### Entry Point ```python theme={null} self.session.model.text_embedding ``` ### Interface ```python theme={null} def invoke( self, model_config: TextEmbeddingModelConfig, texts: list[str], input_type: EmbeddingInputType = EmbeddingInputType.QUERY, ) -> TextEmbeddingResult: pass ``` ## Invoke Rerank ### Entry Point ```python theme={null} self.session.model.rerank ``` ### Interface ```python theme={null} def invoke( self, model_config: RerankModelConfig, docs: list[str], query: str ) -> RerankResult: pass ``` ## Invoke TTS ### Entry Point ```python theme={null} self.session.model.tts ``` ### Interface ```python theme={null} def invoke( self, model_config: TTSModelConfig, content_text: str ) -> Generator[bytes, None, None]: pass ``` The `bytes` stream returned by the `tts` interface is an `mp3` audio byte stream, and each iteration returns a complete audio segment. For more in-depth processing, choose an appropriate audio library. ## Invoke Speech2Text ### Entry Point ```python theme={null} self.session.model.speech2text ``` ### Interface ```python theme={null} def invoke( self, model_config: Speech2TextModelConfig, file: IO[bytes] ) -> str: pass ``` Here, `file` is an audio file encoded in `mp3` format. ## Invoke Moderation ### Entry Point ```python theme={null} self.session.model.moderation ``` ### Interface ```python theme={null} def invoke(self, model_config: ModerationModelConfig, text: str) -> bool: pass ``` A return value of `true` indicates that the `text` contains sensitive content. ## Related Resources * [Reverse Invocation of Dify Services](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation) - Understand the fundamental concepts of reverse invocation * [Reverse Invocation of App](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-app) - Learn how to invoke Apps within the platform * [Reverse Invocation of Tool](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-tool) - Learn how to invoke other plugins * [Model Plugin Development Guide](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/creating-new-model-provider) - Learn how to develop custom model plugins * [Model Designing Rules](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/model-designing-rules) - Understand the design principles of model plugins # Node Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-node Invoke the Parameter Extractor and Question Classifier nodes from your plugin A plugin can reverse invoke the capabilities of certain nodes within a Dify Chatflow/Workflow application. Plugins can call the `ParameterExtractor` and `QuestionClassifier` nodes. Both encapsulate complex prompt and code logic, using LLMs to handle tasks that are difficult to solve with hardcoded rules. ## Call the Parameter Extractor Node ### Entry Point ```python theme={null} self.session.workflow_node.parameter_extractor ``` ### Interface ```python theme={null} def invoke( self, parameters: list[ParameterConfig], model: ModelConfig, query: str, instruction: str = "", ) -> NodeResponse pass ``` * **`parameters`**: The list of parameters to extract. * **`model`**: Conforms to the `LLMModelConfig` specification. * **`query`**: The source text for parameter extraction. * **`instruction`**: Any additional instructions the LLM might need. For the structure of `NodeResponse`, see the [General Specifications Definition](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications#noderesponse). ### Use Case This example extracts a person's name from a conversation: ```python theme={null} from collections.abc import Generator from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage from dify_plugin.entities.workflow_node import ModelConfig, NodeResponse, ParameterConfig class ParameterExtractorTool(Tool): def _invoke( self, tool_parameters: dict ) -> Generator[ToolInvokeMessage, None, None]: response: NodeResponse = self.session.workflow_node.parameter_extractor.invoke( parameters=[ ParameterConfig( name="name", description="name of the person", required=True, type="string", ) ], model=ModelConfig( provider="langgenius/openai/openai", name="gpt-4o-mini", completion_params={}, ), query="My name is John Doe", instruction="Extract the name of the person", ) extracted_name = response.outputs.get("name", "Name not found") yield self.create_text_message(extracted_name) ``` `NodeResponse` is a Pydantic model defined in `dify_plugin.entities.workflow_node` with three dictionary fields: `process_data`, `inputs`, and `outputs`. Extracted values live under `response.outputs`. ## Call the Question Classifier Node ### Entry Point ```python theme={null} self.session.workflow_node.question_classifier ``` ### Interface ```python theme={null} def invoke( self, classes: list[ClassConfig], model: ModelConfig, query: str, instruction: str = "", ) -> NodeResponse: pass ``` `ClassConfig` is also exported from `dify_plugin.entities.workflow_node`. The interface parameters match those of `ParameterExtractor`, and the final result is stored in `response.outputs["class_name"]`. # Tool Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-tool Call installed tools, Workflow as Tool, and custom tools from your plugin A plugin can reverse invoke other tool-type plugins within the Dify platform. If you are unfamiliar with the basics of reverse invocation, first read [Reverse Invocation of Dify Services](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation). Consider the following scenarios: * A tool-type plugin implements a function, but the result is not as expected and the data needs post-processing. * A task requires a web scraper, and you want the flexibility to choose the scraping service. * You need to aggregate results from multiple tools, which is difficult to handle in a Workflow application. In these cases, your plugin needs to call other existing tools: tools from the marketplace, a self-built Workflow as a Tool, or a custom tool. All of them are available through the plugin's `self.session.tool` field. ## Call Installed Tools Call any tool installed in the current Workspace, including other tool-type plugins. ### Entry Point ```python theme={null} self.session.tool ``` ### Interface ```python theme={null} def invoke_builtin_tool( self, provider: str, tool_name: str, parameters: dict[str, Any] ) -> Generator[ToolInvokeMessage, None, None]: pass ``` * **`provider`**: The plugin ID plus the tool provider name, formatted like `langgenius/google/google`. * **`tool_name`**: The specific tool name. * **`parameters`**: The arguments passed to the tool. ## Call Workflow as Tool See the [Tool Plugin documentation](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin) for more information on Workflow as Tool. ### Entry Point ```python theme={null} self.session.tool ``` ### Interface ```python theme={null} def invoke_workflow_tool( self, provider: str, tool_name: str, parameters: dict[str, Any] ) -> Generator[ToolInvokeMessage, None, None]: pass ``` * **`provider`**: The ID of this tool. * **`tool_name`**: The name specified when the tool was created. ## Call Custom Tool ### Entry Point ```python theme={null} self.session.tool ``` ### Interface ```python theme={null} def invoke_api_tool( self, provider: str, tool_name: str, parameters: dict[str, Any] ) -> Generator[ToolInvokeMessage, None, None]: pass ``` * **`provider`**: The ID of this tool. * **`tool_name`**: The `operation_id` from the OpenAPI specification. If no `operation_id` exists, this is the `tool_name` automatically generated by Dify, which you can find on the tool management page. ## Related Resources * [Reverse Invocation of Dify Services](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation) - Understand the fundamental concepts of reverse invocation * [Reverse Invocation App](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-app) - Learn how to call Apps within the platform * [Reverse Invocation Model](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation-model) - Learn how to call model capabilities within the platform * [Tool Plugin Development Guide](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin) - Learn how to develop tool plugins * [Advanced Tool Plugins](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin) - Learn about advanced features like Workflow as Tool # Multilingual README Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/plugin-types/multilingual-readme Add per-language README files so Dify Marketplace shows your plugin's documentation in each user's preferred language A plugin's README is the first thing users read on the [Dify Marketplace](https://marketplace.dify.ai) detail page. Adding translations lets non-English users read your docs in their own language without losing the original. ## File Specifications | Language | Required | Filename | Path | | :- | :- | :- | :- | | English | Yes | `README.md` | Plugin root | | Simplified Chinese | No | `README_zh_Hans.md` | `readme/` | | Japanese | No | `README_ja_JP.md` | `readme/` | | Portuguese (Brazil) | No | `README_pt_BR.md` | `readme/` | All files must be UTF-8 encoded. The English `README.md` always stays in the plugin root; every other language goes inside a `readme/` subdirectory. ```text theme={null} your_plugin/ ├── README.md ├── readme/ │ ├── README_zh_Hans.md │ ├── README_ja_JP.md │ └── README_pt_BR.md ├── manifest.yaml ├── main.py └── ... ``` ## Recommended Structure Keep READMEs concise, under \~500 words. The Marketplace detail page surfaces the README directly, so optimize it for someone evaluating whether to install: ```markdown theme={null} # Plugin Name One-sentence summary of what the plugin does. ## Features - Key capability 1 - Key capability 2 - Key capability 3 ## Setup 1. Where to get the credentials (link to the upstream service). 2. Where to paste them in Dify. ## Usage A minimal example — for a tool, show the inputs and outputs. For a model provider, show the model selector. Screenshots help. ## Privacy Briefly describe what data the plugin sends to third parties. Link to your PRIVACY.md. ``` Avoid putting a full API reference or development notes in the README; those belong in source comments or a separate docs site. The Marketplace audience is end users picking a plugin, not contributors reading your codebase. ## How the Marketplace Picks a Language When a visitor opens your plugin's detail page, the Marketplace looks for a README matching their UI language. If a match exists in the `readme/` directory, it renders that file. Otherwise it falls back to the English `README.md`. ![Plugin Detail Page in English](https://mintcdn.com/dify-enterprise-docs/5auvTYL_hjrCYTVu/images/develop-plugin/specs/plugin-details-page-en.jpeg?fit=max\&auto=format\&n=5auvTYL_hjrCYTVu\&q=85\&s=fe5fa3b9189e733bea02431a071c805a) > [!NOTE] > > Language codes are matched exactly: `README_zh_Hans.md` serves Simplified Chinese only; Traditional Chinese users see the English fallback. # Manifest Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/plugin-types/plugin-info-by-manifest YAML schema for the plugin manifest that declares name, author, runtime, resources, permissions, and which tools/models/endpoints the plugin ships The manifest is a YAML file that defines a plugin's basic information: name, author, included tools and models, and more. If the file is malformed, plugin parsing and packaging fails. For the overall plugin architecture, see [Basic Concepts of Plugin Development](/en/3.13.x/develop/plugins/getting-started/getting-started-dify-plugin) and the [Developer Cheatsheet](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/cheatsheet). ## Code Example Below is a simple manifest file; each field is explained in the Structure section that follows. For a real-world example, see the [Google tool plugin manifest](https://github.com/langgenius/dify-official-plugins/blob/main/tools/google/manifest.yaml). ```yaml theme={null} version: 0.0.1 type: "plugin" author: "Yeuoly" name: "neko" label: en_US: "Neko" created_at: "2024-07-12T08:03:44.658609186Z" icon: "icon.svg" resource: memory: 1048576 permission: tool: enabled: true model: enabled: true llm: true endpoint: enabled: true app: enabled: true storage: enabled: true size: 1048576 plugins: endpoints: - "provider/neko.yaml" meta: version: 0.0.1 arch: - "amd64" - "arm64" runner: language: "python" version: "3.12" entrypoint: "main" privacy: "./privacy.md" ``` ## Structure **version** `version` *required* Plugin version. **type** `string` *required* Plugin type. Currently only `plugin` is supported; `bundle` support is planned. **author** `string` *required* Author, defined as the organization name in the Marketplace. **label** `object` *required* Multilingual name. **created\_at** `RFC3339` *required* Creation time. The Marketplace requires this to be no later than the current time. **icon** `string` *required* Icon path. **resource** `object` Resources the plugin requests. **memory** `int64` Maximum memory usage in bytes. Mainly relates to AWS Lambda resource allocation on Dify Cloud. **permission** `object` Permissions the plugin requests. **tool** `object` Permission for reverse invocation of tools. **enabled** `boolean` Whether to enable tool permissions. **model** `object` Permission for reverse invocation of models. **enabled** `boolean` Whether to enable model permissions. **llm** `boolean` Whether to enable large language model permissions. **text\_embedding** `boolean` Whether to enable text embedding model permissions. **rerank** `boolean` Whether to enable rerank model permissions. **tts** `boolean` Whether to enable text-to-speech model permissions. **speech2text** `boolean` Whether to enable speech-to-text model permissions. **moderation** `boolean` Whether to enable content moderation model permissions. **node** `object` Permission for reverse invocation of nodes. **enabled** `boolean` Whether to enable node permissions. **endpoint** `object` Permission to register `endpoint`. **enabled** `boolean` Whether to enable endpoint permissions. **app** `object` Permission for reverse invocation of `app`. **enabled** `boolean` Whether to enable app permissions. **storage** `object` Permission to apply for persistent storage. **enabled** `boolean` Whether to enable storage permissions. **size** `int64` Maximum allowed persistent storage size, in bytes. **plugins** `object` *required* Lists the YAML files for the capabilities the plugin extends, as absolute paths within the plugin package. For example, to extend a model, define a file such as `openai.yaml` and list its path here. The file must exist at that path, or packaging fails. > [!WARNING] > > The following combinations are not allowed: > > * Extending both tools and models. > * Extending both models and Endpoints. > * Having no extensions at all. > > Currently, each extension type supports only one provider. **tools** `array[string]` Plugin extension for [Tool](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin) providers. **models** `array[string]` Plugin extension for [Model](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/model-designing-rules) providers. **endpoints** `array[string]` Plugin extension for [Endpoints](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/develop-a-slack-bot-plugin) providers. **agent\_strategies** `array[string]` Plugin extension for [Agent Strategy](/en/3.13.x/develop/plugins/features-and-specs/advanced-development/reverse-invocation) providers. **meta** `object` *required* Metadata for the plugin. **version** `version` *required* Manifest format version. The initial version is `0.0.1`. **arch** `array[string]` *required* Supported architectures. Currently only `amd64` and `arm64` are supported. **runner** `object` *required* Runtime configuration. **language** `string` *required* Programming language. Currently only Python is supported. **version** `string` *required* Language version. Currently only `3.12` is supported. **entrypoint** `string` *required* Program entry point. For Python, this should be `main`. **privacy** `string` Relative path or URL of the plugin's privacy policy, for example `"./privacy.md"` or `"https://your-web/privacy"`. **Required for listing on the Dify Marketplace**, where plugins must clearly state how they use user data. For details, see the [Plugin Privacy Data Protection Guidelines](/en/3.13.x/develop/plugins/publishing/standards/privacy-protection-guidelines). # Plugin Logging Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/plugin-types/plugin-logging Emit logs from your plugin with the SDK's plugin_logger_handler, visible during remote debugging and in daemon container logs While developing or debugging a plugin, you often want to log what your code is doing. The plugin SDK provides a handler for Python's standard `logging` library. Add it to your logger to write any string to both the standard output during remote debugging and the plugin daemon container logs (community edition only). ## Example Import `plugin_logger_handler` and add it to your logger. The following example shows a tool plugin. ```python theme={null} from collections.abc import Generator from typing import Any from dify_plugin import Tool from dify_plugin.entities.tool import ToolInvokeMessage # Import logging and custom handler import logging from dify_plugin.config.logger_format import plugin_logger_handler # Set up logging with the custom handler logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(plugin_logger_handler) class LoggerDemoTool(Tool): def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]: # Log messages with different severity levels logger.info("This is an INFO log message.") logger.warning("This is a WARNING log message.") logger.error("This is an ERROR log message.") yield self.create_text_message("Hello, Dify!") ``` # Plugin Debugging Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin Run your in-development plugin locally and attach it to a live Dify workspace for end-to-end testing, no packaging required Remote debugging is the fastest way to iterate on a plugin. You run the plugin process on your laptop, and Dify treats it as if it were installed in the workspace. Save your edits and restart the process, and the changes take effect immediately. ## Prerequisites * A Dify workspace where you can access **Plugins** in the top-right corner. * A scaffolded plugin project (see [CLI](/en/3.13.x/develop/plugins/getting-started/cli) if you haven't created one yet). * Python 3.12 and the plugin's dependencies installed (`pip install -r requirements.txt`). ## Step 1: Get the Debug URL and Key Open the **Plugins** page in Dify and click the debug icon (the small bug icon next to **Install Plugin**). A dialog shows the **remote install host:port** and an **API key**. ![Remote Debugging Plugin](https://assets-docs.dify.ai/2024/12/053415ef127f1f4d6dd85dd3ae79626a.png) > [tab] Dify Cloud > > The host is something like `debug-plugin.dify.dev:5003`. The key is unique to your workspace; anyone with the key can attach a plugin, so do not share it. > [tab] Self-hosted > > The host defaults to `127.0.0.1:5003` and is configured by `PLUGIN_REMOTE_INSTALLING_HOST` / `PLUGIN_REMOTE_INSTALLING_PORT` in the plugin daemon's environment. Make sure port `5003` is reachable from your dev machine. If Dify runs in Docker on the same host, use the daemon container's bridge IP (or expose the port). ## Step 2: Configure the Plugin's `.env` In your plugin project, copy `.env.example` to `.env` and fill in the values: ```bash theme={null} INSTALL_METHOD=remote REMOTE_INSTALL_URL=debug-plugin.dify.dev:5003 REMOTE_INSTALL_KEY=********-****-****-****-************ ``` > [!NOTE] > > `REMOTE_INSTALL_URL` is the combined `host:port` from Step 1, not two separate variables. ## Step 3: Run the Plugin From the plugin project directory: ```bash theme={null} pip install -r requirements.txt python -m main ``` The process stays in the foreground and logs incoming invocations. Edit your code and restart the process to apply changes. ## Step 4: Verify the Install Go back to the Dify **Plugins** page. The plugin appears in the list, labeled with a debug marker. Other members of the workspace can also see and use it. ![Plugin Installed to Workspace](https://assets-docs.dify.ai/2024/12/ec26e5afc57bbfeb807719638f603807.png) > [!TIP] > > The plugin tile shows a debug indicator and your local terminal logs the first registration handshake. You're attached. Trigger the plugin as you would any other: call it from a workflow node, run it as a tool inside an Agent, or hit an endpoint URL. Invocations land on your local process and you can attach a debugger. ## Troubleshooting > [accordion] Connection refused / cannot reach host > > The daemon is not listening on the address you put in `REMOTE_INSTALL_URL`. On self-hosted setups, confirm the daemon container has `PLUGIN_REMOTE_INSTALLING_ENABLED=true` and that port `5003` is exposed. On cloud, double-check you copied the host:port exactly as shown in the debug dialog. > [accordion] Plugin starts but never appears in the Plugins list > > The most common cause is a stale or wrong `REMOTE_INSTALL_KEY`. Regenerate the key from the debug dialog and rerun `python -m main`. Also confirm the daemon log shows the incoming registration. > [accordion] `plugin_unique_identifier is not valid` > > The `author` field in `manifest.yaml` or in `provider/*.yaml` doesn't match a value the daemon accepts. Set it to your GitHub handle, then restart. > [accordion] Changes don't take effect > > The plugin process needs to restart after every edit; there's no hot reload. Stop with `Ctrl+C` and rerun `python -m main`. ## Related Resources * [CLI](/en/3.13.x/develop/plugins/getting-started/cli)—Scaffold a plugin and set up `.env` * [Plugin Logging](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/plugin-logging)—Emit structured logs from inside your plugin * [Package as Local File and Share](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-by-file)—Ship the plugin once debugging is done # Frequently Asked Questions Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/faq/faq Common issues and fixes for building, packaging, debugging, and installing Dify plugins ## Package and Install ### Why does `dify plugin package` fail with `plugin_unique_identifier is not valid`? The `author` field in `manifest.yaml` and any `provider/*.yaml` file must match your GitHub handle. Update it in every file, repackage with `dify plugin package`, and reinstall. ### Why am I seeing `plugin verification has been enabled, and the plugin you want to install has a bad signature`? Self-hosted Dify enforces signature verification on plugin packages by default. You have two options: 1. **Recommended for production**: sign your package. See [Third-Party Signature Verification](/en/3.13.x/develop/plugins/publishing/standards/third-party-signature-verification). 2. **For development and trusted internal use**: disable verification. Add `FORCE_VERIFYING_SIGNATURE=false` to `docker/.env`, then restart: ```bash theme={null} cd docker docker compose down docker compose up -d ``` This allows installing any unsigned plugin, including ones outside the Marketplace, so only do this in environments you control. ### Is there a maximum size for a `.difypkg` file? Yes. The plugin daemon rejects packages over a configurable limit (default `50MB`). If you ship large model weights or static assets, host them externally and download on first use, or contact Dify support about raising the limit for marketplace plugins. ### My plugin needs Python 3.13. Can I change the runtime? No. Plugins run inside a managed Python 3.12 environment. Pin your dependencies to versions compatible with 3.12. The daemon does not honor a different runtime version in `manifest.yaml`. ## Remote Debugging ### Why does my plugin start but never appear in the workspace? Three things to check, in order: (1) the daemon log shows an incoming registration, (2) the `REMOTE_INSTALL_KEY` matches what's shown in the debug dialog, (3) `REMOTE_INSTALL_URL` uses the `host:port` format (not separate variables). See [Plugin Debugging](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin) for the full troubleshooting list. ### Do my code changes hot-reload? No. Stop the plugin process with `Ctrl+C` and rerun `python -m main` after every change. ## OAuth and Credentials ### What callback URL should I configure with the upstream OAuth provider? Use `https:///console/api/oauth/plugin///tool/callback` for tool plugins, replacing `tool` with `datasource` or `trigger` for those plugin types. The exact pattern is shown in your plugin's OAuth setup card inside Dify. ### Why are my OAuth tokens not refreshing? The plugin SDK refreshes tokens automatically when they expire, provided your provider implementation returns a valid `refresh_token` from the initial authorization. Confirm `OAuthCredentials.refresh_token` is populated, and that your `_oauth_refresh_credentials` method is implemented. ## Marketplace Publishing ### Why was my Marketplace PR rejected by the automated check? The Marketplace workflow runs package, metadata, dependency, disclosure, and install checks. The exact set evolves with the repository. Common blocking failures include: * **More than one `.difypkg` changed**: submit one plugin package per PR. * **Incomplete PR template or risk selection**: keep every template section, select exactly one risk level, and disclose sensitive capabilities. * **Secrets, development artifacts, or unexplained binaries**: remove them from the package and rebuild it. * **Invalid manifest, README, privacy, source, or contact metadata**: keep package metadata and PR claims consistent. * **Dependency policy failure**: Python plugins must use `dify-plugin >= 0.9.0`; resolve installation and vulnerability findings. * **Duplicate version or failed install/package test**: increment the version, rebuild, and test with the current daemon. See [Handle PR Checks and Review](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace#after-you-submit) to interpret the result and decide whether you need to act. ### How long does the Marketplace review take? There is no guaranteed review time. Complete package evidence, a filled PR template, and resolved CI findings reduce review back-and-forth. Monitor the PR for reviewer comments and respond on the same branch. ### How do I publish an update for a plugin already on the Marketplace? Bump `version` in `manifest.yaml`, rebuild the package, and open a new PR against `langgenius/dify-plugins` with the new `.difypkg`. Keep previously published packages in the repository unless a maintainer asks otherwise. See [Submit a Marketplace Pull Request](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace#choose-the-submission-type). ### Can I monetize my plugin? Not currently. The Marketplace only accepts free plugins. Future pricing policies will be announced separately. ## Storage and Limits ### Where do plugin logs go? Self-hosted: container logs of the plugin daemon (`docker compose logs plugin_daemon`). Cloud: visible in the workspace's plugin debug panel during remote debugging only; persisted logs are not exposed in the UI. Use [Plugin Logging](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/plugin-logging) for structured output. ### Is plugin storage scoped per workspace? Yes. The KV storage API (`self.session.storage`) is isolated per workspace per plugin install. Two workspaces using the same plugin do not share keys. See [Persistent Storage (KV)](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/persistent-storage-kv). # Package as Local File and Share Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-by-file Package a Dify plugin into a `.difypkg` file you can install directly or hand off to others, with no marketplace or GitHub release required A `.difypkg` is the portable form of a Dify plugin. Once you have one, anyone can install it through the Plugins page by uploading the file. This is the right path for **private plugins**, **internal testing**, or **out-of-band distribution** to a small group. For wider distribution, see the [Publishing Overview](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview). ## Prerequisites * The [Dify Plugin CLI](/en/3.13.x/develop/plugins/getting-started/cli) installed. Run `dify version` to confirm. * A completed plugin project. If you haven't built one yet, start with the [Tool Plugin walkthrough](/en/3.13.x/develop/plugins/dev-guides-and-walkthroughs/tool-plugin). * The plugin tested with [remote debugging](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin) before packaging. > [!NOTE] > > The `author` field in `manifest.yaml` and every `provider/*.yaml` must match your GitHub handle. Mismatches cause `plugin_unique_identifier is not valid` at install time. See [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) for the full manifest spec. ## Package the Plugin **1. Move above the project** Navigate to the directory **above** your plugin project (so the project is a subdirectory of the current working directory). **2. Run the packager** ```bash theme={null} dify plugin package ./your_plugin_project ``` The CLI produces a `your_plugin_project.difypkg` file in the current directory. ![Generated Plugin File](https://assets-docs.dify.ai/2024/12/98e09c04273eace8fe6e5ac976443cca.png) ## Install from the File **1. Open the Plugins page** In Dify, click the **Plugins** icon in the top-right corner. **2. Choose Install Plugin > Via Local File** Or drag the `.difypkg` onto the empty area of the Plugins page. **3. Confirm the install** Review the permissions the plugin requests, then click **Install**. ![Install Plugin File](https://assets-docs.dify.ai/2024/12/8c31c4025a070f23455799f942b91a57.png) > [!TIP] > > The plugin is now in the workspace and ready to use in Agents, Workflows, or Tools. No further action required. > [!WARNING] > > Self-hosted Dify enforces signature verification by default. Unsigned `.difypkg` files installed via Local File will be rejected unless you sign them or change the verification setting. See [Third-Party Signature Verification](/en/3.13.x/develop/plugins/publishing/standards/third-party-signature-verification). ## Share the File Hand the `.difypkg` file to your users directly: over email, an internal file share, or any channel you control. They install it with the same flow above. If you want broader distribution instead, consider: > [card] [Publish on GitHub](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-to-individual-github-repo) > > Attach the `.difypkg` to a GitHub release; users install via repo URL. > [card] [Publish to Marketplace](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace) > > Open a PR against `langgenius/dify-plugins` for the official catalog. ## Related Resources * [Publishing Overview](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview) * [Dify Plugin CLI](/en/3.13.x/develop/plugins/getting-started/cli) * [Remote Debugging](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin) * [Third-Party Signature Verification](/en/3.13.x/develop/plugins/publishing/standards/third-party-signature-verification) * [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) # Publish Plugins Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview Three ways to distribute a Dify plugin (Marketplace, GitHub repository, or local file) and how to pick the right one Dify supports three ways to distribute a plugin. They differ in how much vetting happens up front and how broad an audience the plugin reaches. Before publishing, finish development and testing, and read the [Plugin Development Guidelines](/en/3.13.x/develop/plugins/publishing/standards/contributor-covenant-code-of-conduct). ## Choose a Method > [card] [Marketplace](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace) > > Official catalog. Reviewed, trusted, one-click install for every Dify user. > [card] [GitHub Repository](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-to-individual-github-repo) > > Self-hosted on GitHub. No review; users install via repo URL. > [card] [Local File](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-by-file) > > A `.difypkg` file you hand off directly. Right for private or internal plugins. ## Compare | | Marketplace | GitHub | Local File | | :- | :- | :- | :- | | **Audience** | Every Dify user | Anyone with the repo URL | People you give the file to | | **Review** | Automated risk and package checks + human review | None | None | | **Install path** | One click from Marketplace UI | Install from GitHub dialog | Upload via Plugins page | | **Versioning** | New package and PR for every version | GitHub releases with `.difypkg` asset | Repackage and redistribute | | **Best for** | Polished, broadly useful plugins | Open-source projects, internal tools shared by URL | Private plugins, internal testing, ad-hoc distribution | > [!TIP] > > Many developers ship to **GitHub first** for fast iteration, then submit to the **Marketplace** once the plugin is stable. The same `.difypkg` works for all three methods; only the distribution channel differs. ## Quick Rules of Thumb * **Want broad reach and review?** Use the **Marketplace**. * **Want full control over releases and versioning?** Use **GitHub**. * **Private or one-off use?** Use a **Local File**. ## Related Resources > [card] [Plugin Development Guidelines](/en/3.13.x/develop/plugins/publishing/standards/contributor-covenant-code-of-conduct) > > Quality bar for Marketplace submissions. > [card] [Privacy Guidelines](/en/3.13.x/develop/plugins/publishing/standards/privacy-protection-guidelines) > > `PRIVACY.md` and data-disclosure requirements. > [card] [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) > > Manifest fields every plugin must set. > [card] [Getting Started](/en/3.13.x/develop/plugins/getting-started/getting-started-dify-plugin) > > New to plugins? Start here. # Publish to Individual GitHub Repository Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-to-individual-github-repo Distribute a Dify plugin from your own GitHub repository so users can install it directly via repo URL, with no marketplace review required Publishing through a personal GitHub repository lets you ship a plugin without going through Dify Marketplace review. Users install the plugin by entering your repo URL and selecting a release that contains a `.difypkg` asset. This method fits when: * You want full control over versioning and the release cadence. * The plugin is open source and you want others to read, fork, or contribute to it. * The plugin is for internal use within a team or org, but you still want one canonical install URL. * Your plugin is awaiting marketplace review and you need an interim distribution channel. For a comparison with other publishing methods, see the [Publishing Overview](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview). ## Prerequisites * A packaged plugin (`.difypkg` file). If you don't have one yet, see [Package as Local File and Share](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-by-file). * A GitHub account. * A Dify workspace where you (or your users) have permission to install plugins. ## Step 1: Create a GitHub Repository **1. Create the repository** On GitHub, create a new public repository. The name typically matches your plugin name (for example, `dify-plugin-flomo`). **2. Push your plugin source** Initialize git in your plugin project and push the source code: ```bash theme={null} cd your_plugin_project git init git add . git commit -m "initial commit" git branch -M main git remote add origin https://github.com//.git git push -u origin main ``` **3. Confirm the manifest** The `author` field in `manifest.yaml` and in any `provider/*.yaml` must match your GitHub handle. Mismatches cause `plugin_unique_identifier is not valid` when users try to install. See the [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) for manifest details. ## Step 2: Build the Plugin Package From the directory **above** your plugin project, run: ```bash theme={null} dify plugin package ./your_plugin_project ``` This produces `your_plugin_project.difypkg` in the current directory. ## Step 3: Publish a GitHub Release GitHub releases are how Dify discovers installable versions of your plugin. **1. Tag a release** On your repository page, click **Releases** > **Draft a new release**. Create a new tag using semantic versioning (for example, `v0.0.1`). The tag should match the `version` field in your `manifest.yaml`. **2. Attach the .difypkg file** In the release form, drag the `.difypkg` file into the **Assets** area. Dify reads this asset when users install from your repo. **3. Publish** Add release notes describing what changed, then click **Publish release**. > [!TIP] > > Repeat Steps 2 and 3 for each new version. Bump the `version` in `manifest.yaml` first, repackage, then create a new tag and release. ## Step 4: Install from Your Repository Share your repository URL with users. They install it in Dify as follows: **1. Open the Plugins page** In Dify, go to **Plugins** in the top-right corner. **2. Install from GitHub** Click **Install Plugin** > **From GitHub**. **3. Enter repository details** Paste the repository URL (for example, `https://github.com//`), then select the version from the dropdown. Dify pulls the matching `.difypkg` asset from that release. **4. Confirm installation** Review the permissions the plugin requests, then click **Install**. > [!TIP] > > The plugin appears on the user's Plugins page within seconds of clicking **Install**. Dify pulls the `.difypkg` from your GitHub release on demand. ## Troubleshooting * **`plugin_unique_identifier is not valid`**: The `author` field in `manifest.yaml` (and `provider/*.yaml`) doesn't match the GitHub handle that owns the repo. Update it, repackage, and re-release. * **No versions appear in the install dialog**: The release has no `.difypkg` asset attached, or the repo has no releases yet. Open the release on GitHub and confirm the asset is listed under **Assets**. * **Signature verification error**: Self-hosted Dify instances may have signature verification enabled. See [Third-Party Signature Verification](/en/3.13.x/develop/plugins/publishing/standards/third-party-signature-verification) to sign your release, or see the [FAQ](/en/3.13.x/develop/plugins/publishing/faq/faq) for the bypass option. ## Related Resources * [Publishing Overview](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview): Compare publishing methods. * [Package as Local File and Share](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-by-file): Build a `.difypkg` package. * [Publish a Plugin to Marketplace](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace#prepare-the-package): Prepare and validate a package for the official Marketplace. * [Third-Party Signature Verification](/en/3.13.x/develop/plugins/publishing/standards/third-party-signature-verification): Sign packages for verified installs. * [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications): Manifest field reference. # Publish a Plugin to Marketplace Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace Prepare and validate a .difypkg, submit it for Marketplace review, respond to the pull request, and review the published plugin's performance and feedback in Creator Center Submit your plugin for Marketplace review through a pull request to [`langgenius/dify-plugins`](https://github.com/langgenius/dify-plugins). ## What You Need * A working plugin project tested with a current Dify deployment. * The [Dify plugin CLI](https://github.com/langgenius/dify-plugin-daemon) for packaging. * Python 3 and [`yq`](https://github.com/mikefarah/yq) for local validation. * A public source repository that reviewers and users can inspect. > [!NOTE] > > The Marketplace accepts a packaged `.difypkg`, not your source tree. Reviewers still use the source repository declared in your metadata and PR to understand behavior that cannot be proven from the package alone. ## Prepare the Package > [tab] Runtime files > > Include only files needed when the plugin runs: `manifest.yaml`, provider or tool definitions, source code, dependencies, README files, privacy policy, and assets. > > Do not package development state such as `.git/`, virtual environments, caches, logs, `.DS_Store`, local settings, IDE files, or test artifacts. Never include `.env` files, access tokens, private keys, cloud credentials, or other secrets. > [tab] Metadata and docs > > Confirm that `manifest.yaml` accurately declares the author, name, version, plugin type, runner, icon, source repository, contact information, and privacy policy. > > The primary `README.md` must be in English and explain setup, usage, required APIs or credentials, connection requirements, and the source repository. Put translations under `readme/README_.md`. > [tab] Dependencies > > Keep dependencies minimal and pinned closely enough to be reproducible. Avoid bare requirements, direct URL installs, and git-based installs unless the PR explains why they are required. > > Python plugins must use `dify-plugin >= 0.9.0`. The validator also checks dependency metadata and queries the [OSV database](https://osv.dev/) for known vulnerabilities. ### Document Privacy and Network Access Your `PRIVACY.md` or hosted privacy policy must describe what user data the plugin collects, stores, logs, or sends to third parties. If the plugin collects no user data, say so explicitly. When a plugin contacts external services, you can declare the expected domains in `manifest.yaml`: ```yaml theme={null} network: domains: - api.example.com - "*.cdn.example.com" ``` Static analysis cannot discover every URL assembled at runtime or hidden inside a vendor SDK. Declaring domains makes those destinations visible even when the scanner cannot infer them from source code. ## Classify the Risk Choose the highest level that matches the plugin. You will select exactly one level in the Marketplace PR template. | Level | Use It When | | :- | :- | | **Low** | The plugin calls fixed, documented HTTPS APIs and does not execute user-controlled code, commands, SQL, file operations, browser automation, or arbitrary network requests. | | **Medium** | The plugin processes uploaded files or user-provided URLs, performs write actions in a third-party service, sends user content externally, or handles personal data that is not highly sensitive. | | **High** | The plugin can execute code or commands, run SQL, access databases or file systems, use SSH/SFTP, automate browsers, proxy or crawl arbitrary URLs, bundle executables, or handle sensitive personal data. | > [!WARNING] > > If more than one level could apply, select the higher level. A lower label does not reduce review scope; it only creates inconsistent evidence and delays review. For medium- and high-risk plugins, document the security boundary: how inputs are constrained, where data goes, which credentials are used, what timeouts apply, and how errors avoid exposing secrets. ## Build and Validate Locally **1. Package the plugin** From the directory above your plugin project, run: ```bash theme={null} dify plugin package ./your-plugin ``` The command creates a `.difypkg` archive. Inspect its filename and file size before continuing. **2. Clone the Marketplace Toolkit** ```bash theme={null} git clone https://github.com/langgenius/dify-marketplace-toolkit.git cd dify-marketplace-toolkit ``` **3. Run package validation** ```bash theme={null} python3 validator/validate-difypkg.py /path/to/your-plugin.difypkg \ --output-dir ./validation-report ``` To compare sensitive-capability findings with your planned PR disclosure, save the PR body to a file and add `--pr-body-file /path/to/pr-body.md`. **4. Resolve the report** Open `validation-report/summary.md`, then inspect the generated `*.errors.txt` and `*.warnings.txt` files. Exit code `0` means no blocking package-level errors were found. Exit code `1` means a blocking finding or environment error must be resolved. Warnings do not fail validation, but reviewers may ask for clarification. The local validator checks safe extraction, package contents and size, secret patterns, binaries, manifest and README metadata, dependency policy, Python compilation and safety patterns, outbound domains, dependency vulnerabilities, financial-activity signals, and optional sensitive-capability disclosure. > [!TIP] > > Only the vulnerability lookup reaches the network. Add `--offline` when necessary; the report will list dependencies without claiming that they are vulnerability-free. ## Choose the Submission Type > [tab] New plugin > > Create a package directory under your author namespace: > > ```text theme={null} > //.difypkg > ``` > > The package metadata, source repository, contact information, README, privacy policy, and risk disclosure must all describe the same plugin. > [tab] Version update > > Increment `version` in `manifest.yaml`, rebuild the package, and add the new `.difypkg` to the existing plugin directory. > > An update PR should normally add only the new package file. Keep old published packages unless a maintainer explicitly asks otherwise. Summarize fixes, features, migrations, and breaking changes in **What changed** so the release pipeline can extract useful release notes. ## Open the PR **1. Fork and synchronize the repository** Fork [`langgenius/dify-plugins`](https://github.com/langgenius/dify-plugins), then clone your fork and keep its `main` branch synchronized with upstream. ```bash theme={null} git clone https://github.com//dify-plugins.git cd dify-plugins git remote add upstream https://github.com/langgenius/dify-plugins.git git fetch upstream git switch main git merge --ff-only upstream/main ``` **2. Create a focused branch** ```bash theme={null} git switch -c add-- mkdir -p / cp /path/to/plugin.difypkg // ``` Confirm that the branch changes exactly one `.difypkg` package: ```bash theme={null} git status --short git diff --stat ``` **3. Commit and push** ```bash theme={null} git add //.difypkg git commit -m "add " git push -u origin HEAD ``` **4. Create the pull request** Open a PR from your fork to `langgenius/dify-plugins:main`. Keep the PR out of draft only when the package and description are ready for automated and human review. > [!WARNING] > > Submit one `.difypkg` per PR. Combining plugins or versions prevents CI from identifying a single package path and blocks the submission. ## Complete the Submission Template The current template is part of the review contract. Do not delete fields or replace it with a short free-form description. > [accordion] Plugin information > > Provide the author, plugin name, version, public source repository, and a monitored contact channel. These values must agree with `manifest.yaml` and the package documentation. > [accordion] Submission type and changes > > Select **New plugin** or **Version update**, then explain what the plugin does or what changed in this version. Write release-note-quality details for updates, including migrations and breaking changes. > [accordion] Risk level > > Select exactly one of **Low risk**, **Medium risk**, or **High risk**. The repository applies a matching `risk:*` label. Selecting none or multiple levels produces `risk: missing` and a bot comment. > [accordion] Required checks > > Confirm package hygiene, testing, README quality, privacy coverage, and English localization only after verifying each item. If a requirement has a limitation, explain it in **Reviewer notes** instead of silently checking the box. > [accordion] Security and privacy notes > > List command or code execution, SQL, SSH/SFTP, browser automation, file operations, arbitrary URL fetching, proxying, and sensitive-data handling. Write `None` only when none apply. > [accordion] Local validation and reviewer notes > > Paste the validator command and result. Add known limitations, package or binary exceptions, migration notes, and context reviewers need to interpret warnings. ## Help Reviewers Verify Your Plugin | Do | Avoid | | :- | :- | | Use English for the PR title, body, and primary README. | Mixing untranslated CJK text into the primary submission fields. | | Link the exact public source repository for the package. | Linking an organization homepage or unrelated monorepo root without directions. | | Explain why sensitive behavior is necessary and constrained. | Describing a high-risk capability as low risk because it is optional. | | Include concrete validation commands and results. | Saying “tested” without environment or result details. | | Keep package bytes and disclosure in sync. | Copying an old PR body for a changed version. | ## Handle PR Checks and Review Opening the PR, pushing commits, or marking a draft ready for review starts the automated checks. Use the result to decide whether you need to act. | Result | What You Do | | :- | :- | | **Pass** | Wait for maintainer review. A passing check does not guarantee approval. | | **Blocking error** | Fix the package or PR, rebuild when needed, and update the same PR. Do not open a replacement PR. | | **Warning** | Review the finding. Fix an actual problem, or add context when the behavior is intentional. A warning alone does not fail the check, but a reviewer may request changes. | | **Changes requested** | Update the source, rebuild the package when needed, push the correction to the same PR, and respond to the reviewer. | After approval and merge, the repository validates the package again and uploads it to the production Marketplace. You do not need to start CI or upload the approved package yourself. ## Review Plugin Performance and Feedback in Creator Center After your plugin appears in Marketplace, view its performance data on the **Plugin** page in [Creator Center](https://creators.dify.ai/). Review individual ratings, likes, and feedback messages in [**Inbox**](https://creators.dify.ai/dashboard/inbox). ### Review Your Published Plugins Under your personal account, connect the GitHub account used to publish your plugins. If you have connected multiple accounts, select the account whose plugins you want to view. Each plugin card shows its downloads, overall rating, rating count, and likes. ### Review Plugin Performance and Feedback With Your Team Select the organization your team uses. Any plugins listed there are visible to all organization members. When creating a new organization for plugins, find the Plugin ID on the plugin's Marketplace details page. Enter the part before `/` in **Unique handle**. For example, if the Plugin ID is `team-name/plugin-name`, enter `team-name`. ![Plugin ID on the Marketplace Details Page](https://mintcdn.com/dify-enterprise-docs/jYo91hkhf89I9jZZ/images/develop-plugin/publish/marketplace-plugin-id.png?fit=max\&auto=format\&n=jYo91hkhf89I9jZZ\&q=85\&s=25e664e52b764cf069587129c532ea07) Plugin ID on the Marketplace Details Page Once the organization is verified as the publisher, its published plugins appear on the **Plugin** page. Invite teammates to view the same plugins without connecting their own GitHub accounts. #### Claim Missing Organization Plugins If a plugin published under your organization's name does not appear on the organization's **Plugin** page, open **Claim plugin** to request access to its performance data and feedback. 1. Under your personal account, select **Claim plugin**. 2. For each plugin, copy its Plugin ID from its Marketplace details page and pair it with the PR that originally published it. 3. Confirm your contact email and describe your role in maintaining the plugins. If a different GitHub account opened the PRs, explain why. 4. Select **Submit claim**. Track the request in **Claim history**. After approval, you can view all plugins from the claimed publisher. If the claim is rejected, review the reason and select **New Claim** to update the evidence and resubmit it. ## Related Resources > [card] [PR template](https://github.com/langgenius/dify-plugins/blob/main/.github/pull_request_template.md) > > Review the live template before submitting; repository requirements can evolve. > [card] [Plugin review guidelines](https://github.com/langgenius/dify-plugins/blob/main/docs/plugin-review-guidelines.md) > > See how maintainers inspect documentation, dependencies, privacy, and sensitive capabilities. # Plugin Development Guidelines Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/standards/contributor-covenant-code-of-conduct Requirements every Dify Marketplace plugin must meet to pass review, covering quality, language, privacy, IP, maintenance, and prohibited content By submitting a plugin to the Dify Marketplace, you agree to follow the requirements on this page. Meeting them up front gets your plugin through review faster and helps keep the Marketplace useful and trustworthy. ## Value and uniqueness * **Generative AI focus.** The plugin's core capability should integrate models, tools, or services that meaningfully extend AI applications on Dify. * **No functional duplicates.** Don't reskin an existing Marketplace plugin. Each plugin should be unique and stand on its own. * **Meaningful updates.** New versions must add real capability, not just metadata bumps. * **Explain new submissions.** In your PR description, say briefly why the plugin is needed and what gap it fills. ## Plugin checklist Before opening the publish PR, confirm each item: * **Unique name.** Search the Marketplace first. * **Brand alignment.** The plugin name reflects what it actually is. * **Works end-to-end.** Tested via [remote debugging](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin); production-ready. * **README in English** with setup steps, required credentials, and usage. No exaggerated claims, ads, self-promotion, offensive content, real user data in screenshots, or dead links. * **Clear error messages** for required fields and failure modes. * **Authentication steps documented in full**, with no skipped steps. * **Privacy policy ready.** See [Privacy Guidelines](/en/3.13.x/develop/plugins/publishing/standards/privacy-protection-guidelines). * **Credentials handled securely**, never hardcoded, never exposed. * **Performance acceptable.** Does not noticeably degrade Dify itself. ## Language English is the primary language for every user-facing string: plugin name, description, field labels, help text, error messages. Additional translations are welcome on top of English. ## Prohibited and restricted plugins | Category | Reason | | - | - | | **Prohibited**: misleading or malicious behavior | spam, phishing, credential theft, deceiving the review process | | **Prohibited**: offensive content | violence, hate speech, discrimination | | **Prohibited**: financial transactions | payments, asset transfers, token transfers | | **Restricted**: frequent defects | repeated submissions with critical bugs | | **Restricted**: unnecessary splitting | multiple plugins for the same API/auth; bundle them instead | | **Restricted**: duplicate submissions | re-submitting essentially the same plugin | Prohibited plugins are rejected. Restricted plugins may be delayed or asked to consolidate. ## Monetization **The Dify Marketplace currently accepts free plugins only.** Pricing policies, if introduced, will be announced separately. ## Trademarks and intellectual property * **You must have the rights** to any logo, trademark, or copyrighted material you include. We may ask for proof for recognizable third-party brands. * **Do not use Dify's logos** in your plugin assets. * **Image quality** must be sharp and well-cropped. No misleading or offensive icons. Dify may ask for changes or remove a plugin if a rights holder complains or if unauthorized use is found. ## Updates and versioning * **Announce breaking changes** in the plugin description or via GitHub Release Notes before users hit them. * **Update regularly** for bug fixes, Dify platform changes, security patches, and upstream-service changes. * **Deprecation notice.** If retiring a plugin, give users time to migrate and suggest alternatives where possible. ## Maintenance and support You own technical support for your plugin. Provide **at least one** support channel (GitHub repository or email) and keep it active. If a plugin is left unmaintained and the owner doesn't respond after a reasonable notification, Dify may tag it as `Maintenance Lacking` or `Potential Risk`, restrict new installs, and eventually unpublish it. ## Privacy and data You **must** declare whether your plugin collects personal data and, if so, what types. The full guidelines are in [Privacy Guidelines](/en/3.13.x/develop/plugins/publishing/standards/privacy-protection-guidelines). Your privacy policy must state: * What data is collected * How it is used * What is shared with third parties (with links to their privacy policies) Plugins that handle sensitive data (health, finance, children's information) get extra scrutiny. Collecting or transmitting user data without consent is grounds for removal. ## Review and discretion * Dify may reject or remove plugins that don't meet these requirements or that abuse the review process. * Reviews aim to land within a reasonable window; turnaround depends on submission volume and complexity. * Reviewers communicate via the support channel you provide; keep it monitored. ## Related resources * [Publishing Overview](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview) * [Publish a Plugin to Marketplace](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace#prepare-the-package) * [Privacy Guidelines](/en/3.13.x/develop/plugins/publishing/standards/privacy-protection-guidelines) * [Remote Debugging](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/remote-debug-a-plugin) # Privacy Guidelines Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/standards/privacy-protection-guidelines How to declare data collection and write the privacy policy required for every plugin submitted to the Dify Marketplace Every plugin submitted to the Dify Marketplace must be transparent about how it handles user data. This page tells you what to declare and how to write the policy reviewers expect. The whole submission boils down to one question: does your plugin collect or transmit any user personal data, either directly or through a third-party service it calls? If yes, list the data types and link a privacy policy. If no, say so explicitly. > [!NOTE] > > "Personal data" means any information that identifies a specific individual on its own or when combined with other data: anything that could locate, contact, or target a unique person. ## Identify the Data Your Plugin Handles Walk through the three categories below. Anything you collect, store, log, or send to a third party must be declared. ### Direct Identifiers * Full name, first name, last name * Email address * Phone number * Home address or other physical address * Government IDs (passport, driver's license, Social Security number, etc.) ### Indirect Identifiers * Device identifiers (IMEI, MAC address, device ID) * IP address * Location data (GPS coordinates, city, region) * Online identifiers (cookies, advertising IDs) * Usernames, profile pictures * Biometric data (fingerprints, facial recognition) * Browsing history, purchase history * Health or financial information ### Combinable Data Data that becomes identifying when joined with other data: * Age, gender * Occupation * Interests ### Third-Party Services Count Too Your plugin is responsible for what the services it calls collect. If your plugin uses Slack, you must reference [Slack's privacy policy](https://slack.com/trust/privacy/privacy-policy) and disclose what Slack receives. Before submitting, read the privacy policy of every third-party API the plugin touches and make sure your declaration covers it. ## Write the Privacy Policy Your policy, either a `PRIVACY.md` in the plugin repository or a hosted URL, must cover: * **What** is collected (from the categories above). * **How** it is used. * **Where** it goes, including any third parties and links to their policies. If you're unsure where to start, look at the privacy policy of any plugin published by the Dify team for a working template. ## Declare It in the Manifest The privacy URL goes in the plugin manifest. See [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) for the exact field. ## Common Questions > [accordion] What counts as 'collect and use' personal data? > > Any of: collecting, transmitting, storing, logging, sharing, or analyzing user data. Concrete examples: > > * Forms that gather personally identifiable information > * Login or third-party-auth flows > * Capturing user input that may contain PII > * Analytics that track user behavior or usage patterns > * Storing messages, chat logs, or email addresses > * Accessing connected social-media profiles > * Collecting health or fitness data > * Storing search queries or browsing behavior > * Processing financial information (bank details, credit scores, transactions) > [accordion] What if my plugin collects nothing? > > Say so explicitly in the privacy policy. Reviewers still expect a `PRIVACY.md` file or hosted URL; it just needs to state that no user data is collected, stored, or transmitted, including by any third-party services the plugin calls. > [accordion] My plugin handles sensitive data: what changes? > > Plugins that touch health, finance, biometrics, or children's data get extra review. Be explicit about each data type, the legal basis for collecting it, retention period, and how users can request deletion. ## Related Resources * [Publishing Overview](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-overview) * [Plugin Development Guidelines](/en/3.13.x/develop/plugins/publishing/standards/contributor-covenant-code-of-conduct) * [Prepare a Marketplace package](/en/3.13.x/develop/plugins/publishing/marketplace-listing/submit-plugin-to-marketplace#prepare-the-package) * [General Specifications](/en/3.13.x/develop/plugins/features-and-specs/plugin-types/general-specifications) # Sign Plugins for Third-Party Signature Verification Source: https://enterprise-docs.dify.ai/en/3.13.x/develop/plugins/publishing/standards/third-party-signature-verification Enable signed `.difypkg` installation in Dify Community Edition without disabling signature verification entirely (generate keys, sign packages, distribute the public key) > [!WARNING] > > Third-party signature verification is a **Dify Community Edition** feature. Dify Cloud manages signatures centrally and does not expose these controls. Self-hosted Dify enforces signature verification by default. Third-party signature verification lets administrators safely install plugins that are not on the Marketplace without disabling verification entirely. Two scenarios: > [card] Admin signs an approved plugin > > The admin reviews a `.difypkg` from a trusted developer and signs it with their own key before installing. > [card] Developer ships a signed plugin > > The developer signs the `.difypkg` and publishes the matching public key. Admins who trust the developer add that public key to the verification list. The mechanics are the same in both cases: generate a key pair, sign with the private key, verify with the public key. ## Generate a Key Pair ```bash theme={null} dify signature generate -f your_key_pair ``` Two files appear in the current directory: | File | Use | | :- | :- | | `your_key_pair.private.pem` | Sign plugins (keep secret) | | `your_key_pair.public.pem` | Verify signatures (share publicly) | > [!WARNING] > > Guard the private key. Anyone who has it can sign plugins that pass verification on installations trusting your public key. ## Sign and Verify a Plugin **1. Sign the package** ```bash theme={null} dify signature sign your_plugin_project.difypkg -p your_key_pair.private.pem ``` Produces `your_plugin_project.signed.difypkg` in the same directory. **2. Verify the signed package** ```bash theme={null} dify signature verify your_plugin_project.signed.difypkg -p your_key_pair.public.pem ``` Confirms the signature matches before you distribute or install. > [!NOTE] > > If you omit `-p`, `dify signature verify` checks against the Dify Marketplace public key. Any plugin not signed by Dify will fail verification in that mode. ## Enable Verification on the Daemon Admins install signed plugins by giving the plugin daemon a list of trusted public keys. **1. Place the public key** Put the `.public.pem` file somewhere the daemon container can reach it. For Docker Compose installs: ```bash theme={null} mkdir -p docker/volumes/plugin_daemon/public_keys cp your_key_pair.public.pem docker/volumes/plugin_daemon/public_keys/ ``` **2. Configure the daemon environment** Set these variables on the `plugin_daemon` service: | Variable | Value | | :- | :- | | `FORCE_VERIFYING_SIGNATURE` | `true` | | `THIRD_PARTY_SIGNATURE_VERIFICATION_ENABLED` | `true` | | `THIRD_PARTY_SIGNATURE_VERIFICATION_PUBLIC_KEYS` | Comma-separated paths to public keys inside the container | A `docker-compose.override.yaml` snippet: ```yaml theme={null} services: plugin_daemon: environment: FORCE_VERIFYING_SIGNATURE: true THIRD_PARTY_SIGNATURE_VERIFICATION_ENABLED: true THIRD_PARTY_SIGNATURE_VERIFICATION_PUBLIC_KEYS: /app/storage/public_keys/your_key_pair.public.pem ``` > [!NOTE] > > `docker/volumes/plugin_daemon` mounts to `/app/storage` inside the container, so the path in `THIRD_PARTY_SIGNATURE_VERIFICATION_PUBLIC_KEYS` must use the in-container path. **3. Restart Dify** ```bash theme={null} cd docker docker compose down docker compose up -d ``` Verified installs are now enforced: signed `.difypkg` files matching the configured public keys install cleanly; unsigned or mismatched ones are rejected. ## Related Resources * [Package as Local File and Share](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-by-file) * [Publish to Individual GitHub Repository](/en/3.13.x/develop/plugins/publishing/marketplace-listing/release-to-individual-github-repo) * [Plugin Development Guidelines](/en/3.13.x/develop/plugins/publishing/standards/contributor-covenant-code-of-conduct) * [Publishing FAQ](/en/3.13.x/develop/plugins/publishing/faq/faq)