API 与工具(1/3)
API for managing knowledge bases, documents, chunks, metadata, tags, and knowledge pipelines
Build and maintain knowledge bases from your own code, without going through the Dify console: create a knowledge base, load documents and chunks into it, organize them with metadata and tags, and query it directly for search or RAG.
Get Your API Endpoint and Key
In Knowledge, click Service API in the top-right corner to open the API configuration panel. From here:
- Copy the Service API endpoint, the base URL for every Knowledge API request.
- Click API Key to create and manage keys.
Store your API key securely on the server side. Never expose it in client-side code or public repositories.
Scoped API Keys
When you create a key, scope it to specific knowledge bases the integration needs to work with. Choose all knowledge bases if the integration needs to list or create knowledge bases.
A scoped key can call only endpoints whose path includes a dataset_id in its scope. Calls with another ID, or without a dataset_id in the path, return 403 forbidden.
For a scoped key, open the knowledge base in Dify and copy the ID after /datasets/ in the page URL. Use that value as the dataset_id in the request path.
To change the scope, create a replacement key. Switch your integration to the new key before deleting the old one.
Deleting a knowledge base also deletes any key scoped only to it. A key that also covers other knowledge bases keeps working for those.
Manage API Access for a Knowledge Base
API access is on for every knowledge base by default. To close one knowledge base to every key, open it, and disable API Access in the lower-left corner.
Create and Manage Knowledge Bases
- Create an Empty Knowledge Base: create a knowledge base with no documents yet.
- List Knowledge Bases: a paginated list, filterable by keyword or tag.
- Get Knowledge Base: one knowledge base's embedding model, retrieval configuration, and document statistics.
- Update Knowledge Base: change the name, permissions, embedding model, or retrieval settings; only the fields you provide are updated.
- Delete Knowledge Base: permanently remove a knowledge base, every document inside it, and any API key scoped only to it.
- Retrieve Chunks from a Knowledge Base / Test Retrieval: search a knowledge base and return the most relevant chunks—the same endpoint serves production retrieval and retrieval testing.
Add and Update Documents
Document creation is asynchronous. Create the document, then poll until indexing finishes:
Call [Create an Empty Knowledge Base](https://docs.dify.ai/en/api-reference/knowledge-bases/create-an-empty-knowledge-base), or use an existing knowledge base.
Call [Create Document by Text](https://docs.dify.ai/en/api-reference/documents/create-document-by-text) or [Create Document by File](https://docs.dify.ai/en/api-reference/documents/create-document-by-file); both return a `batch` ID.
If you didn't set `indexing_technique` (how content is indexed for search) when creating the knowledge base, set it on this first document; later documents inherit it automatically.
Poll [Get Document Indexing Status](https://docs.dify.ai/en/api-reference/documents/get-document-indexing-status) with the `batch` ID until `indexing_status` reaches `completed` or `error`; it progresses through `waiting`, `parsing`, `cleaning`, `splitting`, and `indexing` along the way.
- List Documents: a paginated list, filterable by keyword or indexing status.
- Get Document: one document's indexing status, metadata, and processing statistics; the
metadataquery parameter includes, omits, or returns only the metadata fields. - Download Document: a signed URL for the document's original uploaded file.
- Download Documents as ZIP: bundle up to 100 uploaded-file documents into a single archive.
- Update Document: replace a document's content by uploading a new file, re-triggering indexing; the canonical way to update a file-based document.
- Update Document by Text: update a document's text content, name, or processing configuration inline; re-triggers indexing when the content changes.
- Update Document by File: deprecated alias for uploading a replacement file; use Update Document instead.
- Update Document Status in Batch: enable, disable, archive, or unarchive multiple documents at once.
- Delete Document: permanently remove a document and every chunk inside it.
Manage Chunks and Child Chunks
- Create Chunks: add chunks to a document by hand—indexing already chunks uploaded content automatically. Each chunk requires
content; documents in Q\&A mode also requireanswer. - List Chunks: a paginated list, filterable by keyword or status.
- Get Chunk: one chunk's content, keywords, and indexing status.
- Update Chunk: change a chunk's content, keywords, or answer; re-triggers indexing for that chunk.
- Delete Chunk: permanently remove a chunk.
For documents in Parent-child mode (hierarchical_model), child chunks nest under a parent chunk. Child chunks you create or update through the API are always typed customized, unlike the automatic ones the indexing pipeline generates.
- Create Child Chunk: add a child chunk under a parent chunk.
- List Child Chunks: a paginated list of one parent chunk's child chunks.
- Update Child Chunk: change a child chunk's content.
- Delete Child Chunk: permanently remove a child chunk.
Manage Metadata Fields
Metadata fields annotate documents with structured information that retrieval can filter on:
- Create Metadata Field: add a custom field to the knowledge base, typed
string,number, ortime. - List Metadata Fields: every field, custom and built-in, with a count of documents using each.
- Update Metadata Field: rename a custom field.
- Delete Metadata Field: remove a custom field; documents lose their values for it.
- Get Built-in Metadata Fields: the system-provided fields, such as
document_name,uploader, andupload_date. - Update Built-in Metadata Field: enable or disable built-in fields for the knowledge base.
- Update Document Metadata in Batch: set metadata key-value pairs across multiple documents in a single call.
Metadata also works as a stable external key: store your source system's ID on each document, then filter on it in later sync runs to find and update the same documents.
Organize Knowledge Bases with Tags
Tags live at the workspace level, independent of any single knowledge base:
- Create Knowledge Tag: create a tag for organizing knowledge bases.
- List Knowledge Tags: every tag in the workspace.
- Update Knowledge Tag: rename a tag.
- Delete Knowledge Tag: remove a tag from every knowledge base it was bound to, without deleting those knowledge bases.
- Create Tag Binding: bind one or more tags to a knowledge base; a knowledge base can carry multiple tags.
- Delete Tag Binding: remove tags from a knowledge base.
- Get Knowledge Base Tags: the tags currently bound to one knowledge base.
Look Up Available Models
- Get Available Models: the models available for a given
model_type; querytext-embeddingfor embedding models orrerankfor reranking models when configuring a knowledge base.
Run the Knowledge Pipeline
A knowledge pipeline is a workflow that ingests data from a datasource and turns it into documents:
- Upload Pipeline File: upload a file for the pipeline to process.
- List Datasource Plugins: the datasource nodes configured in the pipeline—published by default, or the draft version with
is_published=false. - Run Datasource Node: execute a single datasource node and stream its results, useful for testing one step in isolation.
- Run Pipeline: execute the full pipeline in
streamingorblockingresponse mode;is_publishedpicks the published version or the current draft.
Our email assistant can now flip through our knowledge base. But what if a customer asks a beyond-knowledge-base question, like: What is in the latest Dify release?
If the knowledge base hasn't been updated yet, the workflow will be at a loss. To fix this, we need to equip it with a Live Search skill!
Tools
<img alt="Tools" />
Tools are the superpower for your AI workflow.
The Dify Marketplace is like a supermarket of ready-made tools—searching Google, checking the weather, drawing images, or calculating complex math. You just install and plug them into your workflow with several clicks.
Now, let's continue to upgrade on current workflow.
Hands-On 1: Upgrade the Sub-process Area in Iteration
We are going to add a new logic to our assistant: Check the Knowledge Base first; if the answer isn't there, go search Google.
To focus on the new logic, let's keep only these nodes: User input, Parameter Extractor, and Iteration.
Step 1: Knowledge Query and the Judge
1. Click to enter the sub-process area of the Iteration node.
2. Keep Knowledge Retrieval node, and make sure the query variable is `{x} item`.
3. Delete the previous LLM node.
Add an LLM node right after Knowledge Retrieval node. Its job is to decide if the Knowledge Base info can actually respond to the questions.
* **For Context session**: Select the `Knowledge Retrieval / {x} result Array [Object]` from Knowledge Retrieval
* **System Prompt**:
Based on the `Context`, determine if the answer contains enough information to answer the questions. If the information is insufficient, you MUST reply with: "Information not found in knowledge base".
* **User Message**:
questions: Iteration/{x} item
<img alt="LLM Settings" />
Here's what it looks like on the canvas.
<img alt="Workflow Preview" />
Step 2: Setting the Crossroads
After LLM node, let's add If/Else node. Set the rule: If LLM Output **Contains** **Information not found in knowledge base**.
This means, when we can't respond with the information in knowledge base.
<img alt="Add if/Else Node" />
Let's connect a search tool after the IF branch. This indicates that when the knowledge base cannot find relevant answer information, we use web search to find the answers.
1. After the IF node, click plus(+) icon and select Tool.
2. In the search box, type Google. Hover over Google, click Install on the right, and then click Install again in the pop-up window.
<img alt="Install Tool" />
Click Google Search in Google.
<img alt="Install Google Search" />
Using Google Search for the first time requires authorization—it's like needing a Wi-Fi password.
<img alt="Google Search Setup" />
1. Click API Key Authorization Configuration, then click Get your SerpApi API key from SerpApi. Sign in to get your private API key.
Your API Key is your passport to the outside world. Keep it safe and avoid sharing it with others.
<img alt="API Key Authorization Configuration" />
2. Copy and paste the API key in SerpApi API key. Click **Save**.
3. Once the API key is successfully authorized, the settings panel shows up immediately. Head to Query string field, and select `Iteration/{x} item`.
<img alt="Add Query String" />
Now, we need different ways to answer depending on which path we're looking at.
**The Search Answer Path**
Add a new LLM node to answer the question based on the search results. Connect it to the Google Search node.
**System**:
You are a Web Research Specialist. Based on Google Search, concisely answer the user's questions. Please do not mention the knowledge base in your response.
**User Message**:
results: GOOGLESEARCH/{x} text
questions: Iteration/{x} item
<img alt="Prompt for LLM 2" />
**The Knowledge Searching Path**
After the Else node, add a new LLM node to handle answers based on the knowledge base.
**System**:
You are a professional Dify Customer Service Manager. Strictly follow the `Context` to reply to questions.
**User Message**:
questions: Iteration/{x} item
<img alt="Prompt for LLM 3" />
1. In the sub-process (inside the Iteration box), add a Variable Aggregator node that connects both LLM 2 and LLM 3 at the very end.
2. In the Variable Aggregator panel, select the variables `LLM 2/{x}text String` and `LLM 3/{x}text String` as the Assign Variables.
In this way, we're merging the two possible answers into a single path.
<img alt="Variable Aggregator Setup" />
This is how the current workflow looks.
<img alt="Workflow Preview 2" />
Step 3: The Final Email Assembly
Now that our logic branches have finished processing, let's combine all the answers into a single, polished email.
Click on the Iteration node, and set `{x}Variable Aggregator/{x}output String` as the output variables.
<img alt="Iteration Output" />
After the Iteration node, connect a new LLM node to summarize all outputs. Feel free to use the prompt below.
**System**:
You are a professional Customer Service Manager. Summarize all the answers of the questions, and organize a clear and complete email reply for the customer.
Do not include content where the knowledge base could not find relevant information.
Signature: Anne.
**User Message**:
questions: Iteration/ {x} output
customer: User Input / {x} customer_name
<img alt="Prompt for LLM 4" />
After the LLM node, add an End node. Set the output variable as `LLM 4/{x}text String`.
<img alt="Output Setup" />
We have now completed the entire setup and configuration of the workflow. Our email assistant can now answer questions based on the Knowledge Base and use Google Search for supplementary answers when needed.
<img alt="Final Workflow Preview" />
Try sending an email with question that definitely isn't in the knowledge base. Let's see if the AI successfully uses Google to find the related answers.
Mini Challenge
- What are other conditions you can choose in If/Else node?
- Browse marketplace to see if you can add another tool for this workflow?
End-to-end sequence for handling a paused Human Input form via the API
When a workflow reaches a Human Input node, it pauses and emits a human_input_required event in the streaming response. The event carries a form_token that your integration uses to drive the form lifecycle until the workflow resumes.
For per-endpoint reference, see the Human Input API.
Steps
The sequence below applies to both Workflow and Chatflow apps. Only the entry endpoint in Step 1 differs between the two.
1. Call [Run Workflow](https://docs.dify.ai/en/api-reference/workflow-runs/run-workflow) (Workflow apps) or [Send Chat Message](https://docs.dify.ai/en/api-reference/chat-messages/send-chat-message) (Chatflow apps), passing your end user's `user` identifier.
2. Watch the SSE stream for the `human_input_required` event and capture its `form_token`.
If `form_token` is `null`, the form uses Email delivery and can't be driven via the API (see [Delivery Method Requirement](#delivery-method-requirement)).
The `human_input_required` event also carries the run's `workflow_run_id`; keep it in case you need to resume listening in Step 5.
Call [Get Human Input Form](https://docs.dify.ai/en/api-reference/human-input/get-human-input-form) with `form_token`. The response includes the rendered Markdown, input field definitions, available actions, pre-filled default values, and an `expiration_time` after which the form can no longer be submitted. Render the form for the recipient.
If the form expires before it is submitted, the paused run follows the node's configured timeout behavior; a resumed stream then carries `human_input_form_timeout` rather than `human_input_form_filled`.
If the recipient attaches a local file to a `file` or `file-list` input, upload it first with [Upload File](https://docs.dify.ai/en/api-reference/files/upload-file). It returns an `id` you reference as `upload_file_id` in the submit payload. Use one consistent `user` across the run, upload, and submit calls (see [End User Identity](https://docs.dify.ai/en/api-reference/guides/end-user-identity) for details).
A remote file needs no upload step: attach it inline in the submit as a `{transfer_method: remote_url, url}` mapping.
Call [Submit Human Input Form](https://docs.dify.ai/en/api-reference/human-input/submit-human-input-form) with the recipient's input values, the selected `action`, and your `user`. The `action` must be one of the actions from the form definition in Step 2.
File inputs accept either a `{transfer_method: local_file, upload_file_id}` mapping (from Step 3) or an inline `{transfer_method: remote_url, url}` mapping. See [Upload First vs. Inline Remote URL](#upload-first-vs-inline-remote-url) for the trade-off.
A successful submit is final: it closes the form and resumes the run along the matching action branch, so the same `form_token` can't be submitted again.
A rejected submit (an invalid action, a missing required input, or a failed remote-file fetch) leaves the form unchanged—fix the inputs and resubmit with the same `form_token`.
If the original SSE stream closed, reopen it via [Stream Workflow Events](https://docs.dify.ai/en/api-reference/workflow-runs/stream-workflow-events) with the `workflow_run_id` from Step 1 and the same `user` that started the run—a different `user` gets a 404.
The resumed stream includes `human_input_form_filled` confirming the submission (or `human_input_form_timeout` if the form expired), then the remaining node events through to completion, like a run that never paused.
Add `include_state_snapshot=true` to first replay the status of nodes that already executed. If the workflow has more than one Human Input node in sequence, the stream closes at each pause by default; pass `continue_on_pause=true` to keep one stream open across all of them.
Upload First vs. Inline Remote URL
Both patterns work for file inputs:
- Pre-upload, then reference
upload_file_id(recommended)
Upload File enforces the file size limits at upload time, so the recipient gets immediate feedback and can retry before committing the whole submission.
- Submit inline with
transfer_method: remote_url
The backend fetches the file at submit time. Faster to integrate, but any size, type, or fetch failure rejects the entire submission, forcing the recipient to redo other fields.
For interactive forms with recipient feedback, prefer the pre-upload pattern. The trade-off only pays off when the integration is fully programmatic and no human is waiting to retype anything.
Delivery Method Requirement
The Human Input API works only with forms delivered via the Human Input node's web app method. Email-only delivery doesn't expose a form_token.
Example: File-Attached Submission
This example uses a form with a feedback paragraph input, an attachments file-list input, and approve / reject actions.
- Call Get Human Input Form to get the form definition:
GET /form/human_input/<form_token>
Authorization: Bearer {api-key}
Returns the form definition:
{
"form_content": "Please review the draft and confirm or request changes.",
"inputs": [
{
"type": "paragraph",
"output_variable_name": "feedback",
"default": {
"type": "constant",
"selector": [],
"value": ""
}
},
{
"type": "file-list",
"output_variable_name": "attachments",
"allowed_file_types": [
"image",
"document"
],
"allowed_file_extensions": [],
"allowed_file_upload_methods": [
"local_file",
"remote_url"
],
"number_limits": 5
}
],
"resolved_default_values": {},
"user_actions": [
{
"id": "approve",
"title": "Approve",
"button_style": "primary"
},
{
"id": "reject",
"title": "Request changes",
"button_style": "default"
}
],
"expiration_time": 1745510400
}
- For each local file, call Upload File:
POST /files/upload
Authorization: Bearer {api-key}
Content-Type: multipart/form-data
file=<binary>
user=abc-123
Returns {"id": "1a77f0df-...", ...}.
- Call Submit Human Input Form with the recipient's input and selected action:
POST /form/human_input/<form_token>
Authorization: Bearer {api-key}
Content-Type: application/json
{
"inputs": {
"feedback": "Looks good to ship",
"attachments": [
{"transfer_method": "local_file", "upload_file_id": "1a77f0df-..."}
]
},
"action": "approve",
"user": "abc-123"
}
Returns {}. The workflow resumes along the approve branch.
- Reconnect to the run's stream with Stream Workflow Events to follow it through to completion, as in Step 5 of the sequence above.
API for Chatflow apps, covering chat messages, workflow-level streaming, conversation management, and Human Input pauses
Chatflow apps run in advanced-chat mode, streaming workflow-level events (node starts, finishes, iterations, and pauses) alongside the reply. Previous turns persist as context, so later messages can reference earlier ones.
Authentication, the base URL, and the user field that scopes end-user data are covered in Get Started and End User Identity.
Send Messages and Stream Replies
- Send Chat Message: send a query to your Chatflow app. Streaming mode carries workflow and node events alongside the answer text; blocking mode returns once the run finishes.
- Stop Chat Message Generation: interrupt a streaming reply before it finishes.
- Get Next Suggested Questions: propose follow-up questions after a reply completes, based on the conversation so far.
Manage Conversations
- List Conversations: the current user's conversations, ordered by most recent activity.
- List Conversation Messages: one conversation's message history, for a scrolling chat UI.
- Rename Conversation: set or auto-generate a display name.
- Delete Conversation: remove a conversation.
- List Conversation Variables: read the values the session persists across turns.
- Update Conversation Variable: change one of those values directly.
Handle Files
- Upload File: upload an image, document, audio, or video file for Send Chat Message to reference. Files are scoped to the uploading end user.
- Download File: preview or download an uploaded file, as long as it belongs to a message in your app.
- Get End User Info: look up an end user's details from an end-user ID, such as the
created_byin the Upload File response.
Transcribe and Synthesize Speech
- Convert Audio to Text: transcribe an uploaded audio file (MP3, M4A, WAV, AMR, or MPGA, up to 30 MB) so end users can speak their input instead of typing it.
- Convert Text to Audio: synthesize a reply back into speech.
Pause for Human Input
When a run reaches a Human Input node whose delivery method is web app, complete the pause over the API:
The event stream emits `human_input_required` carrying a `form_token` and the run's `workflow_run_id`, then ends with the `workflow_paused` event.
Load the form's contents with [Get Human Input Form](https://docs.dify.ai/en/api-reference/human-input/get-human-input-form), using the `form_token`.
Send the recipient's input with [Submit Human Input Form](https://docs.dify.ai/en/api-reference/human-input/submit-human-input-form). Submitting resumes the run.
Open a new stream with [Stream Workflow Events](https://docs.dify.ai/en/api-reference/workflow-runs/stream-workflow-events), using the `workflow_run_id` from the paused stream, and follow the remaining events through the final answer.
For file-attached submissions and the full event sequence, see the Human Input Flow guide.
Inspect Workflow Runs
- Get Workflow Run Detail: a run's status and outputs, by the
workflow_run_idthat appears in the workflow and node events streamed alongside a chat reply. - List Workflow Logs: run-level summaries covering status, token usage, step count, and timing, rather than a node-by-node execution log.
Retrieve App Info and Settings
- Get App Info: the app's name, description, tags, and mode.
- Get App Parameters: the fields your calls send in
inputs(names, types, defaults) plus the app's feature switches—the basis for building requests or a client UI. - Get App Meta: tool icons and other configuration metadata.
- Get App WebApp Settings: the web app's site configuration, theme, and customization options.
Collect Feedback and Annotations
- Submit Message Feedback: end users rate a reply as
likeordislike, with an optional text comment. - List App Feedbacks: every feedback submitted across the app, from both end users and admins.
Annotations pair a question with a fixed answer that the app returns directly instead of generating a new response:
- Create Annotation, List Annotations, Update Annotation, Delete Annotation: manage the annotation set.
- Configure Annotation Reply: turn annotation matching on or off. The change runs asynchronously.
- Get Annotation Reply Job Status: poll with the returned job ID to confirm the change finished.
