dify Documentation

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams...

RAW Doc

Technical Documentation: langgenius/dify

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (README.md)

Dify is an open-source LLM app development platform. Its intuitive interface combines AI workflow, RAG pipeline, agent capabilities, model management, observability features (including Opik, Langfuse, and Arize Phoenix) and more, letting you quickly go from prototype to production. Here's a list of the core features:

Quick start

Before installing Dify, make sure your machine meets the following minimum system requirements:

  • CPU >= 2 Core
  • RAM >= 4 GiB

The easiest way to start the Dify server is through Docker Compose. Before running Dify with the following commands, make sure that Docker and Docker Compose v2.24.0 or later are installed on your machine:

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

After running, you can access the Dify dashboard in your browser at http://localhost/install and start the initialization process.

Seeking help

Please refer to our FAQ if you encounter problems setting up Dify. Reach out to the community and us if you are still having issues.

If you'd like to contribute to Dify or do additional development, refer to our guide to deploying from source code

Key features

1. Workflow:
Build and test powerful AI workflows on a visual canvas, leveraging all the following features and beyond.

2. Comprehensive model support:
Seamless integration with hundreds of proprietary / open-source LLMs from dozens of inference providers and self-hosted solutions, covering GPT, Mistral, Llama3, and any OpenAI API-compatible models. A full list of supported model providers can be found here.

3. Prompt IDE:
Intuitive interface for crafting prompts, comparing model performance, and adding additional features such as text-to-speech to a chat-based app.

4. RAG Pipeline:
Extensive RAG capabilities that cover everything from document ingestion to retrieval, with out-of-box support for text extraction from PDFs, PPTs, and other common document formats.

5. Agent: Autonomous agents with a sandbox of their own: they run commands, install software, and handle files to get open-ended tasks done. Describe the agent you want and it builds itself. Give it skills, connect tools from Dify Marketplace, MCP servers, or your own APIs, and put it to work as a chat app or as a step in any workflow.

6. LLMOps:
Monitor and analyze application logs and performance over time. You could continuously improve prompts, datasets, and models based on production data and annotations.

7. Backend-as-a-Service:
All of Dify's offerings come with corresponding APIs, so you could effortlessly integrate Dify into your own business logic.

Using Dify

  • **Cloud **
    We host Dify Cloud so you can try Dify without managing a server. See the pricing page for current plans and usage allowances. If you run into issues, contact our Cloud support team.

  • Self-hosting Dify Community Edition
    Quickly get Dify running in your environment with this starter guide.
    Use our documentation for further references and more in-depth instructions.

  • Dify Enterprise
    For organizations requiring self-hosting, SSO, RBAC Security and Enterprise Support SLAs, please fill out this form to speak to a solution representative.

Staying ahead

Star Dify on GitHub and be instantly notified of new releases.

Advanced Setup

For custom configuration, observability, and deployment options, see Advanced Setup.

Contributing

Dify welcomes contributions of all kinds:

Contributors

Community & contact

Choose the channel that best fits your question:

  • GitHub Discussions: Get help, share feedback, and propose ideas.
  • GitHub Issues: Report reproducible bugs and track engineering work. Read the Contribution Guide before opening one.
  • Discord: Chat in real time, share your apps, and connect with other Dify users.
  • X: Follow Dify for release news and project updates.

Star History

Security disclosure

Report vulnerabilities privately through GitHub Security Advisories, following our security policy. Do not disclose them in public issues, discussions, or pull requests.

License

This repository is licensed under the Dify Open Source License, based on Apache 2.0 with additional conditions.


Dify Agent Docs Index (`dify-agent/docs/index.md`)

Dify Agent

Runtime modules compose native Pydantic AI capabilities
and toolsets. Getting started covers the HTTP
protocol; operations covers deployment.


Ar SA README (`docs/ar-SA/README.md`)

مشروع Dify هو منصة تطوير تطبيقات الذكاء الصناعي مفتوحة المصدر. تجمع واجهته البديهية بين سير العمل الذكي بالذكاء الاصطناعي وخط أنابيب RAG وقدرات الوكيل وإدارة النماذج وميزات الملاحظة وأكثر من ذلك، مما يتيح لك الانتقال بسرعة من المرحلة التجريبية إلى الإنتاج. إليك قائمة بالميزات الأساسية:

1. سير العمل: قم ببناء واختبار سير عمل الذكاء الاصطناعي القوي على قماش بصري، مستفيدًا من جميع الميزات التالية وأكثر.

2. الدعم الشامل للنماذج: تكامل سلس مع مئات من LLMs الخاصة / مفتوحة المصدر من عشرات من موفري التحليل والحلول المستضافة ذاتيًا، مما يغطي GPT و Mistral و Llama3 وأي نماذج متوافقة مع واجهة OpenAI API. يمكن العثور على قائمة كاملة بمزودي النموذج المدعومين هنا.

3. بيئة التطوير للأوامر: واجهة بيئة التطوير المبتكرة لصياغة الأمر ومقارنة أداء النموذج، وإضافة ميزات إضافية مثل تحويل النص إلى كلام إلى تطبيق قائم على الدردشة.

4. خط أنابيب RAG: قدرات RAG الواسعة التي تغطي كل شيء من استيعاب الوثائق إلى الاسترجاع، مع الدعم الفوري لاستخراج النص من ملفات PDF و PPT وتنسيقات الوثائق الشائعة الأخرى.

5. قدرات الوكيل: يمكنك تعريف الوكلاء بناءً على أمر وظيفة LLM أو ReAct، وإضافة أدوات مدمجة أو مخصصة للوكيل. توفر Dify أكثر من 50 أداة مدمجة لوكلاء الذكاء الاصطناعي، مثل البحث في Google و DALL·E وStable Diffusion و WolframAlpha.

6. الـ LLMOps: راقب وتحلل سجلات التطبيق والأداء على مر الزمن. يمكنك تحسين الأوامر والبيانات والنماذج باستمرار استنادًا إلى البيانات الإنتاجية والتعليقات.

7.الواجهة الخلفية (Backend) كخدمة: تأتي جميع عروض Dify مع APIs مطابقة، حتى يمكنك دمج Dify بسهولة في منطق أعمالك الخاص.

استخدام Dify

  • **سحابة **
    جرّب Dify Cloud دون إدارة خادم. راجع صفحة الأسعار للاطلاع على الخطط وحصص الاستخدام الحالية.

  • استضافة ذاتية لنسخة المجتمع Dify
    ابدأ سريعًا في تشغيل Dify في بيئتك باستخدام [دليل البدء السريع](#البدء السريع).
    استخدم توثيقنا للمزيد من المراجع والتعليمات الأعمق.

  • مشروع Dify للشركات / المؤسسات
    نحن نوفر ميزات إضافية مركزة على الشركات. جدول اجتماع معنا أو أرسل لنا بريدًا إلكترونيًا لمناقشة احتياجات الشركات.

البقاء قدمًا

قم بإضافة نجمة إلى Dify على GitHub وتلق تنبيهًا فوريًا بالإصدارات الجديدة.

البداية السريعة

قبل تثبيت Dify، تأكد من أن جهازك يلبي الحد الأدنى من متطلبات النظام التالية:

  • معالج >= 2 نواة
  • ذاكرة وصول عشوائي (RAM) >= 4 جيجابايت

أسهل طريقة لبدء تشغيل خادم Dify هي تشغيل ملف docker-compose.yml الخاص بنا. قبل تشغيل أمر التثبيت، تأكد من تثبيت Docker و Docker Compose على جهازك:

bash
cd docker
cp .env.example .env
docker compose up -d

بعد التشغيل، يمكنك الوصول إلى لوحة تحكم Dify في متصفحك على http://localhost/install وبدء عملية التهيئة.

إذا كنت ترغب في المساهمة في Dify أو القيام بتطوير إضافي، فانظر إلى دليلنا للنشر من الشفرة (code) المصدرية

الخطوات التالية

لخيارات التكوين المخصص والمراقبة والنشر، راجع الإعداد المتقدم.

المساهمة

يرحب Dify بالمساهمات بجميع أشكالها:

المساهمون

المجتمع والاتصال

اختر القناة الأنسب لسؤالك:

  • مناقشات GitHub: للحصول على المساعدة ومشاركة الملاحظات واقتراح الأفكار.
  • مشكلات GitHub: للإبلاغ عن الأخطاء القابلة لإعادة الإنتاج ومتابعة العمل الهندسي. اقرأ دليل المساهمة قبل فتح مشكلة.
  • Discord: للدردشة الفورية ومشاركة تطبيقاتك والتواصل مع مستخدمي Dify الآخرين.
  • X: لمتابعة أخبار الإصدارات وتحديثات المشروع.

تاريخ النجمة

الكشف عن الأمان

أبلغ عن الثغرات بشكل خاص عبر GitHub Security Advisories وفقًا لسياسة الأمان. لا تفصح عنها في المشكلات أو المناقشات أو طلبات السحب العامة.

الرخصة

هذا المستودع متاح تحت رخصة البرنامج الحر Dify، والتي تعتبر بشكل أساسي Apache 2.0 مع بعض القيود الإضافية.


Bn BD README (`docs/bn-BD/README.md`)

ডিফাই একটি ওপেন-সোর্স LLM অ্যাপ ডেভেলপমেন্ট প্ল্যাটফর্ম। এটি ইন্টুইটিভ ইন্টারফেস, এজেন্টিক AI ওয়ার্কফ্লো, RAG পাইপলাইন, এজেন্ট ক্যাপাবিলিটি, মডেল ম্যানেজমেন্ট, মনিটরিং সুবিধা এবং আরও অনেক কিছু একত্রিত করে, যা দ্রুত প্রোটোটাইপ থেকে প্রোডাকশন পর্যন্ত নিয়ে যেতে সহায়তা করে।

কুইক স্টার্ট

ডিফাই ইনস্টল করার আগে, নিশ্চিত করুন যে আপনার মেশিন নিম্নলিখিত ন্যূনতম কনফিগারেশনের প্রয়োজনীয়তা পূরন করে :

  • সিপিউ >= 2 কোর
  • র‍্যাম >= 4 জিবি

ডিফাই সার্ভার চালু করার সবচেয়ে সহজ উপায় docker compose মাধ্যমে। নিম্নলিখিত কমান্ডগুলো ব্যবহার করে ডিফাই চালানোর আগে, নিশ্চিত করুন যে আপনার মেশিনে Docker এবং Docker Compose ইনস্টল করা আছে :

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

চালানোর পর, আপনি আপনার ব্রাউজারে http://localhost/install-এ ডিফাই ড্যাশবোর্ডে অ্যাক্সেস করতে পারেন এবং ইনিশিয়ালাইজেশন প্রক্রিয়া শুরু করতে পারেন।

সাহায্যের খোঁজে

ডিফাই সেট আপ করতে সমস্যা হলে দয়া করে আমাদের FAQ দেখুন। যদি তবুও সমস্যা থেকে থাকে, তাহলে কমিউনিটি এবং আমাদের সাথে যোগাযোগ করুন।

যদি আপনি ডিফাইতে অবদান রাখতে বা অতিরিক্ত উন্নয়ন করতে চান, আমাদের সোর্স কোড থেকে ডিপ্লয়মেন্টের গাইড দেখুন।

প্রধান ফিচারসমূহ

১. ওয়ার্কফ্লো:
ভিজ্যুয়াল ক্যানভাসে AI ওয়ার্কফ্লো তৈরি এবং পরীক্ষা করুন, নিম্নলিখিত সব ফিচার এবং তার বাইরেও আরও অনেক কিছু ব্যবহার করে।

২. মডেল সাপোর্ট:
GPT, Mistral, Llama3, এবং যেকোনো OpenAI API-সামঞ্জস্যপূর্ণ মডেলসহ, কয়েক ডজন ইনফারেন্স প্রদানকারী এবং সেল্ফ-হোস্টেড সমাধান থেকে শুরু করে প্রোপ্রাইটরি/ওপেন-সোর্স LLM-এর সাথে সহজে ইন্টিগ্রেশন। সমর্থিত মডেল প্রদানকারীদের একটি সম্পূর্ণ তালিকা পাওয়া যাবে এখানে।

3. প্রম্পট IDE:
প্রম্পট তৈরি, মডেলের পারফরম্যান্স তুলনা এবং চ্যাট-বেজড অ্যাপে টেক্সট-টু-স্পিচের মতো বৈশিষ্ট্য যুক্ত করার জন্য ইন্টুইটিভ ইন্টারফেস।

4. RAG পাইপলাইন:
ডকুমেন্ট ইনজেশন থেকে শুরু করে রিট্রিভ পর্যন্ত সবকিছুই বিস্তৃত RAG ক্যাপাবিলিটির আওতাভুক্ত। PDF, PPT এবং অন্যান্য সাধারণ ডকুমেন্ট ফর্ম্যাট থেকে টেক্সট এক্সট্রাকশনের জন্য আউট-অফ-বক্স সাপোর্ট।

5. এজেন্ট ক্যাপাবিলিটি:
LLM ফাংশন কলিং বা ReAct উপর ভিত্তি করে এজেন্ট ডিফাইন করতে পারেন এবং এজেন্টের জন্য পূর্ব-নির্মিত বা কাস্টম টুলস যুক্ত করতে পারেন। Dify AI এজেন্টদের জন্য 50+ বিল্ট-ইন টুলস সরবরাহ করে, যেমন Google Search, DALL·E, Stable Diffusion এবং WolframAlpha।

6. এলএলএম-অপ্স:
সময়ের সাথে সাথে অ্যাপ্লিকেশন লগ এবং পারফরম্যান্স মনিটর এবং বিশ্লেষণ করুন। প্রডাকশন ডেটা এবং annotation এর উপর ভিত্তি করে প্রম্পট, ডেটাসেট এবং মডেলগুলিকে ক্রমাগত উন্নত করতে পারেন।

7. ব্যাকএন্ড-অ্যাজ-এ-সার্ভিস:
ডিফাই-এর সমস্ত অফার সংশ্লিষ্ট API-সহ আছে, যাতে আপনি অনায়াসে ডিফাইকে আপনার নিজস্ব বিজনেস লজিকে ইন্টেগ্রেট করতে পারেন।

ডিফাই-এর ব্যবহার

এগিয়ে থাকুন

GitHub-এ ডিফাইকে স্টার দিয়ে রাখুন এবং নতুন রিলিজের খবর তাৎক্ষণিকভাবে পান।

Advanced Setup

কাস্টম কনফিগারেশন, পর্যবেক্ষণ এবং ডেপ্লয়মেন্ট বিকল্পের জন্য, উন্নত সেটআপ দেখুন।

অবদান

Dify সব ধরনের অবদানকে স্বাগত জানায়:

অবদানকারীরা

কমিউনিটি এবং যোগাযোগ

আপনার প্রশ্নের জন্য সবচেয়ে উপযুক্ত মাধ্যমটি বেছে নিন:

  • GitHub Discussions: সাহায্য নিন, প্রতিক্রিয়া জানান এবং ধারণা প্রস্তাব করুন।
  • GitHub Issues: পুনরুৎপাদনযোগ্য বাগ রিপোর্ট করুন এবং ইঞ্জিনিয়ারিং কাজ অনুসরণ করুন। নতুন ইস্যু খোলার আগে অবদান নির্দেশিকা পড়ুন।
  • Discord: সরাসরি আলোচনা করুন, আপনার অ্যাপ শেয়ার করুন এবং অন্যান্য Dify ব্যবহারকারীর সঙ্গে যুক্ত হন।
  • X: রিলিজের খবর এবং প্রকল্পের হালনাগাদ পেতে Dify অনুসরণ করুন।

স্টার হিস্ট্রি

নিরাপত্তা বিষয়ক

আমাদের নিরাপত্তা নীতি অনুসারে GitHub Security Advisories-এর মাধ্যমে গোপনে নিরাপত্তা দুর্বলতা জানান। প্রকাশ্য issue, আলোচনা বা pull request-এ তা প্রকাশ করবেন না।

লাইসেন্স

এই রিপোজিটরিটি ডিফাই ওপেন সোর্স লাইসেন্স এর অধিনে , যা মূলত অ্যাপাচি ২.০, তবে কিছু অতিরিক্ত বিধিনিষেধ রয়েছে।


Cross Env App Migration README (`docs/cross-env-app-migration/README.md`)

Cross-Environment Data Migration

This guide explains how to move workflow apps, chatflow apps, and their custom tool dependencies from one Dify environment to another.

The recommended best-practice path is:

  1. Run the export wizard in the source environment.
  2. Import the generated migration package in the target environment.

Use scripted export only when you need repeatable automation.

What Gets Migrated

The migration package can contain:

  • Workflow apps and advanced-chat apps.
  • Custom API tool providers.
  • Workflow tool providers.
  • MCP tool providers when secrets are explicitly included.
  • Dependency metadata for MCP tools, built-in tools, and plugin tools that must already exist or be configured in the target environment.

Only single source workspace exports are supported. The source and target workspace names do not need to match.

Run the wizard from the source environment:

bash
cd api
source .venv/bin/activate
uv run flask app-migration-wizard

The wizard asks you to select the source workspace, choose workflow/chatflow apps, discover referenced tools, set import behavior, and write the final migration package JSON.

Then copy the generated JSON package to the target environment and import it:

bash
cd api
source .venv/bin/activate
uv run flask import-app-migration \
  --input migration-data-20260528-120000.json \
  --target-tenant "production Workspace"

This wizard + import combination is the recommended migration workflow because the wizard shows the available apps and tools, discovers app dependencies, summarizes the package before writing it, and uses the same export service as scripted export.

Wizard Command

bash
cd api
source .venv/bin/activate
uv run flask app-migration-wizard

The wizard has no CLI options. Its interactive inputs are:

  • Source tenant: the source workspace to export from. Select one tenant by number.
  • App selection: apps to export. Supported app types are workflow and advanced-chat. Enter all, one number, or comma-separated numbers.
  • Automatically export tools referenced by selected apps?: recommended yes. This scans selected app graphs and automatically includes referenced custom API tools, workflow tools, and MCP tool references.
  • Export additional tools manually?: optional. Use this when you need to migrate tools that are not referenced by the selected apps.
  • Include secrets in output JSON?: default no. When no, workflow/app DSL secrets are omitted or masked, API tool credentials are omitted, and MCP providers are exported as dependency metadata only. When yes, treat the output JSON as sensitive.
  • Create or reuse app API tokens during import?: default no. When yes, import creates an app API token for imported apps that have none, or reuses an existing token.
  • Import ID strategy: preserve-id or generate-new-id. Default is preserve-id.
  • Import conflict strategy: fail, skip, or update. Wizard default is update.
  • Output path: output migration package path. The default is migration-data-YYYYMMDD-HHMMSS.json.
  • Overwrite existing output: shown only if the selected output file already exists.
  • Write migration package?: final confirmation after the wizard prints the summary.

Import Command

bash
cd api
source .venv/bin/activate
uv run flask import-app-migration --input migration-package.json --target-tenant "target Workspace"

Options:

  • --input: required. Path to the migration package JSON generated by the wizard or scripted export.
  • --target-tenant: optional only when package metadata already contains a target tenant. Target workspace name or workspace UUID. This overrides package metadata and is recommended for reusable packages.
  • --operator-email: optional. Email of the target-tenant account used as the import operator. If omitted, import uses the earliest owner account in the target tenant.
  • --id-strategy: optional override for the package import option. Allowed values:
    • preserve-id: keep source app/tool IDs when supported. This is the recommended default for preserving workflow references across environments.
    • generate-new-id: let the target environment generate new IDs and rewrite references through the migration ID mapping.
  • --conflict-strategy: optional override for the package import option. Allowed values:
    • fail: stop at the first existing target resource conflict. Previously committed resources are not rolled back.
    • skip: keep the existing target resource and skip importing that resource.
    • update: update the existing target resource in place.
  • --create-app-api-token-on-import: optional override. Create or reuse app API tokens during import.
  • --no-create-app-api-token-on-import: optional override. Do not create app API tokens during import.

Import prints a report that includes the resolved target tenant, operator, created/updated/skipped resources, unresolved dependencies, app API token counts, and ID mappings used to rewrite references.

Optional Flow: Scripted Export

Scripted export is supported for automation. The recommended scripted path is:

  1. Generate an export config template.
  2. Edit the template.
  3. Run scripted export.
  4. Import the generated package.

Generate the template:

bash
cd api
source .venv/bin/activate
uv run flask app-migration-template --output export-config.json

Edit export-config.json, then run:

bash
cd api
source .venv/bin/activate
uv run flask export-app-migration \
  --input export-config.json \
  --output migration-package.json

Import it:

bash
cd api
source .venv/bin/activate
uv run flask import-app-migration \
  --input migration-package.json \
  --target-tenant "production Workspace"

Template Command

bash
cd api
source .venv/bin/activate
uv run flask app-migration-template [--output export-config.json] [--overwrite]

Options:

  • --output: optional. Path to write the scripted export config JSON template. If omitted, the template is printed to stdout.
  • --overwrite: optional. Allows replacing an existing output file. Without this option, the command fails if --output already exists.

Scripted Export Command

bash
cd api
source .venv/bin/activate
uv run flask export-app-migration --input export-config.json --output migration-package.json

Options:

  • --input: required. Path to the export config JSON.
  • --output: required. Path to write the migration package JSON.
  • --overwrite: optional. Allows replacing an existing output package. Without this option, the command fails if --output already exists.

Export Config Fields

The generated template uses this shape:

json
{
  "source_tenant": {
    "mode": "single",
    "id": "",
    "name": "admin's Workspace"
  },
  "apps": {
    "modes": ["workflow", "advanced-chat"],
    "ids": [],
    "all": true
  },
  "include_referenced_tools": true,
  "additional_tools": {
    "api_tools": [],
    "workflow_tools": [],
    "mcp_tools": []
  },
  "include_secrets": false,
  "import_options": {
    "create_app_api_token_on_import": false,
    "id_strategy": "preserve-id",
    "conflict_strategy": "fail"
  }
}

Fields:

  • source_tenant.mode: must be single.
  • source_tenant.id: optional source workspace UUID. Use this when workspace names are duplicated or when you want strict source selection.
  • source_tenant.name: required source workspace name. When source_tenant.id is set, the ID and name must match.
  • apps.modes: optional list of app modes for validation. Supported values are workflow and advanced-chat.
  • apps.ids: app IDs to export when apps.all is false.
  • apps.all: when true, export all supported apps in the selected source workspace. When false, export only apps.ids.
  • include_referenced_tools: recommended true. Automatically discovers tools referenced by selected workflow/chatflow apps.
  • additional_tools.api_tools: optional custom API tool provider names to export in addition to referenced tools.
  • additional_tools.workflow_tools: optional workflow tool provider IDs to export in addition to referenced tools.
  • additional_tools.mcp_tools: optional MCP provider IDs or server identifiers to export in addition to referenced tools.
  • include_secrets: default false. When false, credentials are omitted and MCP providers are recorded as dependency metadata. When true, custom API credentials, workflow DSL secrets, and full MCP connection data can be written to the package.
  • import_options.create_app_api_token_on_import: default false. Package-level default for import token creation.
  • import_options.id_strategy: package-level default ID strategy. Allowed values are preserve-id and generate-new-id.
  • import_options.conflict_strategy: package-level default conflict strategy. Allowed values are fail, skip, and update.

Referenced Tools

Use automatic referenced-tool discovery whenever possible.

When enabled, Dify scans selected workflow/chatflow graphs and agent tool configs, then de-duplicates discovered custom API tools, workflow tools, and MCP tool references before export. This reduces the chance of importing an app whose workflow references missing providers.

Built-in and plugin tools are not serialized into the package. The migration report records them as dependency metadata; make sure the target environment has the required built-in or plugin tools installed and configured.

MCP providers are also dependency-only unless include_secrets is enabled. If MCP secrets are not exported, configure the corresponding MCP provider manually in the target workspace before running migrated workflows.

Secret Handling

The safe default is include_secrets: false.

Only enable secret export when you have a controlled transfer path for the JSON package. With secrets enabled, the package may include API tool credentials, workflow/app DSL secret values, MCP server URLs, MCP headers, authentication data, and cached MCP tool lists.

FAQ

What happens when `include_secrets` is `false`?

This is the recommended default, but it means the migration package is intentionally incomplete for sensitive runtime configuration.

Important behavior:

  • MCP tools are not exported as full tool providers. They are recorded as dependency metadata only.
  • Custom API tool credentials are not exported. The provider schema can be exported, but credentials must be configured again in the target workspace.
  • Workflow/app DSL secrets are omitted or masked. Any app variables, credentials, or secret-backed settings must be reviewed in the target workspace after import.
  • Built-in and plugin tools are never serialized as custom migration data. They are recorded as dependencies only.

How to handle it:

  • Before importing, install or enable the required built-in/plugin tools in the target environment.
  • For MCP tools, manually create or configure the corresponding MCP provider in the target workspace before running migrated workflows.
  • For custom API tools, open the imported provider in the target workspace and re-enter credentials.
  • After import, review each migrated workflow/chatflow before production use. Pay special attention to tool nodes, agent tool configs, environment variables, app variables, and credential-backed settings.
  • Use the import report. Items marked dependency-only, skipped, or unresolved usually need manual follow-up.

If you need the package to carry full MCP provider configuration or credentials, rerun export with include_secrets set to true and transfer the generated JSON as sensitive data.

What should I consider when `include_secrets` is `true`?

The package can include sensitive runtime configuration such as API tool credentials, workflow/app DSL secret values, MCP server URLs, headers, authentication data, and MCP tool lists.

How to handle it:

  • Store and transfer the JSON package as a secret.
  • Delete the package after import if your security policy requires it.
  • Prefer using this only for controlled one-time migrations where manual target-side credential setup is harder than securing the package.

Should I use `preserve-id` or `generate-new-id`?

The ID strategy controls whether imported resources keep source IDs or receive new IDs in the target environment. It applies to workflow apps and custom tool resources where the target service supports explicit IDs.

Use preserve-id by default. It is recommended for cross-environment app migration because imported apps and tools try to keep their source IDs, which makes workflow references easier to preserve.

Use preserve-id when:

  • You are migrating between environments that are meant to mirror each other, such as staging to production.
  • You want workflow tool references and provider references to remain as stable as possible.
  • The target environment does not already contain unrelated resources with the same IDs.

Watch out for:

  • If the target already has a resource with the same ID, conflict_strategy=fail stops the import, skip keeps the target resource, and update updates it in place.
  • If the same ID was reused for a different resource in the target environment, review carefully before using update.

Use generate-new-id when the target environment should keep its own local IDs.

Use generate-new-id when:

  • The target environment already has resources that may conflict with source IDs.
  • You are importing a package as a copy rather than trying to mirror environments.
  • You want to avoid preserving source database IDs in the target environment.

Watch out for:

  • Import records source-to-target ID mappings. Always review the import report's ID mappings.
  • Workflow DSL provider references are rewritten using the generated ID mapping where possible.
  • Dependencies that are metadata-only, such as MCP providers exported with include_secrets=false, still require manual target-side configuration.
  • Built-in/plugin tools are not remapped as migrated custom resources; the target environment must provide them separately.

De DE README (`docs/de-DE/README.md`)

Dify ist eine Open-Source-Plattform zur Entwicklung von LLM-Anwendungen. Ihre intuitive Benutzeroberfläche vereint agentenbasierte KI-Workflows, RAG-Pipelines, Agentenfunktionen, Modellverwaltung, Überwachungsfunktionen und mehr, sodass Sie schnell von einem Prototyp in die Produktion übergehen können.

Schnellstart

Bevor Sie Dify installieren, stellen Sie sicher, dass Ihr System die folgenden Mindestanforderungen erfüllt:

  • CPU >= 2 Core
  • RAM >= 4 GiB

Der einfachste Weg, den Dify-Server zu starten, ist über docker compose. Stellen Sie vor dem Ausführen von Dify mit den folgenden Befehlen sicher, dass Docker und Docker Compose auf Ihrem System installiert sind:

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

Nachdem Sie den Server gestartet haben, können Sie über Ihren Browser auf das Dify Dashboard unter http://localhost/install zugreifen und den Initialisierungsprozess starten.

Hilfe suchen

Bitte beachten Sie unsere FAQ, wenn Sie Probleme bei der Einrichtung von Dify haben. Wenden Sie sich an die Community und uns, falls weiterhin Schwierigkeiten auftreten.

Wenn Sie zu Dify beitragen oder zusätzliche Entwicklungen durchführen möchten, lesen Sie bitte unseren Leitfaden zur Bereitstellung aus dem Quellcode.

Wesentliche Merkmale

1. Workflow:
Erstellen und testen Sie leistungsstarke KI-Workflows auf einer visuellen Oberfläche, wobei Sie alle der folgenden Funktionen und darüber hinaus nutzen können.

2. Umfassende Modellunterstützung:
Nahtlose Integration mit Hunderten von proprietären und Open-Source-LLMs von Dutzenden Inferenzanbietern und selbstgehosteten Lösungen, die GPT, Mistral, Llama3 und alle mit der OpenAI API kompatiblen Modelle abdecken. Eine vollständige Liste der unterstützten Modellanbieter finden Sie hier.

3. Prompt IDE:
Intuitive Benutzeroberfläche zum Erstellen von Prompts, zum Vergleichen der Modellleistung und zum Hinzufügen zusätzlicher Funktionen wie Text-to-Speech in einer chatbasierten Anwendung.

4. RAG Pipeline:
Umfassende RAG-Funktionalitäten, die alles von der Dokumenteneinlesung bis zur -abfrage abdecken, mit sofort einsatzbereiter Unterstützung für die Textextraktion aus PDFs, PPTs und anderen gängigen Dokumentformaten.

5. Fähigkeiten des Agenten:
Sie können Agenten basierend auf LLM Function Calling oder ReAct definieren und vorgefertigte oder benutzerdefinierte Tools für den Agenten hinzufügen. Dify stellt über 50 integrierte Tools für KI-Agenten bereit, wie zum Beispiel Google Search, DALL·E, Stable Diffusion und WolframAlpha.

6. LLMOps:
Überwachen und analysieren Sie Anwendungsprotokolle und die Leistung im Laufe der Zeit. Sie können kontinuierlich Prompts, Datensätze und Modelle basierend auf Produktionsdaten und Annotationen verbessern.

7. Backend-as-a-Service:
Alle Dify-Angebote kommen mit entsprechenden APIs, sodass Sie Dify mühelos in Ihre eigene Geschäftslogik integrieren können.

Dify verwenden

Immer einen Schritt voraus

Star Dify auf GitHub und lassen Sie sich sofort über neue Releases benachrichtigen.

Erweiterte Einstellungen

Optionen für benutzerdefinierte Konfiguration, Observability und Bereitstellung finden Sie unter Erweiterte Einstellungen.

Mitwirken

Dify freut sich über Beiträge jeder Art:

Mitwirkende

Gemeinschaft & Kontakt

Wählen Sie den Kanal, der am besten zu Ihrem Anliegen passt:

  • GitHub Discussions: Hilfe erhalten, Feedback teilen und Ideen vorschlagen.
  • GitHub Issues: Reproduzierbare Fehler melden und technische Arbeiten verfolgen. Lesen Sie vor dem Erstellen eines Issues den Contribution Guide.
  • Discord: In Echtzeit chatten, Apps teilen und sich mit anderen Dify-Nutzern austauschen.
  • X: Neuigkeiten zu Releases und Projekt-Updates verfolgen.

Star-Geschichte

Offenlegung der Sicherheit

Melden Sie Sicherheitslücken gemäß unserer Sicherheitsrichtlinie vertraulich über GitHub Security Advisories. Veröffentlichen Sie sie nicht in öffentlichen Issues, Diskussionen oder Pull Requests.

Lizenz

Dieses Repository steht unter der Dify Open Source License, die im Wesentlichen Apache 2.0 mit einigen zusätzlichen Einschränkungen ist.


Es ES README (`docs/es-ES/README.md`)

Dify es una plataforma de desarrollo de aplicaciones de LLM de código abierto. Su interfaz intuitiva combina flujo de trabajo de IA, pipeline RAG, capacidades de agente, gestión de modelos, características de observabilidad y más, lo que le permite pasar rápidamente de un prototipo a producción. Aquí hay una lista de las características principales:

1. Flujo de trabajo:
Construye y prueba potentes flujos de trabajo de IA en un lienzo visual, aprovechando todas las siguientes características y más.

2. Soporte de modelos completo:
Integración perfecta con cientos de LLMs propietarios / de código abierto de docenas de proveedores de inferencia y soluciones auto-alojadas, que cubren GPT, Mistral, Llama3 y cualquier modelo compatible con la API de OpenAI. Se puede encontrar una lista completa de proveedores de modelos admitidos aquí.

3. IDE de prompt:
Interfaz intuitiva para crear prompts, comparar el rendimiento del modelo y agregar características adicionales como texto a voz a una aplicación basada en chat.

4. Pipeline RAG:
Amplias capacidades de RAG que cubren todo, desde la ingestión de documentos hasta la recuperación, con soporte listo para usar para la extracción de texto de PDF, PPT y otros formatos de documento comunes.

5. Capacidades de agente:
Puedes definir agentes basados en LLM Function Calling o ReAct, y agregar herramientas preconstruidas o personalizadas para el agente. Dify proporciona más de 50 herramientas integradas para agentes de IA, como Búsqueda de Google, DALL·E, Difusión Estable y WolframAlpha.

6. LLMOps:
Supervisa y analiza registros de aplicaciones y rendimiento a lo largo del tiempo. Podrías mejorar continuamente prompts, conjuntos de datos y modelos basados en datos de producción y anotaciones.

7. Backend como servicio:
Todas las ofertas de Dify vienen con APIs correspondientes, por lo que podrías integrar Dify sin esfuerzo en tu propia lógica empresarial.

Usando Dify

  • **Nube **
    Prueba Dify Cloud sin administrar un servidor. Consulta los planes y límites de uso actuales en la página de precios.

  • Auto-alojamiento de Dify Community Edition
    Pon rápidamente Dify en funcionamiento en tu entorno con esta guía de inicio rápido.
    Usa nuestra documentación para más referencias e instrucciones más detalladas.

  • Dify para Empresas / Organizaciones
    Proporcionamos características adicionales centradas en la empresa. Envíanos un correo electrónico para discutir las necesidades empresariales.

Manteniéndote al tanto

Dale estrella a Dify en GitHub y serás notificado instantáneamente de las nuevas versiones.

Inicio Rápido

Antes de instalar Dify, asegúrate de que tu máquina cumpla con los siguientes requisitos mínimos del sistema:

  • CPU >= 2 núcleos
  • RAM >= 4GB

La forma más fácil de iniciar el servidor de Dify es ejecutar nuestro archivo docker-compose.yml. Antes de ejecutar el comando de instalación, asegúrate de que Docker y Docker Compose estén instalados en tu máquina:

bash
cd docker
cp .env.example .env
docker compose up -d

Después de ejecutarlo, puedes acceder al panel de control de Dify en tu navegador en http://localhost/install y comenzar el proceso de inicialización.

Si deseas contribuir a Dify o realizar desarrollo adicional, consulta nuestra guía para implementar desde el código fuente

Próximos pasos

Para opciones de configuración personalizada, observabilidad y despliegue, consulta la Configuración avanzada.

Contribuir

Dify acepta contribuciones de todo tipo:

Contribuidores

Comunidad y contacto

Elige el canal que mejor se adapte a tu consulta:

  • GitHub Discussions: Obtén ayuda, comparte comentarios y propón ideas.
  • GitHub Issues: Informa de errores reproducibles y sigue el trabajo de ingeniería. Lee la Guía de contribución antes de abrir una incidencia.
  • Discord: Chatea en tiempo real, comparte tus aplicaciones y conecta con otros usuarios de Dify.
  • X: Sigue las noticias de versiones y las actualizaciones del proyecto.

Historial de Estrellas

Divulgación de Seguridad

Informa de las vulnerabilidades en privado mediante GitHub Security Advisories, siguiendo nuestra política de seguridad. No las divulgues en issues, debates ni pull requests públicos.

Licencia

Este repositorio está disponible bajo la Licencia de Código Abierto de Dify, que es esencialmente Apache 2.0 con algunas restricciones adicionales.


Fr FR README (`docs/fr-FR/README.md`)

Dify est une plateforme de développement d'applications LLM open source. Sa interface intuitive combine un flux de travail d'IA, un pipeline RAG, des capacités d'agent, une gestion de modèles, des fonctionnalités d'observabilité, et plus encore, vous permettant de passer rapidement du prototype à la production. Voici une liste des fonctionnalités principales:

1. Flux de travail :
Construisez et testez des flux de travail d'IA puissants sur un canevas visuel, en utilisant toutes les fonctionnalités suivantes et plus encore.

2. Prise en charge complète des modèles :
Intégration transparente avec des centaines de LLM propriétaires / open source offerts par dizaines de fournisseurs d'inférence et de solutions auto-hébergées, couvrant GPT, Mistral, Llama3, et tous les modèles compatibles avec l'API OpenAI. Une liste complète des fournisseurs de modèles pris en charge se trouve ici.

3. IDE de prompt :
Interface intuitive pour créer des prompts, comparer les performances des modèles et ajouter des fonctionnalités supplémentaires telles que la synthèse vocale à une application basée sur des chats.

4. Pipeline RAG :
Des capacités RAG étendues qui couvrent tout, de l'ingestion de documents à la récupération, avec un support prêt à l'emploi pour l'extraction de texte à partir de PDF, PPT et autres formats de document courants.

5. Capacités d'agent :
Vous pouvez définir des agents basés sur l'appel de fonctions LLM ou ReAct, et ajouter des outils pré-construits ou personnalisés pour l'agent. Dify fournit plus de 50 outils intégrés pour les agents d'IA, tels que la recherche Google, DALL·E, Stable Diffusion et WolframAlpha.

6. LLMOps :
Surveillez et analysez les journaux d'application et les performances au fil du temps. Vous pouvez continuellement améliorer les prompts, les ensembles de données et les modèles en fonction des données de production et des annotations.

7. Backend-as-a-Service :
Toutes les offres de Dify sont accompagnées d'API correspondantes, vous permettant d'intégrer facilement Dify dans votre propre logique métier.

Utiliser Dify

  • **Cloud **
    Essayez Dify Cloud sans gérer de serveur. Consultez la page des tarifs pour les offres et quotas actuels.

  • Auto-hébergement Dify Community Edition
    Lancez rapidement Dify dans votre environnement avec ce guide de démarrage.
    Utilisez notre documentation pour plus de références et des instructions plus détaillées.

  • Dify pour les entreprises / organisations
    Nous proposons des fonctionnalités supplémentaires adaptées aux entreprises. Envoyez-nous un e-mail pour discuter des besoins de l'entreprise.

Rester en avance

Mettez une étoile à Dify sur GitHub et soyez instantanément informé des nouvelles versions.

Démarrage rapide

Avant d'installer Dify, assurez-vous que votre machine répond aux exigences système minimales suivantes:

  • CPU >= 2 cœurs
  • RAM >= 4 Go

La manière la plus simple de démarrer le serveur Dify est d'exécuter notre fichier docker-compose.yml. Avant d'exécuter la commande d'installation, assurez-vous que Docker et Docker Compose sont installés sur votre machine:

bash
cd docker
cp .env.example .env
docker compose up -d

Après l'exécution, vous pouvez accéder au tableau de bord Dify dans votre navigateur à http://localhost/install et commencer le processus d'initialisation.

Si vous souhaitez contribuer à Dify ou effectuer un développement supplémentaire, consultez notre guide de déploiement à partir du code source

Prochaines étapes

Pour les options de configuration personnalisée, d’observabilité et de déploiement, consultez la page Configuration avancée.

Contribuer

Dify accueille les contributions de toutes sortes :

Contributeurs

Communauté et contact

Choisissez le canal le plus adapté à votre demande :

  • GitHub Discussions : obtenez de l’aide, partagez vos retours et proposez des idées.
  • GitHub Issues : signalez des bogues reproductibles et suivez les travaux d’ingénierie. Consultez le guide de contribution avant d’ouvrir une issue.
  • Discord : échangez en temps réel, partagez vos applications et rencontrez d’autres utilisateurs de Dify.
  • X : suivez les nouvelles versions et les actualités du projet.

Historique des étoiles

Divulgation de sécurité

Signalez les vulnérabilités en privé via GitHub Security Advisories, conformément à notre politique de sécurité. Ne les divulguez pas dans les issues, discussions ou pull requests publiques.

Licence

Ce référentiel est disponible sous la Licence open source Dify, qui est essentiellement l'Apache 2.0 avec quelques restrictions supplémentaires.


Hi IN README (`docs/hi-IN/README.md`)

Dify एक मुक्त-स्रोत प्लेटफ़ॉर्म है जो LLM अनुप्रयोगों (एप्लिकेशनों) के विकास के लिए बनाया गया है। इसका सहज इंटरफ़ेस एजेंटिक एआई वर्कफ़्लो, RAG पाइपलाइनों, एजेंट क्षमताओं, मॉडल प्रबंधन, ऑब्ज़र्वेबिलिटी (निगरानी) सुविधाओं और अन्य को एक साथ जोड़ता है — जिससे आप प्रोटोटाइप से उत्पादन (प्रोडक्शन) तक जल्दी पहुँच सकते हैं।

त्वरित प्रारंभ

Dify स्थापित करने से पहले, सुनिश्चित करें कि आपकी मशीन निम्नलिखित न्यूनतम सिस्टम आवश्यकताओं को पूरा करती है:

  • CPU >= 2 Core
  • RAM >= 4 GiB

Dify सर्वर शुरू करने का सबसे आसान तरीका Docker Compose के माध्यम से है। नीचे दिए गए कमांड्स से Dify चलाने से पहले, सुनिश्चित करें कि आपकी मशीन पर [Docker] (https://docs.docker.com/get-docker/) और [Docker Compose] (https://docs.docker.com/compose/install/) इंस्टॉल हैं।:

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

रन करने के बाद, आप अपने ब्राउज़र में http://localhost/install पर Dify डैशबोर्ड एक्सेस कर सकते हैं और प्रारंभिक सेटअप प्रक्रिया शुरू कर सकते हैं।

सहायता प्राप्त करना

यदि आपको Dify सेटअप करते समय कोई समस्या आती है, तो कृपया हमारे FAQ को देखें। यदि फिर भी समस्या बनी रहती है, तो the community and us से संपर्क करें।

यदि आप Dify में योगदान देना चाहते हैं या अतिरिक्त विकास करना चाहते हैं, तो हमारे guide to deploying from source code को देखें।

मुख्य विशेषताएँ

1. वर्कफ़्लो:
एक दृश्य कैनवास पर शक्तिशाली एआई वर्कफ़्लो बनाएं और परीक्षण करें, नीचे दी गई सभी सुविधाओं और उससे भी आगे का उपयोग करते हुए।

2. व्यापक मॉडल समर्थन:
कई इन्फ़रेंस प्रदाताओं और स्व-होस्टेड समाधानों से सैकड़ों स्वामित्व / मुक्त-स्रोत LLMs के साथ सहज एकीकरण, जिसमें GPT, Mistral, Llama3, और कोई भी OpenAI API-संगत मॉडल शामिल हैं। समर्थित मॉडल प्रदाताओं की पूरी सूची here पर पाई जा सकती है।

3. प्रॉम्प्ट IDE:
प्रॉम्प्ट बनाने, मॉडल प्रदर्शन की तुलना करने, और चैट-आधारित ऐप में टेक्स्ट-टू-स्पीच जैसी अतिरिक्त सुविधाएँ जोड़ने के लिए सहज इंटरफ़ेस।

4. RAG पाइपलाइन:
विस्तृत RAG क्षमताएँ जो दस्तावेज़ इनजेशन से लेकर रिट्रीवल तक सब कुछ कवर करती हैं, और PDFs, PPTs, तथा अन्य सामान्य दस्तावेज़ प्रारूपों से टेक्स्ट निकालने के लिए आउट-ऑफ़-द-बॉक्स समर्थन प्रदान करती हैं।

5. एजेंट क्षमताएँ:
आप LLM फ़ंक्शन कॉलिंग या ReAct के आधार पर एजेंट परिभाषित कर सकते हैं, और एजेंट के लिए पूर्व-निर्मित या कस्टम टूल जोड़ सकते हैं। Dify एआई एजेंटों के लिए 50+ अंतर्निर्मित टूल प्रदान करता है, जैसे Google Search, DALL·E, Stable Diffusion और WolframAlpha।

6. LLMOps:
समय के साथ एप्लिकेशन लॉग्स और प्रदर्शन की निगरानी और विश्लेषण करें। आप उत्पादन डेटा और एनोटेशनों के आधार पर प्रॉम्प्ट्स, डेटासेट्स और मॉडल्स को निरंतर सुधार सकते हैं।

7. Backend-as-a-Service:
Dify की सभी सेवाएँ संबंधित APIs के साथ आती हैं, जिससे आप Dify को आसानी से अपने व्यावसायिक लॉजिक में एकीकृत कर सकते हैं।

Dify का उपयोग करना

आगे बने रहें

GitHub पर Dify को स्टार करें और नए रिलीज़ की सूचना तुरंत प्राप्त करें।

उन्नत सेटअप

कस्टम कॉन्फ़िगरेशन, ऑब्ज़र्वेबिलिटी और डिप्लॉयमेंट विकल्पों के लिए, उन्नत सेटअप देखें।

योगदान (Contributing)

Dify सभी प्रकार के योगदानों का स्वागत करता है:

  • कोड: Contribution Guide पढ़ें, फिर नए योगदानकर्ताओं के लिए उपयुक्त issues देखें।
  • विचार और प्रतिक्रिया: GitHub Discussion शुरू करें या किसी मौजूदा चर्चा में शामिल हों।
  • अनुवाद: किसी locale को जोड़ने या अपडेट करने के लिए internationalization guide का पालन करें।
  • समुदाय: अपने बनाए हुए ऐप साझा करें, अन्य उपयोगकर्ताओं की मदद करें और Dify के बारे में लोगों को बताएं।

योगदानकर्ता

समुदाय और संपर्क (Community & contact)

अपने प्रश्न के लिए सबसे उपयुक्त माध्यम चुनें:

  • GitHub Discussions: सहायता प्राप्त करें, प्रतिक्रिया साझा करें और विचार सुझाएँ।
  • GitHub Issues: दोहराए जा सकने वाले bugs की रिपोर्ट करें और engineering work को ट्रैक करें। Issue खोलने से पहले Contribution Guide पढ़ें।
  • Discord: रीयल टाइम में बातचीत करें, अपने ऐप साझा करें और अन्य Dify उपयोगकर्ताओं से जुड़ें।
  • X: रिलीज़ समाचार और प्रोजेक्ट अपडेट के लिए Dify को फ़ॉलो करें।

स्टार इतिहास (Star history)

सुरक्षा प्रकटीकरण (Security disclosure)

हमारी सुरक्षा नीति के अनुसार GitHub Security Advisories के ज़रिए निजी तौर पर सुरक्षा खामियों की रिपोर्ट करें। उन्हें सार्वजनिक issues, चर्चाओं या pull requests में उजागर न करें।

लाइसेंस (License)

यह रिपॉज़िटरी Dify Open Source License के अंतर्गत लाइसेंस प्राप्त है, जो Apache 2.0 पर आधारित है और इसमें अतिरिक्त शर्तें शामिल हैं।


Id ID README (`docs/id-ID/README.md`)

Dify adalah platform pengembangan aplikasi Large Language Model (LLM) sumber terbuka (open-source). Antarmukanya yang intuitif menggabungkan AI workflow, pipeline RAG, kapabilitas agen otonom, manajemen model, fitur observabilitas (termasuk Opik, Langfuse, dan Arize Phoenix), dan masih banyak lagi—memungkinkan Anda beralih dari tahap purwarupa (prototype) ke produksi dengan cepat.

Berikut daftar fitur utamanya:

Mulai Cepat (Quick start)

Sebelum menginstal Dify, pastikan sistem komputer atau server Anda memenuhi spesifikasi minimum berikut:

  • CPU >= 2 Core
  • RAM >= 4 GiB

Cara termudah untuk menjalankan server Dify adalah menggunakan Docker Compose. Sebelum menjalankan perintah berikut, pastikan Docker dan Docker Compose versi v2.24.0 atau yang lebih baru telah terpasang:

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

Setelah berjalan, Anda dapat mengakses dashboard Dify melalui peramban web di http://localhost/install untuk memulai proses inisialisasi awal.

Bantuan & FAQ

Silakan merujuk ke FAQ kami jika menemui kendala saat pemasangan Dify. Hubungi komunitas kami jika Anda membutuhkan bantuan lebih lanjut.

Jika ingin berkontribusi pada pengembangan kode Dify, pelajari panduan instalasi dari source code.

Fitur Utama

1. Workflow Visual:
Rancang dan uji alur kerja AI yang kuat di atas kanvas visual, memanfaatkan seluruh integrasi fitur secara menyeluruh.

2. Dukungan Model Komprehensif:
Integrasi mulus dengan ratusan model LLM komersial maupun open-source dari puluhan penyedia inferensi dan solusi self-hosted, meliputi GPT, Mistral, Llama 3, serta semua model yang kompatibel dengan OpenAI API. Daftar lengkap penyedia model dapat dilihat di sini.

3. Prompt IDE:
Antarmuka intuitif untuk meracik prompt, membandingkan performa berbagai model secara berdampingan, dan menambahkan fitur interaktif seperti text-to-speech ke dalam aplikasi obrolan.

4. Pipeline RAG (Retrieval-Augmented Generation):
Kemampuan RAG lengkap mulai dari ingest dokumen hingga pencarian semantik, dilengkapi dukungan bawaan untuk ekstraksi teks dari PDF, dokumen presentasi PPT, dan berbagai format berkas populer lainnya.

5. Autonomous Agent:
Agen mandiri yang beroperasi dalam lingkungan sandbox terisolasi: mereka mampu menjalankan perintah, memasang pustaka perangkat lunak, dan memproses dokumen untuk menyelesaikan tugas yang dinamis. Deskripsikan agen yang Anda butuhkan, dan ia akan menyusun dirinya sendiri. Hubungkan alat dari Dify Marketplace, server MCP, atau API kustom Anda, lalu terapkan sebagai aplikasi obrolan cerdas atau sebagai langkah otomatis dalam workflow.

6. LLMOps:
Pantau dan analisis log riwayat aplikasi serta metrik performanya secara berkala. Anda dapat terus menyempurnakan prompt, dataset, dan model berdasarkan data penggunaan produksi nyata serta anotasi kualitas.

7. Backend-as-a-Service (BaaS):
Seluruh kapabilitas Dify disertai API yang lengkap dan terdokumentasi rapi, memudahkan integrasi fungsionalitas AI ke dalam logika aplikasi backend Anda yang sudah ada.

Pilihan Penerapan Dify

Tetap Terhubung & Update Terbaru

Berikan bintang (star) pada repositori Dify di GitHub untuk mendapatkan pemberitahuan pembaruan versi terbaru:

Konfigurasi Tingkat Lanjut

Untuk konfigurasi kustom, observabilitas mendalam, dan opsi deployment tingkat lanjut, lihat Advanced Setup.

Berkontribusi

Dify menyambut segala bentuk kontribusi dari komunitas:

Kontributor

Komunitas & Kontak

Pilih saluran komunikasi resmi yang paling relevan:

  • GitHub Discussions: Diskusi umum, masukan fitur, dan tanya jawab.
  • GitHub Issues: Laporan bug yang dapat direproduksi dan pelacakan fitur teknis. Baca Panduan Kontribusi sebelum membuka issue baru.
  • Discord: Diskusi interaktif langsung, bertukar proyek aplikasi AI, dan berjejaring dengan pengguna Dify di seluruh dunia.
  • X (Twitter): Berita rilis fitur dan pengumuman resmi.

Riwayat Bintang (Star History)

Kebijakan Pelaporan Kerentanan Keamanan

Laporkan kerentanan secara privat melalui GitHub Security Advisories sesuai kebijakan keamanan. Jangan mengungkapkannya dalam issue, diskusi, atau pull request publik.

Lisensi

Repositori ini dilisensikan di bawah Dify Open Source License, berbasiskan Apache 2.0 dengan beberapa ketentuan tambahan.


It IT README (`docs/it-IT/README.md`)

Dify è una piattaforma open-source per lo sviluppo di applicazioni LLM. La sua interfaccia intuitiva combina flussi di lavoro AI basati su agenti, pipeline RAG, funzionalità di agenti, gestione dei modelli, funzionalità di monitoraggio e altro ancora, permettendovi di passare rapidamente da un prototipo alla produzione.

Avvio Rapido

Prima di installare Dify, assicuratevi che il vostro sistema soddisfi i seguenti requisiti minimi:

  • CPU >= 2 Core
  • RAM >= 4 GiB

Il modo più semplice per avviare il server Dify è tramite docker compose. Prima di eseguire Dify con i seguenti comandi, assicuratevi che Docker e Docker Compose siano installati sul vostro sistema:

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

Dopo aver avviato il server, potete accedere al dashboard di Dify tramite il vostro browser all'indirizzo http://localhost/install e avviare il processo di inizializzazione.

Richiedere Aiuto

Consultate le nostre FAQ se riscontrate problemi durante la configurazione di Dify. Contattateci tramite la community se continuano a verificarsi difficoltà.

Se desiderate contribuire a Dify o effettuare ulteriori sviluppi, consultate la nostra guida al deployment dal codice sorgente.

Caratteristiche Principali

1. Workflow:
Create e testate potenti flussi di lavoro AI su un'interfaccia visuale, utilizzando tutte le funzionalità seguenti e oltre.

2. Supporto Completo dei Modelli:
Integrazione perfetta con centinaia di LLM proprietari e open-source di decine di provider di inferenza e soluzioni self-hosted, che coprono GPT, Mistral, Llama3 e tutti i modelli compatibili con l'API OpenAI. L'elenco completo dei provider di modelli supportati è disponibile qui.

3. Prompt IDE:
Interfaccia intuitiva per creare prompt, confrontare le prestazioni dei modelli e aggiungere funzionalità aggiuntive come text-to-speech in un'applicazione basata su chat.

4. Pipeline RAG:
Funzionalità RAG complete che coprono tutto, dall'acquisizione dei documenti alla loro interrogazione, con supporto pronto all'uso per l'estrazione di testo da PDF, PPT e altri formati di documenti comuni.

5. Capacità degli Agenti:
Potete definire agenti basati su LLM Function Calling o ReAct e aggiungere strumenti predefiniti o personalizzati per l'agente. Dify fornisce oltre 50 strumenti integrati per gli agenti AI, come Google Search, DALL·E, Stable Diffusion e WolframAlpha.

6. LLMOps:
Monitorate e analizzate i log delle applicazioni e le prestazioni nel tempo. Potete migliorare continuamente prompt, dataset e modelli basandovi sui dati di produzione e sulle annotazioni.

7. Backend-as-a-Service:
Tutte le offerte di Dify sono dotate di API corrispondenti, permettendovi di integrare facilmente Dify nella vostra logica di business.

Utilizzo di Dify

  • **Cloud **
    Prova Dify Cloud senza gestire un server. Consulta la pagina dei prezzi per i piani e i limiti di utilizzo attuali.

  • Dify Community Edition Self-Hosted
    Avviate rapidamente Dify nel vostro ambiente con questa guida di avvio rapido. Utilizzate la nostra documentazione per ulteriori informazioni e istruzioni dettagliate.

  • Dify per Aziende / Organizzazioni
    Offriamo funzionalità aggiuntive specifiche per le aziende. Potete scriverci via email per discutere le vostre esigenze aziendali.

Resta Sempre Aggiornato

Mettete una stella a Dify su GitHub e ricevete notifiche immediate sui nuovi rilasci.

Configurazioni Avanzate

Per le opzioni di configurazione personalizzata, osservabilità e distribuzione, consulta le Configurazioni avanzate.

Contribuire

Dify accoglie contributi di ogni tipo:

Collaboratori

Community e contatti

Scegli il canale più adatto alla tua richiesta:

  • GitHub Discussions: ricevi assistenza, condividi feedback e proponi idee.
  • GitHub Issues: segnala bug riproducibili e segui il lavoro di sviluppo. Leggi la Guida ai contributi prima di aprire una issue.
  • Discord: chatta in tempo reale, condividi le tue app e incontra altri utenti Dify.
  • X: segui le notizie sulle release e gli aggiornamenti del progetto.

Storia delle Stelle

Divulgazione sulla Sicurezza

Segnala le vulnerabilità in privato tramite GitHub Security Advisories, seguendo la nostra politica di sicurezza. Non divulgarle in issue, discussioni o pull request pubbliche.

Licenza

Questo repository è disponibile sotto la Dify Open Source License, che è essenzialmente Apache 2.0 con alcune restrizioni aggiuntive.


Ja JP README (`docs/ja-JP/README.md`)

DifyはオープンソースのLLMアプリケーション開発プラットフォームです。直感的なインターフェイスには、AIワークフロー、RAGパイプライン、エージェント機能、モデル管理、観測機能などが組み合わさっており、プロトタイプから本番環境まで迅速に進めることができます。以下の機能が含まれます:

1. ワークフロー:
強力なAIワークフローをビジュアルキャンバス上で構築し、テストできます。以下の機能をはじめ、すべての機能を活用できます。

2. 総合的なモデルサポート:
数百ものプロプライエタリ/オープンソースのLLMと、数十もの推論プロバイダーおよびセルフホスティングソリューションとのシームレスな統合を提供します。GPT、Mistral、Llama3、OpenAI APIと互換性のあるすべてのモデルに対応しています。サポートされているモデルプロバイダーの完全なリストはこちらをご覧ください。

3. プロンプトIDE:
プロンプトの作成、モデルパフォーマンスの比較が行え、チャットベースのアプリに音声合成などの機能も追加できます。

4. RAGパイプライン:
ドキュメントの取り込みから検索までをカバーする広範なRAG機能を備えています。ほかにもPDF、PPT、その他の一般的なドキュメントフォーマットからのテキスト抽出のサポートも提供します。

5. エージェント機能:
LLM Function CallingやReActに基づくエージェントの定義が可能で、AIエージェント用のプリビルトまたはカスタムツールを追加できます。Difyには、Google検索、DALL·E、Stable Diffusion、WolframAlphaなどのAIエージェント用の50以上の組み込みツールを提供しています。

6. LLMOps:
アプリケーションのログやパフォーマンスを監視・分析し、本番環境のデータと注釈に基づいて、プロンプト、データセット、モデルを継続的に改善できます。

7. Backend-as-a-Service:
すべての機能がAPIとして提供されており、Difyを自分のビジネスロジックに簡単に統合できます。

Difyの使用方法

  • **クラウド **
    Dify Cloud なら、サーバーを管理せずに Dify を試せます。最新のプランと利用枠は料金ページをご覧ください。

  • Dify Community Editionのセルフホスティング
    このスタートガイドを使用して、ローカル環境でDifyを簡単に実行できます。
    詳しくはドキュメントをご覧ください。

  • 企業/組織向けのDify
    企業中心の機能を提供しています。メールを送信して企業のニーズについて相談してください。

最新の情報を入手

GitHub上でDifyにスターを付けることで、Difyに関する新しいニュースを受け取れます。

クイックスタート

Difyをインストールする前に、お使いのマシンが以下の最小システム要件を満たしていることを確認してください:

  • CPU >= 2コア
  • RAM >= 4GB

Difyサーバーを起動する最も簡単な方法は、docker-compose.ymlファイルを実行することです。インストールコマンドを実行する前に、マシンにDockerとDocker Composeがインストールされていることを確認してください。

bash
cd docker
cp .env.example .env
docker compose up -d

実行後、ブラウザでhttp://localhost/installにアクセスし、初期化プロセスを開始できます。

Difyに貢献したり、追加の開発を行う場合は、ソースコードからのデプロイガイドを参照してください。

次のステップ

カスタム構成、オブザーバビリティ、デプロイのオプションについては、高度なセットアップを参照してください。

貢献

Difyでは、あらゆる形の貢献を歓迎しています。

  • コード:コントリビューションガイドを読み、good first issueを確認してください。
  • アイデアとフィードバック:GitHub Discussionsで新しい議論を始めるか、既存の議論に参加してください。
  • 翻訳:言語の追加や更新については、国際化ガイドに従ってください。
  • コミュニティ:作成したアプリを共有し、他のユーザーを支援し、Difyを広めてください。

貢献者

コミュニティ & お問い合わせ

目的に合った窓口を選んでください。

  • GitHub Discussions:質問、フィードバックの共有、アイデアの提案にご利用ください。
  • GitHub Issues:再現可能なバグの報告と開発作業の追跡にご利用ください。Issueを作成する前にコントリビューションガイドをお読みください。
  • Discord:リアルタイムで会話し、アプリを共有し、他のDifyユーザーと交流できます。
  • X:リリース情報やプロジェクトの最新情報を確認できます。

スター履歴

ライセンス

このリポジトリは、Dify Open Source License にいくつかの追加制限を加えたDifyオープンソースライセンスの下で利用可能です。


Ko KR README (`docs/ko-KR/README.md`)

Dify는 오픈 소스 LLM 앱 개발 플랫폼입니다. 직관적인 인터페이스를 통해 AI 워크플로우, RAG 파이프라인, 에이전트 기능, 모델 관리, 관찰 기능 등을 결합하여 프로토타입에서 프로덕션까지 빠르게 전환할 수 있습니다. 주요 기능 목록은 다음과 같습니다:

1. 워크플로우:
다음 기능들을 비롯한 다양한 기능을 활용하여 시각적 캔버스에서 강력한 AI 워크플로우를 구축하고 테스트하세요.

2. 포괄적인 모델 지원::

수십 개의 추론 제공업체와 자체 호스팅 솔루션에서 제공하는 수백 개의 독점 및 오픈 소스 LLM과 원활하게 통합되며, GPT, Mistral, Llama3 및 모든 OpenAI API 호환 모델을 포함합니다. 지원되는 모델 제공업체의 전체 목록은 여기에서 확인할 수 있습니다.

3. 통합 개발환경:
프롬프트를 작성하고, 모델 성능을 비교하며, 텍스트-음성 변환과 같은 추가 기능을 채팅 기반 앱에 추가할 수 있는 직관적인 인터페이스를 제공합니다.

4. RAG 파이프라인:
문서 수집부터 검색까지 모든 것을 다루며, PDF, PPT 및 기타 일반적인 문서 형식에서 텍스트 추출을 위한 기본 지원이 포함되어 있는 광범위한 RAG 기능을 제공합니다.

5. 에이전트 기능:
LLM 함수 호출 또는 ReAct를 기반으로 에이전트를 정의하고 에이전트에 대해 사전 구축된 도구나 사용자 정의 도구를 추가할 수 있습니다. Dify는 Google Search, DALL·E, Stable Diffusion, WolframAlpha 등 AI 에이전트를 위한 50개 이상의 내장 도구를 제공합니다.

6. LLMOps:
시간 경과에 따른 애플리케이션 로그와 성능을 모니터링하고 분석합니다. 생산 데이터와 주석을 기반으로 프롬프트, 데이터세트, 모델을 지속적으로 개선할 수 있습니다.

7. Backend-as-a-Service:
Dify의 모든 제품에는 해당 API가 함께 제공되므로 Dify를 자신의 비즈니스 로직에 쉽게 통합할 수 있습니다.

Dify 사용하기

  • **클라우드 **
    Dify Cloud를 통해 서버를 관리하지 않고 Dify를 사용할 수 있습니다. 최신 요금제와 사용 한도는 요금 안내를 확인하세요.

  • 셀프-호스팅 Dify 커뮤니티 에디션
    환경에서 Dify를 빠르게 실행하려면 이 스타터 가이드를 참조하세요.
    추가 참조 및 더 심층적인 지침은 문서를 사용하세요.

  • 기업 / 조직을 위한 Dify
    우리는 추가적인 기업 중심 기능을 제공합니다. 잡거나 이메일 보내기를 통해 기업 요구 사항을 논의하십시오.

앞서가기

GitHub에서 Dify에 별표를 찍어 새로운 릴리스를 즉시 알림 받으세요.

빠른 시작

Dify를 설치하기 전에 컴퓨터가 다음과 같은 최소 시스템 요구 사항을 충족하는지 확인하세요 :

  • CPU >= 2 Core
  • RAM >= 4GB

Dify 서버를 시작하는 가장 쉬운 방법은 docker-compose.yml 파일을 실행하는 것입니다. 설치 명령을 실행하기 전에 Docker 및 Docker Compose가 머신에 설치되어 있는지 확인하세요.

bash
cd docker
cp .env.example .env
docker compose up -d

실행 후 브라우저의 http://localhost/install 에서 Dify 대시보드에 액세스하고 초기화 프로세스를 시작할 수 있습니다.

Dify에 기여하거나 추가 개발을 하고 싶다면 소스 코드에서 배포에 대한 가이드를 참조하세요.

다음 단계

사용자 지정 구성, 관측 가능성 및 배포 옵션은 고급 설정을 참조하세요.

기여

Dify는 모든 형태의 기여를 환영합니다.

  • 코드: 기여 가이드를 읽고 good first issue를 살펴보세요.
  • 아이디어 및 피드백: GitHub 토론을 시작하거나 기존 토론에 참여하세요.
  • 번역: 언어를 추가하거나 업데이트하려면 국제화 가이드를 따르세요.
  • 커뮤니티: 만든 앱을 공유하고, 다른 사용자를 돕고, Dify를 널리 알려주세요.

기여자

커뮤니티 & 연락처

문의 내용에 가장 적합한 채널을 선택하세요.

  • GitHub Discussions: 도움을 받고, 피드백을 공유하고, 아이디어를 제안하세요.
  • GitHub Issues: 재현 가능한 버그를 보고하고 개발 작업을 추적하세요. 이슈를 열기 전에 기여 가이드를 읽어주세요.
  • Discord: 실시간으로 대화하고, 앱을 공유하고, 다른 Dify 사용자와 교류하세요.
  • X: 릴리스 소식과 프로젝트 업데이트를 확인하세요.

Star 히스토리

보안 공개

보안 정책에 따라 GitHub Security Advisories를 통해 취약점을 비공개로 보고하세요. 공개 이슈, 토론 또는 PR에 공개하지 마세요.

라이선스

이 저장소는 기본적으로 몇 가지 추가 제한 사항이 있는 Apache 2.0인 Dify 오픈 소스 라이선스에 따라 사용할 수 있습니다.


Pt BR README (`docs/pt-BR/README.md`)

Dify é uma plataforma de desenvolvimento de aplicativos LLM de código aberto. Sua interface intuitiva combina workflow de IA, pipeline RAG, capacidades de agente, gerenciamento de modelos, recursos de observabilidade e muito mais, permitindo que você vá rapidamente do protótipo à produção. Aqui está uma lista das principais funcionalidades:

1. Workflow:
Construa e teste workflows poderosos de IA em uma interface visual, aproveitando todos os recursos a seguir e muito mais.

2. Suporte abrangente a modelos:
Integração perfeita com centenas de LLMs proprietários e de código aberto de diversas provedoras e soluções auto-hospedadas, abrangendo GPT, Mistral, Llama3 e qualquer modelo compatível com a API da OpenAI. A lista completa de provedores suportados pode ser encontrada aqui.

3. IDE de Prompt:
Interface intuitiva para criação de prompts, comparação de desempenho de modelos e adição de recursos como conversão de texto para fala em um aplicativo baseado em chat.

4. Pipeline RAG:
Extensas capacidades de RAG que cobrem desde a ingestão de documentos até a recuperação, com suporte nativo para extração de texto de PDFs, PPTs e outros formatos de documentos comuns.

5. Capacidades de agente:
Você pode definir agentes com base em LLM Function Calling ou ReAct e adicionar ferramentas pré-construídas ou personalizadas para o agente. O Dify oferece mais de 50 ferramentas integradas para agentes de IA, como Google Search, DALL·E, Stable Diffusion e WolframAlpha.

6. LLMOps:
Monitore e analise os registros e o desempenho do aplicativo ao longo do tempo. É possível melhorar continuamente prompts, conjuntos de dados e modelos com base nos dados de produção e anotações.

7. Backend como Serviço:
Todas os recursos do Dify vêm com APIs correspondentes, permitindo que você integre o Dify sem esforço na lógica de negócios da sua empresa.

Usando o Dify

  • **Nuvem **
    Experimente o Dify Cloud sem gerenciar um servidor. Consulte os planos e limites de uso atuais na página de preços.

  • Auto-hospedagem do Dify Community Edition
    Configure rapidamente o Dify no seu ambiente com este guia inicial.
    Use nossa documentação para referências adicionais e instruções mais detalhadas.

  • Dify para empresas/organizações
    Oferecemos recursos adicionais voltados para empresas. Você pode falar conosco por e-mail para discutir necessidades empresariais.

Mantendo-se atualizado

Dê uma estrela no Dify no GitHub e seja notificado imediatamente sobre novos lançamentos.

Início rápido

Antes de instalar o Dify, certifique-se de que sua máquina atenda aos seguintes requisitos mínimos de sistema:

  • CPU >= 2 Núcleos
  • RAM >= 4 GiB

A maneira mais fácil de iniciar o servidor Dify é executar nosso arquivo docker-compose.yml. Antes de rodar o comando de instalação, certifique-se de que o Docker e o Docker Compose estão instalados na sua máquina:

bash
cd docker
cp .env.example .env
docker compose up -d

Após a execução, você pode acessar o painel do Dify no navegador em http://localhost/install e iniciar o processo de inicialização.

Se você deseja contribuir com o Dify ou fazer desenvolvimento adicional, consulte nosso guia para implantar a partir do código fonte.

Próximos passos

Para opções de configuração personalizada, observabilidade e implantação, consulte a Configuração avançada.

Contribuindo

O Dify aceita contribuições de todos os tipos:

Contribuidores

Comunidade e contato

Escolha o canal mais adequado para a sua dúvida:

  • GitHub Discussions: obtenha ajuda, compartilhe feedback e proponha ideias.
  • GitHub Issues: relate bugs reproduzíveis e acompanhe o trabalho de engenharia. Leia o Guia de Contribuição antes de abrir uma issue.
  • Discord: converse em tempo real, compartilhe seus aplicativos e conecte-se com outros usuários do Dify.
  • X: acompanhe notícias de versões e atualizações do projeto.

Histórico de estrelas

Divulgação de segurança

Relate vulnerabilidades em particular pelo GitHub Security Advisories, seguindo nossa política de segurança. Não as divulgue em issues, discussões ou pull requests públicos.

Licença

Este repositório está disponível sob a Licença de Código Aberto Dify, que é essencialmente Apache 2.0 com algumas restrições adicionais.


Sl SI README (`docs/sl-SI/README.md`)

Dify je odprtokodna platforma za razvoj aplikacij LLM. Njegov intuitivni vmesnik združuje agentski potek dela z umetno inteligenco, cevovod RAG, zmogljivosti agentov, upravljanje modelov, funkcije opazovanja in več, kar vam omogoča hiter prehod od prototipa do proizvodnje.

Hitri začetek

Preden namestite Dify, se prepričajte, da vaša naprava izpolnjuje naslednje minimalne sistemske zahteve:

  • CPU >= 2 Core
  • RAM >= 4 GiB

Najlažji način za zagon strežnika Dify je prek docker compose . Preden zaženete Dify z naslednjimi ukazi, se prepričajte, da sta Docker in Docker Compose nameščena na vašem računalniku:

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

Po zagonu lahko dostopate do nadzorne plošče Dify v brskalniku na http://localhost/install in začnete postopek inicializacije.

Iskanje pomoči

Prosimo, glejte naša pogosta vprašanja FAQ če naletite na težave pri nastavitvi Dify. Če imate še vedno težave, se obrnite na skupnost ali nas.

Če želite prispevati k Difyju ali narediti dodaten razvoj, glejte naš vodnik za uvajanje iz izvorne kode

Ključne značilnosti

1. Potek dela:
Zgradite in preizkusite zmogljive poteke dela AI na vizualnem platnu, pri čemer izkoristite vse naslednje funkcije in več.

2. Celovita podpora za modele:
Brezhibna integracija s stotinami lastniških/odprtokodnih LLM-jev ducatov ponudnikov sklepanja in samostojnih rešitev, ki pokrivajo GPT, Mistral, Llama3 in vse modele, združljive z API-jem OpenAI. Celoten seznam podprtih ponudnikov modelov najdete tukaj.

3. Prompt IDE:
intuitivni vmesnik za ustvarjanje pozivov, primerjavo zmogljivosti modela in dodajanje dodatnih funkcij, kot je pretvorba besedila v govor, aplikaciji, ki temelji na klepetu.

4. RAG Pipeline:
E Obsežne zmogljivosti RAG, ki pokrivajo vse od vnosa dokumenta do priklica, s podporo za ekstrakcijo besedila iz datotek PDF, PPT in drugih običajnih formatov dokumentov.

5. Agent capabilities:
definirate lahko agente, ki temeljijo na klicanju funkcij LLM ali ReAct, in dodate vnaprej izdelana orodja ali orodja po meri za agenta. Dify ponuja več kot 50 vgrajenih orodij za agente AI, kot so Google Search, DALL·E, Stable Diffusion in WolframAlpha.

6. LLMOps:
Spremljajte in analizirajte dnevnike aplikacij in učinkovitost skozi čas. Pozive, nabore podatkov in modele lahko nenehno izboljšujete na podlagi proizvodnih podatkov in opomb.

7. Backend-as-a-Service:
AVse ponudbe Difyja so opremljene z ustreznimi API-ji, tako da lahko Dify brez težav integrirate v svojo poslovno logiko.

Uporaba Dify

  • **Cloud **
    Preizkusite Dify Cloud brez upravljanja strežnika. Trenutne pakete in omejitve uporabe najdete na strani s cenami.

  • Self-hosting Dify Community Edition
    Hitro zaženite Dify v svojem okolju s tem začetnim vodnikom . Za dodatne reference in podrobnejša navodila uporabite našo dokumentacijo .

  • Dify za podjetja/organizacije
    Ponujamo dodatne funkcije, osredotočene na podjetja. Zabeležite svoja vprašanja prek tega klepetalnega robota ali nam pošljite e-pošto, da se pogovorimo o potrebah podjetja.

Staying ahead

Star Dify on GitHub and be instantly notified of new releases.

Napredne nastavitve

Za možnosti konfiguracije po meri, opazovanja in namestitve glejte Napredne nastavitve.

Prispevanje

Dify pozdravlja vse vrste prispevkov:

Sodelavci

Skupnost in stik

Izberite kanal, ki najbolj ustreza vašemu vprašanju:

  • GitHub Discussions: poiščite pomoč, delite povratne informacije in predlagajte ideje.
  • GitHub Issues: prijavite ponovljive napake in spremljajte razvojno delo. Pred odprtjem težave preberite vodnik za prispevke.
  • Discord: klepetajte v živo, delite svoje aplikacije in se povežite z drugimi uporabniki Difyja.
  • X: spremljajte novice o izdajah in posodobitve projekta.

Star history

Varnostno razkritje

Ranljivosti prijavite zasebno prek GitHub Security Advisories v skladu z našo varnostno politiko. Ne razkrivajte jih v javnih prijavah težav, razpravah ali zahtevkih za združitev.

Licenca

To skladišče je na voljo pod odprtokodno licenco Dify , ki je v bistvu Apache 2.0 z nekaj dodatnimi omejitvami.


Tlh README (`docs/tlh/README.md`)

Dify is an open-source LLM app development platform. Its intuitive interface combines AI workflow, RAG pipeline, agent capabilities, model management, observability features (including Opik, Langfuse, and Arize Phoenix) and more, letting you quickly go from prototype to production. Here's a list of the core features:

1. Workflow:
Build and test powerful AI workflows on a visual canvas, leveraging all the following features and beyond.

2. Comprehensive model support:
Seamless integration with hundreds of proprietary / open-source LLMs from dozens of inference providers and self-hosted solutions, covering GPT, Mistral, Llama3, and any OpenAI API-compatible models. A full list of supported model providers can be found here.

3. Prompt IDE:
Intuitive interface for crafting prompts, comparing model performance, and adding additional features such as text-to-speech to a chat-based app.

4. RAG Pipeline:
Extensive RAG capabilities that cover everything from document ingestion to retrieval, with out-of-box support for text extraction from PDFs, PPTs, and other common document formats.

5. Agent capabilities:
You can define agents based on LLM Function Calling or ReAct, and add pre-built or custom tools for the agent. Dify provides 50+ built-in tools for AI agents, such as Google Search, DALL·E, Stable Diffusion and WolframAlpha.

6. LLMOps:
Monitor and analyze application logs and performance over time. You could continuously improve prompts, datasets, and models based on production data and annotations.

7. Backend-as-a-Service:
All of Dify's offerings come with corresponding APIs, so you could effortlessly integrate Dify into your own business logic.

Using Dify

  • **Cloud **
    We host Dify Cloud so you can try Dify without managing a server. See the pricing page for current plans and usage allowances.

  • Self-hosting Dify Community Edition
    Quickly get Dify running in your environment with this starter guide.
    Use our documentation for further references and more in-depth instructions.

  • Dify for Enterprise / Organizations
    We provide additional enterprise-centric features. Send us an email to discuss enterprise needs.

Staying ahead

Star Dify on GitHub and be instantly notified of new releases.

Quick Start

Before installing Dify, make sure your machine meets the following minimum system requirements:

  • CPU >= 2 Core
  • RAM >= 4GB

The easiest way to start the Dify server is to run our docker-compose.yml file. Before running the installation command, make sure that Docker and Docker Compose are installed on your machine:

bash
cd docker
cp .env.example .env
docker compose up -d

After running, you can access the Dify dashboard in your browser at http://localhost/install and start the initialization process.

If you'd like to contribute to Dify or do additional development, refer to our guide to deploying from source code

Next steps

For custom configuration, observability, and deployment options, see Advanced Setup.

Contributing

Dify welcomes contributions of all kinds:

Contributors

Community & Contact

Choose the channel that best fits your question:

  • GitHub Discussions: Get help, share feedback, and propose ideas.
  • GitHub Issues: Report reproducible bugs and track engineering work. Read the Contribution Guide before opening one.
  • Discord: Chat in real time, share your apps, and connect with other Dify users.
  • X: Follow Dify for release news and project updates.

Star History

Security Disclosure

Report vulnerabilities privately through GitHub Security Advisories, following our security policy. Do not disclose them in public issues, discussions, or pull requests.

License

This repository is available under the Dify Open Source License, which is essentially Apache 2.0 with a few additional restrictions.


Tr TR README (`docs/tr-TR/README.md`)

Dify, açık kaynaklı bir LLM uygulama geliştirme platformudur. Sezgisel arayüzü, AI iş akışı, RAG pipeline'ı, ajan yetenekleri, model yönetimi, gözlemlenebilirlik özellikleri ve daha fazlasını birleştirerek, prototipten üretime hızlıca geçmenizi sağlar. İşte temel özelliklerin bir listesi:

1. Workflow:
Görsel bir arayüz üzerinde güçlü AI iş akışları oluşturun ve test edin, aşağıdaki tüm özellikleri ve daha fazlasını kullanarak.

2. Kapsamlı model desteği:
Çok sayıda çıkarım sağlayıcısı ve kendi kendine barındırılan çözümlerden yüzlerce özel / açık kaynaklı LLM ile sorunsuz entegrasyon sağlar. GPT, Mistral, Llama3 ve OpenAI API uyumlu tüm modelleri kapsar. Desteklenen model sağlayıcılarının tam listesine buradan ulaşabilirsiniz.

3. Prompt IDE:
Komut istemlerini oluşturmak, model performansını karşılaştırmak ve sohbet tabanlı uygulamalara metin-konuşma gibi ek özellikler eklemek için kullanıcı dostu bir arayüz.

4. RAG Pipeline:
Belge alımından bilgi çekmeye kadar geniş kapsamlı RAG yetenekleri. PDF'ler, PPT'ler ve diğer yaygın belge formatlarından metin çıkarma için hazır destek sunar.

5. Ajan yetenekleri:
LLM Fonksiyon Çağırma veya ReAct'a dayalı ajanlar tanımlayabilir ve bu ajanlara önceden hazırlanmış veya özel araçlar ekleyebilirsiniz. Dify, AI ajanları için Google Arama, DALL·E, Stable Diffusion ve WolframAlpha gibi 50'den fazla yerleşik araç sağlar.

6. LLMOps:
Uygulama loglarını ve performans metriklerini zaman içinde izleme ve analiz etme imkanı. Üretim ortamından elde edilen verilere ve kullanıcı geri bildirimlerine dayanarak, prompt'ları, veri setlerini ve modelleri sürekli olarak optimize edebilirsiniz. Bu sayede, AI uygulamanızın performansını ve doğruluğunu sürekli olarak artırabilirsiniz.

7. Hizmet Olarak Backend:
Dify'ın tüm özellikleri ilgili API'lerle birlikte gelir, böylece Dify'ı kendi iş mantığınıza kolayca entegre edebilirsiniz.

Dify'ı Kullanma

  • **Cloud **
    Sunucu yönetmeden Dify Cloud ile Dify’ı deneyebilirsiniz. Güncel planlar ve kullanım kotaları için fiyatlandırma sayfasına bakın.

  • Dify Topluluk Sürümünü Kendi Sunucunuzda Barındırma
    Bu başlangıç kılavuzu ile Dify'ı kendi ortamınızda hızlıca çalıştırın.
    Daha fazla referans ve detaylı talimatlar için dokümantasyonumuzu kullanın.

  • Kurumlar / organizasyonlar için Dify
    Ek kurumsal odaklı özellikler sunuyoruz. Kurumsal ihtiyaçları görüşmek için bize bir e-posta gönderin.

Güncel Kalma

GitHub'da Dify'a yıldız verin ve yeni sürümlerden anında haberdar olun.

Hızlı başlangıç

Dify'ı kurmadan önce, makinenizin aşağıdaki minimum sistem gereksinimlerini karşıladığından emin olun:

  • CPU >= 2 Çekirdek
  • RAM >= 4GB

Dify sunucusunu başlatmanın en kolay yolu, docker-compose.yml dosyamızı çalıştırmaktır. Kurulum komutunu çalıştırmadan önce, makinenizde Docker ve Docker Compose'un kurulu olduğundan emin olun:

bash
cd docker
cp .env.example .env
docker compose up -d

Çalıştırdıktan sonra, tarayıcınızda http://localhost/install adresinden Dify kontrol paneline erişebilir ve başlangıç ayarları sürecini başlatabilirsiniz.

Eğer Dify'a katkıda bulunmak veya ek geliştirmeler yapmak isterseniz, kaynak koddan dağıtım kılavuzumuza başvurun.

Sonraki adımlar

Özel yapılandırma, gözlemlenebilirlik ve dağıtım seçenekleri için Gelişmiş Kurulum belgesine bakın.

Katkıda Bulunma

Dify her türlü katkıyı memnuniyetle karşılar:

Katkıda bulunanlar

Topluluk ve iletişim

Sorunuza en uygun kanalı seçin:

  • GitHub Discussions: Yardım alın, geri bildirim paylaşın ve fikir önerin.
  • GitHub Issues: Tekrarlanabilir hataları bildirin ve mühendislik çalışmalarını takip edin. Bir sorun açmadan önce Katkı Kılavuzu'nu okuyun.
  • Discord: Gerçek zamanlı sohbet edin, uygulamalarınızı paylaşın ve diğer Dify kullanıcılarıyla bağlantı kurun.
  • X: Sürüm haberleri ve proje güncellemeleri için Dify'ı takip edin.

Star history

Güvenlik açıklaması

Güvenlik açıklarını güvenlik politikamıza göre GitHub Security Advisories üzerinden özel olarak bildirin. Herkese açık issue, tartışma veya pull request içinde paylaşmayın.

Lisans

Bu depo, temel olarak Apache 2.0 lisansı ve birkaç ek kısıtlama içeren Dify Açık Kaynak Lisansı altında kullanıma sunulmuştur.


Vi VN README (`docs/vi-VN/README.md`)

Dify là một nền tảng phát triển ứng dụng LLM mã nguồn mở. Giao diện trực quan kết hợp quy trình làm việc AI, mô hình RAG, khả năng tác nhân, quản lý mô hình, tính năng quan sát và hơn thế nữa, cho phép bạn nhanh chóng chuyển từ nguyên mẫu sang sản phẩm. Đây là danh sách các tính năng cốt lõi:

1. Quy trình làm việc:
Xây dựng và kiểm tra các quy trình làm việc AI mạnh mẽ trên một canvas trực quan, tận dụng tất cả các tính năng sau đây và hơn thế nữa.

2. Hỗ trợ mô hình toàn diện:
Tích hợp liền mạch với hàng trăm mô hình LLM độc quyền / mã nguồn mở từ hàng chục nhà cung cấp suy luận và giải pháp tự lưu trữ, bao gồm GPT, Mistral, Llama3, và bất kỳ mô hình tương thích API OpenAI nào. Danh sách đầy đủ các nhà cung cấp mô hình được hỗ trợ có thể được tìm thấy tại đây.

3. IDE Prompt:
Giao diện trực quan để tạo prompt, so sánh hiệu suất mô hình và thêm các tính năng bổ sung như chuyển văn bản thành giọng nói cho một ứng dụng dựa trên trò chuyện.

4. Mô hình RAG:
Khả năng RAG mở rộng bao gồm mọi thứ từ nhập tài liệu đến truy xuất, với hỗ trợ sẵn có cho việc trích xuất văn bản từ PDF, PPT và các định dạng tài liệu phổ biến khác.

5. Khả năng tác nhân:
Bạn có thể định nghĩa các tác nhân dựa trên LLM Function Calling hoặc ReAct, và thêm các công cụ được xây dựng sẵn hoặc tùy chỉnh cho tác nhân. Dify cung cấp hơn 50 công cụ tích hợp sẵn cho các tác nhân AI, như Google Search, DALL·E, Stable Diffusion và WolframAlpha.

6. LLMOps:
Giám sát và phân tích nhật ký và hiệu suất ứng dụng theo thời gian. Bạn có thể liên tục cải thiện prompt, bộ dữ liệu và mô hình dựa trên dữ liệu sản xuất và chú thích.

7. Backend-as-a-Service:
Tất cả các dịch vụ của Dify đều đi kèm với các API tương ứng, vì vậy bạn có thể dễ dàng tích hợp Dify vào logic kinh doanh của riêng mình.

Sử dụng Dify

  • **Cloud **
    Dùng thử Dify Cloud mà không cần quản lý máy chủ. Xem các gói và hạn mức sử dụng hiện tại tại trang giá.

  • Tự triển khai Dify Community Edition
    Nhanh chóng chạy Dify trong môi trường của bạn với hướng dẫn bắt đầu này.
    Sử dụng tài liệu của chúng tôi để tham khảo thêm và nhận hướng dẫn chi tiết hơn.

  • Dify cho doanh nghiệp / tổ chức
    Chúng tôi cung cấp các tính năng bổ sung tập trung vào doanh nghiệp. Gửi email cho chúng tôi để thảo luận về nhu cầu doanh nghiệp.

Luôn cập nhật

Yêu thích Dify trên GitHub và được thông báo ngay lập tức về các bản phát hành mới.

Bắt đầu nhanh

Trước khi cài đặt Dify, hãy đảm bảo máy của bạn đáp ứng các yêu cầu hệ thống tối thiểu sau:

  • CPU >= 2 Core
  • RAM >= 4GB

Cách dễ nhất để khởi động máy chủ Dify là chạy tệp docker-compose.yml của chúng tôi. Trước khi chạy lệnh cài đặt, hãy đảm bảo rằng Docker và Docker Compose đã được cài đặt trên máy của bạn:

bash
cd docker
cp .env.example .env
docker compose up -d

Sau khi chạy, bạn có thể truy cập bảng điều khiển Dify trong trình duyệt của bạn tại http://localhost/install và bắt đầu quá trình khởi tạo.

Nếu bạn muốn đóng góp cho Dify hoặc phát triển thêm, hãy tham khảo hướng dẫn triển khai từ mã nguồn của chúng tôi

Các bước tiếp theo

Để biết các tùy chọn cấu hình tùy chỉnh, khả năng quan sát và triển khai, hãy xem Thiết lập nâng cao.

Đóng góp

Dify chào đón mọi hình thức đóng góp:

Người đóng góp

Cộng đồng và liên hệ

Chọn kênh phù hợp nhất với câu hỏi của bạn:

  • GitHub Discussions: nhận trợ giúp, chia sẻ phản hồi và đề xuất ý tưởng.
  • GitHub Issues: báo cáo lỗi có thể tái hiện và theo dõi công việc kỹ thuật. Đọc Hướng dẫn đóng góp trước khi mở issue.
  • Discord: trò chuyện theo thời gian thực, chia sẻ ứng dụng và kết nối với những người dùng Dify khác.
  • X: theo dõi tin tức phát hành và cập nhật dự án.

Lịch sử Yêu thích

Tiết lộ bảo mật

Báo cáo lỗ hổng riêng tư qua GitHub Security Advisories theo chính sách bảo mật. Không công bố trong issue, thảo luận hoặc pull request công khai.

Giấy phép

Kho lưu trữ này có sẵn theo Giấy phép Mã nguồn Mở Dify, về cơ bản là Apache 2.0 với một vài hạn chế bổ sung.


Zh CN README (`docs/zh-CN/README.md`)

Dify 是一个开源的 LLM 应用开发平台。其直观的界面结合了 AI 工作流、RAG 管道、Agent、模型管理、可观测性功能(包括 Opik、Langfuse 和 Arize Phoenix)等,让您可以快速从原型到生产。以下是其核心功能列表:

1. 工作流:
在画布上构建和测试功能强大的 AI 工作流程,利用以下所有功能以及更多功能。

2. 全面的模型支持:
与数百种专有/开源 LLMs 以及数十种推理提供商和自托管解决方案无缝集成,涵盖 GPT、Mistral、Llama3 以及任何与 OpenAI API 兼容的模型。完整的支持模型提供商列表可在此处找到。

3. Prompt IDE:
用于制作提示、比较模型性能以及向基于聊天的应用程序添加其他功能(如文本转语音)的直观界面。

4. RAG Pipeline:
广泛的 RAG 功能,涵盖从文档摄入到检索的所有内容,支持从 PDF、PPT 和其他常见文档格式中提取文本的开箱即用的支持。

5. Agent 智能体:
您可以基于 LLM 函数调用或 ReAct 定义 Agent,并为 Agent 添加预构建或自定义工具。Dify 为 AI Agent 提供了 50 多种内置工具,如谷歌搜索、DALL·E、Stable Diffusion 和 WolframAlpha 等。

6. LLMOps:
随时间监视和分析应用程序日志和性能。您可以根据生产数据和标注持续改进提示、数据集和模型。

7. 后端即服务:
所有 Dify 的功能都带有相应的 API,因此您可以轻松地将 Dify 集成到自己的业务逻辑中。

使用 Dify

  • **云 **
    我们提供 Dify 云服务,无需管理服务器即可体验 Dify。最新套餐与用量额度请参阅定价页面。

  • 自托管 Dify 社区版
    使用这个入门指南快速在您的环境中运行 Dify。
    使用我们的文档进行进一步的参考和更深入的说明。

  • 面向企业/组织的 Dify
    我们提供额外的面向企业的功能。给我们发送电子邮件讨论企业需求。

保持领先

在 GitHub 上给 Dify Star,并立即收到新版本的通知。

安装社区版

系统要求

在安装 Dify 之前,请确保您的机器满足以下最低系统要求:

  • CPU >= 2 Core
  • RAM >= 4 GiB

快速启动

启动 Dify 服务器的最简单方法是运行我们的 docker-compose.yml 文件。在运行安装命令之前,请确保您的机器上安装了 Docker 和 Docker Compose:

bash
cd docker
cp .env.example .env
docker compose up -d

运行后,可以在浏览器上访问 http://localhost/install 进入 Dify 控制台并开始初始化安装操作。

获取帮助

如果在安装 Dify 时遇到问题,请参阅我们的常见问题。如果问题仍未解决,请联系社区和我们。

如果您希望为 Dify 贡献代码或进行额外的开发,请参阅我们的源码部署指南

高级设置

如需自定义配置、可观测性和部署选项,请参阅高级设置。

贡献

Dify 欢迎各种形式的贡献:

贡献者

社区与支持

请选择最适合您问题的渠道:

  • GitHub Discussions:获取帮助、分享反馈并提出想法。
  • GitHub Issues:报告可重现的错误并跟踪工程工作。创建问题前,请先阅读贡献指南。
  • Discord:实时交流、分享您的应用,并与其他 Dify 用户互动。
  • X:关注版本新闻和项目更新。

Star History

安全问题

请按照安全政策,通过 GitHub Security Advisories 私下报告漏洞,不要在公开 issue、讨论或 PR 中披露。

License

本仓库遵循 Dify Open Source License 开源协议,该许可证本质上是 Apache 2.0,但有一些额外的限制。


Zh TW README (`docs/zh-TW/README.md`)

Dify 是一個開源的 LLM 應用程式開發平台。其直觀的界面結合了智能代理工作流程、RAG 管道、代理功能、模型管理、可觀察性功能等,讓您能夠快速從原型進展到生產環境。

快速開始

安裝 Dify 之前,請確保您的機器符合以下最低系統要求:

  • CPU >= 2 核心
  • 記憶體 >= 4 GiB

啟動 Dify 伺服器最簡單的方式是透過 docker compose。在使用以下命令運行 Dify 之前,請確保您的機器已安裝 Docker 和 Docker Compose:

bash
cd dify
cd docker
cp .env.example .env
docker compose up -d

運行後,您可以在瀏覽器中通過 http://localhost/install 訪問 Dify 儀表板並開始初始化過程。

尋求幫助

如果您在設置 Dify 時遇到問題,請參考我們的 常見問題。如果仍有疑問,請聯絡 社區和我們。

如果您想為 Dify 做出貢獻或進行額外開發,請參考我們的 從原始碼部署指南

核心功能

1. 工作流程:
在視覺化畫布上建立和測試強大的 AI 工作流程,利用以下所有功能及更多。

2. 全面的模型支援:
無縫整合來自數十個推理提供商和自託管解決方案的數百個專有/開源 LLM,涵蓋 GPT、Mistral、Llama3 和任何與 OpenAI API 兼容的模型。您可以在此處找到支援的模型提供商完整列表。

3. 提示詞 IDE:
直觀的界面,用於編寫提示詞、比較模型性能,以及為聊天型應用程式添加文字轉語音等額外功能。

4. RAG 管道:
廣泛的 RAG 功能,涵蓋從文件擷取到檢索的全部流程,內建支援從 PDF、PPT 和其他常見文件格式提取文本。

5. 代理功能:
您可以基於 LLM 函數調用或 ReAct 定義代理,並為代理添加預構建或自定義工具。Dify 為 AI 代理提供 50 多種內建工具,如 Google 搜尋、DALL·E、Stable Diffusion 和 WolframAlpha。

6. LLMOps:
監控並分析應用程式日誌和長期效能。您可以根據生產數據和標註持續改進提示詞、數據集和模型。

7. 後端即服務:
Dify 的所有功能都提供相應的 API,因此您可以輕鬆地將 Dify 整合到您自己的業務邏輯中。

使用 Dify

保持領先

在 GitHub 上為 Dify 加星,即時獲取新版本通知。

進階設定

如需自訂設定、可觀測性和部署選項,請參閱進階設定。

貢獻

Dify 歡迎各種形式的貢獻:

貢獻者

社群與聯絡方式

請選擇最符合您問題的管道:

  • GitHub Discussions:取得協助、分享意見並提出想法。
  • GitHub Issues:回報可重現的錯誤並追蹤工程工作。建立議題前,請先閱讀貢獻指南。
  • Discord:即時交流、分享您的應用程式,並與其他 Dify 使用者互動。
  • X:追蹤版本消息與專案更新。

星星歷史

安全揭露

請依照安全政策,透過 GitHub Security Advisories 私下回報漏洞,不要在公開議題、討論或 PR 中揭露。

授權條款

本代碼庫採用 Dify 開源授權,這基本上是 Apache 2.0 授權加上一些額外限制條款。


Dify Agent Docs Dify Agent Index (`dify-agent/docs/dify-agent/index.md`)

Dify Agent runtime

Dify Agent hosts native Pydantic AI runs behind FastAPI. Implementations remain
under src/dify_agent; there is no separate agent composition framework.

Each module declares Pydantic Config, State, and exactly one native
Capability or Toolset. The server registry maps a name to a module. Names
identify configuration, state and instances; aliases can use the same module
with independent state. New instances are created for every run.

ctx.deps.layers[name] contains JSON config and state. Config is read-only
within a run and comes from the current request. State belongs to its module;
validated models are copies, so mutations require explicit
entry["state"] = state.model_dump(mode="json") writeback. Stateful tools that
read and modify across awaits execute sequentially.

deps.services borrows lifespan clients and server settings. deps.resources
holds only operation leases, shell sessions and temporary credentials. The
capability that acquires a resource releases it in wrap_run using finally,
including failures and cancellation. The API owns durable Binding/Workspace
retirement and saves snapshots in the owning session.

Registered production names are agent_soul_prompt, workflow_node_job_prompt,
workflow_user_prompt, agent_app_user_prompt, execution_context, runtime,
shell, config, history, llm, tools, core_tools, knowledge, output,
plus prompt and user_prompt convenience names. HTTP input cannot supply an
import path. Cross-module references live in Config, for example
execution_context, runtime, and shell; the loader validates their targets
before I/O. Instruction ordering is unspecified. Native capability ordering
preserves Runtime → Shell → Config resource scopes.

An enabled Local runtime requires a nonblank deployment auth token matching
shellctl. When shellctl path isolation is enabled, Landlock setup errors abort
the job before its user script executes. Deployment settings may explicitly
disable path isolation. See the operations guide for setup.

Model, output type, current user content and initial history use explicit runner
assembly and native Agent arguments. Knowledge eager results stay in the user
role through a native model-request hook. Tool dispatch, instructions and
capability hooks use native Pydantic AI interfaces.

See run lifecycle,
resources, and the
operations guide.


Dify Agent Docs Dify Agent Examples Index (`dify-agent/docs/dify-agent/examples/index.md`)

Dify Agent examples

These examples live under examples/dify_agent/dify_agent_examples. They use
registered modules and depend on the Agent server, Redis, Dify API, and plugin
daemon settings described in the operations guide.

Run a Dify plugin-daemon backed model

snippet {path="/examples/dify_agent/dify_agent_examples/run_pydantic_ai_agent.py"}

Poll run events

snippet {path="/examples/dify_agent/dify_agent_examples/run_server_consumer.py"}

Use the synchronous client

snippet {path="/examples/dify_agent/dify_agent_examples/run_server_sync_client.py"}

Stream run events with SSE

snippet {path="/examples/dify_agent/dify_agent_examples/run_server_sse_consumer.py"}

Dify Agent Docs Dify Agent Get Started Index (`dify-agent/docs/dify-agent/get-started/index.md`)

Get started

Create a run with POST /runs; poll /runs/{run_id} or consume its event stream.
The composition schema version is 2. Each entry contains a registered name and
current JSON config. Module identity comes from the server registry; there are
no graph type/dependency fields or generic per-module exit policy.

json
{
  "composition": {
    "schema_version": 2,
    "layers": [
      {"name": "execution_context", "config": {"tenant_id": "tenant", "agent_mode": "agent_app", "invoke_from": "service-api"}},
      {"name": "prompt", "config": {"prefix": "Be helpful", "user": "Hello"}},
      {"name": "history", "config": {}},
      {"name": "llm", "config": {"execution_context": "execution_context", "plugin_id": "langgenius/openai", "model_provider": "openai", "model": "gpt-4o-mini"}}
    ]
  }
}

Resume by including the previous terminal session_snapshot and submitting the
current composition. llm is required, history and output are optional.
Resource cleanup always happens at exit. Cancellation is a separate operation;
its terminal event is published only after the owner run has cleaned up.


Dify Agent Docs Dify Agent Guide Index (`dify-agent/docs/dify-agent/guide/index.md`)

Operating the Dify Agent Run Server

This guide describes how to run the MVP Dify Agent API server. The server is
implemented in dify-agent/src/dify_agent/server/app.py and uses Redis for run
records and per-run event streams. Optional E2B usage collection is triggered by
the API's existing Celery Beat schedule through a separate one-shot endpoint.
It adds no operation logging, polling loop, leader election or accounting context
to business runtime execution.

Default local startup

Start Redis, then run one FastAPI/uvicorn process:

bash
uv run --project dify-agent uvicorn dify_agent.server.app:app --reload

By default, the FastAPI lifespan creates:

  • one Redis-backed run store used by HTTP routes
  • shared plugin-daemon and Dify API inner httpx.AsyncClient instances
  • one deployment-selected, stateless runtime backend profile when configured
  • one process-local scheduler that starts background asyncio run tasks

This means local development needs one uvicorn process plus Redis, and
plugin-backed runs also need a reachable Dify plugin daemon. Run execution still
happens outside request handlers, so client disconnects do not cancel the agent
run.

Configuration

ServerSettings loads environment variables with the DIFY_AGENT_ prefix. It
also reads .env and dify-agent/.env when present.

OpenShell-specific settings are listed in the
OpenShell configuration reference.

Independent E2B execution accounting, activation and rollout checks are described
in E2B runtime metering.

Environment variable Default Description
DIFY_AGENT_REDIS_URL redis://localhost:6379/0 Redis connection URL.
DIFY_AGENT_REDIS_PREFIX dify-agent Prefix for Redis record and event keys.
DIFY_AGENT_SHUTDOWN_GRACE_SECONDS 30 Seconds to wait for active local runs during graceful shutdown before cancellation.
DIFY_AGENT_RUN_RETENTION_SECONDS 7200 Seconds to retain Redis run records and per-run event streams after their last write; defaults to 2 hours.
DIFY_AGENT_RUN_EVENT_STREAM_MAX_LENGTH 5000 Approximate target maximum for replayable events retained in each per-run Redis Stream.
DIFY_AGENT_STREAM_TEXT_DELTA_COALESCING_ENABLED true Set false to publish each text delta without coalescing.
DIFY_AGENT_STREAM_TEXT_DELTA_FLUSH_INTERVAL_MS 100 Soft debounce interval for compatible text deltas. Already-ready source events may continue to merge after this interval; a waiting source triggers the timed flush. Must be greater than zero; use DIFY_AGENT_STREAM_TEXT_DELTA_COALESCING_ENABLED=false to disable coalescing.
DIFY_AGENT_STREAM_TEXT_DELTA_MAX_CHARS 4096 Character threshold that flushes a buffered text-delta event immediately.
DIFY_AGENT_RUN_TIMEOUT_SECONDS 3600 Wall-clock deadline in seconds for the Pydantic AI agent.run(...) model/tool loop. Deadline failures use agent_run_limit_exceeded. Its default intentionally matches DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS, but the settings are independently configurable.
DIFY_AGENT_BINDING_FILE_DOWNLOAD_COMMAND_TIMEOUT_SECONDS 210 Shell command deadline for running the sandbox dify-agent file upload --no-download-link conversion. Keep it above the CLI's 180-second upload deadline.
DIFY_AGENT_API_TOKEN empty Optional Bearer token required by private run, Execution Binding, Home Snapshot, and Binding file control-plane routes. Must match Dify API AGENT_BACKEND_API_TOKEN.
DIFY_AGENT_PLUGIN_DAEMON_URL http://localhost:5002 Base URL for the Dify plugin daemon.
DIFY_AGENT_PLUGIN_DAEMON_API_KEY empty API key sent to the Dify plugin daemon.
DIFY_AGENT_INNER_API_URL http://localhost:5001 Dify API service root used when dify-agent calls /inner/api/... endpoints.
DIFY_AGENT_INNER_API_KEY empty API key sent to Dify API inner plugin endpoints. Set this to Dify API INNER_API_KEY_FOR_PLUGIN (Docker: PLUGIN_DIFY_INNER_API_KEY).
DIFY_AGENT_RUNTIME_BACKEND local Selects one coherent local, enterprise, e2b, or openshell Home Snapshot + Execution Binding backend profile.
DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT empty Local shellctl data-plane URL. With the default Local selection, leaving it empty disables dify.runtime and resource endpoints.
DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN empty Required nonblank bearer token when the Local endpoint is configured; must match shellctl's SHELLCTL_AUTH_TOKEN.
DIFY_AGENT_LOCAL_SANDBOX_MATERIALIZED_HOME_ROOT /home/dify Root directory, on the Local shellctl filesystem, for per-Binding materialized Homes.
DIFY_AGENT_LOCAL_SANDBOX_WORKSPACE_ROOT /workspace Root directory, on the Local shellctl filesystem, for mutable Workspaces.
DIFY_AGENT_LOCAL_SANDBOX_HOME_SNAPSHOT_ROOT /home/dify/.snapshots Root directory, on the Local shellctl filesystem, for immutable Home Snapshots.
DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_ENDPOINT empty Enterprise Gateway endpoint required by configuration. Default-Home Bindings are supported; immutable Home Snapshot operations remain unsupported.
DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_AUTH_TOKEN empty Optional X-Inner-Api-Key sent to the Enterprise Gateway.
DIFY_AGENT_ENTERPRISE_SANDBOX_GATEWAY_TIMEOUT 30 Enterprise control-plane timeout in seconds.
DIFY_AGENT_ENTERPRISE_SANDBOX_PROXY_TIMEOUT 60 Enterprise shellctl-proxy timeout in seconds.
DIFY_AGENT_E2B_API_KEY empty E2B API key; required for E2B.
DIFY_AGENT_E2B_TEMPLATE difys-default-team/dify-agent-local-sandbox Prepared E2B template containing shellctl and the deployment-default Home environment.
DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS 3600 Maximum continuous active time for the RuntimeLease spanning one complete Agent run. Its default intentionally matches DIFY_AGENT_RUN_TIMEOUT_SECONDS, but the settings are independently configurable. Binding resources pause on timeout; this setting does not own the run terminal state and is not a retention TTL.
DIFY_AGENT_E2B_SHELLCTL_PORT 5004 shellctl port exposed by the E2B template.
DIFY_AGENT_SHELL_REDACT_PATTERNS empty JSON array of additional regex patterns redacted from Shell output.
DIFY_AGENT_STUB_API_BASE_URL empty HTTP(S) Agent Stub API base URL reachable from the Sandbox. It may be the service root or /agent-stub. Enables DIFY_AGENT_STUB_* env injection for user shell.run jobs.
DIFY_AGENT_SANDBOX_FILES_BASE_URL empty Dify API base URL reachable from the Sandbox for signed /files/* upload/download bytes, including Config file and skill pulls. Required when Agent Stub file operations are enabled. May include an ingress path prefix, but not a query or fragment.
DIFY_AGENT_STUB_UPLOAD_FILE_SIZE_LIMIT 50 Agent service-owned maximum Agent Stub upload size in MiB. The file-request handler factory converts it to bytes and sends it to Dify API as the required max_size used to sign a size-limited upload URL.
DIFY_AGENT_SERVER_SECRET_KEY empty Security-sensitive server-wide root secret used to derive the JWE encryption key for Agent Stub bearer tokens; required when DIFY_AGENT_STUB_API_BASE_URL is set. The supplied default config uses a development value; set a unique unpadded base64url 32-byte secret in production.
DIFY_AGENT_OUTBOUND_HTTP_CONNECT_TIMEOUT 10 Shared outbound HTTP connect timeout in seconds.
DIFY_AGENT_OUTBOUND_HTTP_READ_TIMEOUT 600 Shared outbound HTTP read timeout in seconds.
DIFY_AGENT_OUTBOUND_HTTP_WRITE_TIMEOUT 30 Shared outbound HTTP write timeout in seconds.
DIFY_AGENT_OUTBOUND_HTTP_POOL_TIMEOUT 10 Shared outbound connection-pool wait timeout in seconds.
DIFY_AGENT_OUTBOUND_HTTP_MAX_CONNECTIONS 100 Maximum total shared outbound HTTP connections.
DIFY_AGENT_OUTBOUND_HTTP_MAX_KEEPALIVE_CONNECTIONS 20 Maximum idle shared outbound HTTP connections.
DIFY_AGENT_OUTBOUND_HTTP_KEEPALIVE_EXPIRY 30 Idle keep-alive expiry in seconds.
DIFY_AGENT_TRAJECTORY_ENABLED false Opt-in switch for the separate Agent trajectory export pipeline.
DIFY_AGENT_TRAJECTORY_OTLP_TRACES_ENDPOINT empty Full HTTP(S) OTLP traces endpoint required when trajectory export is enabled.
DIFY_AGENT_TRAJECTORY_OTLP_HEADERS {} JSON object of request headers sent with Agent OTLP trace exports.
DIFY_AGENT_TRAJECTORY_SERVICE_NAME dify-agent-trajectory Resource service name attached to Agent trajectory spans.
DIFY_AGENT_TRAJECTORY_INCLUDE_CONTENT false Include message and tool content in Agent trajectory spans.
DIFY_AGENT_TRAJECTORY_TRACE_CONTEXT_MODE isolated isolated starts independent platform/Agent traces; shared preserves cross-instance parent context. Requires process restart to change.
DIFY_AGENT_TRAJECTORY_MAX_QUEUE_SIZE 2048 Maximum number of spans queued for Agent trace export; must be positive.
DIFY_AGENT_TRAJECTORY_MAX_EXPORT_BATCH_SIZE 512 Maximum spans per export batch; must be positive and no greater than the queue size.
DIFY_AGENT_TRAJECTORY_SCHEDULE_DELAY_MS 5000 Delay between scheduled Agent span exports, in milliseconds; must be positive.
DIFY_AGENT_TRAJECTORY_EXPORT_TIMEOUT_MS 5000 Batch processor export timeout setting, in milliseconds; must be positive. Does not change the OTLP HTTP exporter request timeout.

Platform observability uses the process-level Logfire instance and standard
OTEL_* / LOGFIRE_* configuration. Agent observability uses a separate local
Logfire instance and is disabled by default. Set DIFY_AGENT_TRAJECTORY_ENABLED=true
and a full DIFY_AGENT_TRAJECTORY_OTLP_TRACES_ENDPOINT to opt in;
DIFY_AGENT_TRAJECTORY_OTLP_HEADERS is a JSON object of request headers. Agent
traces do not inherit platform endpoints, credentials, sampling, or console
export. Message/tool content requires the separate
DIFY_AGENT_TRAJECTORY_INCLUDE_CONTENT opt-in. Platform FastAPI parameter/error
payloads, HTTPX bodies/headers and Redis statements are not captured by these
instrumentations. The Agent instance is created at service startup and shut down
after active runs finish. These are deployment-level settings, not yet
per-tenant authorization or routing; a shared backend does not provide storage
isolation.

With DIFY_AGENT_TRAJECTORY_TRACE_CONTEXT_MODE=isolated (the default), Agent
run spans start independent traces instead of inheriting platform request
parents. Platform HTTPX/Redis instrumentation also detaches local Agent
parents while preserving platform-only and incoming distributed trace
relationships. In shared mode both pipelines retain cross-instance parent
context and the Agent sampler respects the parent sampling decision. Use
shared only when both pipelines export to the same queryable backend space;
otherwise missing-root spans can recur. Service names do not select the mode.
The two SDK instances, exporters, enable switch, and content opt-in remain
separate. The mode is fixed at process initialization and requires a restart
to change. No extra shared root span is added; incomplete traces may still
appear temporarily while a run or export is in progress.

Example .env:

text
/* Detailed source-code truncated for AI context efficiency. */

The two Sandbox-facing base URLs have different owners. Agent Stub control
requests use DIFY_AGENT_STUB_API_BASE_URL; signed file bytes use
DIFY_AGENT_SANDBOX_FILES_BASE_URL. DIFY_AGENT_INNER_API_URL remains a
trusted service-to-service URL and is never returned to the Sandbox.

Config file and skill pulls use the same split: Agent Stub authorizes the
Config target and returns a short-lived URL, then the Sandbox fetches the bytes
directly from the Dify API /files/* data plane.

Removing Agent Stub gRPC is a breaking transport migration: replace every
grpc:// Agent Stub URL with HTTP(S), remove
DIFY_AGENT_STUB_GRPC_BIND_ADDRESS, and deploy without a gRPC fallback.

For a remote Sandbox, expose only /agent-stub/* from Agent Backend and the
existing /files/* Dify API data plane. The /files/* ingress must preserve
the complete signed query string and set its request-body limit above the
configured file-size limit to leave room for multipart framing and headers; the
two limits need not be numerically equal. Use response streaming and timeouts
suitable for large downloads. Do not expose Agent Backend /runs, Workspace,
or Binding management routes through the Sandbox ingress.

Browser presentation URLs are independent. Configure Dify API FILES_URL to a
browser-reachable public origin, or leave it empty so responses use same-origin
relative /files/... URIs. Never set FILES_URL to a Docker-only service name
such as http://api:5001.

DIFY_AGENT_SHELLCTL_ENTRYPOINT and DIFY_AGENT_SHELLCTL_AUTH_TOKEN remain
accepted only as legacy aliases for the two Local settings. New deployments
must use DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT and
DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN. There is no compatibility setting for
the removed shell-provider selector.

Local shellctl deployments must start with shellctl serve --require-auth-token
and set SHELLCTL_AUTH_TOKEN to the same secret as the Agent Backend. Compose's
local_sandbox command enables this check; missing, empty, or whitespace-only
tokens fail before service initialization. E2B and Enterprise retain their
existing token requirements, and an unset Local endpoint still disables runtime.

For Compose, set DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN in a shared interpolation
source: the invoking shell, docker/.env, or a Compose --env-file. This supplies
the same secret to Agent Backend and shellctl. Setting it only in a service env
file is insufficient: Compose's explicit environment values override that
file, including with an empty interpolated value. The legacy token alias remains
accepted. Deploy this change with a rebuilt runtime image containing
--require-auth-token; the previously published 1.17.1 image does not support
the new flag.

When shellctl path isolation is enabled, any Landlock setup error aborts the job
with exit code 125 before its user script executes. Deployments may explicitly
set SHELLCTL_ENABLE_PATH_ISOLATION=false to disable shellctl path isolation.

The backend selection is deployment-private. Shell-enabled run requests use an
Execution Context, dify.runtime, and dify.shell graph. Runtime config carries
only the opaque backend_binding_ref resolved by Dify API. See
Runtime resources for the ownership
and lifecycle contract.

Run records and event streams use the same retention. Status writes refresh the
record TTL, and event writes refresh both the stream TTL and the corresponding
record TTL so active runs that keep producing events remain observable. Text
deltas for the same response part and provider metadata are coalesced within a
soft debounce/size window before being published. The debounce timer flushes
when reading the next source event would block; already-ready events may keep
merging until the character threshold or a non-compatible event is reached.
Every Redis Stream write also applies the configured approximate maximum length. A reconnect cursor older than the
retained window resumes from the oldest remaining event, so callers must treat
the terminal snapshot and application-owned history as authoritative rather
than relying on the Agent event stream as long-term history.

Validate the E2B Compose deployment

The E2B overlay requires a prepared template that starts shellctl on port 5004.
The default is difys-default-team/dify-agent-local-sandbox. It also requires
an E2B API key in DIFY_AGENT_E2B_API_KEY; the Compose interpolation accepts
E2B_API_KEY and E2B_API_TOKEN only as deployment-level fallbacks.

From the repository root, keep the normal docker/.env unchanged and export the
secret for this shell:

bash
export DIFY_AGENT_E2B_API_KEY="${DIFY_AGENT_E2B_API_KEY:-${E2B_API_KEY:-${E2B_API_TOKEN:-}}}"
test -n "$DIFY_AGENT_E2B_API_KEY"
export DIFY_AGENT_E2B_TEMPLATE=difys-default-team/dify-agent-local-sandbox

docker compose \
  --env-file docker/.env \
  -f docker/docker-compose.yaml \
  -f docker/docker-compose.e2b.yaml \
  up -d --build

The overlay builds dify-api:e2b-local and
dify-agent-backend:e2b-local from the current checkout. It disables the
normal Local sandbox service, switches Dify Agent to E2B, and mounts PostgreSQL
on the separate dify_e2b_postgres_data Compose volume. That database is empty
when the volume is first created and is isolated from the normal stack; later
starts reuse it until an operator explicitly removes the volume.

Verify the merged deployment and the branch-built Dify Agent API:

bash
docker compose \
  --env-file docker/.env \
  -f docker/docker-compose.yaml \
  -f docker/docker-compose.e2b.yaml \
  ps

agent_backend_port="$(
  docker compose \
    --env-file docker/.env \
    -f docker/docker-compose.yaml \
    -f docker/docker-compose.e2b.yaml \
    port agent_backend 5050 | awk -F: 'NR == 1 { print $NF }'
)"
test -n "$agent_backend_port"
curl --fail --silent --show-error \
  --connect-timeout 2 --max-time 5 \
  --retry 12 --retry-delay 1 --retry-connrefused --retry-max-time 60 \
  "http://127.0.0.1:${agent_backend_port}/openapi.json" \
  >/dev/null

docker compose \
  --env-file docker/.env \
  -f docker/docker-compose.yaml \
  -f docker/docker-compose.e2b.yaml \
  logs --tail=100 agent_backend api worker

Stop the validation stack without deleting its isolated database volume:

bash
docker compose \
  --env-file docker/.env \
  -f docker/docker-compose.yaml \
  -f docker/docker-compose.e2b.yaml \
  down

DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS controls continuous active E2B time.
The physical resource behind a Binding pauses when that timeout fires, preserving
the current Workspace. The setting is not a resource-age TTL, does not delete
paused resources or immutable snapshots, and does not authoritatively finalize
the Agent run. If the paused Sandbox is first observed by a Shell tool, that
provider failure is returned to Pydantic AI as a tool error observation.

The run and E2B defaults both equal 3600 seconds, but independent clocks and
asynchronous E2B pause propagation make their ordering nondeterministic. A Shell
provider RuntimeError observed first becomes a tool observation. In contrast,
run-deadline cancellation propagates through the Shell boundary; only the Dify
Agent run deadline owns the terminal agent_run_limit_exceeded failure.

The E2B backend uses SDK 2.55.1 or later with three control-plane retries.
The SDK retries 502 only for replayable operations, including when the response
has Retry-After; a gateway can return 502 after a resource was already created.
Sandbox and snapshot creation therefore surface 502 without replaying the
request. The SDK still retries 503, 429 with Retry-After, and safely
replayable network failures. Backend adapters invoke each SDK operation once;
exhausted retries and timeouts do not start a second SDK request budget.
Resource creation and snapshot creation are also not replayed after an ambiguous
post-write network failure. See the SDK replay policy.

This policy covers E2B lifecycle API calls. Shell commands and normal file
operations use the separate shellctl client, and usage collection uses its own
HTTP client. Neither inherits the E2B SDK retry or connection-pool settings.

The backend explicitly requests mode="full" for timeout pauses, explicit
pauses, and Home Snapshots, preserving both filesystem and memory state. Binding
acquisition uses on_resume="restore"; connect does not accept a snapshot
mode. These settings preserve the existing full-memory restore intent while
replacing the deprecated keep_memory option. They do not override platform
fallbacks: E2B may save only the filesystem if a timeout pause is continuously
refused because a previous snapshot is still being finalized. See the
E2B persistence contract.

OpenShell backend

See the OpenShell Runtime Backend guide for its configuration
reference, runtime image build instructions, gateway and shared-volume setup,
and deployment validation.

Run runtime-backend integration contracts

Run the disposable Local contract from the dify-agent directory. The script
starts one local-sandbox container on an unused port and removes that exact
container on exit. It intentionally has no image fallback: provide a Local
Sandbox image built from the same commit as the code under test so an older
shellctl implementation cannot make the lifecycle contract pass incorrectly:

bash
cd dify-agent
DIFY_AGENT_TEST_LOCAL_SANDBOX_IMAGE=<same-commit-local-sandbox-image> \
  tests/integration/dify_agent/runtime_backend/run_local_integration.sh

To use an already managed Local shellctl endpoint instead:

bash
cd dify-agent
DIFY_AGENT_TEST_LOCAL_SHELLCTL_ENDPOINT=http://127.0.0.1:5004 \
DIFY_AGENT_TEST_LOCAL_SHELLCTL_AUTH_TOKEN=replace-with-shellctl-token \
  pdm run pytest --import-mode=importlib \
  tests/integration/dify_agent/runtime_backend/test_working_environment.py \
  -k local -q -rs

Run the real E2B contract with an explicit test credential and template:

bash
cd dify-agent
DIFY_AGENT_TEST_E2B_API_KEY="$E2B_API_TOKEN" \
DIFY_AGENT_TEST_E2B_TEMPLATE=difys-default-team/dify-agent-local-sandbox \
  pdm run pytest --import-mode=importlib \
  tests/integration/dify_agent/runtime_backend/test_working_environment.py \
  -k e2b -q -rs

For OpenShell, see Run the OpenShell integration contract.

The Local auth token is optional when shellctl has authentication disabled.
The E2B contract uses the one-hour E2B_MAX_ACTIVE_TIMEOUT_SECONDS RuntimeLease
limit. This is continuous active test time, not a post-test retention TTL. All
contracts create unique resources and perform explicit cleanup in finally
blocks.

Scheduling and shutdown semantics

POST /runs persists a running run record and starts an asyncio task in the
same process. There is no Redis job stream, consumer group, pending reclaim, or
automatic retry layer. Request-shaped runtime failures such as bad composition,
prompt, output, or snapshot inputs are reported later as failed runs rather than
rejected synchronously once the request DTO itself is accepted.

Each run explicitly limits Pydantic AI to 500 model-request steps. Tool calls do
not have a separate count limit, but every model request used to continue the
tool loop consumes one of those steps.

DIFY_AGENT_RUN_TIMEOUT_SECONDS additionally applies a wall-clock deadline around
native Pydantic AI's agent.run(...). This includes capability entry, RuntimeLease
acquisition, dynamic tool preparation, the model/tool loop, and the event handler.
Request validation and agent assembly happen before this deadline. Expiry cancels
the native run; capability scopes unwind and release resources before the runner
generates the session snapshot and finalizes the run as failed with
error_type: "agent_run_limit_exceeded". History persistence, snapshot generation,
and terminal finalization occur after native execution.

During FastAPI shutdown the scheduler rejects new runs, waits up to
DIFY_AGENT_SHUTDOWN_GRACE_SECONDS for active tasks, then cancels remaining tasks
and attempts to finalize them as failed. Success and failure use an atomic Redis
transition. Cancellation first atomically records a private intent; after the
owner exits the runner, a second atomic transition appends run_cancelled,
updates the run record, and deletes the intent. The first accepted success,
failure, or cancellation intent wins. A hard process crash can still leave
active runs, including runs with accepted cancellation intent, stuck as
running; there is no in-service recovery or worker handoff.

Horizontal scaling is possible by running multiple API processes against the same
Redis prefix, but each process executes only the runs it accepted. Redis provides
shared status/event visibility, not load balancing or queued-job recovery. The
cancel endpoint can atomically accept a running run on any process. The process
that owns the runner observes the private cancellation-intent stream, cancels
and cleans up its local task, and only then emits run_cancelled. The HTTP
response confirms that cancellation intent is durable; GET /runs/{run_id} may
still report running until cleanup finishes. Retrying an accepted or completed
cancellation is idempotent.

Atomic terminal finalization currently assumes the configured Redis URL targets
one Redis deployment that can execute all run-coordination keys in a Lua script.
The record and event key names are unchanged, and cancellation adds a private
cancel-intent key. These keys do not contain a shared Redis Cluster hash tag, so
Redis Cluster is not supported for this transition. During
a rolling upgrade, older processes can still use the former split event/status
writes; treat the single-terminal invariant as active only after those processes
have exited. Deploy atomic terminal finalization everywhere first, then ensure
every process that can own a runner has the cancellation observer before relying
on route-independent cancellation. Operators should then alert on more than one
terminal event per run and on disagreement between the run record status and
terminal event type.

Run inputs and session snapshots

Submit a RunComposition with registered module names and JSON Config. The
llm model module is required and references an execution_context module.
Prompt modules contribute instructions and config.user input:

json
{
  "composition": {
    "schema_version": 2,
    "layers": [
      {"name": "prompt", "config": {"prefix": "You are concise.", "user": "Summarize the current state."}},
      {"name": "execution_context", "config": {"tenant_id": "tenant-id", "agent_mode": "agent_app", "invoke_from": "web-app"}},
      {"name": "llm", "config": {"plugin_id": "langgenius/openai", "model_provider": "openai", "model": "gpt-4o-mini"}}
    ]
  }
}

config.user can be a string or a list of strings. Empty or whitespace-only
effective prompts and module configuration are validated by the runner before
resource acquisition or model I/O. HTTP create-run parses the wire shape, persists
the run and schedules execution; configuration errors produce run_failed.

Agent App callers can use the agent_app_user_prompt module to send text and images
in the same model turn. Each image must provide exactly one transport: an
HTTP(S) url or unprefixed Base64 data in base64_data. The image is passed as
structured multimodal content; it is not interpolated into config.text.

json
{
  "name": "agent_app_user_prompt",
  "config": {
    "text": "Describe this image.",
    "files": [
      {
        "delivery": "multimodal",
        "type": "image",
        "filename": "earth.png",
        "mime_type": "image/png",
        "format": "png",
        "url": "https://files.example.com/earth.png",
        "base64_data": null,
        "detail": "high"
      }
    ]
  }
}

All attachments use config.files. The delivery field selects how an attachment
is presented, independently of its file type (image, document, audio,
video, or custom):

  • delivery: "multimodal" currently supports type: "image" only. Dify API
    chooses URL or Base64 transport according to MULTIMODAL_SEND_FORMAT.
  • delivery: "download" preserves the original file type, including image
    when the selected model has no Vision feature. It contains either
    transfer_method: "remote_url" with url, or a local_file, tool_file, or
    datasource_file transfer method with a canonical reference.

The module appends sandbox file-download instructions for download attachments
and adds multimodal attachments as structured model content. Callers keep
config.text as the original user text. Omitting config.files is equivalent
to an empty list.

The optional history module uses the reserved name history. It persists captured
messages, including failure and cancellation history, with current instructions
removed. Snapshots have schema_version: 2 and a layers JSON dict containing only
State. Submit current Config on each turn along with the previous snapshot. Modules
can be added or removed between turns; retained state is matched by name.

Known v1 snapshots are converted once at read time without restoring legacy
instances or lifecycle. Native resource scopes always release leases and clear
tracked shell jobs at run exit. Success always contains the resulting snapshot;
failure and cancellation contain one when validated run data was available and
cleanup produced a snapshot. Callers retain the previous snapshot when none is
returned. Product Workspace retirement remains owned by the API.

Observing runs

Use the HTTP status endpoint for coarse state and the event endpoints for detailed
progress:

  • POST /runs creates a running run and schedules it locally.
  • GET /runs/{run_id} returns running, succeeded, failed, or cancelled.
    Failed records can also expose a stable machine-readable error_type alongside
    the diagnostic error text.
  • POST /runs/{run_id}/cancel atomically accepts cancellation on any API process
    and returns immediately. CancelRunResponse.status == "cancelled" acknowledges
    a durably accepted cancellation intent, not completed runner cleanup. Callers
    that require cleanup-complete state or its session snapshot must await the
    public run_cancelled event or use cancel_run_and_wait. The endpoint returns
    409 only when a success/failure terminal already won.
  • GET /runs/{run_id}/events polls the Redis Stream event log with after and
    next_cursor cursors.
  • GET /runs/{run_id}/events/sse replays and streams events over SSE. The SSE
    id is the event Redis Stream ID. after query cursors take precedence over
    Last-Event-ID headers. The server closes the SSE response normally after
    delivering a terminal event. Clients must stop reconnecting after consuming
    that event. Both cursor forms remain exclusive resume cursors, so the server
    does not resend a terminal event that the supplied cursor already excludes.

Both event endpoints replay with nonblocking XREAD, which supports exclusive
resume cursors on Redis 6.0, including 6.0.14. 0-0 starts at the earliest
retained event. Polling returns at most limit events; an empty page preserves
the supplied after as next_cursor. SSE switches to blocking reads after
replay is exhausted. Both endpoints return 404 when the run record is missing.
This read-command compatibility does not define the platform's full Redis
support matrix; the Redis deployment constraints above still apply.

Successful runs emit run_started, zero or more pydantic_ai_event, and
run_succeeded. Failed runs end with run_failed, and accepted cancellations
end with run_cancelled. Each run can append at most one of these terminal
events. Event envelopes retain id, run_id, type, data, and created_at;
data is typed per event type,
including Pydantic AI's AgentStreamEvent payload for pydantic_ai_event and a
terminal event may contain a SessionSnapshot for resumption.
run_succeeded always contains it; run_failed and run_cancelled contain it
when the runner produced State after native capability cleanup. A successful run
contains JSON-safe output, which may be null.
Failed event payloads contain the diagnostic error, optional source-specific
reason, optional stable error_type, and optional session_snapshot.
Cancelled payloads likewise may contain session_snapshot. Pydantic AI request/step budget
exhaustion enforced by Dify Agent is reported as
error_type: "agent_run_limit_exceeded"; consumers should branch on that value
rather than parsing the error text. The Dify Agent-owned wall-clock run deadline
uses the same error type; provider and connection timeouts do not. The matching
failed run record and terminal event are committed atomically with the same error
type. For independently deployed Agent backend and API services, deploy consumers
that accept the optional field before producers begin emitting it because the
public protocol models reject unknown fields.

Examples

The repository includes simple consumers that print observed output/events:

  • dify-agent/examples/dify_agent/dify_agent_examples/run_server_consumer.py
    creates a run and polls events.
  • dify-agent/examples/dify_agent/dify_agent_examples/run_server_sse_consumer.py
    consumes raw SSE frames for an existing run id.

The create-run examples submit Dify plugin model modules, so they require Redis,
the Agent server, Dify API gateway settings, and a configured model provider in Dify.


Dify Agent Docs Dify Agent Concepts Run Lifecycle Index (`dify-agent/docs/dify-agent/concepts/run-lifecycle/index.md`)

Agent run lifecycle

The server validates current Config, restored State and module references before
external operations. It creates fresh native Capability/Toolset instances and
runs Pydantic AI with a per-run Deps object. Current prompts and instructions are
built from that run's config.

Native wrap_run scopes acquire operation resources and clean them in finally.
Runtime acquires a lease; Shell bootstraps once and removes tracked jobs on exit;
Config pulls mentioned assets on successful first initialization. Initialization
flags are written only after successful setup, so failures can retry. The API's
workflow terminal events own Workspace retirement and physical resource collection.

The runner saves captured conversation history in its outer finally, strips
transient instructions and marks unexecuted trailing tool calls interrupted.
If no messages were captured, restored history remains intact. Compaction rewrites
are included. A terminal state snapshot is built after capability cleanup for
success, failure and cancellation.

Snapshot v2 stores only JSON state:

json
{"schema_version": 2, "layers": {"history": {"messages": []}}}

Configurations, clients, lease handles, tokens, models and lifecycle enums are
excluded. State is keyed by name, so instruction order does not constrain resume;
known optional modules can be added or removed. The API resubmits current Config
and retains session ownership through AgentWorkspaceBinding.session_snapshot.
All snapshot readers use SessionSnapshot validation. Its migrate_snapshot
validator dispatches v1 (including unversioned legacy lists) to the data-only
migrate_snapshot_v1_to_v2 helper. V2 is validated directly; unknown explicit
versions are rejected. Reading converts data in memory without updating stored
JSON; the API saves the terminal v2 snapshot through its existing session owner.
Known legacy names map to their meaningful State and removed AskHuman slots are
discarded. Their unanswered tool calls are marked interrupted so native history
repair closes them before the first new user turn. All runs use the native runner.
Unknown legacy names and malformed state are rejected.


Dify Agent Docs Dify Agent Concepts Runtime Resources Index (`dify-agent/docs/dify-agent/concepts/runtime-resources/index.md`)

Runtime resources

Dify separates persistent product resources from request-time execution:

  • a Home Snapshot is immutable Agent-owned Home content;
  • a Workspace is mutable working data owned by a product scope such as a
    conversation, Build Draft, or Workflow run;
  • an Execution Binding is one materialized Agent participant, including its
    private Home and resumable session, attached to a Workspace;
  • a RuntimeLease is operation-scoped access to the physical Binding.

AgentWorkspaceBinding.id is the participant, materialized Home, and persisted
module session identity. agent_id identifies the source Agent. The same
Agent can therefore have multiple active Bindings in one Workspace:
each has an independent Home and session, while all may share Workspace files.

Home and Workspace are logically independent. A backend may still couple their
physical representation. For example, current E2B maps one Binding and its
Workspace to one E2B resource, while Local can attach multiple materialized
Homes to one shared Workspace.

Runtime modules

Agent requests do not expose separate Home, Workspace, or Sandbox layers. Dify
API resolves the Binding selected by the product flow and sends its opaque
backend ref to the runtime module:

mermaid
flowchart LR
    EC["dify.execution_context<br/>request identity"]
    RT["dify.runtime<br/>opaque backend_binding_ref"]
    SH["dify.shell<br/>commands and jobs"]

    EC --> SH
    RT --> SH

runtime.Capability calls the selected ExecutionBindingBackend.acquire() when
its native wrap_run scope opens and release() when the operation ends. It exposes
the resulting RuntimeLease only while that context is active. The module does
not create, retire, or destroy persistent resources, and it stores no backend
SDK object in an module session snapshot.

The Shell module consumes RuntimeLease.commands and RuntimeLease.layout. It
tracks only request-local shell job ids and offsets.
Closing a run clears that job state; it does not retire the Binding.

State ownership

Dify API is the lifecycle ledger. It stores three resource records:

Record Meaning Backend field
agent_home_snapshots One immutable Home version owned by an Agent. snapshot_ref
agent_workspaces One mutable Workspace owned by a product scope. backend_workspace_ref
agent_workspace_bindings One materialized participant, private Home, and resumable session attached to a Workspace. backend_binding_ref

Backend refs are opaque strings interpreted only by the selected backend
adapter. Dify API stores the latest module session snapshot on the Binding, but
it does not serialize RuntimeLease, SDK clients, credentials, or temporary
access tokens.

Dify Agent does not connect to the Dify product database and has no persistent
resource registry. Its private control-plane endpoints create or destroy
backend resources from requests made by Dify API. Redis run records and event
streams are observability state, not the Home/Workspace/Binding ledger.

When DIFY_AGENT_API_TOKEN is configured, every private control-plane request must carry the matching Dify API AGENT_BACKEND_API_TOKEN as a Bearer token.

Creation and execution flow

Agent creation does not create a Home Snapshot. A config with no logical Home
Snapshot asks the selected backend to materialize its deployment-default Home
when the Binding is created. This default Home is mutable and private to the
Binding; it does not produce an agent_home_snapshots row or an implicit
snapshot ref.

Build Draft Apply uses POST /home-snapshots/from-binding: Dify Agent acquires
the exact source Binding, snapshots its materialized Home through the
backend-native operation, releases the lease, and returns a new opaque snapshot
ref. Dify API then stores a new immutable agent_home_snapshots row and records
its logical id on the resulting config version. There is no replay or fallback
when the source Binding is unavailable.

Before an Agent request, Dify API loads the specific product context. If it has
no associated Binding, Dify API materializes one and saves the Binding id in the
same database transaction. Otherwise it resolves only that Binding and validates
its owner and config/Home generation. Missing, retired, or mismatched Bindings
fail fast; Dify API does not search by Agent, Workspace, candidate count, or
recency, and it does not create a replacement implicitly.

POST /execution-bindings accepts either an exact home_snapshot_ref or
null. An exact ref must be materialized without fallback; null selects the
backend's deployment-default Home. It returns opaque Binding and Workspace
refs. Every create request represents a new participant, even when the Agent,
Snapshot, config generation, and Workspace match another Binding. The request
composition contains:

json
{
  "name": "runtime",
  "config": {"backend_binding_ref": "opaque-backend-binding-ref"}
}

Each Agent request acquires that ref for the duration of the run and releases it
afterward. Local release closes the operation's shellctl connection. E2B release
also pauses the underlying E2B resource with memory preserved. A later request
or Binding file operation acquires a new lease for the same Binding ref. If a
backend confirms the resource is gone, acquisition fails; it does not create an
empty replacement Workspace.

Retirement and collection

Retirement is a database transition from ACTIVE to RETIRED. It prevents new
product use without performing network I/O inside the caller's transaction.
Product lifecycle paths commit this transition synchronously. After the
transaction commits, one Celery task asks Dify Agent to destroy the physical
resources. A successful collector deletes the corresponding ledger row. If a
collector raises, the task logs the tenant, resource type, and resource ID and
continues with the other independent resources in the batch. After all resources
have been attempted, any failure makes the Celery task fail and prevents Agent
aggregate deletion. Failed RETIRED rows remain available for a later retry. A
failure to publish the Celery task is also propagated to the product caller. No
automatic retry or reconciliation is performed.

The unified collect_agent_resources task is registered on normal Celery
workers and explicitly uses the existing retention queue. Standard workers
already consume that queue, so no dedicated Agent resource worker or new queue
is required. At a Workflow terminal event, the graph layer synchronously retires
and commits the run's Workspaces before enqueueing collection. When a Workflow
change may orphan Workflow-only Agents, the main product transaction commits
first; a fresh session then rechecks effective ownership and retires only Agents
that remain unowned. An effective reference is a binding in a normal App's
current draft or current published Workflow. This ownership check applies only
to implicit retirement of Workflow-only Agents. Explicit deletion of a roster
Agent or Agent App proceeds even while Workflows reference it.

Retiring a final Binding also retires its Workspace. Workspace collection
destroys the physical Workspace through one Binding and then collects remaining
materialized Homes. Home Snapshots are retired when their owning Agent is
retired. RETIRED is the sole physical-deletion condition for a Home Snapshot;
Draft and Config Snapshot references are historical pointers and do not keep it
alive. After every external resource in a deletion batch succeeds, Dify API
hard-deletes the archived Agent together with its Drafts, Config Snapshots,
Config Revisions, debug-conversation mappings, and resource ledgers in one
database transaction. Workflow Agent bindings belong to
their Workflows and remain unchanged, so they may hold a dangling Agent ID after
explicit deletion. Dify Agent itself remains stateless.

A RETIRED Workspace without a RETIRED Binding cannot identify a backend
participant through which to destroy the Workspace. That state is a lifecycle
invariant violation and fails collection instead of being logged as success.

There is currently no age-based TTL, periodic GC, or global orphan reconciler.
Backend destroy operations are idempotent where supported. Dify API does not
perform cross-system compensation after a backend create returns success. Any
later API failure, including Python, flush, or commit failure, may leave a
physical orphan for a future global reconciler.

Backends still clean up partial resources when a create operation fails before
returning success. For example, E2B kills a Sandbox when its initialization
fails, and Local removes paths created by an incomplete operation. This
backend-local cleanup does not cross the database commit boundary.

Binding file boundary

Dify API's public file APIs accept a product locator, not a Binding id or
backend ref: a Conversation, a debug Build Draft, or a Workflow Node Execution.
Dify API authorizes that object and resolves its associated active Binding. It
does not select the latest Binding or fall back to another product context.

The resolved request reaches Dify Agent through its private
POST /execution-bindings/files/list, POST /execution-bindings/files/read,
and POST /execution-bindings/files/download endpoints. Each operation receives a
backend_binding_ref, acquires a fresh RuntimeLease, performs the file action,
and releases the lease.

BindingFileService resolves relative paths from workspace_dir, ~ and
~/... from home_dir, and leaves absolute paths in the Binding filesystem
namespace. It does not enforce Workspace containment or reject ..; the
selected backend's isolation policy remains authoritative. List and preview
run bounded inspection scripts through RuntimeLease.commands. Download runs
dify-agent file upload --no-download-link inside the Binding so bytes stream
directly from the runtime to Dify's existing ToolFile endpoint. Dify Agent
returns only the canonical ToolFile reference and releases the lease before
Dify API signs a browser URL.

The default Binding-download deadline chain leaves each caller time to receive
and normalize the lower layer's result: the sandbox CLI upload is 180 seconds,
DIFY_AGENT_BINDING_FILE_DOWNLOAD_COMMAND_TIMEOUT_SECONDS is 210 seconds,
Dify API's AGENT_BACKEND_BINDING_FILE_DOWNLOAD_TIMEOUT_SECONDS is 240 seconds,
and DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS is 3600 seconds.

RuntimeLayout.home_dir and RuntimeLayout.workspace_dir are canonical paths
inside the backend execution namespace. They are not host paths, product ids,
or request configuration. Shell commands start in workspace_dir, and HOME
is forced to home_dir. The standard temp variables TMPDIR, TMP, and TEMP
also point directly to workspace_dir, so the Workspace is both the command
cwd and temp space. On Local, sibling materialized Homes may exist in the same
shellctl namespace, while path isolation restricts the active lease to its own
Home plus the shared Workspace.

Backend support

Backend Home Snapshot operations Binding operations Physical relationship
Local Supported Supported, including default empty Homes and attaching multiple Bindings to one Workspace Snapshot directory, per-Binding materialized Home, and Workspace directory are separate.
E2B Supported Supported with template-backed default Homes, without shared-Workspace attachment Binding and Workspace refs map to the same E2B resource; checkpoints use E2B snapshots.
Enterprise Not implemented Default-Home Binding creation, acquire, and coupled destroy are supported Binding and Workspace refs map to one Gateway sandbox. Explicit Home Snapshot materialization fails fast.
OpenShell Supported via directory copies on an operator-provided shared volume Supported with image-backed default Homes, without shared-Workspace attachment Binding and Workspace refs map to the same OpenShell sandbox, addressed by its stable name; snapshots live under home-snapshots/<tenant-digest>/ on the shared volume. Production deployments must use one workspace and one dedicated volume per tenant.

Local creates a new Home for every Binding id. Destroying one Binding without
the Workspace leaves sibling Homes and the shared Workspace intact. Current E2B
rejects existing_workspace_ref with shared_workspace_unsupported, because
its Binding and Workspace are one Sandbox. It also rejects binding-only destroy.
OpenShell shares the E2B shape: one sandbox per Binding, no
existing_workspace_ref, no binding-only destroy. Neither path creates a
fallback Workspace or switches backends.

DIFY_AGENT_E2B_ACTIVE_TIMEOUT_SECONDS limits continuous active time for an E2B
resource to one hour. The limit covers the complete Agent run held by one
RuntimeLease rather than an individual tool call. Its 3600-second default is
intentionally the same as DIFY_AGENT_RUN_TIMEOUT_SECONDS, but the two settings
remain independently configurable. Runtime resources pause on timeout, but this
resource setting does not own the Agent run terminal state. It is not a retention
TTL and does not delete paused resources or immutable snapshots.

See the Shell module for request
composition, the Operations Guide for Local and E2B
validation, and the OpenShell guide for OpenShell
configuration and validation.


Dify Agent Docs Dify Agent User Manual Execution Context Layer Index (`dify-agent/docs/dify-agent/user-manual/execution-context-layer/index.md`)

Execution context module

dify_agent.layers.execution_context.layer declares Config, empty State and
Capability. Config carries tenant/user/app/invoke identity and correlation IDs.
Other modules refer to its registered name in their Config. Server-only daemon
settings and clients are borrowed from Deps.services. Knowledge retrieval
requires its complete caller identity before any external request.


Dify Agent Docs Dify Agent User Manual History Layer Index (`dify-agent/docs/dify-agent/user-manual/history-layer/index.md`)

History module

dify_agent.layers.history declares Config, State and Capability. Config is
empty. State contains messages, encoded as JSON using Pydantic AI message
schemas. The runner explicitly loads initial message_history and writes the
captured history on every terminal outcome, preserving compaction and partial
responses. Current instructions are removed and unmatched trailing calls are
marked interrupted on failure or cancellation. The reserved name is history.


Dify Agent Docs Dify Agent User Manual Plugin Llm Layer Index (`dify-agent/docs/dify-agent/user-manual/plugin-llm-layer/index.md`)

Model module

dify_agent.layers.dify_plugin.llm_layer declares Config, State and Capability.
The reserved llm name selects model assembly. Public Config contains plugin,
provider, model, model settings, context window and an execution_context name.
The runtime builds a model through the Dify API metered gateway with borrowed
lifespan HTTP services. Credentials stay API-owned; no model/client is persisted.


Dify Agent Docs Dify Agent User Manual Plugin Tool Layer Index (`dify-agent/docs/dify-agent/user-manual/plugin-tool-layer/index.md`)

Plugin tool module

dify_agent.layers.dify_plugin.tools_layer declares Config, State and native
Toolset. The tools registry name accepts API-prepared declarations, parameters,
runtime values and model-facing schema, plus execution_context and optional
shell Config references. Hidden/default parameter merging, loose schemas and
observation mapping preserve the API-prepared contract. Sandbox paths use the
referenced live shell session to upload files; file mappings resolve signed URLs
through the borrowed Dify API client. Config and credentials are never snapshotted.

Each prepared tool includes plugin_unique_identifier (version and checksum)
alongside plugin_id. The daemon receives it as X-Plugin-Unique-Identifier
and executes that exact plugin package, even if the installed version changes
during the run. Tool clients are shared only within the same complete identifier.
Older configurations can omit the identifier and retain plugin-ID dispatch.


Dify Agent Docs Dify Agent User Manual Prompt Layer Index (`dify-agent/docs/dify-agent/user-manual/prompt-layer/index.md`)

Prompt module

dify_agent.layers.prompt declares Config, State and native Toolset. Config
accepts prefix, suffix and user string fragments or lists. Prefix/suffix
become dynamic instructions; user contributes current user content. State is
empty. Instruction order is unspecified. Product names agent_soul_prompt,
workflow_node_job_prompt, and workflow_user_prompt map to this module.


Dify Agent Docs Dify Agent User Manual Shell Layer Index (`dify-agent/docs/dify-agent/user-manual/shell-layer/index.md`)

Shell module

dify_agent.layers.shell.layer declares Config, State and Capability. Config
contains CLI tools, environment values, secret names, redaction patterns and
runtime / optional execution_context references. Native ordering ensures an
active lease exists before shell bootstrap and config eager pulls.

The Capability exposes shell_run, shell_wait, shell_input and shell_interrupt
through a native sequential Toolset. JSON State holds initialized, job_ids and
job_offsets; live tokens remain in the run-scoped ShellSession. Bootstrap marks
initialized only on success. Exit cleanup removes tracked jobs and clears IDs,
offsets and credentials before Runtime releases the lease, including cancellation.
The API owns Workspace/Binding retirement. HOME is reusable system space; cwd
and TMPDIR/TMP/TEMP refer to the active Workspace.


Dify Agent Docs Dify Agent User Manual Structured Output Layer Index (`dify-agent/docs/dify-agent/user-manual/structured-output-layer/index.md`)

Structured output module

dify_agent.layers.output.output_layer declares Config, empty State and
Capability. The reserved output name accepts a top-level object JSON Schema,
optional description and strictness. The runner resolves native output_type
before running the agent. A fresh dynamic type exposes the schema and performs
JSON Schema validation in Pydantic AI's retry pipeline. The model-facing tool
name is final_output. Local #/$defs/ references are supported; remote or
recursive references are rejected before I/O. Resume resubmits current Config.


ADVANCED SETUP (`docs/ADVANCED_SETUP.md`)

Advanced Setup

Custom configurations

If you need to customize the configuration, edit docker/.env. The essential startup defaults live in docker/.env.example, and optional advanced variables are split under docker/envs/ by theme. After making any changes, re-run docker compose up -d from the docker directory. You can find the full list of available environment variables here.

Metrics Monitoring with Grafana

Import the dashboard to Grafana, using Dify's PostgreSQL database as data source, to monitor metrics in granularity of apps, tenants, messages, and more.

Deployment with Kubernetes

If you'd like to configure a highly available setup, there are community-contributed Helm Charts and YAML files which allow Dify to be deployed on Kubernetes.

Using Terraform for Deployment

Deploy Dify to Cloud Platform with a single click using terraform

Azure Global

Google Cloud

Using AWS CDK for Deployment

Deploy Dify to AWS with CDK

AWS

Using Alibaba Cloud Computing Nest

Quickly deploy Dify to Alibaba cloud with Alibaba Cloud Computing Nest

Using Alibaba Cloud Data Management

One-Click deploy Dify to Alibaba Cloud with Alibaba Cloud Data Management

Deploy to AKS with Azure Devops Pipeline

One-Click deploy Dify to AKS with Azure Devops Pipeline Helm Chart by @LeoZhang

Using Sealos for Deployment

Deploy Dify with one click using the Sealos App Store


Ar SA ADVANCED SETUP (`docs/ar-SA/ADVANCED_SETUP.md`)

الإعداد المتقدم

اضبط الإعدادات المحلية في docker/.env. يحتوي .env.example على القيم اللازمة للنشر الافتراضي فقط، وتوجد الإعدادات الاختيارية والخاصة بالخدمات في docker/envs/. انسخ القوالب المطلوبة دون اللاحقة .example. تكون الأولوية لقيم .env. بعد التعديل، شغّل docker compose up -d من docker/. راجع دليل Docker.

مراقبة المقاييس باستخدام Grafana

استيراد لوحة التحكم إلى Grafana، باستخدام قاعدة بيانات PostgreSQL الخاصة بـ Dify كمصدر للبيانات، لمراقبة المقاييس بدقة للتطبيقات والمستأجرين والرسائل وغير ذلك.

النشر باستخدام Kubernetes

يوجد مجتمع خاص بـ Helm Charts وملفات YAML التي تسمح بتنفيذ Dify على Kubernetes للنظام من الإيجابيات العلوية.

استخدام Terraform للتوزيع

انشر Dify إلى منصة السحابة بنقرة واحدة باستخدام terraform

Azure Global

Google Cloud

استخدام AWS CDK للنشر

انشر Dify على AWS باستخدام CDK

AWS

استخدام Alibaba Cloud للنشر

بسرعة نشر Dify إلى سحابة علي بابا مع عش الحوسبة السحابية علي بابا

استخدام Alibaba Cloud Data Management للنشر

انشر ​​Dify على علي بابا كلاود بنقرة واحدة باستخدام Alibaba Cloud Data Management

استخدام Azure Devops Pipeline للنشر على AKS

انشر Dify على AKS بنقرة واحدة باستخدام Azure Devops Pipeline Helm Chart by @LeoZhang

استخدام Sealos للنشر

انشر Dify بنقرة واحدة باستخدام Sealos App Store


Bn BD ADVANCED SETUP (`docs/bn-BD/ADVANCED_SETUP.md`)

উন্নত সেটআপ

স্থানীয় সেটিংস docker/.env-এ পরিবর্তন করুন। .env.example-এ ডিফল্ট ডেপ্লয়মেন্টের প্রয়োজনীয় মান থাকে; ঐচ্ছিক ও পরিষেবা-নির্দিষ্ট সেটিংস docker/envs/-এ রয়েছে। প্রয়োজনীয় টেমপ্লেটের .example প্রত্যয় বাদ দিয়ে কপি করুন। .env-এর মান অগ্রাধিকার পায়। পরিবর্তনের পরে docker/ থেকে docker compose up -d চালান। Docker নির্দেশিকা দেখুন।

Grafana দিয়ে মেট্রিক্স মনিটরিং

Dify-এর PostgreSQL ডাটাবেসকে ডেটা সোর্স হিসাবে ব্যবহার করে, অ্যাপ, টেন্যান্ট, মেসেজ ইত্যাদির গ্র্যানুলারিটিতে মেট্রিক্স মনিটর করার জন্য Grafana-তে ড্যাশবোর্ড ইম্পোর্ট করুন।

Kubernetes এর সাথে ডেপ্লয়মেন্ট

যদি আপনি একটি হাইলি এভেইলেবল সেটআপ কনফিগার করতে চান, তাহলে কমিউনিটি Helm Charts এবং YAML ফাইল রয়েছে যা Dify কে Kubernetes-এ ডিপ্লয় করার প্রক্রিয়া বর্ণনা করে।

টেরাফর্ম ব্যবহার করে ডিপ্লয়

terraform ব্যবহার করে এক ক্লিকেই ক্লাউড প্ল্যাটফর্মে Dify ডিপ্লয় করুন।

অ্যাজুর গ্লোবাল

গুগল ক্লাউড

AWS CDK ব্যবহার করে ডিপ্লয়

CDK দিয়ে AWS-এ Dify ডিপ্লয় করুন

AWS

Alibaba Cloud ব্যবহার করে ডিপ্লয়

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management ব্যবহার করে ডিপ্লয়

Alibaba Cloud Data Management

AKS-এ ডিপ্লয় করার জন্য Azure Devops Pipeline ব্যবহার

Azure Devops Pipeline Helm Chart by @LeoZhang ব্যবহার করে Dify কে AKS-এ এক ক্লিকে ডিপ্লয় করুন

Sealos ব্যবহার করে ডিপ্লয়

Sealos App Store ব্যবহার করে Dify-কে এক ক্লিকে ডিপ্লয় করুন


De DE ADVANCED SETUP (`docs/de-DE/ADVANCED_SETUP.md`)

Erweiterte Einstellungen

Konfigurieren Sie Ihre Installation in docker/.env. .env.example enthält die nötigen Startwerte für die Standardbereitstellung; optionale und dienstspezifische Einstellungen liegen unter docker/envs/. Kopieren Sie benötigte Vorlagen ohne die Endung .example. Werte aus .env haben Vorrang. Führen Sie nach Änderungen docker compose up -d in docker/ aus. Siehe Docker-Anleitung.

Metriküberwachung mit Grafana

Importieren Sie das Dashboard in Grafana, wobei Sie die PostgreSQL-Datenbank von Dify als Datenquelle verwenden, um Metriken in der Granularität von Apps, Mandanten, Nachrichten und mehr zu überwachen.

Bereitstellung mit Kubernetes

Falls Sie eine hochverfügbare Konfiguration einrichten möchten, gibt es von der Community bereitgestellte Helm Charts und YAML-Dateien, die es ermöglichen, Dify auf Kubernetes bereitzustellen.

Terraform für die Bereitstellung verwenden

Stellen Sie Dify mit nur einem Klick mithilfe von terraform auf einer Cloud-Plattform bereit.

Azure Global

Google Cloud

Verwendung von AWS CDK für die Bereitstellung

Bereitstellung von Dify auf AWS mit CDK

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Ein-Klick-Bereitstellung von Dify in der Alibaba Cloud mit Alibaba Cloud Data Management

Verwendung von Azure Devops Pipeline für AKS-Bereitstellung

Stellen Sie Dify mit einem Klick in AKS bereit, indem Sie Azure Devops Pipeline Helm Chart by @LeoZhang verwenden

Bereitstellung mit Sealos

Stellen Sie Dify mit einem Klick über den Sealos App Store bereit


De DE CONTRIBUTING (`docs/de-DE/CONTRIBUTING.md`)

MITWIRKEN

Sie möchten also zu Dify beitragen - das ist großartig, wir können es kaum erwarten zu sehen, was Sie entwickeln. Als Startup mit begrenztem Personal und Finanzierung haben wir große Ambitionen, den intuitivsten Workflow für die Entwicklung und Verwaltung von LLM-Anwendungen zu gestalten. Jede Hilfe aus der Community zählt wirklich.

Wir müssen wendig sein und schnell liefern, aber wir möchten auch sicherstellen, dass Mitwirkende wie Sie eine möglichst reibungslose Erfahrung beim Beitragen haben. Wir haben diesen Leitfaden zusammengestellt, damit Sie sich schnell mit der Codebasis und unserer Arbeitsweise mit Mitwirkenden vertraut machen können.

Dieser Leitfaden ist, wie Dify selbst, in ständiger Entwicklung. Wir sind dankbar für Ihr Verständnis, falls er manchmal hinter dem eigentlichen Projekt zurückbleibt, und begrüßen jedes Feedback zur Verbesserung.

Bitte nehmen Sie sich einen Moment Zeit, um unsere Lizenz- und Mitwirkungsvereinbarung zu lesen. Die Community hält sich außerdem an den Verhaltenskodex.

Bevor Sie loslegen

Suchen Sie nach einer Aufgabe? Durchstöbern Sie unsere Einsteiger-Issues und wählen Sie eines zum Einstieg!

Haben Sie eine neue Modell-Runtime oder ein Tool hinzuzufügen? Öffnen Sie einen PR in unserem Plugin-Repository.

Möchten Sie eine bestehende Modell-Runtime oder ein Tool aktualisieren oder Bugs beheben? Besuchen Sie unser offizielles Plugin-Repository!

Vergessen Sie nicht, in der PR-Beschreibung ein bestehendes Issue zu verlinken oder ein neues zu erstellen.

Fehlermeldungen

Melden Sie Sicherheitslücken gemäß der Sicherheitsrichtlinie vertraulich, statt ein öffentliches Issue zu erstellen.

[!WICHTIG]
Bitte stellen Sie sicher, dass Sie folgende Informationen bei der Einreichung eines Fehlerberichts angeben:

  • Ein klarer und beschreibender Titel
  • Eine detaillierte Beschreibung des Fehlers, einschließlich Fehlermeldungen
  • Schritte zur Reproduktion des Fehlers
  • Erwartetes Verhalten
  • Logs bei Backend-Problemen (sehr wichtig, zu finden in docker-compose logs)
  • Screenshots oder Videos, falls zutreffend

Unsere Priorisierung:

Fehlertyp Priorität
Fehler in Kernfunktionen (Cloud-Service, Login nicht möglich, Anwendungen funktionieren nicht) Kritisch
Nicht-kritische Fehler, Leistungsverbesserungen Mittlere Priorität
Kleinere Korrekturen (Tippfehler, verwirrende aber funktionierende UI) Niedrige Priorität

Feature-Anfragen

[!HINWEIS]
Bitte stellen Sie sicher, dass Sie folgende Informationen bei der Einreichung einer Feature-Anfrage angeben:

  • Ein klarer und beschreibender Titel
  • Eine detaillierte Beschreibung des Features
  • Ein Anwendungsfall für das Feature
  • Zusätzlicher Kontext oder Screenshots zur Feature-Anfrage

Unsere Priorisierung:

Feature-Typ Priorität
Hochprioritäre Features (durch Teammitglied gekennzeichnet) Hohe Priorität
Beliebte Feature-Anfragen aus unserem Community-Feedback-Board Mittlere Priorität
Nicht-Kernfunktionen und kleinere Verbesserungen Niedrige Priorität
Wertvoll, aber nicht dringend Zukunfts-Feature

Einreichen Ihres PRs

Pull-Request-Prozess

  1. Repository forken
  2. Vor dem Erstellen eines PRs bitte ein Issue zur Diskussion der Änderungen erstellen
  3. Einen neuen Branch für Ihre Änderungen erstellen
  4. Tests ergänzen oder aktualisieren, wenn die Änderung beobachtbares Verhalten beeinflusst oder ein relevantes Regressionsrisiko birgt.
  5. Sicherstellen, dass Ihr Code die bestehenden Tests besteht
  6. Issue in der PR-Beschreibung verlinken (fixes #)
  7. Auf den Merge warten!

Projekt einrichten

Frontend

Für die Einrichtung des Frontend-Service folgen Sie bitte unserer ausführlichen Anleitung in der Datei web/README.md.

Backend

Für die Einrichtung des Backend-Service folgen Sie bitte unseren detaillierten Anweisungen in der Datei api/README.md.

Hilfe bekommen

Wenn Sie beim Mitwirken Fragen haben oder nicht weiterkommen, stellen Sie Ihre Fragen einfach im entsprechenden GitHub Issue oder besuchen Sie unseren Discord für einen schnellen Austausch.


Es ES ADVANCED SETUP (`docs/es-ES/ADVANCED_SETUP.md`)

Configuración avanzada

Configura la instalación en docker/.env. .env.example contiene los valores necesarios para el despliegue predeterminado; las opciones avanzadas y específicas de cada servicio están en docker/envs/. Copia las plantillas necesarias sin el sufijo .example. Los valores de .env tienen prioridad. Tras los cambios, ejecuta docker compose up -d desde docker/. Consulta la guía de Docker.

Monitorización de Métricas con Grafana

Importe el panel a Grafana, utilizando la base de datos PostgreSQL de Dify como fuente de datos, para monitorizar métricas en granularidad de aplicaciones, inquilinos, mensajes y más.

Implementación con Kubernetes

Si desea configurar una configuración de alta disponibilidad, la comunidad proporciona Gráficos Helm y archivos YAML, a través de los cuales puede desplegar Dify en Kubernetes.

Uso de Terraform para el despliegue

Despliega Dify en una plataforma en la nube con un solo clic utilizando terraform

Azure Global

Google Cloud

Usando AWS CDK para el Despliegue

Despliegue Dify en AWS usando CDK

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Despliega Dify en Alibaba Cloud con un solo clic con Alibaba Cloud Data Management

Uso de Azure Devops Pipeline para implementar en AKS

Implementa Dify en AKS con un clic usando Azure Devops Pipeline Helm Chart by @LeoZhang

Implementación con Sealos

Despliega Dify con un solo clic desde Sealos App Store


Es ES CONTRIBUTING (`docs/es-ES/CONTRIBUTING.md`)

CONTRIBUIR

Así que estás buscando contribuir a Dify - eso es fantástico, estamos ansiosos por ver lo que haces. Como una startup con personal y financiación limitados, tenemos grandes ambiciones de diseñar el flujo de trabajo más intuitivo para construir y gestionar aplicaciones LLM. Cualquier ayuda de la comunidad cuenta, realmente.

Necesitamos ser ágiles y enviar rápidamente dado donde estamos, pero también queremos asegurarnos de que colaboradores como tú obtengan una experiencia lo más fluida posible al contribuir. Hemos elaborado esta guía de contribución con ese propósito, con el objetivo de familiarizarte con la base de código y cómo trabajamos con los colaboradores, para que puedas pasar rápidamente a la parte divertida.

Esta guía, como Dify mismo, es un trabajo en constante progreso. Agradecemos mucho tu comprensión si a veces se queda atrás del proyecto real, y damos la bienvenida a cualquier comentario para que podamos mejorar.

En términos de licencia, por favor tómate un minuto para leer nuestro breve Acuerdo de Licencia y Colaborador. La comunidad también se adhiere al código de conducta.

Antes de empezar

¿Buscas algo en lo que trabajar? Explora nuestros buenos primeros issues y elige uno para comenzar.

¿Tienes un nuevo modelo o herramienta genial para añadir? Abre un PR en nuestro repositorio de plugins y muéstranos lo que has construido.

¿Necesitas actualizar un modelo existente, herramienta o corregir algunos errores? Dirígete a nuestro repositorio oficial de plugins y haz tu magia.

¡Únete a la diversión, contribuye y construyamos algo increíble juntos! 💡✨

No olvides vincular un issue existente o abrir uno nuevo en la descripción del PR.

Informes de errores

Informa de las vulnerabilidades en privado según la política de seguridad, sin abrir un issue público.

[!IMPORTANT]
Por favor, asegúrate de incluir la siguiente información al enviar un informe de error:

  • Un título claro y descriptivo
  • Una descripción detallada del error, incluyendo cualquier mensaje de error
  • Pasos para reproducir el error
  • Comportamiento esperado
  • Logs, si están disponibles, para problemas del backend, esto es realmente importante, puedes encontrarlos en los logs de docker-compose
  • Capturas de pantalla o videos, si es aplicable

Cómo priorizamos:

Tipo de Issue Prioridad
Errores en funciones principales (servicio en la nube, no poder iniciar sesión, aplicaciones que no funcionan) Crítica
Errores no críticos, mejoras de rendimiento Prioridad Media
Correcciones menores (errores tipográficos, UI confusa pero funcional) Prioridad Baja

Solicitudes de funcionalidades

[!NOTE]
Por favor, asegúrate de incluir la siguiente información al enviar una solicitud de funcionalidad:

  • Un título claro y descriptivo
  • Una descripción detallada de la funcionalidad
  • Un caso de uso para la funcionalidad
  • Cualquier otro contexto o capturas de pantalla sobre la solicitud de funcionalidad

Cómo priorizamos:

Tipo de Funcionalidad Prioridad
Funcionalidades de alta prioridad etiquetadas por un miembro del equipo Prioridad Alta
Solicitudes populares de funcionalidades de nuestro tablero de comentarios de la comunidad Prioridad Media
Funcionalidades no principales y mejoras menores Prioridad Baja
Valiosas pero no inmediatas Futura-Funcionalidad

Enviando tu PR

Proceso de Pull Request

  1. Haz un fork del repositorio
  2. Antes de redactar un PR, por favor crea un issue para discutir los cambios que quieres hacer
  3. Crea una nueva rama para tus cambios
  4. Añade o actualiza pruebas cuando el cambio afecte al comportamiento observable o implique un riesgo significativo de regresión.
  5. Asegúrate de que tu código pasa las pruebas existentes
  6. Por favor vincula el issue en la descripción del PR, fixes #<número_del_issue>
  7. ¡Fusiona tu código!

Configuración del proyecto

Frontend

Para configurar el servicio frontend, por favor consulta nuestra guía completa en el archivo web/README.md. Este documento proporciona instrucciones detalladas para ayudarte a configurar el entorno frontend correctamente.

Backend

Para configurar el servicio backend, por favor consulta nuestras instrucciones detalladas en el archivo api/README.md. Este documento contiene una guía paso a paso para ayudarte a poner en marcha el backend sin problemas.

Obteniendo Ayuda

Si alguna vez te quedas atascado o tienes una pregunta urgente mientras contribuyes, simplemente envíanos tus consultas a través del issue relacionado de GitHub, o únete a nuestro Discord para una charla rápida.


Fr FR ADVANCED SETUP (`docs/fr-FR/ADVANCED_SETUP.md`)

Configuration avancée

Configurez votre installation dans docker/.env. .env.example contient les paramètres nécessaires au déploiement par défaut ; les options avancées et propres aux services sont dans docker/envs/. Copiez les modèles nécessaires sans le suffixe .example. Les valeurs de .env sont prioritaires. Après modification, exécutez docker compose up -d depuis docker/. Consultez le guide Docker.

Surveillance des Métriques avec Grafana

Importez le tableau de bord dans Grafana, en utilisant la base de données PostgreSQL de Dify comme source de données, pour surveiller les métriques avec une granularité d'applications, de locataires, de messages et plus.

Déploiement avec Kubernetes

Si vous souhaitez configurer une configuration haute disponibilité, la communauté fournit des Helm Charts et des fichiers YAML, à travers lesquels vous pouvez déployer Dify sur Kubernetes.

Utilisation de Terraform pour le déploiement

Déployez Dify sur une plateforme cloud en un clic en utilisant terraform

Azure Global

Google Cloud

Utilisation d'AWS CDK pour le déploiement

Déployez Dify sur AWS en utilisant CDK

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Déployez Dify en un clic sur Alibaba Cloud avec Alibaba Cloud Data Management

Utilisation d'Azure Devops Pipeline pour déployer sur AKS

Déployez Dify sur AKS en un clic en utilisant Azure Devops Pipeline Helm Chart by @LeoZhang

Déploiement avec Sealos

Déployez Dify en un clic depuis le Sealos App Store


Fr FR CONTRIBUTING (`docs/fr-FR/CONTRIBUTING.md`)

CONTRIBUER

Vous cherchez donc à contribuer à Dify - c'est fantastique, nous avons hâte de voir ce que vous allez faire. En tant que startup avec un personnel et un financement limités, nous avons de grandes ambitions pour concevoir le flux de travail le plus intuitif pour construire et gérer des applications LLM. Toute aide de la communauté compte, vraiment.

Nous devons être agiles et livrer rapidement compte tenu de notre position, mais nous voulons aussi nous assurer que des contributeurs comme vous obtiennent une expérience aussi fluide que possible lors de leur contribution. Nous avons élaboré ce guide de contribution dans ce but, visant à vous familiariser avec la base de code et comment nous travaillons avec les contributeurs, afin que vous puissiez rapidement passer à la partie amusante.

Ce guide, comme Dify lui-même, est un travail en constante évolution. Nous apprécions grandement votre compréhension si parfois il est en retard par rapport au projet réel, et nous accueillons tout commentaire pour nous aider à nous améliorer.

En termes de licence, veuillez prendre une minute pour lire notre bref Accord de Licence et de Contributeur. La communauté adhère également au code de conduite.

Avant de vous lancer

Vous cherchez quelque chose à réaliser ? Parcourez nos problèmes pour débutants et choisissez-en un pour commencer !

Vous avez un nouveau modèle ou un nouvel outil à ajouter ? Ouvrez une PR dans notre dépôt de plugins et montrez-nous ce que vous avez créé.

Vous devez mettre à jour un modèle existant, un outil ou corriger des bugs ? Rendez-vous sur notre dépôt officiel de plugins et faites votre magie !

Rejoignez l'aventure, contribuez, et construisons ensemble quelque chose d'extraordinaire ! 💡✨

N'oubliez pas de lier un problème existant ou d'ouvrir un nouveau problème dans la description de votre PR.

Rapports de bugs

Signalez les vulnérabilités en privé selon la politique de sécurité, sans ouvrir d’issue publique.

[!IMPORTANT]
Veuillez vous assurer d'inclure les informations suivantes lors de la soumission d'un rapport de bug :

  • Un titre clair et descriptif
  • Une description détaillée du bug, y compris tous les messages d'erreur
  • Les étapes pour reproduire le bug
  • Comportement attendu
  • Logs, si disponibles, pour les problèmes de backend, c'est vraiment important, vous pouvez les trouver dans les logs de docker-compose
  • Captures d'écran ou vidéos, si applicable

Comment nous priorisons :

Type de Problème Priorité
Bugs dans les fonctions principales (service cloud, impossibilité de se connecter, applications qui ne fonctionnent pas) Critique
Bugs non critiques, améliorations de performance Priorité Moyenne
Corrections mineures (fautes de frappe, UI confuse mais fonctionnelle) Priorité Basse

Demandes de fonctionnalités

[!NOTE]
Veuillez vous assurer d'inclure les informations suivantes lors de la soumission d'une demande de fonctionnalité :

  • Un titre clair et descriptif
  • Une description détaillée de la fonctionnalité
  • Un cas d'utilisation pour la fonctionnalité
  • Tout autre contexte ou captures d'écran concernant la demande de fonctionnalité

Comment nous priorisons :

Type de Fonctionnalité Priorité
Fonctionnalités hautement prioritaires étiquetées par un membre de l'équipe Priorité Haute
Demandes populaires de fonctionnalités de notre tableau de feedback communautaire Priorité Moyenne
Fonctionnalités non essentielles et améliorations mineures Priorité Basse
Précieuses mais non immédiates Fonctionnalité Future

Soumettre votre PR

Processus de Pull Request

  1. Forkez le dépôt
  2. Avant de rédiger une PR, veuillez créer un problème pour discuter des changements que vous souhaitez apporter
  3. Créez une nouvelle branche pour vos changements
  4. Ajoutez ou mettez à jour les tests si le changement affecte un comportement observable ou présente un risque significatif de régression.
  5. Assurez-vous que votre code passe les tests existants
  6. Veuillez lier le problème dans la description de la PR, fixes #<numéro_du_problème>
  7. Faites fusionner votre code !

Configuration du projet

Frontend

Pour configurer le service frontend, veuillez consulter notre guide complet dans le fichier web/README.md. Ce document fournit des instructions détaillées pour vous aider à configurer correctement l'environnement frontend.

Backend

Pour configurer le service backend, veuillez consulter nos instructions détaillées dans le fichier api/README.md. Ce document contient un guide étape par étape pour vous aider à faire fonctionner le backend sans problème.

Obtenir de l'aide

Si jamais vous êtes bloqué ou avez une question urgente en contribuant, envoyez-nous simplement vos questions via le problème GitHub concerné, ou rejoignez notre Discord pour une discussion rapide.


Hi IN ADVANCED SETUP (`docs/hi-IN/ADVANCED_SETUP.md`)

उन्नत सेटअप

कस्टम कॉन्फ़िगरेशन

स्थानीय सेटिंग्स docker/.env में बदलें। .env.example में डिफ़ॉल्ट परिनियोजन के लिए आवश्यक मान हैं; वैकल्पिक और सेवा-विशिष्ट सेटिंग्स docker/envs/ में हैं। ज़रूरी टेम्पलेट को .example प्रत्यय हटाकर कॉपी करें। .env के मान प्राथमिकता लेते हैं। बदलाव के बाद docker/ से docker compose up -d चलाएँ। Docker गाइड देखें।

Grafana के साथ मेट्रिक्स मॉनिटरिंग

Grafana में Dify के PostgreSQL डेटाबेस को डेटा स्रोत के रूप में उपयोग करते हुए डैशबोर्ड आयात करें, ताकि आप ऐप्स, टेनेंट्स, संदेशों आदि के स्तर पर मेट्रिक्स की निगरानी कर सकें।

Kubernetes के साथ डिप्लॉयमेंट

यदि आप उच्च उपलब्धता (high-availability) सेटअप कॉन्फ़िगर करना चाहते हैं, तो समुदाय द्वारा योगदान किए गए Helm Charts और YAML फ़ाइलें उपलब्ध हैं जो Dify को Kubernetes पर डिप्लॉय करने की अनुमति देती हैं।

डिप्लॉयमेंट के लिए Terraform का उपयोग

terraform का उपयोग करके एक क्लिक में Dify को क्लाउड प्लेटफ़ॉर्म पर डिप्लॉय करें।

Azure Global

Google Cloud

डिप्लॉयमेंट के लिए AWS CDK का उपयोग

CDK का उपयोग करके Dify को AWS पर डिप्लॉय करें।

AWS

Alibaba Cloud Computing Nest का उपयोग

Alibaba Cloud Computing Nest के साथ Dify को Alibaba Cloud पर तेज़ी से डिप्लॉय करें।

Alibaba Cloud Data Management का उपयोग

Alibaba Cloud Data Management के साथ एक क्लिक में Dify को Alibaba Cloud पर डिप्लॉय करें।

Azure Devops Pipeline के साथ AKS पर डिप्लॉय करें

Azure Devops Pipeline Helm Chart by @LeoZhang के साथ एक क्लिक में Dify को AKS पर डिप्लॉय करें।

Sealos के साथ डिप्लॉय करें

Sealos App Store के साथ एक क्लिक में Dify को डिप्लॉय करें।


Hi IN CONTRIBUTING (`docs/hi-IN/CONTRIBUTING.md`)

योगदान (CONTRIBUTING)

तो आप Dify में योगदान देना चाहते हैं — यह शानदार है, हम उत्सुक हैं यह देखने के लिए कि आप क्या बनाते हैं। सीमित टीम और फंडिंग वाले एक स्टार्टअप के रूप में, हमारा बड़ा लक्ष्य LLM एप्लिकेशनों के निर्माण और प्रबंधन के लिए सबसे सहज वर्कफ़्लो डिज़ाइन करना है। समुदाय से मिलने वाली कोई भी मदद वास्तव में मायने रखती है।

हमारे वर्तमान चरण को देखते हुए हमें तेज़ी से काम करना और डिलीवर करना होता है, लेकिन हम यह भी सुनिश्चित करना चाहते हैं कि आपके जैसे योगदानकर्ताओं के लिए योगदान देने का अनुभव यथासंभव सरल और सुगम हो।
इसी उद्देश्य से हमने यह योगदान गाइड तैयार किया है, ताकि आप कोडबेस से परिचित हो सकें और जान सकें कि हम योगदानकर्ताओं के साथ कैसे काम करते हैं — ताकि आप जल्दी से मज़ेदार हिस्से पर पहुँच सकें।

यह गाइड, Dify की तरह ही, एक निरंतर विकसित होता दस्तावेज़ है। यदि यह कभी-कभी वास्तविक प्रोजेक्ट से पीछे रह जाए तो हम आपके समझ के लिए आभारी हैं, और सुधार के लिए किसी भी सुझाव का स्वागत करते हैं।

लाइसेंसिंग के संदर्भ में, कृपया एक मिनट निकालकर हमारा छोटा License and Contributor Agreement पढ़ें।
समुदाय code of conduct का भी पालन करता है।

शुरू करने से पहले

कुछ योगदान करने की तलाश में हैं? हमारे good first issues ब्राउज़ करें और किसी एक को चुनकर शुरुआत करें!

कोई नया मॉडल रनटाइम या टूल जोड़ना चाहते हैं? हमारे plugin repo में एक PR खोलें और हमें दिखाएँ कि आपने क्या बनाया है।

किसी मौजूदा मॉडल रनटाइम या टूल को अपडेट करना है, या कुछ बग्स को ठीक करना है? हमारे official plugin repo पर जाएँ और अपना जादू दिखाएँ!

मज़े में शामिल हों, योगदान दें, और चलिए मिलकर कुछ शानदार बनाते हैं! 💡✨

PR के विवरण में मौजूदा issue को लिंक करना या नया issue खोलना न भूलें।

बग रिपोर्ट (Bug reports)

सुरक्षा खामियों की रिपोर्ट सार्वजनिक issue में करने के बजाय सुरक्षा नीति के अनुसार निजी तौर पर करें।

[!IMPORTANT]
कृपया बग रिपोर्ट सबमिट करते समय निम्नलिखित जानकारी अवश्य शामिल करें:

  • एक स्पष्ट और वर्णनात्मक शीर्षक
  • बग का विस्तृत विवरण, जिसमें कोई भी त्रुटि संदेश (error messages) शामिल हो
  • बग को पुन: उत्पन्न करने के चरण
  • अपेक्षित व्यवहार
  • लॉग्स, यदि उपलब्ध हों — बैकएंड समस्याओं के लिए यह बहुत महत्वपूर्ण है, आप इन्हें docker-compose logs में पा सकते हैं
  • स्क्रीनशॉट या वीडियो (यदि लागू हो)

हम प्राथमिकता कैसे तय करते हैं:

समस्या प्रकार (Issue Type) प्राथमिकता (Priority)
मुख्य कार्यों में बग (क्लाउड सेवा, लॉगिन न होना, एप्लिकेशन न चलना) गंभीर (Critical)
गैर-गंभीर बग, प्रदर्शन सुधार मध्यम प्राथमिकता (Medium Priority)
छोटे सुधार (टाइपो, भ्रमित करने वाला लेकिन काम करने वाला UI) निम्न प्राथमिकता (Low Priority)

फ़ीचर अनुरोध (Feature requests)

[!NOTE]
कृपया फ़ीचर अनुरोध सबमिट करते समय निम्नलिखित जानकारी अवश्य शामिल करें:

  • एक स्पष्ट और वर्णनात्मक शीर्षक
  • फ़ीचर का विस्तृत विवरण
  • फ़ीचर के उपयोग का मामला (use case)
  • फ़ीचर अनुरोध से संबंधित कोई अन्य संदर्भ या स्क्रीनशॉट

हम प्राथमिकता कैसे तय करते हैं:

फ़ीचर प्रकार (Feature Type) प्राथमिकता (Priority)
किसी टीम सदस्य द्वारा उच्च प्राथमिकता (High-Priority) के रूप में चिह्नित फ़ीचर उच्च प्राथमिकता (High Priority)
हमारे community feedback board से लोकप्रिय फ़ीचर अनुरोध मध्यम प्राथमिकता (Medium Priority)
गैर-मुख्य फ़ीचर्स और छोटे सुधार निम्न प्राथमिकता (Low Priority)
मूल्यवान लेकिन तात्कालिक नहीं भविष्य का फ़ीचर (Future-Feature)

अपना PR सबमिट करना (Submitting your PR)

पुल रिक्वेस्ट प्रक्रिया (Pull Request Process)

  1. रिपॉज़िटरी को Fork करें
  2. PR ड्राफ्ट करने से पहले, कृपया अपने बदलावों पर चर्चा करने के लिए एक issue बनाएँ
  3. अपने परिवर्तनों के लिए एक नई शाखा (branch) बनाएँ
  4. बदलाव से प्रत्यक्ष व्यवहार प्रभावित हो या रिग्रेशन का महत्वपूर्ण जोखिम हो, तो टेस्ट जोड़ें या अपडेट करें।
  5. सुनिश्चित करें कि आपका कोड मौजूदा टेस्ट पास करता है
  6. PR विवरण में issue लिंक करें, जैसे: fixes #
  7. मर्ज हो जाएँ! 🎉

प्रोजेक्ट सेटअप करें (Setup the project)

फ्रंटएंड (Frontend)

फ्रंटएंड सेवा सेटअप करने के लिए, कृपया हमारी विस्तृत guide देखें जो web/README.md फ़ाइल में उपलब्ध है।
यह दस्तावेज़ आपको फ्रंटएंड वातावरण को सही ढंग से सेटअप करने के लिए विस्तृत निर्देश प्रदान करता है।

बैकएंड (Backend)

बैकएंड सेवा सेटअप करने के लिए, कृपया हमारी विस्तृत instructions देखें जो api/README.md फ़ाइल में दी गई हैं।
यह दस्तावेज़ चरण-दर-चरण मार्गदर्शन प्रदान करता है जिससे आप बैकएंड को सुचारू रूप से चला सकें।

सहायता प्राप्त करना (Getting Help)

यदि योगदान करते समय आप कहीं अटक जाएँ या कोई महत्वपूर्ण प्रश्न हो, तो संबंधित GitHub issue के माध्यम से हमें अपने प्रश्न भेजें, या त्वरित बातचीत के लिए हमारे Discord पर जुड़ें।


It IT ADVANCED SETUP (`docs/it-IT/ADVANCED_SETUP.md`)

Configurazioni Avanzate

Configura l’installazione in docker/.env. .env.example contiene i valori necessari per il deployment predefinito; le opzioni avanzate e specifiche dei servizi sono in docker/envs/. Copia i modelli necessari senza il suffisso .example. I valori di .env hanno la precedenza. Dopo le modifiche, esegui docker compose up -d da docker/. Consulta la guida Docker.

Monitoraggio delle Metriche con Grafana

Importate la dashboard in Grafana, utilizzando il database PostgreSQL di Dify come origine dati, per monitorare le metriche a livello di app, tenant, messaggi e altro ancora.

Distribuzione con Kubernetes

Se desiderate configurare un'installazione ad alta disponibilità, ci sono Helm Charts e file YAML forniti dalla community che consentono di distribuire Dify su Kubernetes.

Utilizzo di Terraform per la Distribuzione

Distribuite Dify con un solo clic su una piattaforma cloud utilizzando terraform.

Azure Global

Google Cloud

Utilizzo di AWS CDK per la Distribuzione

Distribuzione di Dify su AWS con CDK

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Distribuzione con un clic di Dify su Alibaba Cloud con Alibaba Cloud Data Management

Utilizzo di Azure DevOps Pipeline per la Distribuzione su AKS

Distribuite Dify con un clic in AKS utilizzando Azure DevOps Pipeline Helm Chart di @LeoZhang

Distribuzione con Sealos

Distribuite Dify con un clic tramite Sealos App Store


Ja JP ADVANCED SETUP (`docs/ja-JP/ADVANCED_SETUP.md`)

高度なセットアップ

ローカル設定は docker/.env に記入します。.env.example には標準デプロイに必要な設定のみが含まれ、オプションやサービス固有の設定は docker/envs/ にあります。必要なテンプレートを .example 接尾辞なしでコピーしてください。.env の値が優先されます。変更後は docker/ で docker compose up -d を実行します。詳細は Docker ガイドを参照してください。

Grafanaを使用したメトリクス監視

Grafanaにダッシュボードをインポートし、DifyのPostgreSQLデータベースをデータソースとして使用して、アプリ、テナント、メッセージなどの粒度でメトリクスを監視します。

Kubernetesでのデプロイ

高可用性設定を設定する必要がある場合、コミュニティはHelm ChartsとYAMLファイルにより、DifyをKubernetesにデプロイすることができます。

Terraformを使用したデプロイ

terraform を使用して、ワンクリックでDifyをクラウドプラットフォームにデプロイします

Azure Global

Google Cloud

AWS CDK を使用したデプロイ

CDK を使用して、DifyをAWSにデプロイします

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Alibaba Cloud Data Management を利用して、DifyをAlibaba Cloudへワンクリックでデプロイできます

AKSへのデプロイにAzure Devops Pipelineを使用

Azure Devops Pipeline Helm Chart by @LeoZhangを使用してDifyをAKSにワンクリックでデプロイ

Sealosを使用したデプロイ

Sealos App Storeを使用してDifyをワンクリックでデプロイできます


Ja JP CONTRIBUTING (`docs/ja-JP/CONTRIBUTING.md`)

貢献ガイド

Difyに貢献しようとお考えですか?素晴らしいですね。私たちは、あなたがどのような貢献をしてくださるのか、とても楽しみにしています。スタートアップとして限られた人員と資金の中で、LLMアプリケーションの構築と管理のための最も直感的なワークフローを設計するという大きな目標を持っています。コミュニティからのあらゆる支援が、本当に重要な意味を持ちます。

私たちは迅速に開発を進める必要がありますが、同時に貢献者の皆様にとってスムーズな経験を提供したいと考えています。このガイドは、コードベースと私たちの貢献者との協働方法を理解していただき、すぐに楽しい開発に取り掛かれるようにすることを目的としています。

このガイドは、Dify自体と同様に、常に進化し続けています。実際のプロジェクトの進行状況と多少のずれが生じる場合もございますが、ご理解いただけますと幸いです。改善のためのフィードバックも歓迎いたします。

ライセンスについては、ライセンスと貢献者同意書をご一読ください。また、コミュニティは行動規範に従っています。

始める前に

取り組むべき課題をお探しですか?初心者向けの課題から選んで始めてみましょう!

新しいモデルランタイムやツールを追加したいですか?プラグインリポジトリでPRを作成し、あなたの成果を見せてください。

既存のモデルランタイムやツールの更新、バグ修正をしたいですか?公式プラグインリポジトリで作業を進めてください。

参加して、貢献して、一緒に素晴らしいものを作りましょう!💡✨

PRの説明には、既存のイシューへのリンクを含めるか、新しいイシューを作成することを忘れないでください。

バグ報告

脆弱性は公開イシューを作成せず、セキュリティポリシーに従って非公開で報告してください。

[!IMPORTANT]
バグ報告時には、以下の情報を必ず含めてください:

  • 明確で分かりやすいタイトル
  • エラーメッセージを含む詳細なバグの説明
  • バグの再現手順
  • 期待される動作
  • バックエンドの問題の場合はログ(docker-composeのログで確認可能)が非常に重要です
  • 該当する場合はスクリーンショットや動画

優先順位の付け方:

問題の種類 優先度
コア機能のバグ(クラウドサービス、ログイン不可、アプリケーション不具合) 最重要
重要度の低いバグ、パフォーマンス改善 中程度
軽微な修正(タイプミス、分かりにくいが動作するUI) 低

機能リクエスト

[!NOTE]
機能リクエスト時には、以下の情報を必ず含めてください:

  • 明確で分かりやすいタイトル
  • 機能の詳細な説明
  • 使用事例
  • その他の文脈や画面のスクリーンショット

優先順位の付け方:

機能の種類 優先度
チームメンバーによって高優先度とラベル付けされた機能 高
コミュニティフィードボードでの人気の機能リクエスト 中程度
非コア機能と軽微な改善 低
価値はあるが緊急性の低いもの 将来対応

PRの提出

プルリクエストのプロセス

  1. リポジトリをフォークする
  2. PRを作成する前に、変更内容についてイシューで議論する
  3. 変更用の新しいブランチを作成する
  4. 観察可能な動作に影響する変更や、無視できないリグレッションのリスクがある変更には、テストを追加または更新する。
  5. 既存のテストをパスすることを確認する
  6. PRの説明文にイシューをリンクする(fixes #)
  7. マージ完了!

プロジェクトのセットアップ

フロントエンド

フロントエンドサービスのセットアップについては、web/README.mdのガイドを参照してください。このドキュメントには、フロントエンド環境を適切にセットアップするための詳細な手順が記載されています。

バックエンド

バックエンドサービスのセットアップについては、api/README.mdの手順を参照してください。このドキュメントには、バックエンドを正しく動作させるためのステップバイステップのガイドが含まれています。

サポートを受ける

貢献中に行き詰まったり、緊急の質問がある場合は、関連するGitHubイシューで質問するか、Discordで気軽にチャットしてください。


Ko KR ADVANCED SETUP (`docs/ko-KR/ADVANCED_SETUP.md`)

고급 설정

로컬 설정은 docker/.env에서 변경하세요. .env.example에는 기본 배포에 필요한 설정만 있으며, 선택 사항과 서비스별 설정은 docker/envs/에 있습니다. 필요한 템플릿을 .example 접미사 없이 복사하세요. .env의 값이 우선합니다. 변경 후 docker/에서 docker compose up -d를 실행하세요. 자세한 내용은 Docker 가이드를 참고하세요.

Grafana를 사용한 메트릭 모니터링

Dify의 PostgreSQL 데이터베이스를 데이터 소스로 사용하여 앱, 테넌트, 메시지 등에 대한 세분화된 메트릭을 모니터링하기 위해 대시보드를 Grafana로 가져옵니다.

Kubernetes를 통한 배포

Dify를 Kubernetes에 배포하고 프리미엄 스케일링 설정을 구성했다는 커뮤니티가 제공하는 Helm Charts와 YAML 파일이 존재합니다.

Terraform을 사용한 배포

terraform을 사용하여 단 한 번의 클릭으로 Dify를 클라우드 플랫폼에 배포하십시오

Azure Global

Google Cloud

AWS CDK를 사용한 배포

CDK를 사용하여 AWS에 Dify 배포

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Alibaba Cloud Data Management를 통해 원클릭으로 Dify를 Alibaba Cloud에 배포할 수 있습니다

AKS에 배포하기 위해 Azure Devops Pipeline 사용

Azure Devops Pipeline Helm Chart by @LeoZhang을 사용하여 Dify를 AKS에 원클릭으로 배포

Sealos를 사용한 배포

Sealos App Store를 사용하여 Dify를 원클릭으로 배포할 수 있습니다


Ko KR CONTRIBUTING (`docs/ko-KR/CONTRIBUTING.md`)

기여하기

Dify에 기여하려고 하시는군요 - 정말 멋집니다, 당신이 무엇을 할지 기대가 됩니다. 인력과 자금이 제한된 스타트업으로서, 우리는 LLM 애플리케이션을 구축하고 관리하기 위한 가장 직관적인 워크플로우를 설계하고자 하는 큰 야망을 가지고 있습니다. 커뮤니티의 모든 도움은 정말 중요합니다.

우리는 현재 상황에서 민첩하게 빠르게 배포해야 하지만, 동시에 당신과 같은 기여자들이 기여하는 과정에서 최대한 원활한 경험을 얻을 수 있도록 하고 싶습니다. 우리는 이러한 목적으로 이 기여 가이드를 작성했으며, 여러분이 코드베이스와 우리가 기여자들과 어떻게 협업하는지에 대해 친숙해질 수 있도록 돕고, 빠르게 재미있는 부분으로 넘어갈 수 있도록 하고자 합니다.

이 가이드는 Dify 자체와 마찬가지로 끊임없이 진행 중인 작업입니다. 때로는 실제 프로젝트보다 뒤처질 수 있다는 점을 이해해 주시면 감사하겠으며, 개선을 위한 피드백은 언제든지 환영합니다.

라이센스 측면에서, 간략한 라이센스 및 기여자 동의서를 읽어보는 시간을 가져주세요. 커뮤니티는 또한 행동 강령을 준수합니다.

시작하기 전에

처리할 작업을 찾고 계신가요? 초보자를 위한 이슈를 살펴보고 시작할 것을 선택하세요!

추가할 새로운 모델 런타임이나 도구가 있나요? 우리의 플러그인 저장소에 PR을 열고 당신이 만든 것을 보여주세요.

기존 모델 런타임, 도구를 업데이트하거나 버그를 수정해야 하나요? 우리의 공식 플러그인 저장소로 가서 당신의 마법을 펼치세요!

함께 즐기고, 기여하고, 멋진 것을 함께 만들어 봅시다! 💡✨

PR 설명에 기존 이슈를 연결하거나 새 이슈를 여는 것을 잊지 마세요.

버그 보고

보안 취약점은 공개 이슈를 만들지 말고 보안 정책에 따라 비공개로 보고하세요.

[!IMPORTANT]
버그 보고서를 제출할 때 다음 정보를 포함해 주세요:

  • 명확하고 설명적인 제목
  • 오류 메시지를 포함한 버그에 대한 상세한 설명
  • 버그를 재현하는 단계
  • 예상되는 동작
  • 가능한 경우 로그, 백엔드 이슈의 경우 매우 중요합니다. docker-compose 로그에서 찾을 수 있습니다
  • 해당되는 경우 스크린샷 또는 비디오

우선순위 결정 방법:

이슈 유형 우선순위
핵심 기능의 버그(클라우드 서비스, 로그인 불가, 애플리케이션 작동 불능) 중대
비중요 버그, 성능 향상 중간 우선순위
사소한 수정(오타, 혼란스럽지만 작동하는 UI) 낮은 우선순위

기능 요청

[!NOTE]
기능 요청을 제출할 때 다음 정보를 포함해 주세요:

  • 명확하고 설명적인 제목
  • 기능에 대한 상세한 설명
  • 해당 기능의 사용 사례
  • 기능 요청에 관한 기타 컨텍스트 또는 스크린샷

우선순위 결정 방법:

기능 유형 우선순위
팀 구성원에 의해 레이블이 지정된 고우선순위 기능 높은 우선순위
우리의 커뮤니티 피드백 보드에서 인기 있는 기능 요청 중간 우선순위
비핵심 기능 및 사소한 개선 낮은 우선순위
가치 있지만 즉시 필요하지 않은 기능 미래 기능

PR 제출하기

Pull Request 프로세스

  1. 저장소를 포크하세요
  2. PR을 작성하기 전에, 변경하고자 하는 내용에 대해 논의하기 위한 이슈를 생성해 주세요
  3. 변경 사항을 위한 새 브랜치를 만드세요
  4. 변경이 관찰 가능한 동작에 영향을 주거나 유의미한 회귀 위험이 있으면 테스트를 추가하거나 갱신하세요.
  5. 코드가 기존 테스트를 통과하는지 확인하세요
  6. PR 설명에 이슈를 연결해 주세요, fixes #<이슈_번호>
  7. 병합 완료!

프로젝트 설정하기

프론트엔드

프론트엔드 서비스를 설정하려면, web/README.md 파일에 있는 우리의 종합 가이드를 참조하세요. 이 문서는 프론트엔드 환경을 적절히 설정하는 데 도움이 되는 자세한 지침을 제공합니다.

백엔드

백엔드 서비스를 설정하려면, api/README.md 파일에 있는 우리의 상세 지침을 참조하세요. 이 문서는 백엔드를 원활하게 실행하는 데 도움이 되는 단계별 가이드를 포함하고 있습니다.

도움 받기

기여하는 동안 막히거나 긴급한 질문이 있으면, 관련 GitHub 이슈를 통해 질문을 보내거나, 빠른 대화를 위해 우리의 Discord에 참여하세요.


Pt BR ADVANCED SETUP (`docs/pt-BR/ADVANCED_SETUP.md`)

Configuração avançada

Configure a instalação em docker/.env. .env.example contém os valores necessários para a implantação padrão; opções avançadas e específicas dos serviços ficam em docker/envs/. Copie os modelos necessários sem o sufixo .example. Os valores de .env têm prioridade. Após alterações, execute docker compose up -d em docker/. Consulte o guia do Docker.

Monitoramento de Métricas com Grafana

Importe o dashboard para o Grafana, usando o banco de dados PostgreSQL do Dify como fonte de dados, para monitorar métricas na granularidade de aplicativos, inquilinos, mensagens e muito mais.

Implantação com Kubernetes

Se deseja configurar uma instalação de alta disponibilidade, há Helm Charts e arquivos YAML contribuídos pela comunidade que permitem a implantação do Dify no Kubernetes.

Usando o Terraform para Implantação

Implante o Dify na Plataforma Cloud com um único clique usando terraform

Azure Global

Google Cloud

Usando AWS CDK para Implantação

Implante o Dify na AWS usando CDK

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Implante o Dify na Alibaba Cloud com um clique usando o Alibaba Cloud Data Management

Usando Azure Devops Pipeline para Implantar no AKS

Implante o Dify no AKS com um clique usando Azure Devops Pipeline Helm Chart by @LeoZhang

Implantação com Sealos

Implante o Dify com um clique usando a Sealos App Store


Pt BR CONTRIBUTING (`docs/pt-BR/CONTRIBUTING.md`)

CONTRIBUINDO

Então você está procurando contribuir para o Dify - isso é incrível, mal podemos esperar para ver o que você vai fazer. Como uma startup com equipe e financiamento limitados, temos grandes ambições de projetar o fluxo de trabalho mais intuitivo para construir e gerenciar aplicações LLM. Qualquer ajuda da comunidade conta, verdadeiramente.

Precisamos ser ágeis e entregar rapidamente considerando onde estamos, mas também queremos garantir que colaboradores como você tenham uma experiência o mais tranquila possível ao contribuir. Montamos este guia de contribuição com esse propósito, visando familiarizá-lo com a base de código e como trabalhamos com os colaboradores, para que você possa rapidamente passar para a parte divertida.

Este guia, como o próprio Dify, é um trabalho em constante evolução. Agradecemos muito a sua compreensão se às vezes ele ficar atrasado em relação ao projeto real, e damos as boas-vindas a qualquer feedback para que possamos melhorar.

Em termos de licenciamento, por favor, dedique um minuto para ler nosso breve Acordo de Licença e Contribuidor. A comunidade também adere ao código de conduta.

Antes de começar

Procurando algo para resolver? Navegue por nossos problemas para iniciantes e escolha um para começar!

Tem um novo modelo ou ferramenta para adicionar? Abra um PR em nosso repositório de plugins e mostre-nos o que você construiu.

Precisa atualizar um modelo existente, ferramenta ou corrigir alguns bugs? Vá para nosso repositório oficial de plugins e faça sua mágica!

Junte-se à diversão, contribua e vamos construir algo incrível juntos! 💡✨

Não se esqueça de vincular um problema existente ou abrir um novo problema na descrição do PR.

Relatórios de bugs

Relate vulnerabilidades em particular, seguindo a política de segurança, sem abrir uma issue pública.

[!IMPORTANT]
Por favor, certifique-se de incluir as seguintes informações ao enviar um relatório de bug:

  • Um título claro e descritivo
  • Uma descrição detalhada do bug, incluindo quaisquer mensagens de erro
  • Passos para reproduzir o bug
  • Comportamento esperado
  • Logs, se disponíveis, para problemas de backend, isso é realmente importante, você pode encontrá-los nos logs do docker-compose
  • Capturas de tela ou vídeos, se aplicável

Como priorizamos:

Tipo de Problema Prioridade
Bugs em funções centrais (serviço em nuvem, não conseguir fazer login, aplicações não funcionando) Crítica
Bugs não críticos, melhorias de desempenho Prioridade Média
Correções menores (erros de digitação, interface confusa mas funcional) Prioridade Baixa

Solicitações de recursos

[!NOTE]
Por favor, certifique-se de incluir as seguintes informações ao enviar uma solicitação de recurso:

  • Um título claro e descritivo
  • Uma descrição detalhada do recurso
  • Um caso de uso para o recurso
  • Qualquer outro contexto ou capturas de tela sobre a solicitação de recurso

Como priorizamos:

Tipo de Recurso Prioridade
Recursos de alta prioridade conforme rotulado por um membro da equipe Prioridade Alta
Solicitações populares de recursos do nosso quadro de feedback da comunidade Prioridade Média
Recursos não essenciais e melhorias menores Prioridade Baixa
Valiosos mas não imediatos Recurso Futuro

Enviando seu PR

Processo de Pull Request

  1. Faça um fork do repositório
  2. Antes de elaborar um PR, por favor crie um problema para discutir as mudanças que você quer fazer
  3. Crie um novo branch para suas alterações
  4. Adicione ou atualize testes quando a alteração afetar o comportamento observável ou apresentar risco significativo de regressão.
  5. Certifique-se de que seu código passa nos testes existentes
  6. Por favor, vincule o problema na descrição do PR, fixes #<número_do_problema>
  7. Faça o merge do seu código!

Configurando o projeto

Frontend

Para configurar o serviço frontend, por favor consulte nosso guia abrangente no arquivo web/README.md. Este documento fornece instruções detalhadas para ajudá-lo a configurar o ambiente frontend adequadamente.

Backend

Para configurar o serviço backend, por favor consulte nossas instruções detalhadas no arquivo api/README.md. Este documento contém um guia passo a passo para ajudá-lo a colocar o backend em funcionamento sem problemas.

Obtendo Ajuda

Se você ficar preso ou tiver uma dúvida urgente enquanto contribui, simplesmente envie suas perguntas através do problema relacionado no GitHub, ou entre no nosso Discord para uma conversa rápida.


Sl SI ADVANCED SETUP (`docs/sl-SI/ADVANCED_SETUP.md`)

Napredne nastavitve

Lokalne nastavitve uredite v docker/.env. .env.example vsebuje nujne vrednosti za privzeto namestitev; izbirne nastavitve in nastavitve posameznih storitev so v docker/envs/. Potrebne predloge kopirajte brez končnice .example. Vrednosti v .env imajo prednost. Po spremembah v docker/ zaženite docker compose up -d. Glejte vodnik za Docker.

Spremljanje metrik z Grafana

Uvoz nadzorne plošče v Grafana, z uporabo Difyjeve PostgreSQL baze podatkov kot vir podatkov, za spremljanje metrike glede na podrobnost aplikacij, najemnikov, sporočil in drugega.

Namestitev s Kubernetes

Če želite konfigurirati visoko razpoložljivo nastavitev, so na voljo Helm Charts in datoteke YAML, ki jih prispeva skupnost, ki omogočajo uvedbo Difyja v Kubernetes.

Uporaba Terraform za uvajanje

namestite Dify v Cloud Platform z enim klikom z uporabo terraform

Azure Global

Google Cloud

Uporaba AWS CDK za uvajanje

Uvedite Dify v AWS z uporabo CDK

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Z enim klikom namestite Dify na Alibaba Cloud z Alibaba Cloud Data Management

Uporaba Azure Devops Pipeline za uvajanje v AKS

Z enim klikom namestite Dify v AKS z uporabo Azure Devops Pipeline Helm Chart by @LeoZhang

Namestitev s Sealos

Z enim klikom namestite Dify prek Sealos App Store


Tlh ADVANCED SETUP (`docs/tlh/ADVANCED_SETUP.md`)

Advanced Setup

Set local configuration in docker/.env. .env.example contains essential startup defaults; optional and service-specific settings live under docker/envs/. Copy the templates you need without the .example suffix. Values in .env take precedence. After changes, run docker compose up -d from docker/. See the Docker deployment guide.

Kubernetes

If you'd like to configure a highly-available setup, there are community-contributed Helm Charts and YAML files which allow Dify to be deployed on Kubernetes.

Terraform atorlugu pilersitsineq

wa'logh nIqHom neH ghun deployment toy'wI' terraform lo'laH.

Azure Global

Google Cloud

AWS CDK atorlugh pilersitsineq

wa'logh nIqHom neH ghun deployment toy'wI' CDK lo'laH.

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Alibaba Cloud Data Management

AKS 'e' Deploy je Azure Devops Pipeline lo'laH

Azure Devops Pipeline Helm Chart by @LeoZhang lo'laH Dify AKS 'e' wa'DIch click 'e' Deploy

Sealos lo'laH Deploy

Sealos App Store lo'laH Dify wa'DIch click 'e' Deploy


Tr TR ADVANCED SETUP (`docs/tr-TR/ADVANCED_SETUP.md`)

Gelişmiş Kurulum

Yerel ayarları docker/.env içinde düzenleyin. .env.example varsayılan dağıtım için gereken başlangıç değerlerini içerir; isteğe bağlı ve hizmete özel ayarlar docker/envs/ altındadır. Gereken şablonları .example son eki olmadan kopyalayın. .env değerleri önceliklidir. Değişikliklerden sonra docker/ dizininde docker compose up -d çalıştırın. Docker kılavuzuna bakın.

Grafana ile Metrik İzleme

Uygulamalar, kiracılar, mesajlar ve daha fazlasının granularitesinde metrikleri izlemek için Dify'nin PostgreSQL veritabanını veri kaynağı olarak kullanarak panoyu Grafana'ya aktarın.

Kubernetes ile Dağıtım

Yüksek kullanılabilirliğe sahip bir kurulum yapılandırmak isterseniz, Dify'ın Kubernetes üzerine dağıtılmasına olanak tanıyan topluluk katkılı Helm Charts ve YAML dosyaları mevcuttur.

Dağıtım için Terraform Kullanımı

Dify'ı bulut platformuna tek tıklamayla dağıtın terraform kullanarak

Azure Global

Google Cloud

AWS CDK ile Dağıtım

CDK kullanarak Dify'ı AWS'ye dağıtın

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Alibaba Cloud Data Management kullanarak Dify'ı tek tıkla Alibaba Cloud'a dağıtın

AKS'ye Dağıtım için Azure Devops Pipeline Kullanımı

Azure Devops Pipeline Helm Chart by @LeoZhang kullanarak Dify'ı tek tıkla AKS'ye dağıtın

Sealos ile Dağıtım

Sealos App Store kullanarak Dify'ı tek tıkla dağıtın


Tr TR CONTRIBUTING (`docs/tr-TR/CONTRIBUTING.md`)

KATKIDA BULUNMAK

Demek Dify'a katkıda bulunmak istiyorsunuz - bu harika, ne yapacağınızı görmek için sabırsızlanıyoruz. Sınırlı personel ve finansmana sahip bir startup olarak, LLM uygulamaları oluşturmak ve yönetmek için en sezgisel iş akışını tasarlama konusunda büyük hedeflerimiz var. Topluluktan gelen her türlü yardım gerçekten önemli.

Bulunduğumuz noktada çevik olmamız ve hızlı hareket etmemiz gerekiyor, ancak sizin gibi katkıda bulunanların mümkün olduğunca sorunsuz bir deneyim yaşamasını da sağlamak istiyoruz. Bu katkı rehberini bu amaçla hazırladık; sizi kod tabanıyla ve katkıda bulunanlarla nasıl çalıştığımızla tanıştırmayı, böylece hızlıca eğlenceli kısma geçebilmenizi hedefliyoruz.

Bu rehber, Dify'ın kendisi gibi, sürekli gelişen bir çalışmadır. Bazen gerçek projenin gerisinde kalırsa anlayışınız için çok minnettarız ve gelişmemize yardımcı olacak her türlü geri bildirimi memnuniyetle karşılıyoruz.

Lisanslama konusunda, lütfen kısa Lisans ve Katkıda Bulunan Anlaşmamızı okumak için bir dakikanızı ayırın. Topluluk ayrıca davranış kurallarına da uyar.

Başlamadan Önce

Üzerinde çalışacak bir şey mi arıyorsunuz? İlk katkıda bulunanlar için iyi sorunlarımıza göz atın ve başlamak için birini seçin!

Eklenecek harika bir yeni model runtime'ı veya aracınız mı var? Eklenti depomuzda bir PR açın ve ne yaptığınızı bize gösterin.

Mevcut bir model runtime'ını, aracı güncellemek veya bazı hataları düzeltmek mi istiyorsunuz? Resmi eklenti depomuza gidin ve sihrinizi gösterin!

Eğlenceye katılın, katkıda bulunun ve birlikte harika bir şeyler inşa edelim! 💡✨

PR açıklamasında mevcut bir sorunu bağlamayı veya yeni bir sorun açmayı unutmayın.

Hata Raporları

Güvenlik açıklarını herkese açık issue oluşturmadan güvenlik politikasına göre özel olarak bildirin.

[!IMPORTANT]
Lütfen bir hata raporu gönderirken aşağıdaki bilgileri dahil ettiğinizden emin olun:

  • Net ve açıklayıcı bir başlık
  • Hata mesajları dahil hatanın ayrıntılı bir açıklaması
  • Hatayı tekrarlamak için adımlar
  • Beklenen davranış
  • Mümkünse Loglar, backend sorunları için, bu gerçekten önemlidir, bunları docker-compose loglarında bulabilirsiniz
  • Uygunsa ekran görüntüleri veya videolar

Nasıl önceliklendiriyoruz:

Sorun Türü Öncelik
Temel işlevlerdeki hatalar (bulut hizmeti, giriş yapamama, çalışmayan uygulamalar) Kritik
Kritik olmayan hatalar, performans artışları Orta Öncelik
Küçük düzeltmeler (yazım hataları, kafa karıştırıcı ama çalışan UI) Düşük Öncelik

Özellik İstekleri

[!NOTE]
Lütfen bir özellik isteği gönderirken aşağıdaki bilgileri dahil ettiğinizden emin olun:

  • Net ve açıklayıcı bir başlık
  • Özelliğin ayrıntılı bir açıklaması
  • Özellik için bir kullanım durumu
  • Özellik isteği hakkında diğer bağlamlar veya ekran görüntüleri

Nasıl önceliklendiriyoruz:

Özellik Türü Öncelik
Bir ekip üyesi tarafından etiketlenen Yüksek Öncelikli Özellikler Yüksek Öncelik
Topluluk geri bildirim panosundan popüler özellik istekleri Orta Öncelik
Temel olmayan özellikler ve küçük geliştirmeler Düşük Öncelik
Değerli ama acil olmayan Gelecek-Özellik

PR'nizi Göndermek

Pull Request Süreci

  1. Depoyu fork edin
  2. Bir PR taslağı oluşturmadan önce, yapmak istediğiniz değişiklikleri tartışmak için lütfen bir sorun oluşturun
  3. Değişiklikleriniz için yeni bir dal oluşturun
  4. Değişiklik gözlemlenebilir davranışı etkiliyorsa veya önemli bir regresyon riski taşıyorsa test ekleyin ya da güncelleyin.
  5. Kodunuzun mevcut testleri geçtiğinden emin olun
  6. Lütfen PR açıklamasında sorunu bağlayın, fixes #<sorun_numarası>
  7. Kodunuzu birleştirin!

Projeyi Kurma

Frontend

Frontend hizmetini kurmak için, lütfen web/README.md dosyasındaki kapsamlı rehberimize bakın. Bu belge, frontend ortamını düzgün bir şekilde kurmanıza yardımcı olacak ayrıntılı talimatlar sağlar.

Backend

Backend hizmetini kurmak için, lütfen api/README.md dosyasındaki detaylı talimatlarımıza bakın. Bu belge, backend'i sorunsuz bir şekilde çalıştırmanıza yardımcı olacak adım adım bir kılavuz içerir.

Yardım Almak

Katkıda bulunurken takılırsanız veya yanıcı bir sorunuz olursa, sorularınızı ilgili GitHub sorunu aracılığıyla bize gönderin veya hızlı bir sohbet için Discord'umuza katılın.


Vi VN ADVANCED SETUP (`docs/vi-VN/ADVANCED_SETUP.md`)

Thiết lập nâng cao

Cấu hình cục bộ nằm trong docker/.env. .env.example chỉ chứa các giá trị cần cho triển khai mặc định; cấu hình tùy chọn và riêng cho từng dịch vụ nằm trong docker/envs/. Sao chép mẫu cần dùng và bỏ hậu tố .example. Giá trị trong .env được ưu tiên. Sau khi thay đổi, chạy docker compose up -d từ docker/. Xem hướng dẫn Docker.

Giám sát Số liệu với Grafana

Nhập bảng điều khiển vào Grafana, sử dụng cơ sở dữ liệu PostgreSQL của Dify làm nguồn dữ liệu, để giám sát số liệu theo mức độ chi tiết của ứng dụng, người thuê, tin nhắn và hơn thế nữa.

Triển khai với Kubernetes

Nếu bạn muốn cấu hình một cài đặt có độ sẵn sàng cao, có các Helm Charts và tệp YAML do cộng đồng đóng góp cho phép Dify được triển khai trên Kubernetes.

Sử dụng Terraform để Triển khai

Triển khai Dify lên nền tảng đám mây với một cú nhấp chuột bằng cách sử dụng terraform

Azure Global

Google Cloud

Sử dụng AWS CDK để Triển khai

Triển khai Dify trên AWS bằng CDK

AWS

Alibaba Cloud

Alibaba Cloud Computing Nest

Alibaba Cloud Data Management

Triển khai Dify lên Alibaba Cloud chỉ với một cú nhấp chuột bằng Alibaba Cloud Data Management

Sử dụng Azure Devops Pipeline để Triển khai lên AKS

Triển khai Dify lên AKS chỉ với một cú nhấp chuột bằng Azure Devops Pipeline Helm Chart bởi @LeoZhang

Triển khai với Sealos

Triển khai Dify chỉ với một cú nhấp chuột từ Sealos App Store


Vi VN CONTRIBUTING (`docs/vi-VN/CONTRIBUTING.md`)

ĐÓNG GÓP

Bạn đang muốn đóng góp cho Dify - thật tuyệt vời, chúng tôi rất mong được thấy những gì bạn sẽ làm. Là một startup với nguồn nhân lực và tài chính hạn chế, chúng tôi có tham vọng lớn trong việc thiết kế quy trình trực quan nhất để xây dựng và quản lý các ứng dụng LLM. Mọi sự giúp đỡ từ cộng đồng đều rất có ý nghĩa.

Chúng tôi cần phải nhanh nhẹn và triển khai nhanh chóng, nhưng cũng muốn đảm bảo những người đóng góp như bạn có trải nghiệm đóng góp thuận lợi nhất có thể. Chúng tôi đã tạo hướng dẫn đóng góp này nhằm giúp bạn làm quen với codebase và cách chúng tôi làm việc với người đóng góp, để bạn có thể nhanh chóng bắt đầu phần thú vị.

Hướng dẫn này, giống như Dify, đang được phát triển liên tục. Chúng tôi rất cảm kích sự thông cảm của bạn nếu đôi khi nó chưa theo kịp dự án thực tế, và hoan nghênh mọi phản hồi để cải thiện.

Về giấy phép, vui lòng dành chút thời gian đọc Thỏa thuận Cấp phép và Người đóng góp ngắn gọn của chúng tôi. Cộng đồng cũng tuân theo quy tắc ứng xử.

Trước khi bắt đầu

Đang tìm việc để thực hiện? Hãy xem qua các issue dành cho người mới và chọn một để bắt đầu!

Bạn có một model runtime hoặc công cụ mới thú vị để thêm vào? Mở PR trong repo plugin của chúng tôi và cho chúng tôi thấy những gì bạn đã xây dựng.

Cần cập nhật model runtime, công cụ hiện có hoặc sửa lỗi? Ghé thăm repo plugin chính thức và thực hiện phép màu của bạn!

Hãy tham gia, đóng góp và cùng nhau xây dựng điều tuyệt vời! 💡✨

Đừng quên liên kết đến issue hiện có hoặc mở issue mới trong mô tả PR.

Báo cáo lỗi

Báo cáo lỗ hổng riêng tư theo chính sách bảo mật, không tạo issue công khai.

[!QUAN TRỌNG]
Vui lòng đảm bảo cung cấp các thông tin sau khi gửi báo cáo lỗi:

  • Tiêu đề rõ ràng và mô tả
  • Mô tả chi tiết về lỗi, bao gồm các thông báo lỗi
  • Các bước để tái hiện lỗi
  • Hành vi mong đợi
  • Log, nếu có, cho các vấn đề backend, điều này rất quan trọng, bạn có thể tìm thấy chúng trong docker-compose logs
  • Ảnh chụp màn hình hoặc video, nếu có thể

Cách chúng tôi ưu tiên:

Loại vấn đề Mức độ ưu tiên
Lỗi trong các chức năng cốt lõi (dịch vụ đám mây, không thể đăng nhập, ứng dụng không hoạt động) Quan trọng
Lỗi không nghiêm trọng, cải thiện hiệu suất Ưu tiên trung bình
Sửa lỗi nhỏ (lỗi chính tả, UI gây nhầm lẫn nhưng vẫn hoạt động) Ưu tiên thấp

Yêu cầu tính năng

[!LƯU Ý]
Vui lòng đảm bảo cung cấp các thông tin sau khi gửi yêu cầu tính năng:

  • Tiêu đề rõ ràng và mô tả
  • Mô tả chi tiết về tính năng
  • Trường hợp sử dụng cho tính năng
  • Bất kỳ ngữ cảnh hoặc ảnh chụp màn hình nào về yêu cầu tính năng

Cách chúng tôi ưu tiên:

Loại tính năng Mức độ ưu tiên
Tính năng ưu tiên cao được gắn nhãn bởi thành viên nhóm Ưu tiên cao
Yêu cầu tính năng phổ biến từ bảng phản hồi cộng đồng Ưu tiên trung bình
Tính năng không cốt lõi và cải tiến nhỏ Ưu tiên thấp
Có giá trị nhưng không cấp bách Tính năng tương lai

Gửi PR của bạn

Quy trình tạo Pull Request

  1. Fork repository
  2. Trước khi soạn PR, vui lòng tạo issue để thảo luận về các thay đổi bạn muốn thực hiện
  3. Tạo nhánh mới cho các thay đổi của bạn
  4. Thêm hoặc cập nhật kiểm thử khi thay đổi ảnh hưởng đến hành vi có thể quan sát được hoặc có nguy cơ hồi quy đáng kể.
  5. Đảm bảo code của bạn vượt qua các test hiện có
  6. Vui lòng liên kết issue trong mô tả PR, fixes #<số_issue>
  7. Được merge!

Thiết lập dự án

Frontend

Để thiết lập dịch vụ frontend, vui lòng tham khảo hướng dẫn chi tiết của chúng tôi trong file web/README.md. Tài liệu này cung cấp hướng dẫn chi tiết để giúp bạn thiết lập môi trường frontend một cách đúng đắn.

Backend

Để thiết lập dịch vụ backend, vui lòng tham khảo hướng dẫn chi tiết của chúng tôi trong file api/README.md. Tài liệu này chứa hướng dẫn từng bước để giúp bạn khởi chạy backend một cách suôn sẻ.

Nhận trợ giúp

Nếu bạn bị mắc kẹt hoặc có câu hỏi cấp bách trong quá trình đóng góp, chỉ cần gửi câu hỏi của bạn thông qua issue GitHub liên quan, hoặc tham gia Discord của chúng tôi để trò chuyện nhanh.


Zh CN ADVANCED SETUP (`docs/zh-CN/ADVANCED_SETUP.md`)

高级设置

自定义配置

在 docker/.env 中设置本地配置。.env.example 只包含默认部署所需的启动配置,可选和服务专用配置位于 docker/envs/。需要时,将对应模板复制为不带 .example 后缀的文件;.env 中的值优先。修改后,在 docker/ 目录运行 docker compose up -d。详见 Docker 部署指南。

使用 Grafana 进行指标监控

将仪表板导入 Grafana,使用 Dify 的 PostgreSQL 数据库作为数据源,以监控应用、租户、消息等粒度的指标。

使用 Helm Chart 或 Kubernetes 资源清单(YAML)部署

使用 Helm Chart 版本或者 Kubernetes 资源清单(YAML),可以在 Kubernetes 上部署 Dify。

使用 Terraform 部署

使用 terraform 一键将 Dify 部署到云平台

Azure Global

Google Cloud

使用 AWS CDK 部署

使用 CDK 将 Dify 部署到 AWS

AWS

使用 阿里云计算巢 部署

使用 阿里云计算巢 将 Dify 一键部署到 阿里云

使用 阿里云数据管理DMS 部署

使用 阿里云数据管理DMS 将 Dify 一键部署到 阿里云

使用 Azure Devops Pipeline 部署到AKS

使用Azure Devops Pipeline Helm Chart by @LeoZhang 将 Dify 一键部署到 AKS

使用 Sealos 部署

通过 Sealos App Store 一键部署 Dify


Zh CN CONTRIBUTING (`docs/zh-CN/CONTRIBUTING.md`)

贡献指南

非常感谢你考虑为 Dify 做出贡献!作为一家资源有限的创业公司,我们希望打造最直观的 LLM 应用开发和管理工作流程。社区的每一份贡献对我们来说都弥足珍贵。

我们需要保持敏捷和快速迭代,同时也希望确保贡献者能获得尽可能流畅的参与体验。这份贡献指南旨在帮助你熟悉代码库和我们的工作方式,让你可以尽快进入有趣的开发环节。

本指南和 Dify 一样在不断完善中。如果有任何滞后于项目实际情况的地方,恳请谅解,我们也欢迎任何改进建议。

关于许可证,请花一分钟阅读我们简短的许可和贡献者协议。同时也请遵循社区行为准则。

开始之前

想寻找可以着手的任务?浏览我们的新手友好议题并选择一个开始!

有酷炫的新模型运行时或工具要添加?在我们的插件仓库开启 PR,展示你的作品。

需要更新现有模型运行时、工具或修复 bug?前往我们的官方插件仓库大展身手!

加入我们,一起贡献,共同打造精彩项目!💡✨

请记得在 PR 描述中关联现有 issue 或创建新的 issue。

Bug 报告

安全漏洞请按安全政策私下报告,不要创建公开 issue。

[!IMPORTANT]
提交 bug 报告时请务必包含以下信息:

  • 清晰描述性的标题
  • 详细的 bug 描述,包括任何错误信息
  • 复现步骤
  • 预期行为
  • 日志,如果是后端问题,这点很重要,可以在 docker-compose 日志中找到
  • 截图或视频(如果适用)

优先级划分:

问题类型 优先级
核心功能 bug(云服务、登录失败、应用无法使用) 紧急
非关键 bug、性能优化 中等优先级
小修复(拼写错误、界面混乱但可用) 低优先级

功能请求

[!NOTE]
提交功能请求时请务必包含以下信息:

  • 清晰描述性的标题
  • 详细的功能描述
  • 功能使用场景
  • 其他相关上下文或截图

优先级划分:

功能类型 优先级
被团队成员标记为高优先级的功能 高优先级
来自社区反馈板的热门功能请求 中等优先级
非核心功能和小改进 低优先级
有价值但非紧急的功能 未来特性

提交 PR

PR 提交流程

  1. Fork 本仓库
  2. 在提交 PR 之前,请先创建 issue 讨论你想要做的修改
  3. 为你的修改创建一个新的分支
  4. 当修改影响可观察行为或存在明显回归风险时,添加或更新测试。
  5. 确保你的代码能通过现有的测试
  6. 请在 PR 描述中关联相关 issue,格式为 fixes #
  7. 等待合并!

项目设置

前端

关于前端服务的设置,请参考 web/README.md 文件中的详细指南。该文档提供了帮助你正确配置前端环境的详细说明。

后端

关于后端服务的设置,请参考 api/README.md 文件中的详细说明。该文档包含了帮助你顺利运行后端的步骤说明。

获取帮助

如果你在贡献过程中遇到困难或有紧急问题,可以通过相关 GitHub issue 向我们提问,或加入我们的 Discord 进行快速交流。


Zh TW ADVANCED SETUP (`docs/zh-TW/ADVANCED_SETUP.md`)

進階設定

在 docker/.env 中設定本機配置。.env.example 僅包含預設部署所需的啟動設定,可選與服務專用設定位於 docker/envs/。需要時,將對應範本複製為不含 .example 後綴的檔案;.env 中的值優先。修改後,在 docker/ 目錄執行 docker compose up -d。詳見 Docker 部署指南。

使用 Grafana 進行指標監控

將儀表板匯入 Grafana,使用 Dify 的 PostgreSQL 資料庫作為資料來源,以監控應用程式、租戶、訊息等顆粒度的指標。

使用 Kubernetes 部署

如果您想配置高可用性設置,社區貢獻的 Helm Charts 和 Kubernetes 資源清單(YAML)允許在 Kubernetes 上部署 Dify。

使用 Terraform 進行部署

使用 terraform 一鍵部署 Dify 到雲端平台

Azure 全球

Google Cloud

使用 AWS CDK 進行部署

使用 CDK 部署 Dify 到 AWS

AWS

使用 阿里云计算巢進行部署

阿里云

使用 阿里雲數據管理DMS 進行部署

透過 阿里雲數據管理DMS,一鍵將 Dify 部署至阿里雲

使用 Azure Devops Pipeline 部署到AKS

使用Azure Devops Pipeline Helm Chart by @LeoZhang 將 Dify 一鍵部署到 AKS

使用 Sealos 部署

透過 Sealos App Store 一鍵部署 Dify


Zh TW CONTRIBUTING (`docs/zh-TW/CONTRIBUTING.md`)

參與貢獻

我們很高興你想要為 Dify 做出貢獻!作為一個資源有限的新創團隊,我們期望打造最直觀的 LLM 應用開發與管理工作流程。社群中的每一份貢獻對我們來說都非常重要。

作為一個快速發展的專案,我們需要保持敏捷並快速迭代,同時也希望能為貢獻者提供順暢的參與體驗。我們準備了這份貢獻指南,幫助你了解程式碼庫和我們與貢獻者合作的方式,讓你能夠盡快投入有趣的開發工作。

這份指南與 Dify 一樣,都在持續完善中。如果指南內容有落後於實際專案的情況,還請見諒,也歡迎提供改進建議。

關於授權部分,請花點時間閱讀我們簡短的授權和貢獻者協議。社群也需遵守行為準則。

開始之前

想找點事做?瀏覽我們的新手友善議題並挑選一個開始!

有酷炫的模型執行時期或工具要新增?在我們的外掛倉庫開啟 PR 展示你的作品。

需要更新現有的模型執行時期、工具或修復錯誤?前往我們的官方外掛倉庫開始你的魔法之旅!

加入我們,一起貢獻並打造令人驚艷的作品吧!💡✨

別忘了在 PR 描述中連結現有議題或開啟新議題。

錯誤回報

安全漏洞請依照安全政策私下回報,不要建立公開議題。

[!IMPORTANT]
提交錯誤回報時,請務必包含以下資訊:

  • 清晰明確的標題
  • 詳細的錯誤描述,包含任何錯誤訊息
  • 重現錯誤的步驟
  • 預期行為
  • 日誌,如果有的話。對後端問題來說這點很重要,你可以在 docker-compose logs 中找到
  • 截圖或影片(如適用)

優先順序評估:

議題類型 優先級
核心功能錯誤(雲端服務、無法登入、應用程式無法運作) 緊急
非緊急錯誤、效能優化 中等
次要修正(拼字錯誤、介面混淆但可運作) 低

功能請求

[!NOTE]
提交功能請求時,請務必包含以下資訊:

  • 清晰明確的標題
  • 詳細的功能描述
  • 功能的使用情境
  • 其他相關背景說明或截圖

優先順序評估:

功能類型 優先級
團隊成員標記為高優先級的功能 高
來自社群回饋板的熱門功能請求 中
非核心功能和小幅改進 低
有價值但非急迫的功能 未來功能

提交 PR

PR 流程

  1. Fork 專案
  2. 在開始撰寫 PR 前,請先建立議題討論你想做的更改
  3. 為你的更改建立新分支
  4. 當更改影響可觀察行為或存在明顯回歸風險時,新增或更新測試。
  5. 確保你的程式碼通過現有測試
  6. 請在 PR 描述中連結相關議題,使用 fixes #
  7. 等待合併!

專案設定

前端

關於前端服務的設定,請參考 web/README.md 中的完整指南。此文件提供詳細說明,幫助你正確設定前端環境。

後端

關於後端服務的設定,請參考 api/README.md 中的詳細說明。此文件包含逐步指引,幫助你順利啟動後端服務。

尋求協助

如果你在貢獻過程中遇到困難或有急切的問題,可以透過相關的 GitHub 議題詢問,或加入我們的 Discord 進行即時交流。


Web Docs Bundle Size (`web/docs/bundle-size.md`)

Bundle analysis in pull requests

The main CI calls Web Bundle Analysis when its Web style checks are required,
for both pull requests and merge queue entries. It builds the event's exact base
commit and the tested merge commit from github.sha in parallel. Both run the
complete build:vinext pipeline, including the unused translations check.
No SSR, reference-analysis, or standalone stage is skipped.

This replaces the separate Vinext build in Web Style. Static checks run alongside
the analysis workflow, and the existing Web Style required check succeeds only
when both complete successfully. Main CI owns change detection and duplicate-run
skipping. Target-branch updates alone do not rerun PRs.

The official Rolldown bundleAnalyzerPlugin is added only to the client environment
through a temporary Vite config wrapper. Each revision keeps its own application
config and lockfile. The plugin is already bundled with the repository's Vite+
runtime through vite/rolldown/experimental; no separate analyzer dependency is
installed. The experimental schema is validated and unsupported data fails the
job instead of appearing as savings.

Reading the report

The full comparison always appears in the Actions summary. Same-repository PRs
receive an updated comment only when the absolute gzip change reaches at least
5 KiB for all client JS, 1 KiB for client CSS, or 2 KiB for any entry present in
both revisions. Increases and decreases both qualify. Raw sizes, package
attribution, and added/removed entry boundaries do not independently trigger a
comment. If a later run falls below every threshold, the existing report comment
is removed to avoid leaving stale results.

Merge queue runs receive the summary and artifacts without
a PR comment. Fork PRs receive the summary and artifacts without a
privileged build or comment token. Reports are informational: growth does not fail
the check; build, analysis, and reporting errors do.

  • All client JS: actual bytes and per-file gzip of the chunks listed in the
    official analyzer. Includes dynamically imported chunks.
  • Client CSS: emitted CSS under dist/client/_next/static, excluding copied
    public assets.
  • Entry static dependencies: recursively follows static chunk edges, with
    shared chunks counted once within an entry. Application source paths identify
    entries independently of output hashes. Dynamic entries are measured when
    loaded; these are not full-page first-load measurements. Entries overlap and
    cannot be summed. The comment shows the 20 largest absolute gzip changes.
    Added/removed entry boundaries appear separately and are not treated as size
    changes from zero.
  • Package attribution: groups module sizes from the official analyzer by npm
    package. This is attribution, not compressed output size; the comment shows the
    15 largest absolute changes.

This measures Vinext/Rolldown output, not Next.js/Turbopack production output or
browser network timings. Compiler versions are recorded in both snapshots.

Both revisions upload the official JSON and Markdown reports, build logs, and
size snapshots for 14 days. The summary links to these artifacts; no local viewer
is required. We do not rely on Vite DevTools' incomplete static Session Compare.

See the Rolldown analyzer documentation.

Local collection

The instrument command renames vite.config.ts and writes a temporary wrapper.
Use it only in a disposable checkout, as CI does:

sh
node web/scripts/bundle-analysis.ts instrument web
pnpm --dir web run build:vinext
node web/scripts/bundle-analysis.ts collect web "$(git rev-parse HEAD)" /tmp/current.json
node web/scripts/bundle-analysis.ts compare /tmp/base.json /tmp/current.json /tmp/report.md

Next.js / Turbopack analysis

The Web analyze script uses Next.js's built-in Turbopack analyzer:

sh
pnpm --dir web analyze --output

Save web/.next/diagnostics/analyze before changing code, then collect another
report with the same compiler version and environment. Omit --output to open
the interactive analyzer and inspect route-specific client/server import chains.
These reports are separate from the Vinext snapshots above.

If analysis panics inside next-api/src/nft.rs, move
web/.next/cache/turbopack outside .next and retry before changing production
configuration. A stale filesystem cache caused this failure locally with
Next.js 16.3.6; rebuilding the cache let the unchanged configuration complete.

Check import chains before adding configuration. Next.js already optimizes
imports from libraries such as ahooks and Heroicons. serverExternalPackages
affects server bundling; it does not remove dependencies from browser bundles.

A lazy component can still have eager dependencies if shared utilities import
its SDK statically. Console analytics keeps its initialization state and event
helpers lightweight, loading Amplitude and session replay only after analytics
is enabled and consent is granted. Keep SDK imports in shared helpers type-only
and use the initialized client for events. When changing this boundary, verify
revocation and unmount during loading, concurrent initialization, and failure
recovery as well as entry static dependencies and total emitted bytes.


Web Docs Hotkeys (`web/docs/hotkeys.md`)

Keyboard Commands

Use TanStack Hotkeys for application commands. Keep registration, business actions, and
availability with the feature owner; keep text editing, widget navigation, and dismissal with
their existing editor or Dify UI primitive. Do not add a generic shortcut wrapper.

The official React guide owns library options and defaults, including input filtering,
keyboard layouts, composition matching, and repeats. This document adds Dify's integration
contracts. Check the installed declarations when an API differs from the latest documentation.

Registration and availability

For commands belonging to mounted popup content, pass the actual owner's ref:

tsx
const PUBLISH_HOTKEY = 'Mod+Shift+P' satisfies HotkeyChord
const popupRef = useRef<HTMLDivElement>(null)

useHotkey(PUBLISH_HOTKEY, publish, {
  target: popupRef,
  enabled: canPublish,
  requireReset: true,
})

Attach the ref to the Popup. Import the hook and type from @tanstack/react-hotkeys and
useRef from React. Call the button's action, including its validation and permission checks.

  • Use enabled when an unavailable command should release the key entirely. A disabled
    registration does not consume the event. If the browser action must remain suppressed,
    keep the registration enabled and guard the business action inside its callback instead.
  • Use default input filtering unless the feature requires otherwise. Form submission may need
    ignoreInputs: false; canvas commands use true to preserve editing. See defaults.
  • Use requireReset: true for one-shot commands with default consumption; allow continuous
    actions such as zoom to repeat. Conditional event owners follow the rules below.
  • Pass a ref, not ref.current. An empty ref skips registration; a bare null target falls back
    to document. Ref mutation does not re-render the owner: put the hook in mounted content or
    use the actual Form's onKeyDown when it mounts later. Lexical root replacement can use its
    root subscription with element state; disable registration while that element is null.
  • For form commands, call event.currentTarget.requestSubmit() to share native submission and
    validation. React events from nested portals follow React ancestry; check DOM containment
    when those portals must be excluded. The Skills file tree intentionally includes its menus.

Bindings and display

Boundary Contract
One command / a group useHotkey / useHotkeys; preserve feature command IDs.
Chord-only strings / objects HotkeyChord / RawHotkeyChord; use satisfies for constants.
Both chord forms RegisterableHotkeyChord; Hotkey / RegisterableHotkey also admit sequences.
Existing React handler matchesKeyboardEvent(event.nativeEvent, chord) matches one chord only.
Keycaps Share the binding with registration; use formatForDisplay(..., { parts: true }) and Dify UI Kbd / KbdGroup.

Use DisplayHotkeyChord for chord-only display boundaries. Sequence formatting returns groups
of keycaps; do not widen a chord renderer without implementing that UI. Follow formatting for
logical/physical keys, validation, and labels. Preserve the initial platform through hydration,
as navigation search does. aria-keyshortcuts uses Meta+K or Control+K, not glyphs or Mod.

Local constants are the default. Use native app hotkeys when a product needs app-wide discovery
or remapping: declarations contain no callbacks; business callbacks stay with their feature.
Recording, sequences, and modifier hints are optional capabilities, not migration requirements.

Event ownership and scopes

A DOM target limits event origin; a scope controls whether TanStack registrations are active.
Neither replaces editor handling or Dify UI dismissal. Use a scoped provider above its hook
consumers, with a unique name for independently mounted surfaces. Same-scope matches may all
run; conflictBehavior: 'replace' is not a restoring stack, and metadata is not activation.

Use exclusive when a modal feature must suspend background application commands. Activate it
with the interactive content, not a permanently mounted Root. Content may retain exclusivity
through its closing transition; hidden retained content needs explicit enabled handling.
Preserve commands needed inside the modal: GotoAnything consumes repeated Mod+K inside its
scope while the global opener is suspended. Scope precedence and exceptions belong to scope.

Use normal library consumption unless the owner must decide whether to claim an event:

  • An element's native listener can precede child React handlers. When children must go first,
    handle React bubbling, or use document bubble plus owner containment as Workflow does.
    capture: true is for an intentional requirement to precede descendants, not a general fix.
  • The manager does not skip defaultPrevented. Conditional owners set preventDefault: false
    and stopPropagation: false, check scope and defaultPrevented, then consume accepted events.
    Consume repeats before returning on event.repeat; leave requireReset unset in this mode
    so its callback latch cannot bypass that consumption. stopPropagation() does not stop
    another callback on the same manager target.
  • Keep IME protection for custom submission and logical Enter/Escape, including existing
    composition-end handling. Library composition filtering does not cover those named keys.
  • A container delegating child events retains its real semantics. Explain a necessary lint
    exception instead of adding a fake button role or tab stop.

Character shortcuts, including Shift plus a character, must be disableable, remappable to
include a non-character key, or limited to focus within their owning component. Input filtering
or an active page-wide scope alone is insufficient.

Workflow boundaries

Owner Responsibility
Canvas WorkflowCanvas supplies the ReactFlow root ref. useWorkflowHotkeys runs after child React handlers and accepts only events within that subtree.
Graph actions Existing graph hooks own permissions, mutations, history, and persistence. Keyboard commands invoke them.
Editors and nodes ReactFlow, local handlers, Lexical, CodeMirror, and forms own navigation, undo, suggestions, and submission.
Portalled menus Match displayed commands and act on the actual node, edge, or selection.
Run and history Header features own page commands; header focus is unnecessary.
Comments Focused draft/thread dismissal runs after suggestions. Active pointer-following placement owns Escape without taking focus.

The outer Workflow container includes unrelated panels; use the canvas root for graph scope.
Restore canvas focus after deleting its focused object or applying graph undo/redo. Use Popup
finalFocus when a menu action deletes its return target. Hold-to-dim combines held-key state
with canvas focus and clears on focus loss; held-key state alone does not establish ownership.

Verification

Follow Web testing. Use the real matcher/manager to verify affected scope, availability,
mount/reopen behavior, child priority, IME flags, and repeats. Check native editing, focus, and
selection in a browser, and both platform modifiers for binding or hint changes. State the
limits of simulated IME and mocked business actions.


Web Docs Landmarks (`web/docs/landmarks.md`)

Page Landmarks

Web owns landmark composition across route layouts and feature components. Use the
W3C landmark guide for role semantics and the Dify UI naming contract for accessible
names. This guide records how those contracts apply to Web pages.

Page Ownership

  • Place perceivable page content in meaningful landmark regions and check coverage after
    composing the layout and its children.
  • Trace the parent layouts before adding a page-level landmark. Inspect the composed
    page, including parallel route slots and portals, rather than judging a component alone.
  • MainNavLayout provides the console's main and skip-navigation target. Descendant
    pages and editors must not create another main. Hiding the main navigation does not
    remove this wrapper. A route outside this layout must establish its own main-content
    boundary in its owning layout or page.
  • Keep the skip link and its target under the same layout owner. Preserve the target ID
    and focus behavior when changing wrappers; a landmark role alone does not move focus.
  • Keep page and section headings meaningful inside these boundaries. A heading does not
    create a landmark or automatically name its surrounding section.

Choose Roles by Content

  • Use nav for a meaningful group of navigation links. A grid of resource cards is not
    automatically navigation merely because its cards can open detail pages.
  • A visual sidebar is not automatically complementary content. File controls, editors,
    and builder or version panels are parts of the current task. Use ordinary containers
    or named sections according to their navigation value. Follow APG's recommendation
    to keep genuine complementary landmarks at the top level.
  • Reserve named section regions for content useful to reach directly. Avoid turning
    every wrapper, card, or modal body into a landmark. Prefer an existing visible heading
    as the naming source, following the naming contract.
  • Give repeated landmarks distinct names by purpose unless their content and purpose
    are identical. Keep names localized and avoid repeating the role in the name.
  • Page-level header and footer can expose banner and contentinfo. Their implicit
    roles depend on ancestors; local panel headers and footers do not necessarily expose
    those landmarks. Check the composed context before adding explicit roles.

Verify the Composed Page

  • Check the main-content boundary, landmark hierarchy, names, and heading relationships
    in the relevant loaded, empty, collapsed, and open-overlay states. Exclude hidden
    skeletons from the exposed landmark inventory. Check that label references still
    resolve when conditional content changes.
  • When changing a semantic element, inspect affected unit tests and E2E locators,
    including CSS selectors such as closest('main'). Locate the intended feature or
    control instead of relying on an extra page landmark or positional selection among
    duplicate landmarks.
  • Follow Web testing policy for regression coverage. At composition boundaries, keep
    the components that own landmark semantics real; a mocked sidebar cannot prove the
    real sidebar's role. Distinguish DOM assertions and Cucumber dry-runs from actual
    browser or assistive-technology verification.

Web Docs Lint (`web/docs/lint.md`)

Static Check Guide

See the repository tooling guide for linting, formatting, static checks, and custom rule maintenance.


Web Docs Test (`web/docs/test.md`)

Frontend Testing Guide

This document is the single source of truth for automated frontend tests under web/. Tests should protect product behavior and make refactoring safer. They are not a file-by-file completion exercise. Dify UI owns its package-specific test boundary in the Dify UI testing contract.

Testing Mindset

Write or update a test when a change affects a stable, observable contract:

  • User interactions and resulting UI state.
  • Navigation, URL state, persistence, permissions, or data flow.
  • Loading, success, error, and empty states that users can actually reach.
  • Accessibility semantics, keyboard behavior, focus management, or disabled state.
  • Business logic or a reusable utility with meaningful input/output behavior.
  • A bug fix whose regression can be reproduced through a public boundary.

Do not add tests merely for file/prop coverage, render-without-crashing checks, React implementation choices, or inputs excluded by TypeScript and the product contract.

Decide whether a regression needs lasting automated coverage before choosing its boundary or runtime. Check existing tests first. For visual-only changes, default to reviewing the real UI at representative widths and states; record the result without adding a permanent test. Automate a stable visual requirement or meaningful regression risk, not every design adjustment. Do not move a low-value test to another runner or a screenshot suite merely to keep coverage.

Coverage

Coverage is a diagnostic signal, not a quality target. This guide defines no required percentage and reviewers should not request tests solely to increase coverage. Use a report to find suspicious gaps, then decide whether each gap represents a product risk worth protecting.

The unit coverage report includes authored JavaScript and TypeScript throughout web/, including runtime entry points, scripts, plugins, and files that no test imports. It excludes test infrastructure, stories, declarations, generated sources, tool configuration, build output, and vendored static code. TypeScript modules containing only erased types have no executable statements and are not meaningful zero-coverage findings. Local coverage runs also produce an HTML report at coverage/index.html.

Run the full unit project before using coverage to identify untested modules. A focused run measures only the selected tests. CI collects Browser Mode coverage separately and combines it with unit coverage under the same Codecov web flag. Zero unit coverage does not imply that Browser Mode or E2E never exercises the file; E2E does not contribute to the coverage report. Anonymous VM scripts and subprocesses can also execute code without attributing coverage to its source file. Check existing tests and separate product modules from development tooling when prioritizing the findings.

Choose the Right Boundary

Use the smallest boundary that includes the behavior owner and proves the product contract without coupling the test to implementation:

  • Test pure transformations and business rules as unit tests.
  • Test hooks directly only when the hook itself exposes a reusable public contract. Otherwise, exercise the hook through its owning component or feature.
  • Use React Testing Library for component and feature behavior visible through the DOM or external side effects.
  • Use integration tests for behavior that crosses meaningful module boundaries.
  • Use the browser project when it adds meaningful browser evidence under Browser Mode Admission.
  • Follow the Dify UI testing contract for the Storybook and Vitest boundary of Dify UI primitives.

Test the behavior owner. Barrel exports, pass-through wrappers, and purely presentational children do not need separate tests when the owning feature already proves their contract. Do not repeat generic behavior already owned by Base UI, React Aria, or the browser; test Dify's integration, overrides, and known regressions.

Browser Mode Admission

Web defaults to the unit project in happy-dom. This is a project tradeoff, not a Vitest restriction: Vitest component testing recommends Browser Mode, and Vitest visual regression testing supports visual contracts.

A new browser test must establish all three:

  • Value: name the user-visible failure or stable visual requirement worth protecting. Layout, focus, portals, observers, and “happy-dom cannot do this” alone are not justification; neither are primitive or native defaults such as focus returning to the trigger that opened an overlay or Space activating a button.
  • Additional evidence: identify what existing owner tests miss and what real rendering or browser interaction adds. Do not repeat a state matrix just because a browser fixture exists; a viewport, theme, key, or variant row needs its own failure mode, otherwise keep the hardest row.
  • Faithful boundary: exercise the production owner and assert the claimed result. A copied layout cannot prove page integration; cursor or hover styling cannot prove that clicking performs an action.

Use the smallest scenario that supplies that evidence. Native selection, focus restoration to CSS-hidden controls, hit testing, scrolling, and animation completion can justify browser coverage. Ordinary event handling and DOM state usually belong in unit. Synthetic events can test handler responses but do not prove native gesture generation, capture, or event ordering; use the Vitest Interactivity API when those are the contract.

Do not add permanent tests solely to freeze decorative spacing, radii, or artwork dimensions from a one-off visual adjustment. Geometry and computed styles are appropriate when they prove the chosen contract, such as readable content, unobstructed controls, or visible keyboard focus. Visual baselines need an explicit stable requirement and controlled rendering environment.

Each *.browser.spec.{ts,tsx} must make its regression and additional evidence clear from its scenario and assertions; add a short explanation only when needed. Do not use forced interaction, fixed sleeps, private DOM assertions, or real network requests.

Browser input is real and nothing waits between keys. Split a userEvent.keyboard sequence wherever a later key depends on state an earlier key produces, such as an opened menu or moved focus, and await that state with expect.element before continuing.

Browser Mode remains a focused component or feature test and currently proves Chromium only. Use the end-to-end suite for a running application, authentication, real routing, backend APIs, persistence, or complete journeys.

Assert Behavior, Not Implementation

  • Drive state transitions through props, user interaction, URL changes, or public APIs.
  • Assert rendered UI, ARIA state, navigation, persistence, network-boundary calls, or another observable result.
  • For a reset-or-persistence regression in a hidden surface, exercise the public transition: open, modify, close and wait for the surface to disappear, then reopen. Assert the intended behavior without coupling the test to hook placement, component names, keys, or private mount structure.
  • Do not inspect React state, refs, hook call order, effect dependencies, or private DOM structure.
  • Test referential identity only when identity is itself a documented public contract.
  • One test should describe one behavior. It may contain multiple assertions when they jointly prove that behavior.
  • Test only input states supported by the type and product contract. Do not manufacture null, undefined, or extreme values without a reachable scenario.
  • Do not assert CSS class names or mechanically translate them into computed-style assertions. Assert the required outcome; use visual review for incidental styling.
  • Use DOM or data snapshots only when serialized output is itself an intentionally public, stable contract. Visual baselines follow Browser Mode Admission.

Queries, Interaction, and Accessibility

Prefer selectors in this order:

  1. getByRole with an accessible name.
  2. getByLabelText for labeled form controls.
  3. getByText, getByPlaceholderText, or other user-visible queries when appropriate.
  4. getByTestId only for boundaries with no useful DOM semantics, such as canvas output, editor shims, or mocked non-visual integrations.

When repeated content creates ambiguity, narrow to a semantic container, then query within it with within in React Testing Library or locator chaining in Browser Mode.

If an interactive control cannot be found semantically, first check whether the production markup needs a real button, link, label, landmark, or accessible name.

  • In React Testing Library tests, use a userEvent.setup() instance inside the test. Use fireEvent only when the low-level event itself is the contract.
  • In Browser Mode, interact through awaited locators. Use .element() only for DOM APIs that locators do not expose; it does not wait, so await the element with expect.element first.
  • Semantic queries and automated checks do not constitute complete accessibility conformance.
  • Exact copy assertions are valid when the copy or translation key is the contract; otherwise prefer a semantic query or resilient match.
  • In React Testing Library, use queryBy* for synchronous absence, findBy* for asynchronous appearance, and waitForElementToBeRemoved or waitFor for asynchronous disappearance. In Browser Mode, use expect.element for eventual assertions.

Mock at Real Boundaries

Keep the production code that owns or transforms the asserted behavior real. Mock only dependencies outside the target contract, where isolation improves the signal:

  • Service and network boundaries.
  • Next.js navigation or browser APIs not provided by the test environment.
  • External SDKs and expensive providers.
  • Independently tested child boundaries that do not own or transform the asserted behavior and whose setup would otherwise dominate the owner test.

Mocks must preserve the public contract needed by the test. Do not mock interactive Dify UI primitives or feature-owned wrappers around them. Keep their semantic roles, state attributes, portals, focus behavior, and render(props, state) contract real; mock only service or external-data boundaries needed to reach the scenario.

  • Never make real network requests.
  • Reset shared mock state before each test that mutates it.
  • Create a fresh TanStack Query client for tests that exercise query behavior.
  • Prefer typed builders with valid defaults for complex data. Add overrides only for fields relevant to the scenario.
  • Keep local mocks local. Move a mock helper to web/__mocks__/ only when multiple suites genuinely share it.

Async, Time, and Isolation

  • Await user interactions, promises, findBy*, and waitFor.
  • Wait for observable state changes. Do not use fixed sleeps or broad retries to hide incorrect timing.
  • Use fake timers only when timer behavior is part of the contract. Restore real timers after the test.
  • Control time, randomness, network responses, and shared stores so tests are deterministic.
  • web/vitest.setup.ts already runs Testing Library cleanup and resets Zustand stores after each test.
  • Vitest 5 clears mock call history before each test. This does not reset mock implementations or external state; set those up explicitly for each case. Do not use afterEach to prepare the next test.

Dify Test Setup

  • Following Vite+ testing configuration, tests under web/ use two explicit projects in web/vite.config.ts. Supported commands and CI select one project explicitly: unit runs in happy-dom and loads web/vitest.setup.ts, while browser runs matching {app,features}/**/*.browser.spec.{ts,tsx} files in Playwright Chromium and loads web/vitest.browser.setup.ts. Bare vp test runs both registered projects.
  • Browser string locators use Vitest 5's exact, case-sensitive matching. Use a regular expression or a per-locator { exact: false } only when partial matching protects the intended behavior. Node tests use @testing-library/jest-dom/vitest; a regular-expression check against rendered text can use expect(element.textContent).toMatch(pattern) when the Vitest 5 browser matcher types conflict with jest-dom's toHaveTextContent overload.
  • Tests in one browser file share a page. web/vitest.browser.setup.ts resets the viewport and pointer before each test; set the viewport a test depends on inside that test.
  • Browser failures keep screenshots and Playwright traces under web/.vitest-browser/. CI uploads that directory only when failure artifacts exist; Browser Mode does not own coverage or report merging.
  • New component and feature specs should generally use a sibling __tests__/ directory. Existing colocated utility and hook specs may follow their owning module's convention. Cross-feature integration specs belong in web/__tests__/.
  • The shared react-i18next mock is loaded globally. Use createReactI18nextMock from web/test/i18n-mock only when a test needs custom translations.
  • For nuqs behavior, use the helpers in web/test/nuqs-testing.tsx and assert URL updates. Mock nuqs only when URL synchronization is explicitly outside the test contract.
  • Do not add another test runner, DOM environment, or network interception library without a demonstrated project-level need.

Workflow

Use the behavior owner and nearby tests to identify a realistic regression and the assertion that would catch it. For a behavior change or bug fix, establish the failing case first when practical. Remove redundant tests and assertions as readily as adding missing coverage.

Run the focused spec and the affected suite when it adds coverage beyond that spec, plus the required static checks. Once these pass, broaden or repeat verification only for new changes, failures, or unresolved concerns. Diagnose CI-only failures from the failing job and reproduce them locally when possible; reruns do not replace diagnosis or reporting.

Commands

Run from web/:

bash
# happy-dom; omit the path to run the full unit project
vp test run --project unit path/to/spec-or-directory

# Browser Mode; omit the path to run the full browser project
vp test run --project browser path/to/spec.browser.spec.tsx

# Watch mode; select browser instead for Browser Mode
vp test watch --project unit path/to/spec

# Diagnostic coverage report for the unit project; not an acceptance target
vp test run --project unit --coverage path/to/spec-or-directory

Always pass --project unit or --project browser. Bare vp test runs both registered projects and is not the standard Web test command.

References


Web Docs Toasts (`web/docs/toasts.md`)

Toasts

A toast reports a result the user cannot see where they acted. It is the last choice for feedback, not the default completion signal of a mutation.

Choose the Feedback Owner

Before adding a toast, check in order:

  1. If the result is already visible where the user acted, add nothing.
  2. If the feedback can live at the trigger, such as a button state, an inline message, or a field error, put it there.
  3. Otherwise a toast is appropriate.

Show at most one toast for one user action. When an action succeeds with a warning, show the warning and not a separate success message.

Choose the Type

The type says whether the thing the user asked for happened.

Type Meaning Example
success It happened as asked, and the result is not on screen. An export finished; reindexing started.
warning It happened, but incompletely or with a side effect the user should know about. An import completed with warnings.
error It did not happen. A request failed.
info Something the user did not trigger happened, and it needs no response from the user. A collaborator restored a version of the shared workflow.

A toast is not the place to explain why an action is unavailable. When a precondition is not met, such as missing permission, a response still in progress, or a feature that is not available, prevent the action at the control instead: disable it, keep it focusable, and give the reason in a tooltip or inline text next to it.

Success

Do not show a success toast when:

  • A switch, select, segmented control, checkbox, toggle, or rating control shows the new value itself. After a failed request the control must show the server value again.
  • A button copies content. Show the copied state on the button. For an icon button use CopyFeedback, which changes the icon, the tooltip, and the accessible name.
  • The created, changed, or removed item is visible on the current surface, whether the action ran inline, from a menu, or through a dialog that closed.
  • The action navigates to the item it just created, or the page reloads right after.

A success toast is appropriate when the result is not on screen: a background job started, an import, export, or download finished, a save left the page looking the same, or the action left the page that showed its subject, such as deleting an item from its detail page. The message must name what happened. Do not use generic messages such as “Action succeeded” or “Modified successfully” in new code.

Errors

  • When a request fails and the server returns an error message, the request layer shows that message unless the request is silent; see afterResponseErrorCode in request layer. Do not add a second toast for the same failure in catch or onError.
  • To present a request error differently, make the request silent ({ context: { silent: true } } for generated clients) and show the error inline. A silent request with no other error presentation fails without any feedback.
  • Failures that never reach the request layer, such as a rejected clipboard write or a client-side exception, still need their own feedback.
  • Client-side validation belongs at the field through the form contract, never in a toast.

Existing Code

Many existing calls predate these rules and are migrated in batches. Do not copy them into new code, and do not remove an error toast without confirming the request layer covers that failure.


Web Docs Truncated Text Disclosure (`web/docs/truncated-text-disclosure.md`)

Truncated Text Disclosure

Treat native title as an opt-in, supplemental product behavior. Do not treat it as a mechanical companion to truncate, text-overflow, or line-clamp-*.

Browser-rendered title tooltips are exempt from the author-controlled hover and focus behavior in WCAG 1.4.13, but that exception is not an accessibility endorsement. MDN documents unreliable access for touch, keyboard, and assistive-technology users. The classifications below decide whether to add title; they do not establish WCAG conformance for the surrounding interaction.

Missing title is not by itself an accessibility defect. Native title tooltips must not:

  • be the only way to access essential information;
  • replace a visible label, accessible name, or accessible description;
  • compete with an existing hover, focus, pointer, expand, copy, or detail interaction.

For automated title additions, trace the displayed value, final DOM element, and existing disclosure owner. Apply SKIP, COVERED, AUTO, and REVIEW in that order; add title only for AUTO candidates.

These classifications limit automatic title additions. For a requested disclosure fix, continue with the appropriate feature-owned interaction. REVIEW calls for resolving the disclosure design; it does not require stopping an already authorized fix or asking for approval of routine implementation choices.

AUTO

Automatically add title only when every condition below is satisfied:

  • The target is a native, non-editable, pointer-reachable text container whose own hit area receives the pointer, or a documented component that forwards title unchanged to that final DOM element.
  • The final element intentionally implements single-line truncation. A truncation-related class alone is not sufficient evidence.
  • The full content is a bounded, non-sensitive, single-line plain string.
  • The truncated portion is supplemental; users do not need it to understand, distinguish, or complete the current task.
  • “Bounded” means fixed text, an enum, or a value with an explicit owner-level maximum length.
  • The exact already-evaluated display value can be reused without repeating a function call, getter, conversion, mutation, async operation, or other potentially effectful expression.
  • The final rendered element does not already receive an equivalent title through its props, wrapper, child component, or covering interaction target.
  • No Tooltip, Popover, expandable content, “show more” action, detail view, copy/reveal action, or other full-content owner exists. A PreviewCard counts only under the COVERED rule below.
  • The native tooltip will not compete with another hover, focus, pointer, or keyboard interaction.

COVERED

Classify as COVERED and make no change when the full content is already available through the current content, an accessible interaction, or a linked destination. An overlay is not automatically a disclosure owner:

  • a Tooltip only when it duplicates non-essential full text already available from its trigger's readable text or accessible name;
  • a PreviewCard whose trigger is a real destination link and whose destination contains the equivalent full content; the preview popup itself is only a visual enhancement, not the disclosure owner;
  • a Popover that exposes the full content through pointer, keyboard, touch, and assistive technology;
  • expandable or “show more” content;
  • a detail view opened from the current surface;
  • a copy or reveal action;
  • a parent or covering interaction target that already provides the equivalent title.

SKIP

Classify as SKIP and make no change when any condition below applies:

  • The value contains or may contain a secret, token, API key, password, credential, or other sensitive data.
  • The value is unbounded user content, multiline content, a comment, prompt, generated output, log body, or another potentially large string.
  • The visible content is JSX, ReactNode, structured content, or would require a stringification helper.
  • Producing the title would repeat or relocate evaluation of a function call, getter, conversion, mutation, async operation, or other potentially effectful expression.
  • The element is an input, textarea, editable surface, pointer-events-none, covered by another element, or not the actual pointer target.
  • An existing title, including title="", would need to be overwritten or removed.

REVIEW

Classify a proposed automatic title addition as REVIEW and explain the unresolved disclosure requirement when:

  • the correct disclosure owner is ambiguous or product-specific;
  • users need the full value to understand, distinguish, or complete the task, but no cross-input disclosure owner exists;
  • the value bound or sensitivity cannot be proven;
  • the final DOM element or pointer owner cannot be traced;
  • the component is interactive;
  • Tooltip or PreviewCard content would be the only path to the full content, or a PreviewCard trigger is not a destination link;
  • a Popover or other disclosure cannot be reached across pointer, keyboard, touch, and assistive technology;
  • the content uses line-clamp-* without an existing full-content path;
  • actual truncation or the intended product behavior cannot be established from the owner contract.

Before adding title to a custom component, inspect its implementation and trace the prop to the final DOM element. A value, label, or similar prop may already provide the native title; do not add a duplicate at the call site.

Do not introduce:

  • a repository-wide missing-title lint error;
  • a mass autofix or migration;
  • a ReactNode-to-string helper;
  • suppressions for candidates outside the allowlist.

Test the feature-owned disclosure behavior through its public interface. Assert native title only when it is an explicitly accepted product contract. Do not use getByTitle or toHaveAttribute('title', ...) merely to prove a migration, and do not use title-based selectors to test unrelated interactions.


Web Docs Webapp Document Gate (`web/docs/webapp-document-gate.md`)

WebApp document availability gate

The optional Proxy gate checks default /chat/:code, /chatbot/:code, /workflow/:code, /completion/:code, and /agent/:code addresses before Next starts rendering. It does not replace Gateway checks on subsequent API requests. Environment/Enterprise address routing is unchanged.

Configure both server-only variables:

  • WEBAPP_ACCESS_PREFLIGHT_URL: the fixed internal Gateway /api/webapp/access-mode endpoint. Do not point it at Core or a public redirecting origin.
  • WEBAPP_ACCESS_PREFLIGHT_PROXY_SECRET: a random shared ingress secret. Do not use a NEXT_PUBLIC_ variable, commit its value, include it in logs, or expose it in a response.

Every ingress location that forwards documents to Web must overwrite, not append or preserve, X-Dify-Webapp-Client-Ip with its validated visitor address and X-Dify-Webapp-Proxy-Secret with this secret. The ingress must itself have an explicit trusted-proxy policy; an arbitrary inbound XFF/CF header is not evidence of visitor identity. Web should not have an unprotected public port.

Web verifies the proof with a constant-time comparison and validates a single IP, then creates a fresh Gateway request with only Accept and a one-address X-Forwarded-For. Gateway must trust the Web peer's network and resolve the forwarded address using its existing trusted-hop policy. Original XFF, Forwarded, CF headers, Authorization, Cookie, and ingress proof are not forwarded. The URL is configuration-owned; request queries cannot select another upstream or supply an IP.

An unset URL leaves self-hosted routing unchanged. Once configured, missing/invalid attestation, timeout, redirects, invalid payloads, and dependency failures produce a non-cacheable 503. They are not application-not-found responses. Only the canonical Gateway/Core 404 app_not_found produces the existing generic unavailable page, with a 404 status fixed before rendering and Cache-Control: no-store. The allow path retains existing rendering and authentication behavior.

The internal /webapp-unavailable destination has no application lookup, uses no caller-supplied query state, and is always a 404. Proxy clears its internal IP header on every request, including direct visits. Only a verified denial can populate that header. Locale resources are provided for server rendering; the existing error-page UI remains the owner of language selection, appearance, and navigation.

Validation must include real Next HTTP requests, not only an assertion on NextResponse.status: verify document status, absence of redirect, non-cacheability, matching missing/denied body, and unchanged allowed rendering. API availability and the edge trust configuration must be deployed before enabling these variables. Do not enable them globally in an environment whose Gateway does not route /api.


Packages Dify Ui Docs Accessible Names And Descriptions (`packages/dify-ui/docs/accessible-names-and-descriptions.md`)

Accessible Names and Descriptions

This cross-component contract is owned by Dify UI. It applies to Dify UI primitives and to
consumers composing those primitives. It depends only on Dify UI component contracts and upstream
web standards; application packages may add localization, testing, and product-specific rules
without redefining this contract.

Base UI accessibility owns the primitive mechanics it implements, such as roles, relationships,
keyboard interaction, and focus management. Dify UI and its consumers still own the final element,
label content, composition, and product meaning. Use this guide to choose those naming and
description sources. Open a component guide only when the decision reaches that component.

Use ARIA in HTML for authoring conformance and the name and description computation
specification
to understand the current computation model. APG and MDN provide authoring
guidance; Base UI documents the behavior and usage guidance of the primitives Dify wraps. The Dify
conventions below choose among valid options without making a prohibited naming relationship valid.

Start Here

An accessible name is the flat string that identifies a named element to assistive technology; not
every role permits one. An accessible description adds optional help, instructions, or consequences.
State such as checked, expanded, or disabled remains separate from the name, and changing status
remains with the feature's status or live-region owner.

For each changed element:

  1. Inspect the final rendered element, role, text, and props forwarded by its primitive.
  2. Prefer meaningful visible text or a native label relationship.
  3. Use aria-labelledby when suitable visible text exists elsewhere in the DOM.
  4. Use aria-label only when the role permits naming and no visible text can provide the name.
  5. Add aria-describedby only for useful supplemental text; do not repeat the name.
  6. Verify the computed name and description in every changed responsive and interaction state.

These choices follow the W3C APG naming techniques and MDN aria-label guidance. Nearby
text is not a label relationship by proximity alone.

Common Decisions

Surface Contract
Text button or link Let meaningful child text name the action; do not repeat it in aria-label. Follow Button when a focused loading button changes its label.
Form control Follow Forms. Use its label primitive or an associated native label, preserving label activation.
Icon-only command Follow IconButton. Its component-specific contract requires one accessible-name source and a decorative glyph.
Dialog or named region Reuse the visible title through the primitive title API or aria-labelledby; use aria-label only when no suitable visible title exists.
Related form-control group Follow Forms. Use Fieldset with FieldsetLegend and preserve each control's own label. Other composite widgets follow their owning primitive.
Table or figure Prefer caption or figcaption when appropriate. See the APG caption guidance for name and description differences.
Image Supply meaningful alt, or alt="" for a decorative image.
Plain div or span Keep readable content; do not add aria-label or aria-labelledby to the default generic role.

Naming permission comes from semantics, not the presence of an aria-* prop. Other roles also
prohibit naming. Do not invent a role merely to permit a label. A plain span may contain text
referenced by another element's aria-labelledby; that relationship names the referencing element,
not the span. Check ARIA in HTML for restrictions on the final element.

Names, Descriptions, and State

A description is optional when the name is sufficient. For a file action, the name might identify
the operation and file, while the description explains retention or recovery. Avoid repeating the
same sentence in both. See the name and description computation specification.

A name or description attribute is not a general announcement mechanism. Keep progress and
asynchronous updates with their existing feature owner. Follow Button for the narrower case of a
focused loading button whose visible label changes, and Forms for field error relationships.

Overrides and References

Authoring preference differs from computation priority. An aria-labelledby value with at least
one valid ID reference is evaluated first. If its computed text is non-empty, it takes precedence
over aria-label and normal native or content naming. If its result is empty, name computation
continues to lower-priority sources; do not rely on that fallback to excuse a broken reference. A
non-empty aria-label also overrides normal native or content naming; these sources are not
concatenated. See the computation steps.

  • With aria-labelledby, reference the intended text directly. Multiple IDs are read in attribute
    order; do not build chains of elements that each use aria-labelledby.
  • Overriding a button or link's content-derived name can suppress meaningful descendant content in
    its accessible representation. Preserve the necessary visible wording in the resulting name.
  • Inspect IDs generated by primitives before overriding them. Keep IDs unique across repeated rows
    and simultaneous dialogs, and ensure referenced nodes exist in relevant open, closed, and
    responsive states. Preserve existing description IDs when adding another relationship.
  • Do not use title, placeholder, or Tooltip content as the only naming source. Native title
    does not replace an intentional name or description relationship.

Write Useful Names

Keep the visible label's wording in the accessible name, preferably at the beginning. Add target
context when identical visible actions would otherwise be ambiguous. Matching visible words also
lets speech-input users invoke what they see. See WCAG Label in Name.

Use concise action or purpose wording. Avoid appending role words already announced by assistive
technology or duplicating state exposed by the control. Consumers own localization and pass the
complete localized text through public props or children; Dify UI primitives do not import
application i18n.

The following fragment assumes localized strings and owner-scoped unique IDs. It combines the
visible action with the file it affects:

tsx
<>
  <span id={fileNameId}>{fileName}</span>
  <Button aria-labelledby={`${deleteLabelId} ${fileNameId}`}>
    <span id={deleteLabelId}>{deleteLabel}</span>
  </Button>
</>

Associate Descriptions

Use aria-describedby to associate concise help or consequences with a named control. The
referenced content becomes a plain string: headings, lists, and interactive links do not retain
their structure in the description. Keep rich instructions reachable as normal content or through
the Overlay contract. aria-details may supplement structured content where supported; it does
not replace that reachable content. See MDN aria-describedby guidance.

In Dify fields, compose FieldDescription and FieldError with the appropriate label and control.
These primitives own their relationships, including invalid-state feedback. Do not overwrite them
with a second label or a competing error association:

tsx
<Field name="fileName">
  <FieldLabel>{fileNameLabel}</FieldLabel>
  <Input required />
  <FieldDescription>{formatHint}</FieldDescription>
  <FieldError match="valueMissing">{requiredMessage}</FieldError>
</Field>

Use DialogTitle and, when useful, DialogDescription for a short dialog summary. Do not turn a
whole form or rich dialog body into one description. Tooltip content is not the trigger's
accessible-name source: icon-only triggers still need their own name, while persistent visible
trigger text should continue to name the control.

Prefer descriptions associated with DOM text. When considering aria-description, verify target
browser and assistive-technology behavior. The AccName 1.2 working draft gives
aria-describedby precedence over aria-description, followed by applicable native description
sources and unused title fallback. It specifies using only the first applicable source, even when
that source computes to an empty description. Do not stack mechanisms to force repeated output.

Hidden Text and Safe Removal

  • sr-only hides text visually while retaining it for assistive technology. It can contribute to
    a content-derived name or serve as a referenced label or description. A standalone span does not
    name a sibling control, and sr-only is not an automatic replacement for aria-label.
  • hidden, display: none, visibility: hidden, and aria-hidden="true" normally exclude content
    during name calculation. Explicitly referenced hidden nodes can still contribute; inspect the
    reference and its subtree instead of assuming all hidden text is ignored. See the computation
    steps
    and description reference.
  • Before removing a label, inspect the resulting name and description in collapsed navigation,
    responsive icon-only layouts, loading, and disabled states. CSS truncation alone does not remove
    underlying text. Preserve primitive relationships and necessary status information. Add hidden
    text only when information would otherwise be missing.
  • Verify observable names, descriptions, and keyboard behavior at the changed boundary. Follow the
    test policy owned by that package or consumer. Dify UI changes follow Package testing; complex
    overrides may also require inspecting the rendered accessibility tree and relevant screen-reader
    behavior.

Packages Dify Ui Docs Authoring (`packages/dify-ui/docs/authoring.md`)

Public API Authoring

Each src//index.tsx is an explicit public API boundary. Keep implementation details
module-local and publish the complete surface through separate export { ... } and
export type { ... } manifests at the bottom of the file. Do not mix scattered inline exports
with the manifest or use wildcard exports.

Base UI imports

Import a Base UI part once per module and read its types from that binding's namespace, such as
BaseRadio.Root.Props. Use import type only when the module has no runtime use of the part. Do
not keep a value import and a type import of the same module side by side.

Add a public utility subpath only when an application consumer needs it. Inside the package,
use an existing utility entrypoint; otherwise import directly from @base-ui/utils.

React imports

Use React namespace imports throughout this package, including stories and tests. Use
import * as React from 'react' when calling React runtime APIs, and
import type * as React from 'react' when referencing only React types. A runtime namespace
import also covers React types; do not add separate named type imports. JSX alone does not
require an explicit React import.

Use namespace imports for react-dom, react-dom/client, and react-dom/server as well.
Write grouping fragments as <React.Fragment> and remove unnecessary fragment wrappers.

Component writing style

Define named components with function declarations or function expressions. Arrow functions
remain appropriate for event handlers, render props, and Storybook render callbacks. Name function
expressions when JavaScript cannot infer their name. Use event or error instead of e.

Subpaths and names

Every public primitive needs a matching package.json#exports subpath. Import relatively between
package components; consumers import only through public subpaths.

Keep package-private helpers in src/internal/; top-level runtime utility modules in src/ are
public utility subpaths. Components share code through the owning component's entrypoint or an
explicit internal module, not another component's implementation files.

Use the primitive name without a Root suffix for the canonical boundary and matching props type:
Select and SelectProps, Drawer and DrawerProps.

Every runtime component must have an accurate, importable props type with the matching name. Use a
direct alias for an unchanged Base UI part. Define Dify-authored composite props at the Dify UI
boundary instead of copying upstream shapes.

Use a discriminated union when one prop changes the valid shape of related props, such as
controlled versus uncontrolled state or single versus multiple selection.

Generic contracts

Preserve generic relationships end to end, including picker Value and Multiple, form values,
radio and slider values, and overlay payloads or handles. Do not erase caller-owned types with
any or a hard-coded string. Use unknown only as the safe default for independently consumed
anatomy whose value JSX cannot infer from its parent.

Do not add a root-only generic when separately rendered anatomy can produce values outside the
root's inferred type. Preserve the upstream contract until the whole component family can enforce
one value type. Tabs intentionally follows Base UI's non-generic root because its current tab
value type is any | null; do not advertise a type relationship the complete anatomy cannot
enforce.

Preserve upstream anatomy when its parts own distinct semantics, interaction, or positioning.
Create a Dify-authored convenience component only when the package adds a shared contract; do not
hide primitive parts merely to shorten a consumer call site.

Keep the public surface small

A type is not public merely because Base UI names it or an implementation once exported it. In
addition to matching component props, export a type only when it pairs with a public factory or a
real consumer must name it independently.

State, controlled-state helpers, context values, render helpers, styling helpers, and upstream
passthrough aliases are private by default. Public props already provide contextual typing for
inline render and event callbacks. Expose styling helpers only when consumers need to reuse
appearance independently.

Event details and reasons are the exception. A component that aliases or wraps a Base UI part
re-exports that part's *EventDetails and *EventReason types under its own name. A composite
that only uses a part internally does not. State and enum namespaces stay private.

Preserve upstream className and style callbacks. Resolve className with the owning Base UI
part's state before merging default classes with cn(), including through composite wrappers.
Forward style unchanged unless the wrapper needs to merge styles; then resolve its callback first.
Do not add state callbacks to native DOM props or unrelated custom APIs. See Styling.

Evidence

Use local public-subpath type tests to protect generic inference, required relationships, and
intentional errors. Read current official Base UI documentation and installed type declarations
before changing an upstream-derived contract.


Packages Dify Ui Docs Forms (`packages/dify-ui/docs/forms.md`)

Forms

Dify UI form primitives compose Base UI's native form semantics, field accessibility, and Dify
styling. They are not a form state-management or schema framework. See the Base UI forms
handbook
for the upstream model.

Submit boundary

Every group of controls that saves or submits together needs a real <form> boundary. Do not wire
an Input and a click-only Button together as an informal form.

Use Form when the Dify UI boundary should own Base UI's structured onFormSubmit values,
consolidated errors, actionsRef, or validationMode. It renders a native <form>. A native form
remains correct when another form library owns submission and validation; do not nest form owners.

Set Button submit buttons to type="submit" explicitly. Keep every other button inside a form
at type="button".

Value and state ownership

Form owns the submission and validation boundary described above, not each field's draft.

Choose controlledness from source-of-truth needs, independently from where a draft is stored.
Prefer defaultValue when application React code does not need to own the current value. Use
value and change handlers when application rendering or coordination must own it while editing.
Listening to change events, tracking dirty state, and native or primitive validation do not by
themselves require controlled state.

Application code owns the draft in the narrowest component whose lifetime matches it. A value can
be controlled locally without being lifted. An uncontrolled field can participate in a persisted
workflow when that workflow captures its value at an explicit persistence boundary. The
surrounding surface defines its mount lifecycle; owner placement determines whether draft state
lives inside or outside that lifecycle.

Fields and labels

Use Field when a control needs a shared name, label, validation, description, or error state. A
standalone Input may use a native <label htmlFor> relationship, but normal form rows should
prefer a visible label. FieldDescription and FieldError provide the corresponding accessible
message relationships.

Choose the label primitive by the control:

  • Text-like inputs, Textarea, input-based Combobox and Autocomplete, a single Checkbox,
    each Radio option, Switch, and NumberField use FieldLabel.
  • Trigger-based Select fields use SelectLabel.
  • Date/time pickers use their own DatePickerLabel, TimePickerLabel or DateTimePickerLabel
    to focus the trigger without opening it. They currently support native forms, not Base UI
    Field/Form registration; see the picker field contract.
  • Slider fields follow the Base UI Slider anatomy and use SliderLabel; only multi-thumb
    sliders add per-thumb aria-label to distinguish the thumbs.
  • SelectGroupLabel and AutocompleteGroupLabel label option groups inside popup content. They
    are not field labels.

Use InputGroup when a prefix, suffix, or action shares the input's visual surface.

Grouped controls

Use Fieldset and FieldsetLegend when one field contains related controls, such as checkbox or
radio groups, multi-thumb sliders, or a section of related inputs. Wrap each checkbox or radio
option with FieldItem and give it its own label:

tsx
<Field name="allowedNetworkProtocols">
  <Fieldset render={<CheckboxGroup />}>
    <FieldsetLegend>Allowed network protocols</FieldsetLegend>
    <FieldItem>
      <FieldLabel className="flex items-center gap-2">
        <Checkbox value="https" />
        HTTPS
      </FieldLabel>
    </FieldItem>
  </Fieldset>
</Field>

Fieldset owns group semantics and the legend relationship, not interactive state. Pass
disabled, value, defaultValue, and change handlers to the group primitive.

Every radio belongs to a RadioGroup. Use FieldsetLegend to name the group and FieldLabel to
name each option; do not render a standalone Radio.

Keep form state, schemas, server validation, and reset behavior outside the primitive internals,
in the nearest application owner with the required lifetime. Pass observable state through the
public field and control props instead of replacing the semantic structure.


Packages Dify Ui Docs Overlays (`packages/dify-ui/docs/overlays.md`)

Overlays

Dify UI overlay primitives own their Base UI portals, normal application layer, positioning,
focus, modal behavior, and dismissal contracts. Consumers choose the semantic primitive and
compose its exported anatomy instead of recreating those responsibilities.

Portals and root isolation

Floating surfaces render through Base UI Portal into document.body. Convenience components
such as DialogContent, PopoverContent, and SelectContent own their portals internally;
primitives with explicit anatomy expose the constituent portal and content parts.

Mounting and state lifetime

An overlay root's React lifetime, its open state, and its portal subtree's presence are separate.
Presence is part of each primitive's contract. Convenience content follows its primitive's
default mount behavior; for example, DialogContent owns a Dialog.Portal whose subtree mounts
when the dialog opens and unmounts after any close transition completes. The Dialog root may
remain mounted and controlled independently of that content lifetime. Removing the controlled
root with the same condition that closes it bypasses the primitive's closing lifecycle.

Application code can use an unmounting content subtree as the owner of state scoped to one mounted
content session. State that must survive the subtree's unmount belongs to an explicit longer-lived
feature owner.
Unmounting resets only DOM and component state owned inside that subtree; state declared by an
ancestor or external store survives. Portal placement alone is not a reset boundary.
Consumers using explicit anatomy may opt into keepMounted where that portal supports it; they
must then define which state persists and which state resets instead of relying on a remount.
Check the selected primitive's API rather than assuming every overlay portal has the same presence
options.

The host must establish an isolated stacking context at its application root:

tsx
<body>
  <div className="isolate">{children}</div>
</body>

Equivalent CSS is isolation: isolate. It creates a stacking context so
application descendants cannot use high z-index values to compete with sibling surfaces portalled
to body. Portalling avoids clipping by application ancestors; isolation itself does not fix
clipping.

Layering

Overlays set no z-index; portal DOM order stacks them. A Base UI modal blocks outside clicks with
an unstyled sibling of its popup, so any overlay z-index can lift a lower layer above that guard.
Only a body-level layer that must stay above overlays mounted after it sets one. A portal into an
application container sits inside the isolated root and layers against its siblings there.

Positioners hide with their anchor: Base UI marks them data-anchor-hidden when the anchor is
clipped, display: none or unmounted, and the shared positioner class turns that into
visibility: hidden plus pointer-events: none so a popup never lingers at the viewport origin.

  • Do not add call-site z-* overrides or force a backdrop to block clicks. Fix the owning overlay
    structure when content is clipped, hidden, or clickable behind a modal.
  • Do not wrap a Dify UI overlay in another manual portal.
  • Add shared backdrop or presentation chrome inside the owning exported component, not at call
    sites.

Primitive semantics

  • Use Dialog for modal content that needs focus containment and scroll locking. DialogContent
    is the centered modal surface: compose DialogHeader, DialogBody and DialogFooter in it, and
    DialogBody scrolls between the other two. A wrapper between the surface and its parts, such as
    a form, keeps the flex chain with contents. DialogPopup is the bare dialog element for a
    surface that places and dresses itself.
    DialogContent and AlertDialogContent allow transition-none, including state variants,
    without requiring custom popup composition.
    DialogHeaderCloseButton is the optional standard close icon inside DialogHeader; the header
    reserves inline-end space when it contains the button. Without it, the header keeps its normal
    gutters. Use the unstyled DialogClose with render for footer actions and custom close controls.
  • Use AlertDialog only for a destructive or must-confirm decision requiring an explicit answer.
    It blocks outside-press dismissal but still closes on Escape; cancel that close in
    onOpenChange when the answer must be explicit. AlertDialogHeader holds the title and
    description; anything the user fills in or reviews before answering goes in AlertDialogBody.
  • Use Drawer for side-panel interactions that follow the drawer model.
  • Use DropdownMenu for button-triggered action lists and ContextMenu for context actions.
    A long action list filters with DropdownMenuFilterProvider; choosing a value is
    Combobox in Selection.
  • Use Tooltip for a supplementary visual label on a control that already has a primary
    action and an accessible name. Use Infotip when the information icon's action is to open
    the explanation. Text length alone does not determine the component. Follow the
    Infotip contract for its composition and accessible names.
  • Use PreviewCard as a non-interactive enhancement for a link destination. Essential
    information must also exist without the preview.
  • Use Popover for explanatory, structured, or interactive content that users must reach on
    touch or with assistive technology.

Use a real `` for button-like triggers. If a Base UI trigger intentionally
renders a non-button element, set nativeButton={false}. Let the primitive own placement and
spacing unless its API documents a measured exception.


Packages Dify Ui Docs Selection (`packages/dify-ui/docs/selection.md`)

Selection

Choose a selection primitive from the value and interaction contract, then preserve the caller's
domain value type through its public API.

Primitive choice

  • RadioGroup selects one persistent field value from a visible set of options. Every Radio or
    RadioItem belongs to a group; do not render a standalone radio.
  • SegmentedControl selects one mode, filter, or view. It follows radio-group semantics: an active
    item cannot be toggled off, Tab enters on the selected item, and arrow keys move and select.
  • Tabs selects a panel and provides tablist and tabpanel semantics.
  • Autocomplete accepts free-form text with optional suggestions.
  • Combobox selects and remembers one or more values from a searchable collection.
  • Select chooses from a closed, scannable list without text entry.
  • Date and time pickers select civil dates, wall times or instants. Their fixed value models
    do not use collection generics; the family guide owns anatomy and commit semantics.

Multiple-selection comboboxes follow the Base UI chips composition: chips and the input share the
input group, chips wrap, and the group grows vertically.

For chip-based multiple comboboxes, render ComboboxValue around ComboboxChips and label the
chips container only while it has the conditional toolbar role. Consumers must localize the
ComboboxChip Backspace/Delete description, the item-specific ComboboxChipRemove name, and the
input's selection count and Left Arrow hint. If FieldDescription already sets aria-describedby,
put the input hint there because it takes precedence over aria-description.

Autocomplete, Combobox, and Select popups use Base UI's --anchor-width and --available-width
variables to follow their trigger while clamping to the viewport. Do not replace that sizing with
a fixed width or an unclamped minimum width.

When a Combobox renders its input inside the popup, do not add a control that clears the typed
query. The query is per-open state that Base UI resets: choosing an item clears it in multiple
mode and closes the popup in single mode, and closing the popup (Escape, outside press) clears it.
A clear control there adds a second tab stop to the popup's focus loop and a second x that means
something other than ComboboxClear, which clears the selected value. Outside the popup, use
ComboboxClear or AutocompleteClear.

Use Radio for the default radio appearance. Use RadioItem when custom content itself is a
radio item, and put RadioControl inside it for Dify UI's visual indicator. RadioControl is a
visual part, not a standalone radio.

Import the complete family from its single public subpath:

tsx
import { Radio, RadioControl, RadioGroup, RadioItem } from '@langgenius/dify-ui/radio-group'

Typed values

Do not widen domain values to string. Use Select<Value, Multiple>, RadioGroup<Value>,
Radio<Value>, and RadioItem<Value> for enums, unions, booleans, numbers, objects, or nullable
placeholder values.

Root generics type value, defaultValue, and value-dependent callbacks. JSX children do not
inherit the parent's generic, so type independently consumed anatomy when its value cannot be
inferred locally:

tsx
<RadioGroup<PromptMode> value={promptMode} onValueChange={setPromptMode}>
  <Radio<PromptMode> value={PROMPT_MODE.default} />
  <RadioItem<PromptMode> value={PROMPT_MODE.custom}>
    <RadioControl />
    Custom prompt
  </RadioItem>
</RadioGroup>

For Select and Combobox, the literal multiple-value type must match runtime mode:
<Combobox<Subject, true> multiple>. Value display can still receive null before selection.
Repeat the domain type on independently consumed render anatomy rather than annotating callback
parameters:

tsx
<Combobox<Subject, true> multiple value={subjects} onValueChange={setSubjects}>
  <ComboboxValue<Subject, true>>
    {(selected) => selected?.map((subject) => subject.name).join(', ') ?? 'Anyone'}
  </ComboboxValue>
  <ComboboxList<Subject>>
    {(subject) => <ComboboxItem value={subject}>{subject.name}</ComboboxItem>}
  </ComboboxList>
</Combobox>

AutocompleteList follows the same rule. Groups may infer their local type from items; a nested
Collection is a separate JSX boundary. Dynamic multiple={condition} produces the corresponding
single-or-multiple union.

Prefer the Base UI items collection pattern so the root, value display, and item list share one
runtime source of truth. Convert values to strings only at real serialization boundaries.

Treat collection values exposed for rendering as read-only views. In multiple mode, SelectValue
may receive a shared frozen empty array, and useAutocompleteFilteredItems exposes internal
filtered state. Use non-mutating transforms such as map, filter, or toSorted; create an
explicit copy only when a mutable array is required.

Combobox source items and selected values

Combobox has separate types for the selected business value and the source record rendered by the
list:

tsx
import {
  Combobox,
  ComboboxItem,
  ComboboxList,
  createComboboxItems,
} from '@langgenius/dify-ui/combobox'
import { useMemo } from 'react'

const userItems = useMemo(
  () =>
    createComboboxItems(users, {
      getValue: user => user.id,
      getLabel: user => user.name,
    }),
  [users],
)

<Combobox<string, true, User>
  multiple
  items={userItems}
  value={selectedUserIds}
  onValueChange={setSelectedUserIds}
>
  <ComboboxList<User>>
    {user => <ComboboxItem<string> value={user.id}>{user.name}</ComboboxItem>}
  </ComboboxList>
</Combobox>

The first generic is Value, the second is the literal multiple-selection mode, and the third is
the source Item. ComboboxValue and ComboboxItem use Value; filter, ComboboxList,
ComboboxGroup, ComboboxCollection, and useComboboxFilteredItems use source items. Grouped
roots use the leaf record as Item, while the list callback receives the group object.

Use createComboboxItems when the business contract stores a stable primitive ID but list rows
need complete records. Its getValue result must be unique and stable, and getLabel owns default
filtering, typeahead, and selected-value display. Create static collections at module scope and
memoize collections derived from changing data. Treat the returned collection as opaque and pass
it directly to items.

For server-side search, keep the complete set of records needed to resolve selected labels in the
collection passed to items, and pass the current result window to filteredItems. Filtered items
are source Item records, not derived IDs, and grouped results must retain the collection's group
shape.

Keep object values when the selected record itself is the business state or the selection callback
immediately needs the full record. When async refreshes may replace object references, provide
isItemEqualToValue using the stable domain identity.

itemToStringValue only serializes a selected Value for forms and autofill; it does not change
onValueChange into an ID callback. Do not add it, itemToStringLabel, or a comparator as a
mechanical trio. Primitive IDs normally use the default equality. For async or paged data, keep
selected records in the collection when their labels must remain available after they leave the
current result window, or provide an ID-only label fallback.

CheckboxGroup follows Base UI and uses string[]. Model stronger business ID distinctions at
the domain boundary unless the upstream primitive contract changes.


Packages Dify Ui Docs Styling (`packages/dify-ui/docs/styling.md`)

Styling

Component state

Prefer the primitive's data attributes for state styling, such as data-checked: or
data-disabled:. Use its CSS variables for exposed dynamic values, such as popup anchor width
and available height. Do not mirror primitive state in React solely to style it.

Field validity has three states: data-valid, data-invalid, or neither before validation.
not-data-invalid includes the unvalidated state; it is not equivalent to data-valid. Preserve
existing interaction variants when adding error styles so call-site overrides keep merging.
Disabled surfaces take precedence over invalid and read-only appearance. Keep invalid state and
error associations intact while limiting error colors to enabled controls.

Where supported by the upstream part, className(state) and style(state) read that part's state.
At call sites, before using a callback or React state to calculate styles, check whether data attributes or CSS
variables already express the requirement. When direct state access is needed, add a short comment
explaining why; for example, Tooltip and Popover can share data-popup-open on one trigger while
the style needs only Popover's open state. This does not restrict conditional rendering of content.

Composite content forwards these callbacks to its styled part: for example, PopoverContent
receives Popup state, not Positioner state. Native DOM props and custom convenience APIs do not
automatically support state callbacks.

Use render for element composition, not merely to change styles. A callback on PopoverTrigger
reads Popover state; one on a standalone Button reads Button state. Composition does not change
which state a part owns.

With render={}, Base UI automatically merges the target's props without resolving
its callbacks. Put callbacks on the outer primitive and use class strings and style objects on
that target. With render={(props, state) => ...}, forward the received props and ref, and explicitly
merge any custom classes, styles, or handlers. Do not switch to this form merely for state styling.
See Base UI's styling and composition guides for the upstream contracts.

Tailwind CSS v4

Import Tailwind from the consumer's root stylesheet as described in the Tailwind CSS v4 upgrade
guide
, then import the Dify UI CSS entry:

css
@import 'tailwindcss';
@import '@langgenius/dify-ui/styles.css';

When a workspace consumer scans Dify UI source directly, add an @source entry for the package's
src/ directory using Tailwind CSS functions and directives, resolved from that consumer
stylesheet:

css
/* Example only: resolve paths from this stylesheet. */
@source '../../../packages/dify-ui/src';
@source not '../../../packages/dify-ui/src/**/*.{spec,test}.{ts,tsx}';
@source not '../../../packages/dify-ui/src/**/*.stories.{ts,tsx}';

Border radius

Check the actual radius value in Figma before choosing a rounded-* class; matching token names
do not imply matching values. For example, radius/sm = 6px requires rounded-md, not
rounded-sm (4px). Prefer a standard Tailwind class with the matching value; use an arbitrary
value only when none matches, such as rounded-[10px] for 10px.

Use semantic Dify tokens and existing component variants before hard-coded values or repeated
primitive classes. Use an important modifier only for a tightly scoped compatibility override
after the owning variant, data attribute, and selector structure cannot express the state.

Scroll padding

An item scrolled into view, by the keyboard or on open, keeps the same inset from the visible edge
as it has at the ends of the list. Other rows may be clipped there; that shows more content follows.

Padding scrolls away with the content, so a scroll container with vertical padding around its items
sets matching scroll padding on the same element. Primitives own this pair. A call site adds the
height of a header or group label that must stay visible with the target item.

Cursor

A control does not set a cursor for its enabled state; the consuming app's base styles decide it.
A control sets a cursor only for a state it owns: not-allowed when disabled, the default arrow
when read-only, and the text cursor on a text entry area.

Focus indicator

src/internal/focus.ts owns the outer and inset focus-visible rings and the separated indicator
for checked controls. Both ring constants include focus-visible:outline-hidden; do not repeat
outline handling at their call sites. A package-wide interaction contract can have a shared style
owner; visual similarity alone is not a reason to share constants. Keep component-specific selectors local.

Controls own their focus indicator, so callers never write one. That includes every trigger that
opens a surface (Popover, DropdownMenu, Collapsible, Combobox, Dialog, AlertDialog, Drawer); they
share one ring. Rows inside a composite defer to its highlight. Parts that only attach behavior
(Tooltip, PreviewCard, and ContextMenu triggers, and Close parts) add no styles.

Text controls (Input, Textarea, InputGroup, NumberField, and the Combobox and Autocomplete input
groups) draw that ring on the visible field. It replaces the hover border, and an invalid field
keeps its border and fill inside it. Switch, Checkbox, and Radio leave a gap between the control and
the indicator, because their checked fill is the indicator color. DropdownMenuInputGroup is the
exception: Base UI marks Menu.Input with data-highlighted while the input holds the keyboard
highlight, so the group draws the ring on that state and drops it once the arrow keys move the
highlight into the list.

Attach the indicator to the element that visually represents focus. If a visible wrapper contains
the native focus target, select that descendant state from the wrapper; for example, SliderThumb
uses has-[:focus-visible] because its internal range input receives focus. Select
:focus-visible, except on a text control, which selects :focus because it shows focus however
it was reached.


Packages Dify Ui Docs Testing (`packages/dify-ui/docs/testing.md`)

Testing and Development

Run vp check packages/dify-ui from the repository root for formatting, lint, and TypeScript
diagnostics. Run the remaining commands from packages/dify-ui/:

  • vp test --project unit runs primitive unit tests.
  • vp run storybook starts Storybook.
  • vp test --project storybook --run runs Storybook component tests in browser mode.
  • vp test runs both test projects.

Test boundary

This guide owns the Dify UI testing policy and runtime setup. Add tests for observable Dify
integration behavior or a reproducible regression, not merely because a component or prop exists.
Check existing stories and tests before adding coverage. Browser execution alone does not justify
a new case; review incidental visual adjustments in Storybook without adding a permanent test.

The package has two Vitest projects. Both run in Playwright Chromium Browser Mode; the project
name identifies the behavior owner, not a different runtime.

Use Storybook for a documented component example. Every story is a render contract and runs the
configured accessibility checks through the Storybook Vitest addon. Add play when the example
also owns visible state changes, user interaction, keyboard paths, overlay flows, form behavior,
loading behavior, or controlled-state coordination.

Use regular Vitest tests for Dify integration behavior that does not need a documented example,
such as submitted values, store behavior, or a known regression reached through a public API.
Prop passthrough alone does not justify a test. Assert the resulting behavior instead of CSS class
names or private structure, and do not duplicate behavior already owned by Base UI or the browser.
Vitest 5 browser locators match string names exactly by default. Assert a control's accessible name
or description when that is the contract. toHaveTextContent also checks the full text exactly;
use toMatchTextContent only when the complete text is intentionally outside the test's scope.

Storybook accessibility testing uses a11y.test = 'error', so enabled violations fail the test.
Color contrast is the only globally disabled rule because it is a known design-token gap. Do not
add another global exception. Keep a temporary exception local to the affected story, and do not
use a play test in place of an accessibility fix.

Type contracts

Keep compile-only public API fixtures in __tests__/types.tsx; package type checking includes them
without registering runtime tests. Import public subpaths, verify useful inference with
expectTypeOf, and use @ts-expect-error for intentional API boundaries. Cover nullable callbacks,
value models and unsupported composition, not every forwarded prop. Runtime assertions cannot
prove TypeScript inference, and type fixtures cannot prove focus, DOM semantics or interaction.

A documented example and its play belong in one story; do not create an automatic duplicate just
to run the same render. Keep Docs autoplay off for examples that move focus or open portals. Retain
explicit open previews when needed for accessibility checks on popup content. Regressions that do
not teach a distinct usage belong in the unit project rather than extra sidebar entries.

Animation setup

Base UI can wait for element.getAnimations() before unmounting transition-driven components.
vitest.setup.ts sets BASE_UI_ANIMATIONS_DISABLED = true for primitive tests
that assert final DOM state. Storybook uses its preview setup and retains real animation lifecycles.
A unit test that intentionally asserts animation behavior may set the flag to false locally,
but must restore the previous value during cleanup.


Dify Agent Docs Dify Agent Guide Openshell (`dify-agent/docs/dify-agent/guide/openshell.md`)

OpenShell Runtime Backend

This guide covers OpenShell-specific configuration, deployment, and validation.
See the Operations Guide for shared server configuration and
scheduling behavior.

Configuration

ServerSettings loads environment variables with the DIFY_AGENT_ prefix. It
also reads .env and dify-agent/.env when present. Select
DIFY_AGENT_RUNTIME_BACKEND=openshell to use this backend. Shared settings,
including Agent Stub and file-service URLs, are documented in the
server configuration reference.

Environment variable Default Description
DIFY_AGENT_OPENSHELL_GATEWAY_ENDPOINT empty OpenShell gateway gRPC endpoint as host:port (no scheme); required for OpenShell. Prefer localhost over an IPv6 literal when the gateway listens on loopback.
DIFY_AGENT_OPENSHELL_WORKSPACE default OpenShell workspace that owns the sandboxes. Production multi-tenant deployments must use one workspace and one dedicated shared volume per tenant.
DIFY_AGENT_OPENSHELL_BEARER_TOKEN empty Static OIDC bearer token sent to the gateway. Combines with the mTLS bundle. The token is not refreshed in-process; restart agent_backend or switch to a long-lived token when it expires.
DIFY_AGENT_OPENSHELL_TLS_CA_PATH empty Custom gateway CA certificate path. Empty uses the system trust store.
DIFY_AGENT_OPENSHELL_TLS_CLIENT_CERT_PATH empty mTLS client certificate path; set together with the key path.
DIFY_AGENT_OPENSHELL_TLS_CLIENT_KEY_PATH empty mTLS client key path; set together with the certificate path.
DIFY_AGENT_OPENSHELL_INSECURE false Use a plaintext gRPC channel. Local development only.
DIFY_AGENT_OPENSHELL_SANDBOX_IMAGE langgenius/dify-agent-local-sandbox:latest Build the runtime image yourself from this checkout and explicitly set this to the resulting image reference. Do not rely on the code fallback or a published latest tag: older images may lack iproute2, which the OpenShell supervisor requires alongside shellctl. The env templates use the self-built docker.io/library/dify-agent-runtime:latest; see the build command below.
DIFY_AGENT_OPENSHELL_DRIVER_CONFIG empty JSON SandboxTemplate.driver_config; required for OpenShell and must be a non-empty object. Must mount the shared Home Snapshot volume at the shared mount path in every sandbox.
DIFY_AGENT_OPENSHELL_SHARED_MOUNT_PATH /mnt/dify-agent-shared In-sandbox mount path of the shared volume; Home Snapshots live under home-snapshots/<tenant-digest>/.
DIFY_AGENT_OPENSHELL_EGRESS_ALLOW empty Optional comma-separated host:port egress allowlist (no scheme or path). Empty sends no network policy (gateway/driver default egress). When set, sandbox egress is enforced to exactly these endpoints — include the Agent Stub and files endpoints.
DIFY_AGENT_OPENSHELL_SHELLCTL_AUTH_TOKEN empty Required bearer token the exec-bootstrapped shellctl expects on its data plane. Empty is rejected at startup.
DIFY_AGENT_OPENSHELL_SHELLCTL_PORT 5004 Sandbox-loopback port shellctl listens on; reached through the gateway ForwardTcp tunnel.
DIFY_AGENT_OPENSHELL_READY_TIMEOUT_SECONDS 300 Maximum wait for a sandbox to reach the READY phase.
DIFY_AGENT_OPENSHELL_EXEC_TIMEOUT_SECONDS 120 Timeout for gateway exec calls (bootstrap and maintenance scripts).

Deploy with the OpenShell backend

The OpenShell backend runs each Binding in its own sandbox on a self-hosted
NVIDIA OpenShell gateway. Dify Agent
only talks to the gateway gRPC API: it creates sandboxes from the configured
image, bootstraps shellctl through gateway exec, and reaches the shellctl data
plane through an authenticated ForwardTcp tunnel.

New Bindings are initialized and then stopped. Acquire starts a stopped sandbox
when needed, verifies its Home and Workspace, ensures shellctl is running, and
opens a fresh lease-local tunnel. Release closes only that lease's HTTP client
and tunnel; it does not stop the sandbox or shellctl. Subsequent operations can
reuse the running sandbox, and releasing one lease does not interrupt another
lease on the same Binding.

There is no automatic idle-stop or sandbox TTL in this adapter. After a
successful acquire/release cycle, the sandbox remains running until explicitly
stopped or destroyed, or a runtime failure stops it. Operators must account for
these running resources. Binding creation and failed-acquire cleanup retain
their existing stop behavior; this change only makes lease release lightweight.
Explicitly stopped sandboxes are restarted on the next acquire.

Backend selection lives in docker/.env; create it from the template first if
this deployment does not have one yet (cp docker/.env.example docker/.env).

Deployment prerequisites:

  1. An OpenShell gateway, version 0.0.106 or newer (validated against
    0.0.106–0.0.110; the bundled SDK is pinned >=0.0.106,<0.1.0), reachable
    from agent_backend at DIFY_AGENT_OPENSHELL_GATEWAY_ENDPOINT, with
    credentials via DIFY_AGENT_OPENSHELL_BEARER_TOKEN or the mTLS bundle
    paths. Prefer localhost:17670 when the gateway listens on loopback.
    Sandboxes reconnect to the gateway through host.openshell.internal; on
    macOS local development bind the gateway to 127.0.0.1:17670 so that
    alias can reach it.

  2. Sandboxes must reach DIFY_AGENT_STUB_API_BASE_URL and
    DIFY_AGENT_SANDBOX_FILES_BASE_URL. When the gateway runs outside this
    Compose stack, set both to externally reachable URLs; compose-internal
    hostnames are not resolvable from OpenShell sandboxes. When the
    deployment restricts sandbox egress, set
    DIFY_AGENT_OPENSHELL_EGRESS_ALLOW so the sandbox policy carries an
    enforced allowlist covering at least those two endpoints:

    text
    DIFY_AGENT_OPENSHELL_EGRESS_ALLOW=agent.example.com:443,dify.example.com:443

    Left empty (the default), the policy carries no network rules and egress
    follows the gateway/driver default — a stock Docker driver leaves sandbox
    outbound unrestricted, which agent-run tools (package installs, web
    access) may rely on. When set, egress is restricted to exactly the listed
    endpoints, from any in-sandbox binary.

  3. Build the runtime image yourself from the current checkout. It must
    bundle shellctl and iproute2. A published or cached
    langgenius/dify-agent-local-sandbox:latest is not a substitute: older images
    lack iproute2, causing the OpenShell supervisor to exit during startup.

  4. A required DIFY_AGENT_OPENSHELL_SHELLCTL_AUTH_TOKEN. shellctl is
    bootstrapped with SHELLCTL_ENABLE_PATH_ISOLATION=false because the
    sandbox Landlock policy is authoritative; stacking both would require
    re-granting every device path twice. The token still authenticates the
    in-sandbox command plane.

  5. A shared Home Snapshot volume mounted into every sandbox via
    DIFY_AGENT_OPENSHELL_DRIVER_CONFIG. Production multi-tenant deployments
    must use one OpenShell workspace and one dedicated volume per tenant:
    Landlock is best-effort and every sandbox runs as the same image UID, so a
    shared volume is a shared trust boundary. Snapshots are stored under
    home-snapshots/<tenant-digest>/; the sandbox policy grants only that
    tenant directory.

Build from the repository root (the directory containing dify-agent-runtime/):

bash
docker build -f dify-agent-runtime/docker/Dockerfile \
  -t dify-agent-runtime:latest dify-agent-runtime

Set the exact built image reference in dify-agent/.env for a local Agent
Backend process, or in docker/.env for Docker Compose:

ini
DIFY_AGENT_OPENSHELL_SANDBOX_IMAGE=docker.io/library/dify-agent-runtime:latest

The gateway's Docker driver must use the same Docker daemon containing this
image. For a remote gateway or a multi-node deployment, tag and push the image
to a registry accessible to the compute nodes and configure that registry
reference instead. A local build on your laptop is not available to a remote
gateway automatically. If the configured tag is absent, the driver attempts to
pull it; a mismatched name can fail with ImagePullFailed / pull access denied.

Initialize the volume once. It is operator-owned and shared with the OpenShell
gateway, so create it with these commands rather than declaring it in a compose
file — docker compose down -v on a managing stack would delete every Home
Snapshot. Docker named volume (single-tenant local development; 1777 is not
a multi-tenant control):

bash
docker volume create dify-agent-shared
docker run --rm -v dify-agent-shared:/mnt busybox \
  sh -c "mkdir -p /mnt/home-snapshots && chmod 1777 /mnt /mnt/home-snapshots"

Kubernetes: provision one ReadWriteMany PVC per tenant trust zone and mount
it read-write at DIFY_AGENT_OPENSHELL_SHARED_MOUNT_PATH through that
driver's driver_config (shape is driver-specific; the Docker example
above is the local-dev analogue). Initialize the volume with an
initContainer or fsGroup so the sandbox UID can write
home-snapshots/ — do not rely on chmod 1777 as isolation.

yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: dify-agent-shared-tenant-a
spec:
  accessModes: ["ReadWriteMany"]
  resources:
    requests:
      storage: 20Gi

Configure the backend in docker/.env. The full DIFY_AGENT_OPENSHELL_*
variable reference lives in docker/envs/core-services/dify-agent.env.example;
values may also be set in the envs/core-services/dify-agent.env env_file,
but docker/.env is loaded last into agent_backend and overrides it. These
lines are .env file content, not shell commands — values are taken verbatim,
so the driver_config JSON needs no quoting:

ini
# docker/.env
DIFY_AGENT_RUNTIME_BACKEND=openshell
DIFY_AGENT_OPENSHELL_GATEWAY_ENDPOINT=gateway.example.com:17670
DIFY_AGENT_OPENSHELL_BEARER_TOKEN=replace-with-gateway-token
DIFY_AGENT_OPENSHELL_SANDBOX_IMAGE=docker.io/library/dify-agent-runtime:latest
DIFY_AGENT_OPENSHELL_DRIVER_CONFIG={"docker":{"mounts":[{"type":"volume","source":"dify-agent-shared","target":"/mnt/dify-agent-shared","read_only":false}]}}
DIFY_AGENT_OPENSHELL_SHELLCTL_AUTH_TOKEN=replace-with-shellctl-token

Then start the stack normally:

bash
docker compose -f docker/docker-compose.yaml up -d

The Local backend's local_sandbox container and its dedicated SSRF proxy
stay in the stack unused, exactly as they do in an E2B deployment. The standard
Compose file does not build the OpenShell runtime image or provision its
gateway; complete the prerequisites above and the deployment-specific
networking and certificate setup below before starting the stack.

Home Snapshots are directory copies under
<shared mount>/home-snapshots/<tenant-digest>/; snapshot deletion runs a
short-lived maintenance sandbox granted only that tenant's snapshot root
(unlinking the snapshot directory itself requires write on its parent).

Validate the OpenShell deployment

For local development, run the API and Agent Backend from the current checkout.
Copy dify-agent/.example.env to dify-agent/.env, select
DIFY_AGENT_RUNTIME_BACKEND=openshell, and build the runtime image as described
above. The local template targets localhost:17670 and the Homebrew gateway's
mTLS bundle; adjust those paths if your gateway registration has a different
name. Install Agent Backend dependencies with uv sync --extra server from
dify-agent/ before starting the server.

For Docker Compose, use docker/docker-compose.yaml and explicitly configure
your deployment:

  • Use API and Agent Backend images containing the OpenShell integration. If your
    images predate it, build them from the checkout using api/Dockerfile and
    dify-agent/Dockerfile, and update the corresponding Compose service image
    references. Building the runtime image alone does not update these services.
    Keep the Agent Backend's glibc ≥ 2.39 base (python:3.13-slim-trixie in its
    Dockerfile): the bundled OpenShell wheel requires it.
  • The gateway endpoint must be reachable from the agent_backend container.
    For a gateway on the Docker host, use host.docker.internal:17670, not
    localhost:17670. On Linux Docker, add
    extra_hosts: ["host.docker.internal:host-gateway"] to that service and ensure
    the gateway listens on a container-reachable address. Verify that the gateway
    certificate covers the hostname you use.
  • When using mTLS, add a read-only bind mount for the gateway client bundle to
    agent_backend and set DIFY_AGENT_OPENSHELL_TLS_*_PATH to the paths inside
    the container
    . There is no automatic certificate mount. Ensure the service
    user can traverse the mounted directory and read the files; copy the bundle
    to a dedicated directory with appropriate permissions rather than mounting
    the CLI's private gateway directory directly.
  • Set sandbox-reachable Agent Stub and file-service URLs. Any required service
    port publishing must be configured explicitly; the Agent Backend control
    plane should remain private.

The runtime image must be available to the gateway's compute driver, not merely
in the Docker daemon used to build the API or Agent Backend images.

Smoke-test through the Agent Backend control plane. Set AGENT_BACKEND_BASE_URL
to its reachable service root (http://localhost:5050 for a local process on
port 5050), and export the matching DIFY_AGENT_API_TOKEN from your deployment.
Use a disposable test tenant and binding; the destroy request deletes the test
sandbox and its workspace.

bash
curl -s -w '\n%{http_code}\n' -X POST "$AGENT_BACKEND_BASE_URL/execution-bindings" \
  -H "Authorization: Bearer $DIFY_AGENT_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"tenant_id":"smoke-tenant","agent_id":"smoke-agent","binding_id":"smoke-binding-1","workspace_id":"smoke-ws-1"}'
# → {"binding_ref":"dify-<digest>","workspace_ref":"dify-<digest>"} then 201
curl -s -w '\n%{http_code}\n' -X POST "$AGENT_BACKEND_BASE_URL/execution-bindings/destroy" \
  -H "Authorization: Bearer $DIFY_AGENT_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"binding_ref":"<binding_ref>","destroy_workspace":true,"workspace_ref":"<binding_ref>"}'
# → 204

A created ref verifies gateway authentication, sandbox startup from the
configured runtime image, and Binding initialization. Home Snapshot operations
also require the initialized shared volume described above.

Run the OpenShell integration contract

Run the real OpenShell contract against a reachable gateway. The driver config
must mount an initialized shared Home Snapshot volume (see the OpenShell
deployment section above); pass the gateway credential through the bearer-token
or mTLS-path variables that match your gateway:

bash
cd dify-agent
DIFY_AGENT_TEST_OPENSHELL_GATEWAY_ENDPOINT=gateway.example.com:17670 \
DIFY_AGENT_TEST_OPENSHELL_SANDBOX_IMAGE=docker.io/library/dify-agent-runtime:latest \
DIFY_AGENT_TEST_OPENSHELL_DRIVER_CONFIG='{"docker":{"mounts":[{"type":"volume","source":"dify-agent-shared","target":"/mnt/dify-agent-shared","read_only":false}]}}' \
DIFY_AGENT_TEST_OPENSHELL_BEARER_TOKEN=replace-with-gateway-token \
  uv run --extra server pytest --import-mode=importlib \
  tests/integration/dify_agent/runtime_backend/test_working_environment.py \
  -k openshell -q -rs

The contract creates unique resources and performs explicit cleanup in finally
blocks.


Dify Agent Docs Dify Agent Guide Runtime Metering (`dify-agent/docs/dify-agent/guide/runtime-metering.md`)

E2B runtime metering

One ledger row represents one E2B sandboxExecutionId, from start/resume to
pause/kill. Provider execution time and resource sizes determine compute usage;
LLM token usage, message latency and local SDK-call duration do not.

Scheduled collection and boundaries

The Dify API's existing Celery Beat schedule dispatches
schedule.collect_agent_sandbox_usage.collect_agent_sandbox_usage every 60 seconds
by default, through the existing ops_trace worker queue. The job calls
POST /internal/e2b/usage/collect on the Agent backend using its existing Bearer
service token and a project_id body. The E2B key stays in the Agent backend.

The provider-specific endpoint performs one bounded scan, using request-scoped
HTTP clients. It reads E2B lifecycle events and posts them to the Dify API's
idempotent usage ingestion endpoint. It returns {"completed": true} only after
all scanned pages and the checkpoint have been acknowledged. Partial scans return
completed=false; provider/API errors fail this accounting request only.

There is no Agent-process polling loop, Redis leader election, log outbox,
observation worker, or requested/observed operation reporting. Generic leases,
Agent runs, files, snapshots and binding lookups do not participate in metering.
Their timing, cancellation handling and SDK retries retain their normal behavior.
Metering misconfiguration is checked when collection is invoked, rather than
becoming a prerequisite for business runtime startup or binding operations.

The endpoint has a 240-second deadline. The scheduled HTTP caller has a
260-second timeout, and the Celery task configures 270/300-second soft/hard limits.
Pool support differs: gevent workers do not implement soft time limits, and
blocking work cannot rely on their hard limit. The collection and HTTP deadlines
are the primary bounds; verify the deployed worker pool before relying on Celery
limits. See the Celery time-limit documentation.
Scheduled messages expire after one collection interval to avoid stale backlog.
There is no automatic HTTP retry; future scheduled scans can redeliver provider
IDs safely. Overlapping tasks may duplicate reads, but cannot multiply usage.

Data and attribution

The API owns agent_sandbox_usage_events and agent_sandbox_executions.
Ingestion persists provider facts and projects execution rows atomically; the
execution key is (provider, provider_project_id, provider_execution_id).
A short project transaction lock protects ingestion. Binding creation/lookups do
not register allocations, write accounting rows or acquire that lock.
Steady-state usage-state reads do not take a project FOR UPDATE lock; activation
can be initialized once when first needed.

E2B's existing sandbox metadata contains binding, tenant, Agent and workspace
identifiers. During background ingestion, optional attribution checks those IDs
against the existing Binding → Workspace → App/Agent tenant-owned chain and the
physical sandbox reference. It never trusts labels alone. Missing, malformed or
already-deleted business records leave attribution unresolved while preserving
complete project-level provider usage. A previously verified ownership snapshot
survives later business deletion. Conflicting ownership is not silently reassigned.

No accounting callback or transaction is added to the business path. There is no
pre-create allocation journal. Older diagnostic/allocation columns and records
are not destructively migrated in this revision; new accounting accepts only
provider events and collector checkpoint/coverage-gap control records. Table
retention is unchanged, with no new automatic cleanup policy.

Configuration

Apply the existing usage-table migration before first enabling metering.
Configure Dify API, Beat and the workers consuming ops_trace consistently:

dotenv
AGENT_SANDBOX_METERING_ENABLED=true
AGENT_SANDBOX_METERING_PROJECT_ID=<E2B project/team ID>
AGENT_SANDBOX_METERING_START_AT=<whole-second UTC instant>
AGENT_SANDBOX_METERING_INTERVAL_SECONDS=60

The task reuses AGENT_BACKEND_BASE_URL and AGENT_BACKEND_API_TOKEN; the
existing SSRF-safe HTTP policy must permit that internal service. No E2B key is
copied into API or worker configuration.

Configure the Agent backend's one-shot endpoint:

dotenv
DIFY_AGENT_SANDBOX_METERING_ENABLED=true
DIFY_AGENT_E2B_PROJECT_ID=<same E2B project/team ID>
DIFY_AGENT_SANDBOX_METERING_OVERLAP_SECONDS=900
DIFY_AGENT_SANDBOX_METERING_FULL_SCAN_INTERVAL_SECONDS=3600
DIFY_AGENT_SANDBOX_METERING_MAX_PAGES=1000

It reuses the existing E2B key, DIFY_AGENT_API_TOKEN, inner API URL and inner API
key. The new endpoint requires a nonempty Bearer-token configuration even when
legacy control-plane routes permit unauthenticated local development.
DIFY_AGENT_SANDBOX_METERING_POLL_INTERVAL_SECONDS is no longer used: the interval
belongs to Celery Beat on the API side. Both metering feature flags default off.

Activation T0 is persisted and immutable. Only provider executions started at or
after T0 are metered; starting before T0 and ending after it does not include an
old execution. Resuming an older sandbox after T0 creates a new execution and is
included. There is no historical backfill and no environment column; databases
separate environments. A project ID also scopes and allowlists ingestion.

Failure semantics

  • Only complete provider terminal execution data populates metered duration. A
    local finally, SDK expiry deadline or business success is not a billing clock.
  • Missing terminal fields remain pending; conflicts remain visible. Late starts
    cannot reopen closed executions, and duplicate facts do not add duration twice.
  • Every scan starts provider offset pagination from zero, overlaps prior coverage
    and periodically rescans the retained window. Failed, cancelled or page-bounded
    scans never claim a completed checkpoint. SQL idempotency protects redelivery.
  • The assumed default provider event retention is seven days. Older uncovered
    intervals are recorded as gaps rather than reconstructed or counted as zero.
  • A failed scheduled task affects accounting only. No accounting network request
    is added to create/connect/pause/kill, lease helpers, runner or file operations.

The API's private ingestion endpoints remain:
GET /inner/api/agent/sandbox-usage/state?project_id=... and
POST /inner/api/agent/sandbox-usage/events, authenticated with X-Inner-Api-Key.
Event batches are limited to 100 records and 1 MiB, acknowledged after commit.
They are for the isolated collector, not business-operation logging.

Querying usage

For complete quality='metered' executions:

text
sandbox_hours = sum(metered_duration_ms) / 3600000
vcpu_hours = sum(metered_duration_ms * vcpu_count) / 3600000
ram_gib_hours = sum(metered_duration_ms * memory_mib) / (3600000 * 1024)

Project totals include complete executions with unresolved attribution; report
that count separately. Tenant/app reports require verified resolved attribution.
For UTC windows [A, B), clip execution intervals using start plus provider
duration. Start time can have second precision, so cross-boundary allocation is
not claimed to be millisecond-accurate; complete-window totals conserve duration.

Rollout checks

  1. Verify Beat's schedule, task registration and an existing worker consuming
    ops_trace, along with image revisions, flags, project and immutable T0.
  2. Verify the authenticated one-shot endpoint, real scheduled execution and
    advancing checkpoints. The Agent must not start a metering poller or leader.
  3. Keep a real business binding until collection resolves its owner, then retire
    it and confirm previously copied accounting remains. Also verify complete
    project usage for test sandboxes without business records.
  4. Exercise model success/failure/cancellation, files/list/read/download/errors,
    snapshots/restoration and resource cleanup. Isolated bad accounting settings
    or failing accounting-service stubs must not make business lookups fail.
  5. Compare physical execution IDs, duration and resources against actual E2B
    events; replay scans/events and confirm totals do not increase.
  6. Verify old outbox and collector-leader keys are absent after deployment. Do
    not alter run-store keys or stop shared services to inject accounting faults.

Disable the metering flags and restart the relevant processes to stop collection;
business runtime behavior remains the same. Keep the ledger and original T0.
The independent stdout-only sandbox file-error fix is tracked separately from
this accounting integration.


--- METRICS ---