Merge branch 'main' into main

This commit is contained in:
rishiraj
2025-08-13 20:45:01 +05:30
committed by GitHub
17 changed files with 1132 additions and 289 deletions

View File

@@ -12,6 +12,7 @@
"light": "https://assets-docs.dify.ai/2025/05/d05cfc6ebe48f725d171dc71c64a5d16.svg",
"dark": "https://assets-docs.dify.ai/2025/05/c51f1cda47c1d9a4a162d7736f6e4c53.svg"
},
"navigation": {
"versions": [
{
@@ -289,6 +290,7 @@
"en/plugins/quick-start/develop-plugins/README",
"en/plugins/quick-start/develop-plugins/initialize-development-tools",
"en/plugins/quick-start/develop-plugins/tool-plugin",
"en/plugins/quick-start/develop-plugins/tool-oauth",
{
"group": "Model Plugin",
"pages": [
@@ -389,6 +391,7 @@
"en/development/models-integration/gpustack",
"en/development/models-integration/aws-bedrock-deepseek",
"en/development/models-integration/truefoundry"
"en/development/models-integration/gpt-oss-local-deployment"
]
},
{
@@ -1048,7 +1051,8 @@
"zh-hans/development/models-integration/ollama",
"zh-hans/development/models-integration/litellm",
"zh-hans/development/models-integration/gpustack",
"zh-hans/development/models-integration/aws-bedrock-deepseek"
"zh-hans/development/models-integration/aws-bedrock-deepseek",
"zh-hans/development/models-integration/gpt-oss-local-deployment"
]
},
{
@@ -1691,7 +1695,8 @@
"ja-jp/development/models-integration/ollama",
"ja-jp/development/models-integration/litellm",
"ja-jp/development/models-integration/gpustack",
"ja-jp/development/models-integration/aws-bedrock-deepseek"
"ja-jp/development/models-integration/aws-bedrock-deepseek",
"ja-jp/development/models-integration/gpt-oss-local-deployment"
]
},
{

View File

@@ -0,0 +1,130 @@
---
title: " gpt-oss Local Deployment with Ollama and Dify "
---
# I. Introduction
The gpt-oss series is an open-source model first released by OpenAI in August 2025.
> gpt-oss:20b (fits systems with ~16 GB memory)
>
> gpt-oss:120b (designed for ≥ 60 GB memory)
You can run it locally with Ollama. No cloud calls. Data stays on your machine, which helps with privacy and latency.
Dify is an open-source platform for building AI Agents and Workflows. This guide shows how to run gpt-oss with Ollama and plug it into Dify for a private, high-performance setup.
* * *
# II. Environment Setup
## Step 1: Run gpt-oss with Ollama
1. Install Ollama
[Download](https://ollama.com/) and install for macOS, Windows, or Linux. If anything is unclear, see the [official docs](https://docs.dify.ai/en/development/models-integration/ollama#integrate-local-models-deployed-by-ollama).
2. Pull a model
```Bash
# Recommended for most dev machines
ollama pull gpt-oss:20b
# For large GPUs or multi-GPU hosts
ollama pull gpt-oss:120b
```
Both models are prequantized in **MXFP4** , suitable for local deployment.
3. Start Ollama
The default endpoint is http://localhost:11434.
## Step 2: Install Dify locally
See the [Dify docs](https://docs.dify.ai/en/getting-started/install-self-hosted/readme) for full instructions. Or follow the quick tutorial below.
### Prerequisites
Install [Docker](https://www.docker.com/products/docker-desktop/) and make sure Docker Engine is running.
![1](https://raw.githubusercontent.com/NanSike/image-host/main/images/1.png)
### Install steps
```Bash
git clone https://github.com/langgenius/Dify.git
cd Dify/docker
cp .env.example .env
docker compose up -d
```
![2](https://raw.githubusercontent.com/NanSike/image-host/main/images/2.png)
Open your local Dify instance and complete the initial setup.
![3](https://raw.githubusercontent.com/NanSike/image-host/main/images/3.png)
# III. Add the model and test chat
1. In **Settings → Model Providers → Ollama** , click **Add Ollama model type** .
![4](https://raw.githubusercontent.com/NanSike/image-host/main/images/4.png)
2. Set **Base URL** to `http://localhost:11434`, select **Model name** `gpt-oss:20b`, and fill in the required fields.
![5](https://raw.githubusercontent.com/NanSike/image-host/main/images/5.png)
3. Create a blank template
![6](https://raw.githubusercontent.com/NanSike/image-host/main/images/6.png)
4. Select the app or workflow type you want to build.
![7](https://raw.githubusercontent.com/NanSike/image-host/main/images/7.png)
* * *
# IV. Verification and Usage
* On Difys **model testing** page, send a prompt and check that the response looks correct.
* In a workflow, add an **LLM** node, select `gpt-oss:20b`, and connect the nodes end to end.
![8](https://raw.githubusercontent.com/NanSike/image-host/main/images/8.png)
![9](https://raw.githubusercontent.com/NanSike/image-host/main/images/9.png)
* * *
# V. Appendix — FAQ and tips
**Model Pull Is Slow**
* *Configure a Docker proxy or use an image mirror to speed up downloads.*
**Insufficient GPU Memory**
* *Use* *`gpt-oss:20b`*. You can enable CPU offloading, but responses will be slower.*
**Port Access Issues**
* *Check firewall rules, port bindings, and Docker network settings to ensure connectivity.*

View File

@@ -13,7 +13,7 @@ Dify allows integration with LocalAI for local deployment of large language mode
You can refer to the official [Getting Started](https://localai.io/basics/getting_started/) guide for deployment, or quickly integrate following the steps below:
(These steps are derived from [LocalAI Data query example](https://github.com/go-skynet/LocalAI/blob/master/examples/langchain-chroma/README))
(These steps are derived from [LocalAI Data query example](https://github.com/mudler/LocalAI-examples/tree/main/langchain-chroma/README.md))
1. First, clone the LocalAI code repository and navigate to the specified directory.

View File

@@ -2,14 +2,32 @@
title: Embedding In Websites
---
Dify supports embedding your AI application into your business website, enabling you to build an AI customerservice chatbot, knowledgebase Q&A, and other applications with business data in just minutes.
Dify Apps can be embedded in websites using an iframe. This allows you to integrate your Dify App into your website, blog, or any other web page.
You can embed your AI application in three different ways: using an `<iframe>` tag, using a `<script>` tag, or installing the Dify Chrome extension.
When use Dify Chatbot Bubble Button embed in your website, you can customize the button style, position, and other settings.
Click the **Embed** button on the WebApp card, copy the embed code, and paste it into the target location on your site.
## Using the `<iframe>` Tag
Copy the `<iframe>` code into the element on your site where the AI application should appear, such as a `<div>` or `<section>`.
## Using the `<script>` Tag
Copy the `<script>` code into your sites `<head>` or `<body>` tag.
This will display a Dify chatbot bubble button on your site.
If you paste the `<script>` code into the sites `<body>`, you will get a fullpage AI chatbot.
## Installing the Dify Chrome Extension
Follow the prompts to install the [Dify Chatbot Chrome extension](https://chromewebstore.google.com/detail/dify-chatbot/ceehdapohffmjmkdcifjofadiaoeggaf).
## Customizing the Dify Chatbot Bubble Button
The Dify Chatbot Bubble Button can be customized through the following configuration options:
When you embed the Dify chatbot bubble button (i.e., embedding via the `<script>` tag), you can customize the buttons style, position, and other settings.
The Dify chatbot bubble button can be customized with the following configuration options:
```javascript
window.difyChatbotConfig = {
@@ -25,131 +43,138 @@ window.difyChatbotConfig = {
draggable: false,
// Optional, The axis along which the button is allowed to be dragged, default is `both`, can be `x`, `y`, `both`
dragAxis: 'both',
// Optional, An object of system variables that set in the dify chatbot
systemVariables: {
// key is the system variable name
// e.g.
// user_id: "YOU CAN DEFINE USER ID HERE",
// conversation_id: "YOU CAN DEFINE CONVERSATION ID HERE, IT MUST BE A VALID UUID"
},
// Optional, An object of inputs that set in the dify chatbot
inputs: {
// key is the variable name
// e.g.
// name: "NAME"
},
// Optional, An object of system variables that set in the dify chatbot
systemVariables: {
// e.g.
// user_id: 'USER_ID',
// conversation_id: 'CONVERSATION_ID',
},
// Optional, An object of user variables that set in the dify chatbot
userVariables: {
// e.g.
// avatar_url: 'AVATAR_URL',
// name: 'NAME',
},
}
}
```
## Overriding Default Button Styles
### Overriding Default Button Styles
You can override the default button style using CSS variables or the `containerProps` option. Apply these methods based on CSS specificity to achieve your desired customizations.
You can override the default button styles using CSS variables or the `containerProps` option, according to CSS specificity rules.
### 1.Modifying CSS Variables
* **Modify CSS Variables**
The following CSS variables are supported for customization:
The following CSS variables are supported:
```css
/* Button distance to bottom, default is `1rem` */
--dify-chatbot-bubble-button-bottom
```css
/* Distance from bottom, default `1rem` */
--dify-chatbot-bubble-button-bottom
/* Button distance to right, default is `1rem` */
--dify-chatbot-bubble-button-right
/* Distance from right, default `1rem` */
--dify-chatbot-bubble-button-right
/* Button distance to left, default is `unset` */
--dify-chatbot-bubble-button-left
/* Distance from left, default `unset` */
--dify-chatbot-bubble-button-left
/* Button distance to top, default is `unset` */
--dify-chatbot-bubble-button-top
/* Distance from top, default `unset` */
--dify-chatbot-bubble-button-top
/* Button background color, default is `#155EEF` */
--dify-chatbot-bubble-button-bg-color
/* Background color, default `#155EEF` */
--dify-chatbot-bubble-button-bg-color
/* Button width, default is `50px` */
--dify-chatbot-bubble-button-width
/* Width, default `50px` */
--dify-chatbot-bubble-button-width
/* Button height, default is `50px` */
--dify-chatbot-bubble-button-height
/* Height, default `50px` */
--dify-chatbot-bubble-button-height
/* Button border radius, default is `25px` */
--dify-chatbot-bubble-button-border-radius
/* Border radius, default `25px` */
--dify-chatbot-bubble-button-border-radius
/* Button box shadow, default is `rgba(0, 0, 0, 0.2) 0px 4px 8px 0px)` */
--dify-chatbot-bubble-button-box-shadow
/* Box shadow, default `rgba(0, 0, 0, 0.2) 0px 4px 8px 0px` */
--dify-chatbot-bubble-button-box-shadow
/* Button hover transform, default is `scale(1.1)` */
--dify-chatbot-bubble-button-hover-transform
```
/* Hover transform, default `scale(1.1)` */
--dify-chatbot-bubble-button-hover-transform
```
To change the background color to #ABCDEF, add this CSS:
Example: change background color to `#ABCDEF`:
```css
#dify-chatbot-bubble-button {
--dify-chatbot-bubble-button-bg-color: #ABCDEF;
}
```
```css
#dify-chatbot-bubble-button {
--dify-chatbot-bubble-button-bg-color: #ABCDEF;
}
```
### 2.Using `containerProps`
* **Use `containerProps`**
Set inline styles using the `style` attribute:
Inline style:
```javascript
window.difyChatbotConfig = {
// ...other config
containerProps: {
style: {
backgroundColor: '#ABCDEF',
width: '60px',
height: '60px',
borderRadius: '30px',
},
// For minor overrides, you can also use a string:
// style: 'background-color:#ABCDEF;width:60px;'
},
};
```
CSS class:
```javascript
window.difyChatbotConfig = {
// ...other config
containerProps: {
className: 'dify-chatbot-bubble-button-custom my-custom-class',
},
};
```
## Passing `inputs` to the Embedded App
You can pass initial inputs to your embedded AI application. Four input types are supported:
1. **`text-input`**: Accepts any value; truncated if it exceeds the maximum length.
2. **`paragraph`**: Similar to `text-input`; accepts any value and truncates if too long.
3. **`number`**: Accepts a number or numeric string; strings are converted via `Number`.
4. **`options`**: Accepts any value matching a preconfigured option.
The method differs depending on whether you embed via `<iframe>` or `<script>`.
Example: variable `name` with value `apple`.
### Using the `<iframe>` Tag
For `<iframe>` embedding, append the parameter to the URL:
1. GZIPcompress the value.
2. Base64encode it.
3. `encodeURIComponent` the result.
Example result for `apple`:
`http://localhost/chatbot/{token}?name=H4sIAAAAAAAAA0ssKMhJBQBQ0C6pBQAAAA%3D%3D`
### Using the `<script>` Tag
For `<script>` embedding, pass inputs via the config:
```javascript
window.difyChatbotConfig = {
// ... other configurations
containerProps: {
style: {
backgroundColor: '#ABCDEF',
width: '60px',
height: '60px',
borderRadius: '30px',
},
// For minor style overrides, you can also use a string value for the `style` attribute:
// style: 'background-color: #ABCDEF; width: 60px;',
},
}
```
Apply CSS classes using the `className` attribute:
```javascript
window.difyChatbotConfig = {
// ... other configurations
containerProps: {
className: 'dify-chatbot-bubble-button-custom my-custom-class',
},
}
```
### 3. Passing `inputs`
There are four types of inputs supported:
1. **`text-input`**: Accepts any value. The input string will be truncated if its length exceeds the maximum allowed length.
2. **`paragraph`**: Similar to `text-input`, it accepts any value and truncates the string if it's longer than the maximum length.
3. **`number`**: Accepts a number or a numerical string. If a string is provided, it will be converted to a number using the `Number` function.
4. **`options`**: Accepts any value, provided it matches one of the pre-configured options.
Example configuration:
```javascript
window.difyChatbotConfig = {
// Other configuration settings...
// ...other config
inputs: {
name: 'apple',
},
}
};
```
Note: When using the embed.js script to create an iframe, each input value will be processed—compressed using GZIP and encoded in base64—before being appended to the URL.
For example, the URL with processed input values will look like this:
`http://localhost/chatbot/{token}?name=H4sIAKUlmWYA%2FwWAIQ0AAACDsl7gLuiv2PQEUNAuqQUAAAA%3D`
{/*
Contributing Section
DO NOT edit this section!

View File

@@ -0,0 +1,379 @@
---
title: "Adding OAuth Support to Your Tool Plugin"
---
![b0e673ba3e339b31ac36dc3cd004df04787bcaa64bb6d2cac6feb7152b7b515f.png](/images/b0e673ba3e339b31ac36dc3cd004df04787bcaa64bb6d2cac6feb7152b7b515f.png)
This guide teachs 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:
### Flow 1: OAuth Client Setup (Admin / Developer Flow)
<Note>
On Dify Cloud, Dify team would create OAuth apps for popular tool plugins and set up OAuth clients, saving users the trouble to configure this themselves.
\
Admins of Self-Hosted Dify instances must go through this set up flow.
</Note>
Dify instance's admin / developer first need to register an OAuth app at the third-party service as a trusted application. From this, they'll be able to obtain the necessary credentials to configure the Dify tool provider as an OAuth client. As an example, here are the steps to setting up an OAuth client for Dify's Gmail tool provider:
<AccordionGroup>
<Accordion title="Create a Google Cloud Project">
1. Go to [Google Cloud Console](https://console.cloud.google.com) and create a new project, or select existing one
2. Enable the required APIs (e.g., Gmail API)
</Accordion>
<Accordion title="Configure OAuth Consent Screen:">
1. Navigate to "APIs & Services" → "OAuth consent screen"
2. Choose "External" user type for public plugins
3. Fill in 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>
<Accordion title="Create OAuth 2.0 Credentials">
1. Go to "APIs & Services" → "Credentials"
2. Click "Create Credentials" → "OAuth 2.0 Client IDs"
3. Choose "Web application" type
4. A`client_id` and a`client_secret` will be generated. Save these as the credentials.
</Accordion>
<Accordion title="Enter Credentials in Dify">
Enter the client_id and aclient_secret on the OAuth Client configuration popup to set up the tool provider as a client.
<img
src="/images/acd5f5057235c3a0c554abaedcf276fb48f80567f0231eae9158a795f8e1c45d.png"
alt="acd5f5057235c3a0c554abaedcf276fb48f80567f0231eae9158a795f8e1c45d.png"
title="acd5f5057235c3a0c554abaedcf276fb48f80567f0231eae9158a795f8e1c45d.png"
className="mx-auto"
style={{ width:"66%" }}
/>
</Accordion>
<Accordion title="Authorize Redirect URI">
Register the redirect URI generated by Dify on the Google OAuth Client's page:
<img
src="/images/dfe60a714a275c5bf65f814673bd2f0a0db4fda27573a2f0b28a1c39e4c61da2.png"
alt="dfe60a714a275c5bf65f814673bd2f0a0db4fda27573a2f0b28a1c39e4c61da2.png"
title="dfe60a714a275c5bf65f814673bd2f0a0db4fda27573a2f0b28a1c39e4c61da2.png"
className="mx-auto"
style={{ width:"77%" }}
/>
<Info>
Dify displays the `redirect_uri` in the OAuth Client configuration popup. It usually follows the format:
```bash
https://{your-dify-domain}/console/api/oauth/plugin/{plugin-id}/{provider-name}/{tool-name}/callback
```
For self-hosted Dify, the \{your-dify-domain\} should be consistent with the `CONSOLE_WEB_URL`.
</Info>
</Accordion>
</AccordionGroup>
<Tip>
Each service has unique requirements, so always consult the specific OAuth documentation for the services you're integrating with.
</Tip>
### Flow 2: User Authorization (Dify User Flow)
After configuring OAuth clients, individual Dify users can now authorize your plugin to access their personal accounts.
<img
src="/images/833c205f5441910763b27d3e3ff0c4449a730a690da91abc3ce032c70da04223.png"
alt="833c205f5441910763b27d3e3ff0c4449a730a690da91abc3ce032c70da04223.png"
title="833c205f5441910763b27d3e3ff0c4449a730a690da91abc3ce032c70da04223.png"
className="mx-auto"
style={{ width:"67%" }}
/>
## Implementation
### 1. Define OAuth schema in provider manifest
The `oauth_schema` section of the provider manifest definitions tell Dify what credentials your plugin OAuth needs and what the OAuth flow will produce. Two schemas are required for setting up OAuth:
#### client_schema
This defines the input for OAuth client setup:
```yaml gmail.yaml
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
```
<Info>
The `url` field links directly to help documentations for the third-party service. This helps confused admins / developers.
</Info>
#### credentials_schema
Specifies what the user authorization flow produces (Dify manages these automatically):
```yaml
# also under oauth_schema
credentials_schema:
- name: "access_token"
type: "secret-input"
- name: "refresh_token"
type: "secret-input"
- name: "expires_at"
type: "secret-input"
```
<Info>
Include both `oauth_schema` and `credentials_for_provider` to offer OAuth \+ API key auth options.
</Info>
### 2. Complete required OAuth methods in Tool Provider
Add these imports to where your `ToolProvider` is implemented:
```python
from dify_plugin.entities.oauth import ToolOAuthCredentials
from dify_plugin.errors.tool import ToolProviderCredentialValidationError, ToolProviderOAuthError
```
Your `ToolProvider` class must implement these three OAuth methods (taking `GmailProvider` as an example):
<Warning>
Under no circumstances should the `client_secret` be returned in the credentials of `ToolOAuthCredentials`, as this could lead to security issues.
</Warning>
<CodeGroup>
```python _oauth_get_authorization_url expandable
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
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 creates 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
def _oauth_refresh_credentials(
self, redirect_uri: str, system_credentials: Mapping[str, Any], credentials: Mapping[str, Any]
) -> ToolOAuthCredentials:
"""
Refresh the credentials using 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)}")
```
</CodeGroup>
### 3. Access Tokens in Your Tools
You may use OAuth credentials to make authenticated API calls in your `Tool` implementation like so:
```python
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, you can use `self.runtime.credential_type` to differentiate between the two authentication types.
### 4. Specifying the Correct Versions
Previous versions of the plugin SDK and Dify do not support OAuth authentication. Therefore, you need to set the plugin SDK version to:
```
dify_plugin>=0.4.2,<0.5.0.
```
In `manifest.yaml`, add the minimum Dify version:
```yaml
meta:
version: 0.0.1
arch:
- amd64
- arm64
runner:
language: python
version: "3.12"
entrypoint: main
minimum_dify_version: 1.7.1
```
{/*
Contributing Section
DO NOT edit this section!
It will be automatically generated by the script.
*/}
---
[Edit this page](https://github.com/langgenius/dify-docs/edit/main/en/plugins/quick-start/develop-plugins/tool-oauth.mdx) | [Report an issue](https://github.com/langgenius/dify-docs/issues/new?template=docs.yml)

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

View File

@@ -0,0 +1,99 @@
---
title: " OllamaDify による gpt-oss のローカルデプロイ"
---
## はじめに
gpt-ossシリーズは、2025年8月にOpenAIからリリースされたオープンソースモデルです。
- gpt-oss:20b約16GBのメモリを持つシステム向け
- gpt-oss:120b60GB以上のメモリに対応
ローカルでOllamaを使用して実行できます。クラウド呼び出しは不要で、データは常にローカルに保存され、プライバシー保護と低遅延に貢献します。
DifyはAIエージェントやワークフローを構築するためのオープンソースプラットフォームです。このガイドでは、Ollamaを使ってgpt-ossを実行し、Difyに接続してプライベートかつ高性能な設定を行う方法を示します。
## 環境のセットアップ
### ステップ1Ollamaでgpt-ossを実行する
**1. Ollamaをインストール**
[Ollamaの公式サイト](https://ollama.com/)を通してmacOS、Windows、またはLinux用にダウンロードしてインストールしてください。
**2. gpt-ossモデルをインストール**
```Bash
# 開発マシン用におすすめ
ollama pull gpt-oss:20b
# 大規模GPUまたはマルチGPUホスト用におすすめ
ollama pull gpt-oss:120b
```
これらのモデルはすでに混合精度フォーマットMXFP4で量子化されており、ローカルデプロイに適しています。
**3. Ollamaの起動**
デフォルトのエンドポイントはhttp://localhost:11434です。
### ステップ2Difyをローカルにインストール
Difyの[公式ドキュメント](https://docs.dify.ai/ja-jp/getting-started/install-self-hosted/readme)に完全な手順があります。もしくはこちらのシンプルなチュートリアルをご覧ください。
**前提条件**
[Docker](https://www.docker.com/products/docker-desktop/)をインストールし、Dockerエンジンが正常に動作していることを確認してください。
![1](https://raw.githubusercontent.com/NanSike/image-host/main/images/1.png)
**インストール手順**
```Bash
git clone https://github.com/langgenius/Dify.git
cd Dify/docker
cp .env.example .env
docker compose up -d
```
![2](https://raw.githubusercontent.com/NanSike/image-host/main/images/2.png)
ローカルDifyインスタンスを開き、初期設定を完了させてください。
![3](https://raw.githubusercontent.com/NanSike/image-host/main/images/3.png)
## モデルの追加とチャットのテスト
1. **設定 > モデルプロバイダー > Ollama** に移動し、**「Ollamaモデルタイプを追加」**をクリックしてください。
![4](https://raw.githubusercontent.com/NanSike/image-host/main/images/4.png)
2. 基本URLを`http://localhost:11434`に設定し、モデル名に`gpt-oss`を選択し、必要なフィールドを埋めてください。
![5](https://raw.githubusercontent.com/NanSike/image-host/main/images/5.png)
3. 空のテンプレートを作成します。
![6](https://raw.githubusercontent.com/NanSike/image-host/main/images/6.png)
4. 構築したいアプリのタイプを選択してください。
![7](https://raw.githubusercontent.com/NanSike/image-host/main/images/7.png)
## 検証と使用
- Difyの**モデルテスト**ページでプロンプトを送信し、応答が期待通りであることを確認してください。
- ワークフローに**LLMード**を追加し、`gpt-oss:20b`を選択してノードをエンドツーエンドで接続してください。
![8](https://raw.githubusercontent.com/NanSike/image-host/main/images/8.png)
![9](https://raw.githubusercontent.com/NanSike/image-host/main/images/9.png)
## よくある質問
1. モデルのダウンロードが遅い
ダウンロードを高速化するために、Dockerプロキシを設定するか、イメージミラーを使用してください。
2. GPUメモリ不足
`gpt-oss:20b`を使用してください。CPUオフローディングを有効にすることもできますが、その場合は応答が遅くなります。
3. ポートアクセスの問題
接続を確認するために、ファイアウォールのルール、ポートのバインディング、およびDockerネットワーク設定を確認してください。

View File

@@ -16,7 +16,7 @@ Difyは、LocalAIでデプロイされた大型言語モデルの推論および
公式の[入門ガイド](https://localai.io/basics/getting_started/)を参考にデプロイを行うか、以下の手順で迅速に接続を行うことができます:
(以下の手順は[LocalAI Data query example](https://github.com/go-skynet/LocalAI/blob/master/examples/langchain-chroma/README)から引用しています)
(以下の手順は[LocalAI Data query example](https://github.com/mudler/LocalAI-examples/tree/main/langchain-chroma/README.md)から引用しています)
1. まず、LocalAIのコードリポジトリをクローンし、指定のディレクトリに移動します

View File

@@ -2,154 +2,188 @@
title: Webサイトへの埋め込み
---
Dify は、AI アプリケーションをビジネスウェブサイトに埋め込むことをサポートしており、数分でビジネスデータを使用した公式サイトの AI カスタマーサービス、ビジネス知識の Q&A などのアプリケーションを構築できます。
Dify Apps は iframe を使用してWebサイトに埋め込むことができます。これにより、Dify App をWebサイト、ブログ、またはその他のウェブページに統合できます。
AI アプリケーションをウェブサイトに埋め込む方法は 3 つあります:`<iframe>` タグ方式、`<script>` タグ方式、および Dify Chrome ブラウザ拡張機能のインストール方式です。
Dify Chatbot Bubble Button をWebサイトに埋め込む際に、ボタンのスタイル、位置、その他の設定をカスタマイズできます。
WebApp カードの埋め込みボタンをクリックし、埋め込みコードをコピーして、サイトの目標位置に貼り付けます。
## Dify Chatbot Bubble Button のカスタマイズ
## `<iframe>` タグ方式の使用
Dify Chatbot Bubble Button は、以下の設定オプションでカスタマイズできます。
`<iframe>` コードを、AI アプリケーションを表示するウェブサイトのタグ(`<div>`、`<section>` など)にコピーします。
<Frame caption="埋め込みコードの例">
<img src="https://assets-docs.dify.ai/dify-enterprise-mintlify/zh_CN/guides/application-publishing/1e2e8c9adc620f9d6b4ea157119e8659.png" alt="ウェブサイト埋め込みのコード例を表示" />
</Frame>
## `<script>` タグ方式の使用
`<script>` コードをウェブサイトの `<head>` または `<body>` タグにコピーします。これにより、ウェブサイトに Dify チャットボットのバブルボタンが表示されます。
script コードを公式サイトの `<body>` に貼り付けると、公式サイトの AI ロボットが表示されます:
<Frame caption="埋め込み後の AI ロボット効果">
<img src="https://assets-docs.dify.ai/dify-enterprise-mintlify/zh_CN/guides/application-publishing/f5a5e95e1120906669b3c1ad4e186dea.png" alt="ウェブサイトに埋め込まれた後の AI ロボット効果を表示" />
</Frame>
## Dify Chrome ブラウザ拡張機能のインストール方式
プロンプトに従って、[Dify Chrome ブラウザ拡張機能](https://chromewebstore.google.com/detail/dify-chatbot/ceehdapohffmjmkdcifjofadiaoeggaf)をインストールします。
## Dify チャットボットバブルボタンのカスタマイズ
ウェブサイトに Dify チャットボットバブルボタンを使用する場合(つまり、`<script>` タグ方式で AI アプリケーションをウェブサイトに埋め込む場合)、ボタンのスタイル、位置、その他の設定をカスタマイズできます。
Dify チャットボットバブルボタンは、以下の設定オプションでカスタマイズできます:
```javascript
window.difyChatbotConfig = {
// 必須Dify によって自動的に生成されます
// 必須Dify によって自動的に生成されます
token: 'YOUR_TOKEN',
// オプションデフォルトは false です
// オプションデフォルトは false です
isDev: false,
// オプションisDev が true の場合、デフォルトは '[https://dev.udify.app](https://dev.udify.app)'、それ以外の場合は '[https://udify.app](https://udify.app)' です
// オプションisDev が true の場合、デフォルトは 'https://dev.udify.app'、それ以外の場合は 'https://udify.app' です
baseUrl: 'YOUR_BASE_URL',
// オプション`id` 以外の有効な HTMLElement 属性(例:`style`、`className` など)を受け入れます
// オプション`id` 以外の有効な HTMLElement 属性(例:`style`、`className` など)を受け入れます
containerProps: {},
// オプションボタンのドラッグを許可するかどうか、デフォルトは `false` です
// オプションボタンのドラッグを許可するかどうか、デフォルトは `false` です
draggable: false,
// オプションボタンのドラッグを許可する軸、デフォルトは 'both'、'x'、'y'、'both' のいずれかを指定できます
// オプションボタンのドラッグを許可する軸、デフォルトは `both`、`x`、`y`、`both` のいずれかを指定できます
dragAxis: 'both',
// オプション:dify チャットボットに設定されている入力オブジェクト
// オプションdify チャットボットに設定されている入力オブジェクト
inputs: {
// key は変数名です
// 例:
// キーは変数名です
// 例
// name: "NAME"
},
// オプションdify チャットボットに設定されているシステム変数
// オプションdify チャットボットに設定されているシステム変数
systemVariables: {
// 例:
// 例
// user_id: 'USER_ID',
// conversation_id: 'CONVERSATION_ID',
},
// オプションdify チャットボットに設定されているユーザー情報変数
// オプションdify チャットボットに設定されているユーザー情報変数
userVariables: {
// 例:
// 例
// avatar_url: 'AVATAR_URL',
// name: 'NAME',
},
};
```
## デフォルトボタンスタイルの上書き
### デフォルトボタンスタイルの上書き
CSS 変数または `containerProps` オプションを使用して、デフォルトのボタンスタイルを上書きできます。CSSの優先度に基づいてこれらの方法を適用し、希望のカスタマイズを実現します。
CSS 変数または `containerProps` オプションを使用して、CSS の優先度ルールに従ってデフォルトのボタンスタイルを上書きできます。
### 1.CSS 変数の変更
* **CSS 変数の変更**
以下の CSS 変数をカスタマイズに使用できます
カスタマイズには以下の CSS 変数がサポートされています
```css
/* ボタンの下端からの距離、デフォルトは `1rem` */
--dify-chatbot-bubble-button-bottom
```css
/* 下端からの距離、デフォルトは `1rem` */
--dify-chatbot-bubble-button-bottom
/* 右端からの距離、デフォルトは `1rem` */
--dify-chatbot-bubble-button-right
/* 左端からの距離、デフォルトは `unset` */
--dify-chatbot-bubble-button-left
/* 上端からの距離、デフォルトは `unset` */
--dify-chatbot-bubble-button-top
/* 背景色、デフォルトは `#155EEF` */
--dify-chatbot-bubble-button-bg-color
/* 幅、デフォルトは `50px` */
--dify-chatbot-bubble-button-width
/* 高さ、デフォルトは `50px` */
--dify-chatbot-bubble-button-height
/* 角丸、デフォルトは `25px` */
--dify-chatbot-bubble-button-border-radius
/* ボックスシャドウ、デフォルトは `rgba(0, 0, 0, 0.2) 0px 4px 8px 0px)` */
--dify-chatbot-bubble-button-box-shadow
/* ホバー時の変形、デフォルトは `scale(1.1)` */
--dify-chatbot-bubble-button-hover-transform
```
例えば、ボタンの背景色を #ABCDEF に変更するには、以下の CSS を追加します:
```css
#dify-chatbot-bubble-button {
--dify-chatbot-bubble-button-bg-color: #ABCDEF;
}
```
/* ボタンの右端からの距離、デフォルトは `1rem` */
--dify-chatbot-bubble-button-right
* **`containerProps` オプションの使用**
/* ボタンの左端からの距離、デフォルトは `unset` */
--dify-chatbot-bubble-button-left
/* ボタンの上端からの距離、デフォルトは `unset` */
--dify-chatbot-bubble-button-top
/* ボタンの背景色、デフォルトは `#155EEF` */
--dify-chatbot-bubble-button-bg-color
/* ボタンの幅、デフォルトは `50px` */
--dify-chatbot-bubble-button-width
/* ボタンの高さ、デフォルトは `50px` */
--dify-chatbot-bubble-button-height
/* ボタンの角丸、デフォルトは `25px` */
--dify-chatbot-bubble-button-border-radius
/* ボタンのボックスシャドウ、デフォルトは `rgba(0, 0, 0, 0.2) 0px 4px 8px 0px)` */
--dify-chatbot-bubble-button-box-shadow
/* ボタンホバー時の変形、デフォルトは `scale(1.1)` */
--dify-chatbot-bubble-button-hover-transform
```
例えば、ボタンの背景色を #ABCDEF に変更するには、次の CSS を追加します。
```css
#dify-chatbot-bubble-button {
--dify-chatbot-bubble-button-bg-color: #ABCDEF;
}
```
### 2.`containerProps` を使用する
`style` 属性を使用してインラインスタイルを設定します。
```javascript
window.difyChatbotConfig = {
// ... 他の設定
containerProps: {
style: {
backgroundColor: '#ABCDEF',
width: '60px',
height: '60px',
borderRadius: '30px',
`style` 属性を使用してインラインスタイルを設定:
```javascript
window.difyChatbotConfig = {
// ... 他の設定
containerProps: {
style: {
backgroundColor: '#ABCDEF',
width: '60px',
height: '60px',
borderRadius: '30px',
},
// 軽微なスタイル変更の場合、`style` 属性の値として文字列も使用できます:
// style: 'background-color: #ABCDEF; width: 60px;',
},
// ちょっとしたスタイル変更の場合、style 属性に文字列を使用することもできます。
// style: 'background-color: #ABCDEF; width: 60px;',
},
};
```
}
```
`className` 属性を使用して CSS クラスを適用:
```javascript
window.difyChatbotConfig = {
// ... 他の設定
containerProps: {
className: 'dify-chatbot-bubble-button-custom my-custom-class',
},
};
```
`className` 属性を使用して CSS クラスを適用します:
## 埋め込みウェブサイトのアプリケーションに `inputs` を渡す
埋め込んだ AI アプリケーションに初期入力を渡すことができます。4 種類の入力タイプがサポートされています:
1. **`text-input`**:任意の値を受け入れます。入力文字列の長さが許可される最大長を超える場合、切り詰められます。
2. **`paragraph`**`text-input` と同様に、任意の値を受け入れ、文字列の長さが最大長を超える場合は切り詰められます。
3. **`number`**:数値または数値文字列を受け入れます。文字列が提供された場合、`Number` 関数を使用して数値に変換されます。
4. **`options`**:事前に設定されたオプションのいずれかと一致する任意の値を受け入れます。
`<iframe>` タグ方式と `<script>` タグ方式で AI アプリケーションをウェブサイトに埋め込む場合、`inputs` を渡す方法も異なります。
以下では、変数名が `name`、値が `apple` の場合を例に説明します。
### `<iframe>` タグ方式の使用
AI アプリケーションが `<iframe>` タグ方式でウェブサイトに埋め込まれている場合、URL にパラメータを追加する方式で `inputs` を渡すことができます。
渡される変数の値を最初に GZIP で圧縮し、base64 でエンコードし、得られた base64 値を encodeURIComponent でエンコードしてから、URL に追加する必要があります。
例えば、変数名が `name`、値が `apple` の場合、まず `apple` を圧縮して base64 エンコード `H4sIAAAAAAAAA0ssKMhJBQBQ0C6pBQAAAA==` を得て、次に encodeURIComponent でエンコードして `H4sIAAAAAAAAA0ssKMhJBQBQ0C6pBQAAAA%3D%3D` を得ます。最終的な入力値 URL は次のようになります: `http://localhost/chatbot/{token}?name=H4sIAAAAAAAAA0ssKMhJBQBQ0C6pBQAAAA%3D%3D`。
### `<script>` タグ方式の使用
AI アプリケーションが `<script>` タグ方式でウェブサイトに埋め込まれている場合、前述の設定オプションを通じて `inputs` を渡すだけです。設定例:
```javascript
window.difyChatbotConfig = {
// ... 他の設定
containerProps: {
className: 'dify-chatbot-bubble-button-custom my-custom-class',
},
};
```
### 3. `inputs` の渡し方
サポートされている入力タイプは4種類あります
1. **`text-input`**:任意の値を受け入れます。入力文字列の長さが許容される最大長を超える場合、切り詰められます。
2. **`paragraph`**`text-input` と同様に、任意の値を受け入れ、文字列が最大長を超える場合には切り詰められます。
3. **`number`**:数値または数値の文字列を受け入れます。文字列が提供された場合、`Number` 関数を使用して数値に変換されます。
4. **`options`**:事前に設定されたオプションのいずれかと一致する値を受け入れます。
設定例:
```javascript
window.difyChatbotConfig = {
// 他の設定項目...
inputs: {
name: 'apple',
},
}
```
注意: `embed.js` スクリプトを使用してiframeを作成する場合、各入力値はURLに追加される前にGZIPで圧縮され、base64でエンコードされます。
例えば、処理された入力値を含むURLは以下のようになります
`http://localhost/chatbot/{token}?name=H4sIAKUlmWYA%2FwWAIQ0AAACDsl7gLuiv2PQEUNAuqQUAAAA%3D`
{/*
Contributing Section
DO NOT edit this section!

View File

@@ -0,0 +1,152 @@
---
title: " gpt-oss + Ollama 本地化部署指南 "
---
# 一、引言
* gpt-oss 系列是 OpenAI 于 2025 年 8 月首次发布的开源模型。
> gpt-oss:20b适用于约 16GB 的内存)
>
> gpt-oss:120b适用于≥ 60GB 的内存)
* 使用 Ollama 在本地部署,无需向云端发送 API 请求。数据始终在本地运行,适用于对隐私和响应速度有要求的场景。
* Dify 是一个开源的 LLM 应用平台,支持集成本地模型、快速构建 AI 应用程序和 RAG 流程。
**目标:** 展示如何使用 Ollama 在本地部署 gpt-oss 并将其集成到 Dify 中,以构建一个私有且安全的 LLM 服务。
* * *
# **二、环境准备**
## **第一步:使用 Ollama 本地部署 gpt-oss 模型**
1. 安装 Ollama
访问 [Ollama 官网](https://ollama.com)下载安装,根据操作系统选择 macOS、Windows 或 Linux 版本。
2. 拉取 gpt-oss 模型
* gpt-oss:20b推荐日常开发机器需 ≥16GB 显存或统一内存) `ollama pull gpt-oss:20b`
* gpt-oss:120b需 ≥60GB 显存或多 GPU 支持) `ollama pull gpt-oss:120b`
这两个模型均默认已量化为 MXFP4 格式,适合大多数本地部署场景
3. 启动 Ollama 服务
服务默认监听在: http://localhost:11434。
## **第二步:本地部署 Dify 并准备接入**
详细内容参考Dify[官方文档](https://docs.dify.ai/zh-hans/getting-started/install-self-hosted/readme),也可以参考如下简易教程。
### 前置条件
下载安装[Docker](https://www.docker.com/products/docker-desktop/) 环境,安装完毕后确认 Docker Engine 能正常运行。
![1](https://raw.githubusercontent.com/NanSike/image-host/main/images/1.png)
### 本地部署Dify
1. 使用Git克隆
`git clone` `https://github.com/langgenius/Dify.git`
2. 进入 Dify 源代码的 docker 目录,执行一键启动命令:
`cd Dify/docker` `cp .env.example .env` `d`ouyin
![2](https://raw.githubusercontent.com/NanSike/image-host/main/images/2.png)
3. 进入本地 Dify填写相关信息
![3](https://raw.githubusercontent.com/NanSike/image-host/main/images/3.png)
* * *
# **三、添加模型并测试聊天接口**
1. 点击页面右上角的设置,进入后选择模型提供商,点击添加 Ollama 模型类型: **Settings > Model Providers > Ollama**
![4](https://raw.githubusercontent.com/NanSike/image-host/main/images/4.png)
2. 请填写 ollama 的相关信息。将 **“gpt-oss:20b”** 选作模型名称。如有任何不清楚的地方,您可以参考官方详细的[部署文档](https://docs.dify.ai/en/development/models-integration/ollama#integrate-local-models-deployed-by-ollama)来操作 ollama。
![5](https://raw.githubusercontent.com/NanSike/image-host/main/images/5.png)
3. 新建空白模板
![6](https://raw.githubusercontent.com/NanSike/image-host/main/images/6.png)
4. 选择您想创建的类型
![7](https://raw.githubusercontent.com/NanSike/image-host/main/images/7.png)
* * *
# **四、验证与使用**
* 在 Dify 的模型测试页面中,输入适当的提示语,并确认模型的响应符合您的预期。
* 在您的应用流程中添加一个简单的 LLM 节点,选择 gpt-oss:20b 作为模型,并确保整个工作流程连接无误。
![8](https://raw.githubusercontent.com/NanSike/image-host/main/images/8.png)
![9](https://raw.githubusercontent.com/NanSike/image-host/main/images/9.png)
* * *
# **五、附录**
**常见问题及建议**
* **模型下载速度慢**
提示:配置 Docker 代理或使用图像加速服务以加快下载速度。
* **GPU 内存不足**
提示:对于 GPU 内存有限的设备,请使用 gpt-oss20b。您还可以启用 CPU 转发功能,但这样会导致响应速度变慢。
* **端口访问问题**
提示:检查防火墙规则、端口绑定和 Docker 网络设置,以确保连接正常。

View File

@@ -17,7 +17,7 @@ Dify 支持以本地部署的方式接入 LocalAI 部署的大型语言模型推
可参考官方 [Getting Started](https://localai.io/basics/getting_started/) 进行部署,也可参考下方步骤进行快速接入:
(以下步骤来自 [LocalAI Data query example](https://github.com/go-skynet/LocalAI/blob/master/examples/langchain-chroma/README.md)
(以下步骤来自 [LocalAI Data query example](https://github.com/mudler/LocalAI-examples/tree/main/langchain-chroma/README.md)
1. 首先拉取 LocalAI 代码仓库,并进入指定目录

View File

@@ -2,29 +2,38 @@
title: 嵌入网站
---
Dify 支持将你的 AI 应用嵌入到业务网站中,你可以使用该能力在几分钟内制作具有业务数据的官网 AI 客服、业务知识问答等应用。点击 WebApp 卡片上的嵌入按钮,复制嵌入代码,粘贴到你网站的目标位置。
Dify 支持将你的 AI 应用嵌入到业务网站中,你可以使用该能力在几分钟内制作具有业务数据的官网 AI 客服、业务知识问答等应用。
当你在网站中使用 Dify 聊天机器人气泡按钮时,你可以自定义按钮的样式、位置和其他设置
可以使用 3 种不同的方式将你的 AI 应用嵌入网站,分别为 `<iframe>` 标签方式,`<script>` 标签方式,和安装 Dify Chrome 浏览器扩展方式
* **iframe 标签方式**
点击 WebApp 卡片上的嵌入按钮,复制嵌入代码,粘贴到你网站的目标位置。
将 iframe 代码复制到你网站用于显示 AI 应用的标签中,如 `<div>`、`<section>` 标签
* **script 标签方式**
## 使用 `<iframe>` 标签方式
将 script 代码复制到你网站 `<head>` 或 `<body>` 标签
将 `<iframe>` 代码复制到你网站用于显示 AI 应用的标签中,如 `<div>`、`<section>` 标签。
<Frame caption="嵌入代码示例">
<img src="https://assets-docs.dify.ai/dify-enterprise-mintlify/zh_CN/guides/application-publishing/1e2e8c9adc620f9d6b4ea157119e8659.png" alt="显示嵌入网站的代码示例" />
</Frame>
如果将 script 代码粘贴到官网的 `<body>` 处,你将得到一个官网 AI 机器人:
## 使用 `<script>` 标签方式
将 `<script>` 代码复制到你网站 `<head>` 或 `<body>` 标签中。这会在你的网站上显示一个 Dify 聊天机器人气泡按钮。
如果将 script 代码粘贴到官网的 `<body>` 处,你将得到一个官网 AI 机器人:
<Frame caption="嵌入后的 AI 机器人效果">
<img src="https://assets-docs.dify.ai/dify-enterprise-mintlify/zh_CN/guides/application-publishing/f5a5e95e1120906669b3c1ad4e186dea.png" alt="展示嵌入到网站后的 AI 机器人效果" />
</Frame>
## 安装 Dify Chrome 浏览器扩展方式
按照提示,安装 [Dify Chrome 浏览器扩展](https://chromewebstore.google.com/detail/dify-chatbot/ceehdapohffmjmkdcifjofadiaoeggaf)。
## 自定义 Dify 聊天机器人气泡按钮
当你在网站中使用 Dify 聊天机器人气泡按钮时(即,使用 `<script>` 标签方式将你的 AI 应用嵌入网站),你可以自定义按钮的样式、位置和其他设置。
Dify 聊天机器人气泡按钮可以通过以下配置选项进行自定义:
```javascript
@@ -62,95 +71,109 @@ window.difyChatbotConfig = {
};
```
## 覆盖默认按钮样式
### 覆盖默认按钮样式
你可以使用 CSS 变量或 `containerProps` 选项来覆盖默认按钮样式。根据 CSS 优先级使用这些方法实现自定义样式。
### 1.修改 CSS 变量
* **修改 CSS 变量**
支持以下 CSS 变量进行自定义:
支持以下 CSS 变量进行自定义:
```css
/* 按钮距离底部的距离,默认为 `1rem` */
--dify-chatbot-bubble-button-bottom
```css
/* 按钮距离底部的距离,默认为 `1rem` */
--dify-chatbot-bubble-button-bottom
/* 按钮距离右侧的距离,默认为 `1rem` */
--dify-chatbot-bubble-button-right
/* 按钮距离左侧的距离,默认为 `unset` */
--dify-chatbot-bubble-button-left
/* 按钮距离顶部的距离,默认为 `unset` */
--dify-chatbot-bubble-button-top
/* 按钮背景颜色,默认为 `#155EEF` */
--dify-chatbot-bubble-button-bg-color
/* 按钮宽度,默认为 `50px` */
--dify-chatbot-bubble-button-width
/* 按钮高度,默认为 `50px` */
--dify-chatbot-bubble-button-height
/* 按钮边框半径,默认为 `25px` */
--dify-chatbot-bubble-button-border-radius
/* 按钮盒阴影,默认为 `rgba(0, 0, 0, 0.2) 0px 4px 8px 0px)` */
--dify-chatbot-bubble-button-box-shadow
/* 按钮悬停变换,默认为 `scale(1.1)` */
--dify-chatbot-bubble-button-hover-transform
```
例如,要将按钮背景颜色更改为 #ABCDEF请添加以下 CSS
```css
#dify-chatbot-bubble-button {
--dify-chatbot-bubble-button-bg-color: #ABCDEF;
}
```
/* 按钮距离右侧的距离,默认为 `1rem` */
--dify-chatbot-bubble-button-right
* **使用 `containerProps` 选项**
/* 按钮距离左侧的距离,默认为 `unset` */
--dify-chatbot-bubble-button-left
/* 按钮距离顶部的距离,默认为 `unset` */
--dify-chatbot-bubble-button-top
/* 按钮背景颜色,默认为 `#155EEF` */
--dify-chatbot-bubble-button-bg-color
/* 按钮宽度,默认为 `50px` */
--dify-chatbot-bubble-button-width
/* 按钮高度,默认为 `50px` */
--dify-chatbot-bubble-button-height
/* 按钮边框半径,默认为 `25px` */
--dify-chatbot-bubble-button-border-radius
/* 按钮盒阴影,默认为 `rgba(0, 0, 0, 0.2) 0px 4px 8px 0px)` */
--dify-chatbot-bubble-button-box-shadow
/* 按钮悬停变换,默认为 `scale(1.1)` */
--dify-chatbot-bubble-button-hover-transform
```
例如,要将按钮背景颜色更改为 #ABCDEF请添加以下 CSS
```css
#dify-chatbot-bubble-button {
--dify-chatbot-bubble-button-bg-color: #ABCDEF;
}
```
### 2.使用 `containerProps` 选项
使用 `style` 属性设置内联样式:
```javascript
window.difyChatbotConfig = {
// ... 其他配置
containerProps: {
style: {
backgroundColor: '#ABCDEF',
width: '60px',
height: '60px',
borderRadius: '30px',
使用 `style` 属性设置内联样式:
```javascript
window.difyChatbotConfig = {
// ... 其他配置
containerProps: {
style: {
backgroundColor: '#ABCDEF',
width: '60px',
height: '60px',
borderRadius: '30px',
},
// 对于较小的样式覆盖,也可以使用字符串作为 `style` 属性的值:
// style: 'background-color: #ABCDEF; width: 60px;',
},
// 对于较小的样式覆盖,也可以使用字符串作为 `style` 属性的值:
// style: 'background-color: #ABCDEF; width: 60px;',
},
}
```
}
```
使用 `className` 属性应用 CSS 类:
```javascript
window.difyChatbotConfig = {
// ... 其他配置
containerProps: {
className: 'dify-chatbot-bubble-button-custom my-custom-class',
},
};
```
使用 `className` 属性应用 CSS 类:
## 向嵌入网站的应用传递 `inputs`
```javascript
window.difyChatbotConfig = {
// ... 其他配置
containerProps: {
className: 'dify-chatbot-bubble-button-custom my-custom-class',
},
};
```
### 3. 传递 `inputs`
支持四种类型的输入:
你可以向嵌入你的网站的 AI 应用传递初始输入。支持四种类型的输入:
1. **`text-input`**:接受任何值。如果输入字符串的长度超过允许的最大长度,将被截断。
2. **`paragraph`**:类似于 `text-input`,接受任何值并在字符串长度超过最大长度时截断。
3. **`number`**:接受数字或数字字符串。如果提供的是字符串,将使用 `Number` 函数将其转换为数字。
4. **`options`**:接受任何值,前提是它匹配预先配置的选项之一。
示例配置:
使用 `<iframe>` 标签方式和使用 `<script>` 标签方式将 AI 应用嵌入网站时,传递 `inputs` 的方法亦有所不同。
以下以传入变量名为 `name`,值为 `apple` 的情形为例。
### 使用 `<iframe>` 标签方式
如果你的 AI 应用是使用 `<iframe>` 标签方式嵌入网站的,你可以通过向其 URL 追加参数的方式传递 `inputs`。
你需要将传入变量的值先使用 GZIP 压缩,并以 base64 编码,再将得到的 base64 值使用 encodeURIComponent 编码,最后附加到 URL 上。
例如,变量名为 `name`,值为 `apple`,首先压缩 `apple`,得到 base64 编码 `H4sIAAAAAAAAA0ssKMhJBQBQ0C6pBQAAAA==`,再使用 encodeURIComponent 编码得到 `H4sIAAAAAAAAA0ssKMhJBQBQ0C6pBQAAAA%3D%3D`。最后的输入值 URL 将如下所示: `http://localhost/chatbot/{token}?name=H4sIAAAAAAAAA0ssKMhJBQBQ0C6pBQAAAA%3D%3D`。
### 使用 `<script>` 标签方式
如果你的 AI 应用是使用 `<script>` 标签方式嵌入网站的,则只需要通过前文提到的配置选项即可传递 `inputs`。示例配置:
```javascript
window.difyChatbotConfig = {
@@ -161,10 +184,6 @@ window.difyChatbotConfig = {
}
```
注意:使用 embed.js 脚本创建 iframe 时,每个输入值将被处理——使用 GZIP 压缩并以 base64 编码——然后附加到 URL 上。
例如,处理后的输入值 URL 将如下所示: `http://localhost/chatbot/{token}?name=H4sIAKUlmWYA%2FwWAIQ0AAACDsl7gLuiv2PQEUNAuqQUAAAA%3D`
{/*
Contributing Section
DO NOT edit this section!

View File

@@ -24,7 +24,7 @@ LLM 应用在原型构建阶段通常涉及提示词测试、模型选择、RAG
* **生产阶段**
进入生产环境后,开发团队还需要仔细检查应用关键数据点、增加基准知识库、人工注释以及深入分析运营数据结果。尤其是在应用大规模使用中,运营和数据团队需要持续观测应用成本和性能,对模型以及应用表现进行优化。
进入生产环境后,开发团队还需要仔细检查应用关键数据点、增加基准知识库、人工注释以及深入分析运营数据结果。尤其是在应用大规模使用中,运营和数据团队需要持续观测应用成本和性能,对模型以及应用表现进行优化。
### Dify 与 Ops 工具的集成

View File

@@ -8,7 +8,7 @@ title: 功能简介
插件是 Dify 平台的扩展模块,让你可以轻松地接入**第三方模型与工具**,显著提升应用能力。通过插件系统,你的 AI 应用能够更好地"看"、"听"、"说"、"画"、"计算"、"推理",并连接外部 API执行真实世界的操作。
这是一个对开发者更加友好,可扩展性更强的第三方服务扩展模块。虽然 Dify 平台已内置多个由官方维护与社区贡献者开发的工具,但现有的工具难以全面覆盖各类细分场景的需求,而一个新工具的开发到嵌入 至平台又需要较长周期。
这是一个对开发者更加友好,可扩展性更强的第三方服务扩展模块。虽然 Dify 平台已内置多个由官方维护与社区贡献者开发的工具,但现有的工具难以全面覆盖各类细分场景的需求,而一个新工具的开发到嵌入至平台又需要较长周期。
为了让开发过程更加敏捷,我们决定开放生态并提供完善的插件开发 SDK让每位开发者都能够轻松地打造属于自己的工具轻松使用**第三方模型与工具**,显著提升应用能力。