Runoob Tutorial ArchiveEnglish

Dify Getting Started Tutorial

Dify Getting Started Tutorial

Dify (Do It For You) is the most popular open-source LLM application development platform, designed for building generative AI applications powered by Large Language Models (LLMs).

Dify integrates AI workflow orchestration, RAG knowledge bases, Agent frameworks, model management, and observability into one visual platform, allowing you to quickly move from prototype to production without building LLM infrastructure from scratch.

Dify simplifies the AI application creation process by integrating RAG pipelines, AI workflows, observability tools, and model management.

If LangChain is the parts factory for AI applications (flexible but requires a lot of hand-written code), then Dify is the visual IDE for AI applications—all the components are there, and you can run it by dragging and connecting lines.

Dify runoob

Comparison with other tools

Below is a comparison of Dify with LangChain and n8n across key dimensions.

Dimension Dify LangChain n8n
Primary Users Developers + Product Managers Developer Operations/Automation
Programming requirements Low-code / No-code Requires writing Python/JS Low-code
Built-in RAG Fully built-in Requires manual assembly Limited
Agent framework Built-in Built-in Limited
Observability Built-in Requires third party Limited
Self-hosted Fully supported Supported Supported
License Apache 2.0 MIT Fair-code

Dify's intuitive visual orchestration studio makes it an ideal choice for startups and enterprises needing to quickly build functional AI applications.

LangChain is better suited for complex enterprise applications requiring custom integrations and deep developer involvement.

Who is using Dify?

From biomedicine to the automotive industry, Dify provides reliable solutions for various enterprises.

Volvo Cars uses Dify to rapidly validate ideas in its AI frontier strategic navigation.

Users highly praise Dify for democratizing AI Agent development by integrating powerful AI/ML capabilities into a no-code platform.


Core Concepts

Before starting operations, let's first understand the basic concepts of Dify:

Concept Description
App The basic deployment unit in Dify. Each application corresponds to an independent AI function, with its own System Prompt, associated Knowledge Base, tool configuration, and API Key.
Knowledge Base A Knowledge Base is your own set of data that can be integrated into an AI application. It allows the LLM to use your proprietary data as an additional source of truth when answering, ensuring more accurate, relevant answers and reducing hallucinations.
RAG (Retrieval-Augmented Generation) When a user asks a question, the system first retrieves the most relevant information from the knowledge base (Retrieval), then combines the retrieved results with the user's original question and sends it to the LLM (Augmented), and the LLM generates a more accurate answer based on this context (Generation).
Workflow Build and test powerful AI workflows on a visual canvas by defining multi-step AI processing logic through dragging nodes and connecting lines.
Agent Agents can be defined based on LLM Function Calling or ReAct, and pre-built or custom tools can be added to them. Dify provides over 50 built-in tools for AI Agents, such as Google Search, DALL E, Stable Diffusion, and WolframAlpha.
Node The basic unit of a workflow, each node executes a specific operation: LLM inference, knowledge retrieval, code execution, HTTP request, conditional branching, etc.

Installation and Startup

Four installation methods, from zero-second start to highly available cluster deployment.

Method 1: Dify Cloud (Fastest, 0-second start)

Visit cloud.dify.ai and register an account to start using it immediately.

The free Sandbox package includes 200 messages and 5 applications per month, requiring no environment configuration.

Suitable for quick experience, personal projects, and testing prototypes.

runoob 178 7154 19


Method 2: Docker Compose Self-Hosting (Recommended for production use)

Suitable for users with technical backgrounds who want complete control over data and deployment environment.

System Requirements

Resources Minimum requirements Recommended configuration
CPU 2 cores 4 cores
Memory 4 GB 8 GB
Disk 20 GB 50 GB+
Docker Engine 20.10+ Latest version
Docker Compose v2.2+ Latest version

Installation steps

Step 1: Clone the repository

Clone the Dify repository locally:



git clone https://github.com/langgenius/dify.git

cd dify

Step 2: Enter the docker directory and copy the environment configuration

Original prompt (Chinese, left untranslated)



cd docker

# Copy environment configuration file from template

cp .env.example .env

Step 3 (Important): Configure SECRET_KEY

Starting from v1.14.1, Docker deployment no longer relies on a public default key. When SECRET_KEY is empty, the API will automatically generate and persist a runtime key. It is recommended to explicitly set it in the .env file.

Original prompt (Chinese, left untranslated)



# Generate a secure random key

openssl rand -base64 42

Edit the .env file, find SECRET_KEY, and set it to the randomly generated string above:



SECRET_KEY=your-very-long-random-secret-key-here

Step four: Start the service

Original prompt (Chinese, left untranslated)



# Start all Dify services (first time will pull images, takes about 3-10 minutes)

docker compose up -d

Step five: Access and initialize

Access http://localhost/install in the browser to complete administrator account registration.

Step six: Verify service status

Original prompt (Chinese, left untranslated)



# Check the status of all containers; if all are healthy, it means they are running normally

docker compose ps

All containers (api, worker, web, db, redis, weaviate, nginx, etc.) must be in a healthy state to indicate normal operation.

Stop and restart

Original prompt (Chinese, left untranslated)



# Stop all services (data retained in Docker volumes)

docker compose down



# Restart all services

docker compose up -d

Upgrade to a new version

Original prompt (Chinese, left untranslated)



# Enter docker directory

cd dify/docker



# Pull latest code

git pull origin main



# Pull new image

docker compose pull



# Restart

docker compose up -d

Data persistence is in Docker volumes, so updates will not affect existing applications, knowledge bases, or conversation history. It is recommended to back up the PostgreSQL database before a major version upgrade.


Method Three: One-click deployment on AWS Marketplace

For startups and small businesses operating on AWS, Dify Premium on AWS Marketplace allows for one-click deployment to your own AWS VPC, and also supports custom logos and branding.


Method Four: Kubernetes Deployment (High Availability)

For scenarios requiring a high-availability configuration, the community provides Helm Charts and YAML files to deploy Dify to a Kubernetes cluster.

Original prompt (Chinese, left untranslated)



# Add Dify Helm repository

helm repo add dify https://langgenius.github.io/dify-helm



# Install using custom values.yaml

helm install dify dify/dify -f values.yaml


Configure model providers

After installation, the first step is to connect your AI model.

Operation path

After logging into Dify, click the avatar in the upper right corner, go to Settings, and select Model Provider.

runoob 178 71568144

For example, we can install the DeepSeek model provider and then configure the API key:

runoob 178 7157745 5

Configuration of mainstream providers

Anthropic (Claude series):

Original prompt (Chinese, left untranslated)



Provider: Anthropic

API Key: sk-ant-xxxxxxxx(从 console.anthropic.com 获取)

推荐模型:claude-sonnet-4-6(综合性能最佳)

OpenAI:

Original prompt (Chinese, left untranslated)



Provider: OpenAI

API Key: sk-xxxxxxxx(从 platform.openai.com 获取)

推荐模型:gpt-4o(性价比高)

Google (Gemini series):

Original prompt (Chinese, left untranslated)



Provider: Google

API Key: xxxxxxxx(从 aistudio.google.com 获取)

推荐模型:gemini-2.0-flash(速度快,适合大量请求)

OpenRouter (a key to access 300+ models):

Original prompt (Chinese, left untranslated)



Provider: OpenRouter

API Key: sk-or-xxxxxxxx(从 openrouter.ai 获取)

Base URL: https://openrouter.ai/api/v1

Local models (Ollama):

Original prompt (Chinese, left untranslated)



Provider: Ollama

Base URL: http://host.docker.internal:11434  # Docker 内访问宿主机

(先在宿主机运行:ollama pull llama3.3)

Configure Embedding Model (Required for Knowledge Base)

Vectorization of the knowledge base requires an Embedding Model. The following are recommended options:

Model Feature Applicable Scenario
OpenAI text-embedding-3-small Cheap, good performance General scenarios
Zhipu AI embedding-3 Excellent Chinese support Content primarily in Chinese
Local nomic-embed-text (Ollama) Completely offline High data security requirements

Verify model availability

Go back to Settings, find the configured provider, and click the Test button next to the model name; a green checkmark indicates successful configuration.


Detailed explanation of five application types

On the Dify homepage, clicking Create App will show five types, each corresponding to a different use case.

runoob 178 7161 119

Clicking Create Blank App, you can see five types of applications:

runoob 178 717 5815

1. Chatbot

A standard multi-turn dialogue application with persistent session memory.

Attributes Description
Suitable scenarios Customer service robot, private assistant, FAQ Q&A
Core features Built-in conversation memory (configurable memory strategy), attachable knowledge base (enable RAG), supports streaming output, one-click publishing as web embed code

2. Text Generator

Single input to single output, does not retain conversation history.

Attributes Description
Suitable scenarios Article rewriting, summary generation, SEO copywriting, email drafting
Core features Clear structure (input form + output text), suitable for batch processing, supports variable placeholders (e.g., {{product_name}})

3. Agent

AI that can proactively call tools, autonomously plan, and execute multi-step tasks.

Attributes Description
Suitable scenarios Data querying and analysis, search and summarization, code execution
Core features Supports two reasoning modes, Function Calling and ReAct, built-in 50+ tools (search, image generation, code interpreter, etc.), supports custom API tools, tool calling process is visible to the user

4. Chatflow

Adds multi-turn conversation capability on top of Workflow, combining process orchestration and conversational context.

Attributes Description
Suitable scenarios Complex customer service workflows, conversational bots requiring multi-step judgment
Core features Possesses the node orchestration capability of Workflow while retaining multi-turn conversation memory, allowing automated processes to be triggered during a conversation

5. Workflow

A purely automated multi-step processing workflow without a conversational interface, triggered via API or manually run.

Properties Description
Suitable scenarios Batch data processing, scheduled automated tasks, backend AI processing pipelines
Core features Build and test AI workflows on a visual canvas, support parallel branches, loops, and conditional judgments, support Human-in-the-Loop (Human Input nodes), and output results can be integrated with other systems

Selection guide

Quickly decide which application type to use based on your needs:

Original prompt (Chinese, left untranslated)



需要多轮对话?

├─ 是 → 需要复杂流程逻辑?

│        ├─ 是 → Chatflow

│        └─ 否 → Chatbot 或 Agent(需要工具调用时选 Agent)

└─ 否 → 单次输入输出?

          ├─ 是 → Text Generator

          └─ 需要多步骤自动化 → Workflow


Knowledge Base (RAG): Let AI answer questions based on your private data

The Knowledge Base is one of Dify's most powerful features and the core of most enterprise applications.

Create Knowledge Base

  1. Select Knowledge in the navigation bar, and click Create Knowledge
  2. Name the knowledge base, such as "Product Manual" or "Internal Policy Document"
  3. Select the creation method

runoob 178 716 43741

Method one: Upload files (most common)

Dify accepts PDF, Word (.docx), Markdown (.md), plain text (.txt), CSV, and HTML files.

Markdown or plain text is recommended as they are the most reliable to parse.

Complex or scanned PDFs may require preprocessing; it is recommended to extract text using an OCR tool before uploading.

Method two: Knowledge Pipeline (enterprise level)

Knowledge Pipeline is a visual node-based orchestration system specifically designed for document ingestion and processing.

It solves the three major pain points of traditional RAG: disparate data sources, information loss during parsing (charts and formulas are discarded), and the black-box processing process (difficulty in diagnosing failure reasons).

Method Three: External Knowledge Base API

Synchronizes existing external knowledge bases via API, eliminating the need for data migration.

Document Chunking Strategy

After uploading, Dify automatically performs text chunking. Key parameter descriptions are as follows:

Parameter Description Recommended value
Chunk size Token count per Chunk 500-1000 (Chinese)
Chunk overlap Overlapping tokens between adjacent Chunks 50-100
Delimiter What to cut by (paragraph/sentence) Paragraph

The recommended chunk size for Chinese content is around 500 Tokens. Too long will make retrieval inaccurate, and too short will lose context.

Indexing mode

Mode Description Cost
High quality (default) Use Embedding models to generate vectors for the best results Consume Embedding API
Economic model Inverted index (keyword matching), no Embedding required Free

Retrieval configuration

Enter the knowledge base, select Settings, and configure retrieval parameters:

Retrieval method Description Applicable Scenarios
Vector Search Semantic Similarity Matching Meaning-related Queries
Full-text Search Keyword Matching Exact Term Query
Hybrid Retrieval (Recommended) Combine both and use a re-ranking model to improve accuracy General scenarios

Similarity threshold is suggested to be set between 0.5 and 0.7.

A similarity threshold that is too high will result in no results, while a threshold that is too low will return irrelevant content. It is recommended to start testing from 0.6 and fine-tune based on the results.

Test retrieval effectiveness

In the knowledge base, click Retrieval Testing, enter a test question, and directly view the returned Chunks to verify retrieval quality without initiating a real conversation.

Associate the knowledge base with the application

On the application editing page, select Context, click Add, select the created knowledge base, and save.

After association, every conversation in the application will first retrieve from the knowledge base before answering.


Workflow: Visual orchestration of multi-step tasks

Define multi-step AI processing logic by dragging and connecting nodes.

Enter the Workflow editor

Select Workflow when creating an application, or click Edit in an existing Workflow application to enter the canvas.

runoob 178 716538165

Main node types

The following are the most commonly used nodes in the Workflow editor and their functions:

Node Function Typical Use Case
Start Process entry, define input variables Receive user input or external parameters
LLM Call language model Text generation, analysis, and translation
Knowledge Retrieval Retrieve from knowledge base RAG scenarios
IF/ELSE Conditional branching Route different processing paths based on content
Code Execute Python or JS code Data transformation, format processing, calculation
HTTP Request Call external API Query database, send notification
Template Variable template rendering Combine outputs from multiple nodes
Variable Assigner Set/Update Variable Cross-node Data Transfer
Iteration Process List in a Loop Batch Process Multiple Data Records
Agent Embedded Agent Node Enable autonomous reasoning in a workflow step
Human Input Pause and wait for manual review Key decision points for human-machine collaboration
End Process exit, define output Return the final result

runoob 178 716763335

Variable passing between nodes

The output of each node can be referenced by subsequent nodes using the syntax {{NodeName.OutputVariableName}}.

The following is an example of variable passing in a typical RAG Q&A workflow:

Original prompt (Chinese, left untranslated)



Start 节点输出 user_query

  ↓

Knowledge Retrieval 节点:

  输入:{{Start.user_query}}

  输出:result(检索结果)

  ↓

LLM 节点:

  System Prompt:你是一个客服助理,根据以下资料回答问题

  User:用户问题:{{Start.user_query}}

        参考资料:{{Knowledge Retrieval.result}}

  ↓

End 节点:

  返回:{{LLM.text}}

Human Input Node (HITL)

The Human Input Node is a major update that allows workflows to pause execution at critical decision points.

This node generates a UI interface for manual review and modification of variables (e.g., editing a draft or correcting data), and then determines the subsequent path based on custom buttons (such as "Approve," "Reject," or "Escalate").

This solves the previous binary dilemma of workflows being "either fully automated or fully manual," allowing automated AI to be used in high-risk scenarios (contract review, medical advice, financial decisions).

Debugging Workflows

Click Run in the upper right corner of the canvas, enter test parameters, and observe the input/output and execution time of each node.

A green (success) or red (failure) marker will appear next to the node; clicking it allows you to view detailed execution logs.


Scenario Practice 1: Enterprise Internal Knowledge Q&A Robot

Build a chatbot using Dify that can accurately answer questions from internal documents, providing source citations.

Business Background

The company has a large amount of internal documents (HR policies, product manuals, technical Wikis), and employees frequently need to look up information, but the documents are scattered and difficult to search.

Step 1: Prepare the Knowledge Base

  1. Organize Documents: Export HR policies (PDF), product manuals (Word), and technical Wikis (Markdown) for backup.
  2. In Knowledge, select Create Knowledge and name it "Company Internal Knowledge Base".
  3. Upload files and select high-quality indexing mode
  4. Wait for vectorization to complete (progress bar displayed)

Document quality optimization tips: delete irrelevant information, headers, footers, and special characters. Use clear headings and short paragraphs. If a document covers multiple different topics, consider splitting it into separate files.

Step two: Create Chatbot application

  1. Click Create App, select Chatbot, and name it "Internal Assistant"
  2. Select a model (Claude Sonnet 4.6 or GPT-4o recommended)
  3. Write the System Prompt

runoob 178 717 4347

Original prompt (Chinese, left untranslated)



你是公司内部知识助手,专门帮助员工查找内部文档信息。



Code of Conduct:

- 只根据提供的知识库内容回答,不要编造信息

- 回答时注明来源文档名称

- 如果知识库中没有相关信息,直接说"我在文档中没有找到相关信息",并建议联系对应部门

- 使用简洁、专业的语言

- 不讨论公司机密以外的话题

  1. Click Add in Context and select "Company Internal Knowledge Base"
  2. Configure retrieval parameters: hybrid retrieval, similarity threshold 0.6, return Top 5 chunks

Step three: Testing and tuning

Test with real questions, the following are recommended test cases:

Original prompt (Chinese, left untranslated)



Test question example:

"年假怎么申请?" → 应该从 HR 政策文档返回正确步骤

"产品 A 的定价是多少?" → 应该从产品手册返回准确价格

"如何配置 VPN?" → 应该从技术 Wiki 返回步骤

"CEO 是谁?" → 如果文档中没有,应该诚实说不知道

Common tuning operations

Problem Solution
Inaccurate answers Lower the similarity threshold (e.g., 0.5) and increase the number of returned Chunks
Irrelevant answer Increase the threshold (e.g., 0.7) and check if the document chunking is reasonable
Incomplete answer Increase the chunk size to include more complete paragraphs in each Chunk

Step four: Publishing and Integration

Publish as a web application: Select Overview on the application page, click Embedded, copy the embed code, and paste it into the internal Wiki or Intranet page.

Publish as an API: Select API Reference on the application page, copy the API Key, and use the following call example:

Original prompt (Chinese, left untranslated)



# Call the chat API to send a question to the knowledge Q&A robot

curl -X POST 'https://api.dify.ai/v1/chat-messages' \

  -H 'Authorization: Bearer app-xxxxxxxx' \

  -H 'Content-Type: application/json' \

  -d '{

    "inputs": {},

    "query": "年假怎么申请?",

    "response_mode": "blocking",

    "user": "employee-001"

  }'


Practical Scenario Two: Automated Content Generation Pipeline

Use Workflow to generate marketing content for different channels in parallel.

Business Background

The marketing team needs to batch convert product update logs (technical language) into content for different channels: WeChat official account articles, technical blogs, and short video scripts.

Workflow Design

Original prompt (Chinese, left untranslated)



Start(输入:更新日志文本)

  ↓ 并行分支

  ├─→ LLM-1:生成微信推文(轻松活泼,500字,含表情符号)

  ├─→ LLM-2:生成技术博客(专业详细,1500字,含代码示例)

  └─→ LLM-3:生成短视频脚本(口语化,300字,分镜头格式)

  ↓ 合并

End(输出:三份内容)

Specific Setup Steps

Step 1: Create a Workflow application and name it "Content Generation Pipeline".

Step 2: Configure the Start node and add input variables:

Variable Name Type Description
update_content Text type Original product update log
product_name Text type Product name
version Text type Version number

Step 3: Add three LLM nodes (in parallel).

Connect all three LLM nodes to the Start node; Dify will execute them in parallel automatically.

Prompt example for LLM-1 (WeChat post):

Original prompt (Chinese, left untranslated)



你是一位擅长社交媒体写作的内容创作者。



Please rewrite the changelog for {{product_name}} v{{version}} below into a WeChat official account article:

- 字数:400-600字

- 语气:轻松活泼,贴近用户

- 结构:开头吸引眼球,中间介绍亮点,结尾引导互动

- 适当使用 emoji

- 不要使用技术术语,用用户能理解的语言



Original changelog:

{{Start.update_content}}

LLM-2 (Technical blog) and LLM-3 (Short video script) are configured similarly; just adjust the Prompt and model.

Step 4: Add the End node, and configure the output variables:

Original prompt (Chinese, left untranslated)



wechat_post:引用 {{LLM-1.text}}

tech_blog:引用 {{LLM-2.text}}

video_script:引用 {{LLM-3.text}}

Step five: Integrate into internal tools via API.

Example

import

requests

def

generate_content

(

update_content:

str

,

product_name:

str

,

version:

str

)

:

   

"""Call the Dify Workflow API to batch generate multi-version content"""

   

API Address: Replace api.dify.ai with your Dify instance domain

url

=

"https://api.dify.ai/v1/workflows/run"

   

Request header: Replace with your application API Key

headers

=

{

       

"Authorization"

:

"Bearer app-xxxxxxxx"

,

 

Required: Application API Key

       

"Content-Type"

:

"application/json"

   

}

   

Request body: Pass the three input variables defined in the Start node

payload

=

{

       

"inputs"

:

{

Not Found

"update_content"

: update_content

,

 

Changelog original text

           

"product_name"

: product_name

,

     

Product name

           

"version"

: version

Version number

       

}

,

       

"response_mode"

:

"blocking"

,

 

Blocking mode, waits for the complete result

       

"user"

:

"content-team"

       

User identifier for log tracking

   

}

response

=

requests.

post

(

url

,

headers

=

headers

,

json

=

payload

)

   

Extract the outputs field from the response, which contains the generation results of three LLM nodes

   

return

response.

json

(

)

[

"data"

]

[

"outputs"

]


Scenario Practice Three: Customer Support Agent (with Human-in-the-Loop)

Build an intelligent customer service ticket processing system where AI automatically handles standard issues and transfers complex issues to humans with pre-analysis.

Business Background

An e-commerce platform receives 500+ customer service tickets daily, most of which are standard issues (logistics inquiries, return policies), but about 20% require human intervention (complex complaints, large refunds).

Workflow Design

Original prompt (Chinese, left untranslated)



Start(接收用户工单:问题类型 + 内容 + 订单号)

  ↓

LLM-分类:判断问题类型(standard / complex)

  ↓

IF/ELSE:问题类型是否为 standard?

  ├─ standard →

  │    Knowledge Retrieval(从客服知识库检索)

  │      ↓

  │    LLM-回复:生成标准回答

  │      ↓

  │    End(直接回复用户)

  │

  └─ complex →

       LLM-预分析:生成问题摘要和建议处理方案

         ↓

       Human Input(人工审核,可编辑 AI 建议,选择"批准"/"修改"/"升级")

         ↓

       End(发送经过人工确认的回复)

Key Node Configuration

Classify LLM node (output structured JSON):

Instance

{

 

"system"

:

"You are a customer service ticket classification expert. Please analyze the following ticket and output the classification result in JSON format."

,

 

"output_schema"

:

{

   

"category"

:

"standard or complex"

,

   

"reason"

:

"Classification reason (one sentence)"

,

   

"priority"

:

"low / medium / high"

 

}

,

 

"criteria"

:

{

   

"standard"

:

"Logistics inquiry, return policy, standard refund (<500 RMB), account issues"

,

   

"complex"

:

"Large refunds (>500 RMB), complaints, disputes, product quality issues"

 

}

}

Human Input node configuration:

Configuration item Description
Display content AI pre-analysis results + suggested reply draft
Editable fields Reply content, priority
Custom buttons Approve (use AI suggested reply), Approve after modification (reply after manual editing), Escalate (transfer to specialized handling team)

Expected outcome

Ticket type Handling method Effect improvement
Standard issues (about 80%) Fully automatic AI processing Response time reduced from 4 hours to 30 seconds
Complex issues (about 20%) AI assists human, providing analysis and drafts Human processing time reduced by 60%
Overall - Ticket processing efficiency improved by about 3 times

External release: API, web embedding, and MCP server

Deploy Dify applications to external systems, supporting three methods: API calls, web embedding, and MCP server.

Release as API

Every Dify application automatically has a REST API. Obtain it by selecting API Access on the application page.

Chat application API call example:

Original prompt (Chinese, left untranslated)



# Call chat API (streaming mode)

curl -X POST 'https://api.dify.ai/v1/chat-messages' \

  -H 'Authorization: Bearer {API_KEY}' \

  -H 'Content-Type: application/json' \

  -d '{

    "inputs": {},

    "query": "你好",

    "response_mode": "streaming",

    "conversation_id": "",

    "user": "user-001"

  }'

Workflow Application API Call Example:

Original prompt (Chinese, left untranslated)



# Call Workflow API (blocking mode)

curl -X POST 'https://api.dify.ai/v1/workflows/run' \

  -H 'Authorization: Bearer {API_KEY}' \

  -H 'Content-Type: application/json' \

  -d '{

    "inputs": {"your_variable": "your_value"},

    "response_mode": "blocking",

    "user": "user-001"

  }'

The API Key format starts with app-. Ensure it is passed in the request header as Authorization: Bearer, not as a query parameter. Each API Key corresponds to a specific application, and keys for different applications are not interchangeable.

Web Embedding

In the application page, select Overview, click Embedded, and provide three embedding methods:

Method One: iframe Embedding

Example

Method Two: Bubble Button (floating in the bottom right corner of the webpage)

Example

Method three: full-screen web page, independent access, share the link directly: https://udify.app/chat/xxxxxxxx.

Publish as an MCP server

Dify supports publishing a built workflow or Agent as a standard MCP server, supporting pre-authorized and no-authentication modes.

This means: the knowledge base Q&A application you build in Dify can directly become a tool node for AI programming tools like Claude Code, Cursor, omp, etc., seamlessly integrating into the development workflow.

Operation path: Select Publish in the application, then click MCP Server.


Observability: Monitoring and continuous optimization

Continuously monitor and optimize the performance of AI applications through logs, annotations, statistics, and external platform integration.

View application logs

In the application page, select Logs to view the complete input/output of each conversation, Token usage (input and output separately), response time, model, and parameter information.

Annotate conversations

In the logs, click on a specific conversation and click the thumbs up or thumbs down button next to the answer to add the ideal answer as an annotation.

The uses of annotated data include: building fine-tuning datasets through annotations, identifying knowledge base coverage gaps, and discovering frequently occurring problem types.

Application Data Statistics

In the application page, select Overview and click Analytics to view:

Statistics Items Description
Conversation count trend Conversation volume change by day/week/month
Average Token consumption Average Token usage per conversation
User satisfaction score Like/dislike distribution statistics
Number of active users Number of unique users who used this application

Integrate external observability platforms

Dify supports observability platforms such as Opik, Langfuse, and Arize Phoenix.

For example, with Langfuse: Select Monitoring in Settings, select Langfuse, and after entering the Public Key and Secret Key, save. Subsequently, the call traces of all applications will be automatically synchronized to Langfuse, allowing you to view complete Span tracing and Token consumption details.

Continuous Optimization Loop

It is recommended to establish the following continuous optimization process:

Original prompt (Chinese, left untranslated)



部署上线

  ↓

收集对话日志(1-2 周)

  ↓

分析差评对话:哪些问题回答得不好?

  ↓

改进知识库(补充文档、调整分块)或优化 Prompt

  ↓

A/B 测试:对比改进前后的效果

  ↓

再次部署


Costs and Plans

Understand the pricing structures for Dify Cloud and self-hosted options to choose the plan that best suits you.

Dify Cloud Plans

Package Monthly fee Description
Sandbox Free 200 messages/month, 5 applications, applicable to experience scenarios
Professional $59/month 5,000 messages/month, 50 applications, team collaboration support
Team $159/month 10,000 messages/month, unlimited applications, priority support
Enterprise Customization Unlimited usage, private deployment option, SLA guarantee

Self-hosted cost

The self-hosted community edition is completely free with no usage restrictions.

You only need to pay for server hosting fees (a VPS is about $5-50/month) and AI model API call fees.

Cost estimate (self-hosted, 10,000 conversations/month):

Component Cost estimate
VPS (4 cores 8 GB) $20-40/month
Claude Sonnet 4.6 (approx. 1K Tokens per conversation) ~$30/month
Embedding (text-embedding-3-small) ~$2/month
Total ~$52-72/month

Compared to Dify Cloud Professional ($59/month, plus model API fees), self-hosting is usually more economical with heavy usage.

Tips to reduce costs

Tips Description
Knowledge base indexing using economic model Vectorization is unnecessary when existing keyword search is sufficient
Select the appropriate model Use GPT-4o-mini or Gemini Flash for simple Q&A, and flagship models for complex tasks
Set the token limit Set max_tokens in the LLM node to prevent excessively long single calls
Enable caching Automatically reuse the last answer for similar questions (Prompt Cache)

FAQ and Troubleshooting

Troubleshooting methods covering four categories of common issues: startup, knowledge base retrieval, API calls, and workflows.

Startup Issues

Problem: Service is unhealthy after docker compose up -d

Example

Check the api container logs to locate the specific error

docker compose logs api

View worker container logs

docker compose logs worker

Check if there is enough memory (at least 4 GB is required)

free

-h

Check if the port is in use (80 or 443)

sudo

lsof

-i

:

80

Problem: Accessing http://localhost shows 502 Bad Gateway

Instance

Wait for all containers to fully start (usually takes 1-2 minutes)

docker compose

ps

Revisit after confirming that api, web, and worker are all in a healthy state

Knowledge base retrieval issues

Issue: Knowledge base cannot retrieve relevant content

Troubleshooting steps:

  1. In the knowledge base, click Retrieval Testing to test the specific issue and confirm if retrieval is possible
  2. If no results are retrieved: Lower the similarity threshold (from 0.6 to 0.3) and test for results
  3. If there are still no results: Confirm that the Embedding model configuration is correct and that the knowledge base indexing is complete
  4. If there are results but the content is incorrect: Check the document chunking strategy and consider manually splitting large files

Issue: RAG returned content is irrelevant

Check the content of the retrieved Chunk. If the Chunk is irrelevant, reduce the chunk size and increase the score threshold. If no Chunk is returned, the threshold might be set too high; temporarily lower it to 0.3 and test. Also, confirm that the knowledge base has been associated with the application's orchestration panel.

API call issues

Issue: API returns 401 Unauthorized

Verify the API Key format—Dify application API Keys start with app-. Ensure it is passed in the request header as Authorization: Bearer, not as a query parameter. Also, confirm that this API Key belongs to the correct application—the Key is application-level and not universal across different applications.

Issue: Streaming response is truncated midway

This is usually a timeout issue. Check the timeout settings of the reverse proxy—Nginx defaults to 60 seconds, which may be insufficient for complex workflows.

Original prompt (Chinese, left untranslated)



# Add timeout configuration in nginx.conf to ensure long-running workflows are not interrupted

proxy_read_timeout 300s;

proxy_connect_timeout 300s;

proxy_send_timeout 300s;

Workflow issues

Issue: A node in the workflow reports an error

Troubleshooting steps:

  1. Open the debug panel and check the input/output of the error node
  2. Click the red marker next to the node to view detailed error information
  3. Common causes: Incorrect variable reference path (check the spelling of {{NodeName.VariableName}})

Resources

Recommended learning paths and related resources to help you from beginner to expert.

Recommended learning paths

Original prompt (Chinese, left untranslated)



注册 Dify Cloud,用 Sandbox 体验

    ↓

配置自己的模型提供商(Anthropic 或 OpenAI)

    ↓

创建第一个知识库,上传 5-10 个文档,测试检索效果

    ↓

创建 Chatbot 应用,关联知识库,完成场景实战一

    ↓

学习 Workflow,完成场景实战二(内容生成流水线)

    ↓

探索 Human Input 节点,完成场景实战三(客服 Agent)

    ↓

用 Docker Compose 搭建本地/服务器自托管版本

    ↓

通过 API 将 Dify 应用集成到现有系统

    ↓

探索 MCP Server 发布,接入 AI 编程工具生态

Official Resources

Resources Links Description
Official Website dify.ai Product Information and Registration Entrance
Documentation docs.dify.ai Complete product documentation
GitHub github.com/langgenius/dify Apache 2.0 open source, you can view the source code and submit issues
Discord community discord.gg/FngNHpbcY7 Communicate with community members and the official team
Template Marketplace In-app Templates Directly use workflow templates shared by the community
Dify Blog dify.ai/blog Feature updates and use cases
Knowledge Base FAQ docs.dify.ai/faq Official FAQ Answers