### Docker Compose Up Output Example Source: https://docs.dify.ai/zh/self-host/quick-start/docker-compose This output shows the status of each container as it starts up. It includes network creation and individual service container status. ```text [+] Running 13/13 ✔ Network docker_ssrf_proxy_network Created 10.0s ✔ Network docker_default Created 0.1s ✔ Container docker-sandbox-1 Started 0.3s ✔ Container docker-db_postgres-1 Healthy 2.8s ✔ Container docker-web-1 Started 0.3s ✔ Container docker-redis-1 Started 0.3s ✔ Container docker-ssrf_proxy-1 Started 0.4s ✔ Container docker-weaviate-1 Started 0.3s ✔ Container docker-worker_beat-1 Started 3.2s ✔ Container docker-api-1 Started 3.2s ✔ Container docker-worker-1 Started 3.2s ✔ Container docker-plugin_daemon-1 Started 3.2s ✔ Container docker-nginx-1 Started 3.4s ``` -------------------------------- ### Start the Web Service Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Launch the web service after building. This command starts the Next.js development server. ```bash pnpm start ``` -------------------------------- ### Example .env.local Configuration Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Create a .env.local file and populate it with these example environment variables. Adjust values according to your deployment needs, especially NEXT_PUBLIC_API_PREFIX and NEXT_PUBLIC_PUBLIC_API_PREFIX. ```dotenv # For production release, change this to PRODUCTION NEXT_PUBLIC_DEPLOY_ENV=DEVELOPMENT # The deployment edition, SELF_HOSTED or CLOUD NEXT_PUBLIC_EDITION=SELF_HOSTED # The base URL of console application, refers to the Console base URL of WEB service if console domain is different from api or web app domain. # example: http://cloud.dify.ai/console/api NEXT_PUBLIC_API_PREFIX=http://localhost:5001/console/api # The URL for Web APP, refers to the Web App base URL of WEB service if web app domain is different from console or api domain. # example: http://udify.app/api NEXT_PUBLIC_PUBLIC_API_PREFIX=http://localhost:5001/api # When the frontend and backend run on different subdomains, set NEXT_PUBLIC_COOKIE_DOMAIN=1. NEXT_PUBLIC_COOKIE_DOMAIN= # SENTRY NEXT_PUBLIC_SENTRY_DSN= NEXT_PUBLIC_SENTRY_ORG= NEXT_PUBLIC_SENTRY_PROJECT= ``` -------------------------------- ### Install Web Service Dependencies Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Install all necessary project dependencies using PNPM. The --frozen-lockfile flag ensures that the exact versions specified in the lockfile are installed. ```bash pnpm install --frozen-lockfile ``` -------------------------------- ### Install Specific Dify Version with Git Source: https://docs.dify.ai/zh/self-host/quick-start/faqs Use the `--branch` flag with `git clone` to install a specific version of Dify. Ensure the rest of the setup follows the latest version's instructions. ```bash git clone https://github.com/langgenius/dify.git --branch 0.15.3 ``` -------------------------------- ### Install Plugin Dependencies Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-md-exporter Install the necessary Python dependencies for your plugin using the provided `requirements.txt` file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Python FastAPI Code Example Source: https://docs.dify.ai/zh/use-dify/workspace/api-extension/api-extension A practical code example using Python's FastAPI framework to implement the API extension, including dependency installation, code structure, and service startup instructions. ```APIDOC ## Python FastAPI Code Example This code example is based on the Python FastAPI framework. ### 1. Install Dependencies ```bash pip install fastapi[all] uvicorn ``` ### 2. Write Code According to API Specification ```python from fastapi import FastAPI, Body, HTTPException, Header from pydantic import BaseModel app = FastAPI() class InputData(BaseModel): point: str params: dict = {} @app.post("/api/dify/receive") async def dify_receive(data: InputData = Body(...), authorization: str = Header(None)): """ Receive API query data from Dify. """ expected_api_key = "123456" # TODO Your API key of this API auth_scheme, _, api_key = authorization.partition(' ') if auth_scheme.lower() != "bearer" or api_key != expected_api_key: raise HTTPException(status_code=401, detail="Unauthorized") point = data.point # for debug print(f"point: {point}") if point == "ping": return { "result": "pong" } if point == "app.external_data_tool.query": return handle_app_external_data_tool_query(params=data.params) # elif point == "{point name}": # TODO other point implementation here raise HTTPException(status_code=400, detail="Not implemented") def handle_app_external_data_tool_query(params: dict): app_id = params.get("app_id") tool_variable = params.get("tool_variable") inputs = params.get("inputs") query = params.get("query") # for debug print(f"app_id: {app_id}") print(f"tool_variable: {tool_variable}") print(f"inputs: {inputs}") print(f"query: {query}") # TODO your external data tool query implementation here, # return must be a dict with key "result", and the value is the query result if inputs.get("location") == "London": return { "result": "City: London\nTemperature: 10°C\nRealFeel®: 8°C\nAir Quality: Poor\nWind Direction: ENE\nWind " "Speed: 8 km/h\nWind Gusts: 14 km/h\nPrecipitation: Light rain" } else: return {"result": "Unknown city"} ``` ### 3. Start the API Service The API service will run on port 8000 by default. The complete API address is `http://127.0.0.1:8000/api/dify/receive`. The configured API Key is `123456`. ```bash uvicorn main:app --reload --host 0.0.0.0 ``` ### 4. Configure the API in Dify Configure this API within Dify. ### 5. Select the API Extension in the App Choose this API extension within your Dify App. **App Debugging:** When debugging an app, Dify will send requests to the configured API with the following example payload: ```json { "point": "app.external_data_tool.query", "params": { "app_id": "61248ab4-1125-45be-ae32-0ce91334d021", "tool_variable": "weather_retrieve", "inputs": { "location": "London" }, "query": "How's the weather today?" } } ``` The API response will be: ```json { "result": "City: London\nTemperature: 10°C\nRealFeel®: 8°C\nAir Quality: Poor\nWind Direction: ENE\nWind Speed: 8 km/h\nWind Gusts: 14 km/h\nPrecipitation: Light rain" } ``` ``` -------------------------------- ### Navigate to Web Directory Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Change your current directory to the 'web' folder to proceed with the setup. ```bash cd web ``` -------------------------------- ### Copy Example .env File Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-md-exporter Copy the example environment file to `.env` to configure your Dify debugging environment. Ensure you fill in your specific Dify environment details. ```bash cp .env.example .env ``` -------------------------------- ### Basic Plugin Manifest Example Source: https://docs.dify.ai/zh/develop-plugin/features-and-specs/plugin-types/plugin-info-by-manifest This is a fundamental example of a plugin's manifest file. It outlines essential plugin metadata and configurations. ```yaml 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" ``` -------------------------------- ### Install API Service Dependencies with uv Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Install the required dependencies for the API service using `uv`. For macOS users, ensure `libmagic` is installed via Homebrew. ```bash uv sync --dev ``` -------------------------------- ### Install PNPM using npm Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Use this command to globally install PNPM if you have npm available. ```bash npm i -g pnpm ``` -------------------------------- ### Install FFmpeg on Ubuntu Source: https://docs.dify.ai/zh/self-host/troubleshooting/integrations Install FFmpeg on Ubuntu using apt-get. This is required for OpenAI Text-to-Speech (TTS) audio stream segmentation. ```bash sudo apt-get update sudo apt-get install ffmpeg ``` -------------------------------- ### Create Custom Environment File Source: https://docs.dify.ai/zh/self-host/quick-start/docker-compose To configure specific settings, such as for vector stores like Milvus, copy the example environment file and rename it. This allows for customization without altering the original example file. Ensure you are in the `dify/docker` directory before running this command. ```bash cd dify/docker cp envs/vectorstores/milvus.env.example envs/vectorstores/milvus.env ``` -------------------------------- ### Install Dify CLI on Mac Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-flomo-plugin Use Homebrew to tap the Dify repository and install the CLI tool. ```bash brew tap langgenius/dify brew install dify ``` -------------------------------- ### Install Dependencies for Schema Migration Source: https://docs.dify.ai/zh/self-host/troubleshooting/weaviate-v4-migration Installs the necessary Python packages (weaviate-client and requests) for the schema migration script. It's recommended to do this within a temporary virtual environment. ```bash cd /path/to/dify python3 -m venv weaviate_migration_env source weaviate_migration_env/bin/activate pip install weaviate-client requests ``` -------------------------------- ### External Data Tool Example Source: https://docs.dify.ai/zh/use-dify/workspace/api-extension/api-extension This example demonstrates how to use the external data tool to fetch weather information for a specific region, which can then be used as context. ```APIDOC ## External Data Tool Example This section provides an example for the external data tool, where the scenario is to get external weather information based on a region to serve as context. ### API Example #### Endpoint `POST https://fake-domain.com/api/dify/receive` #### Headers ``` Content-Type: application/json Authorization: Bearer 123456 ``` #### Request Body ```json { "point": "app.external_data_tool.query", "params": { "app_id": "61248ab4-1125-45be-ae32-0ce91334d021", "tool_variable": "weather_retrieve", "inputs": { "location": "London" }, "query": "How's the weather today?" } } ``` #### API Response ```json { "result": "City: London\nTemperature: 10°C\nRealFeel®: 8°C\nAir Quality: Poor\nWind Direction: ENE\nWind Speed: 8 km/h\nWind Gusts: 14 km/h\nPrecipitation: Light rain" } ``` ``` -------------------------------- ### Pull New Docker Images and Start Services Source: https://docs.dify.ai/zh/self-host/platform-guides/dify-premium Pull the latest Docker images for Dify and start the services using Docker Compose. This completes the upgrade process. ```bash docker compose pull docker compose -f docker-compose.yaml -f docker-compose.override.yaml up -d ``` -------------------------------- ### Run FastAPI Application Source: https://docs.dify.ai/zh/use-dify/workspace/api-extension/api-extension Command to start the FastAPI development server using uvicorn, making the API accessible. ```bash uvicorn main:app --reload --host 0.0.0.0 ``` -------------------------------- ### Start Dify Services with Docker Compose Source: https://docs.dify.ai/zh/self-host/quick-start/docker-compose Launch all Dify services, including core components and dependencies, in detached mode. Ensure you have Docker Compose version 2.24.0 or higher installed. ```bash docker compose up -d ``` -------------------------------- ### Prepare API Service Environment Variables Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Navigate to the 'api' directory and prepare the environment variables for the API service by copying the example file. Adjust `COOKIE_DOMAIN` if frontend and backend are on different subdomains. ```bash cd api cp .env.example .env ``` -------------------------------- ### JavaScript with External Libraries (Lodash) Source: https://docs.dify.ai/zh/use-dify/nodes/code Example of using external JavaScript libraries like Lodash for utility functions. Ensure these libraries are available in your Dify installation's sandbox environment. ```javascript // JavaScript: Import lodash, moment, etc. const _ = require('lodash'); function main(data) { return { unique: _.uniq(data) }; } ``` -------------------------------- ### Python with External Libraries (NumPy, Pandas) Source: https://docs.dify.ai/zh/use-dify/nodes/code Example of using external Python libraries like NumPy and Pandas for data manipulation. Ensure these libraries are available in your Dify installation's sandbox environment. ```python # Python: Import numpy, pandas, requests, etc. import numpy as np import pandas as pd def main(data: list) -> dict: df = pd.DataFrame(data) return {'mean': float(np.mean(df['values']))} ``` -------------------------------- ### Initialize Bundle Plugin Project Source: https://docs.dify.ai/zh/develop-plugin/features-and-specs/advanced-development/bundle Run this command to create a new Bundle plugin project. Ensure you have the Dify plugin scaffold tool and Python 3.12 installed. ```bash ./dify-plugin-darwin-arm64 bundle init ``` ```bash dify bundle init ``` -------------------------------- ### Structure Extraction Prompt for LLM Node Source: https://docs.dify.ai/zh/use-dify/tutorials/article-reader This prompt guides the LLM to parse article content, extract its structure, and summarize key information. It specifies the task, requirements, output format, and provides an example. ```text 阅读以下文章内容并执行任务 {{文档提取器结果的变量}} # 任务 - **主要目标**:全面解析文章的结构。 - **目标**:详细说明文章每个部分的内容。 - **要求**:尽可能详细地分析。 - **限制**:无特别的格式限制,但需要保持解析的条理性和逻辑性。 - **预期输出**:文章结构的详细解析,包括每个部分的主要内容和作用。 # 推理顺序 - **推理部分**:通过仔细阅读文章,识别和解析其结构。 - **结论部分**:提供每个部分的具体内容和作用。 # 输出格式 - **解析格式**:每个部分应以标题形式列出,后跟对该部分内容的详细说明。 - **结构形式**:Markdown,以增强可读性。 - **具体说明**:每个部分的内容和作用,包括但不限于引言、正文、结论、引用等。 # 示例输出 ## 示例文章解析 ### 引言 - **内容**:介绍研究的背景、目的和重要性。 - **作用**:吸引读者的注意力,为文章内容提供上下文。 ### 方法 - **内容**:描述研究的具体方法和步骤,包括实验设计、数据收集和分析技术。 - **作用**:使读者了解研究的科学性和可重复性。 ### 结果 - **内容**:展示研究的主要发现和数据。 - **作用**:提供研究结论的证据基础。 ### 讨论 - **内容**:解释结果的意义,对比其他研究,提出可能的改进方向。 - **作用**:帮助读者理解结果的广泛影响和未来研究的潜力。 ### 结论 - **内容**:总结研究的主要发现和贡献。 - **作用**:强化文章的核心信息,提供明确的结论。 ### 引用 - **内容**:列出文章中引用的所有文献。 - **作用**:提供进一步阅读的资源,确保学术诚信。 # 备注 - **边缘情况**:如果文章结构不典型(例如,缺少某些部分或有额外的部分),应在解析中明确指出这些特殊情况。 - **重要考虑事项**:解析时应关注文章的逻辑性和连贯性,确保每个部分的内容与文章的整体目标一致。 ``` -------------------------------- ### Reinstall Weaviate Client for Source Installation Source: https://docs.dify.ai/zh/self-host/troubleshooting/weaviate-v4-migration Commands to uninstall the old weaviate-client and install the specific v4 version for source code installations. ```bash # 对于源码安装 pip uninstall weaviate-client pip install weaviate-client==4.17.0 ``` -------------------------------- ### Create Plugin Entry Point Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-md-exporter Set up the main entry point for the Dify plugin. This involves initializing `PluginRunner` with the created export tools. ```python 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 ) ``` -------------------------------- ### Place Public Key for Verification Source: https://docs.dify.ai/zh/develop-plugin/publishing/standards/third-party-signature-verification Copy the public key file to a location accessible by the plugin daemon. This example places it in a 'public_keys' directory within the plugin daemon's volume. ```bash mkdir docker/volumes/plugin_daemon/public_keys cp your_key_pair.public.pem docker/volumes/plugin_daemon/public_keys ``` -------------------------------- ### Build the Web Service Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Compile and build the web service for deployment using PNPM. ```bash pnpm build ``` -------------------------------- ### Verify Dify CLI Installation Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-flomo-plugin Check the installed Dify CLI version. ```bash dify version ``` -------------------------------- ### Start Middleware Services with Docker Compose Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Use Docker Compose to launch the necessary middleware services for Dify, such as databases and other dependencies. Ensure to configure the `middleware.env` file if you are not using the default PostgreSQL and Weaviate configurations. ```bash cd docker cp envs/middleware.env.example middleware.env # 如果不使用 PostgreSQL 和 Weaviate,请修改 middleware.env 中的 DB_TYPE 或 COMPOSE_PROFILES。 docker compose --env-file middleware.env -f docker-compose.middleware.yaml -p dify up -d ``` -------------------------------- ### Install FastAPI Dependencies Source: https://docs.dify.ai/zh/use-dify/workspace/api-extension/api-extension Command to install the necessary Python packages for building a FastAPI application. ```bash pip install fastapi[all] uvicorn ``` -------------------------------- ### Initialize New Dify Plugin Project Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-flomo-plugin Use the Dify CLI to create a new plugin project. Follow the prompts to name your plugin, select its type, and fill in required fields. ```bash dify plugin init ``` -------------------------------- ### Install Dify CLI on Linux Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-flomo-plugin Download the appropriate Dify CLI binary from the GitHub releases page, make it executable, and move it to your system's PATH. ```bash # Download appropriate version chmod +x dify-plugin-linux-amd64 mv dify-plugin-linux-amd64 dify sudo mv dify /usr/local/bin/ ``` -------------------------------- ### Initialize Agent Strategy Plugin Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/agent-strategy-plugin Use the Dify CLI to create a new agent strategy plugin project. Follow the on-screen prompts to configure the plugin's name, author, description, language, and type. ```bash dify plugin init ``` ```bash ➜ Dify Plugins Developing dify plugin init Edit profile of the plugin Plugin name (press Enter to next step): # Enter the plugin name Author (press Enter to next step): Author name # Enter the plugin author Description (press Enter to next step): Description # Enter the plugin description --- Select the language you want to use for plugin development, and press Enter to con BTW, you need Python 3.12+ to develop the Plugin if you choose Python. -> python # Select Python environment go (not supported yet) --- Based on the ability you want to extend, we have divided the Plugin into four type - Tool: It's a tool provider, but not only limited to tools, you can implement an - Model: Just a model provider, extending others is not allowed. - Extension: Other times, you may only need a simple http service to extend the fu - Agent Strategy: Implement your own logics here, just by focusing on Agent itself What's more, we have provided the template for you, you can choose one of them b tool -> agent-strategy # Select Agent strategy template llm text-embedding --- Configure the permissions of the plugin, use up and down to navigate, tab to sel Backwards Invocation: Tools: Enabled: [✔] You can invoke tools inside Dify if it's enabled # Enabled by default Models: Enabled: [✔] You can invoke models inside Dify if it's enabled # Enabled by default LLM: [✔] You can invoke LLM models inside Dify if it's enabled # Enabled by default Text Embedding: [✘] You can invoke text embedding models inside Dify if it' Rerank: [✘] You can invoke rerank models inside Dify if it's enabled ... ``` -------------------------------- ### Install FFmpeg on CentOS Source: https://docs.dify.ai/zh/self-host/troubleshooting/integrations Install FFmpeg on CentOS. This is required for OpenAI Text-to-Speech (TTS) audio stream segmentation. ```bash sudo yum install epel-release sudo rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm sudo yum update sudo yum install ffmpeg ffmpeg-devel ``` -------------------------------- ### Install FFmpeg on macOS Source: https://docs.dify.ai/zh/self-host/troubleshooting/integrations Install FFmpeg using Homebrew on macOS. This is required for OpenAI Text-to-Speech (TTS) audio stream segmentation. ```bash brew install ffmpeg ``` -------------------------------- ### Initialize New Dify Plugin Project Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/tool-plugin Use the Dify plugin CLI tool to create a new Dify plugin project. Ensure the binary is accessible in your PATH or use its direct path. ```bash ./dify-plugin-darwin-arm64 plugin init ``` ```bash dify plugin init ``` -------------------------------- ### Configure Remote Debugging Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/develop-a-slack-bot-plugin This bash command configures the plugin for remote installation by setting environment variables for the installation method, URL, and key. ```bash INSTALL_METHOD=remote REMOTE_INSTALL_URL=debug.dify.ai:5003 REMOTE_INSTALL_KEY=********-****-****-****-************ ``` -------------------------------- ### Start API Service Source: https://docs.dify.ai/zh/self-host/advanced-deployments/local-source-code Launch the Dify API service in debug mode, accessible on all network interfaces. This command starts a development server. ```bash uv run flask run --host 0.0.0.0 --port=5001 --debug ``` -------------------------------- ### Package Bundle Project Source: https://docs.dify.ai/zh/develop-plugin/features-and-specs/advanced-development/bundle Execute this command to package your Bundle project into a .difybndl file. The output file will be created in the current directory. ```bash dify-plugin bundle package ./bundle ``` -------------------------------- ### Cron Expression Examples Source: https://docs.dify.ai/zh/use-dify/nodes/trigger/schedule-trigger See practical examples of Cron expressions for various scheduling requirements, from specific times on weekdays to monthly last days. ```text 工作日上午 9 点 `0 9 * * MON-FRI` or `0 9 * * 1-5` 每周三下午 2:30 `30 14 * * WED` 每周日凌晨 12 点 `0 0 * * 0` 每周二每 2 小时一次 `0 */2 * * 2` 每月第一天凌晨 12 点 `0 0 1 * *` 1 月 1 日和 6 月 1 日的中午 12 点 `0 12 1 JAN,JUN *` 每月最后一天下午 5 点 `0 17 L * *` 每月最后一个星期五晚上 10 点 `0 22 * * 5L` ``` -------------------------------- ### 设置数据源插件 SDK 版本 Source: https://docs.dify.ai/zh/develop-plugin/dev-guides-and-walkthroughs/datasource-plugin 在 requirements.txt 文件中指定数据源插件开发所使用的 Dify 插件 SDK 版本范围。 ```yaml dify-plugin>=0.5.0,<0.6.0 ``` -------------------------------- ### Invoke Chat Application Example Source: https://docs.dify.ai/zh/develop-plugin/features-and-specs/advanced-development/reverse-invocation-app Example of how to invoke a chat-type application within an Endpoint and handle streaming responses. Ensure correct invocation of `self.session.app.chat.invoke`. ```python 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(): # Note: The original example incorrectly called self.session.app.workflow.invoke # It should call self.session.app.chat.invoke for a chat app. # Assuming a chat app is intended here based on the section title. response = self.session.app.chat.invoke( app_id=app_id, inputs={}, # Provide actual inputs as needed response_mode="streaming", conversation_id="some-conversation-id", # Provide a conversation ID if needed files=[] ) for data in response: yield f"{json.dumps(data)}
" return Response(generator(), status=200, content_type="text/html") ```