API 与工具(2/3)
Choose a response mode, parse the SSE stream, dispatch events, and recover when a connection drops
Generation endpoints return either one complete response or a Server-Sent Events (SSE) stream, chosen per request with response_mode. Streaming is the usual choice: the reply renders as it generates, and long runs aren't cut off mid-flight.
Choose a Response Mode
blocking returns a single JSON body once generation finishes. It's the simpler integration for short, non-interactive calls, but long generations risk interruption: proxies cut long requests, and on Dify Cloud the edge proxy may end the connection if the upstream response doesn't arrive within its timeout.
streaming delivers the reply as SSE events. Use it for anything user-facing, for long runs, and for every flow that pauses for Human Input.
Legacy Agent and Agent apps stream only.
Parse the Stream
Every event except ping arrives as a data: line holding one JSON object, terminated by a blank line.
Read the event field to decide what to do, and skip anything that isn't a data: line: the keep-alive ping arrives as a bare event: ping line with no data: payload.
Chatflow and Workflow app streams open with a ping as the very first frame, and more arrive roughly every 10 seconds during the run. Treat the first data: event (workflow_started), not the first frame, as the signal that the run was accepted.
import json
import requests
body = {
"query": "What are this month's top issues?",
"inputs": {},
"user": "customer-4821",
"response_mode": "streaming",
}
with requests.post(url, headers=headers, json=body, stream=True) as r:
for line in r.iter_lines(decode_unicode=True):
if not line or not line.startswith("data: "):
continue # skips blank separators and ping lines
event = json.loads(line[len("data: "):])
handle(event)
On the wire, a stream looks like this:
event: ping
data: {"event": "workflow_started", "task_id": "c3800678-…", "workflow_run_id": "fb47b2e6-…", "data": {…}}
data: {"event": "node_finished", "task_id": "c3800678-…", "workflow_run_id": "fb47b2e6-…", "data": {…}}
When testing with curl, pass -N (--no-buffer) so events print as they arrive instead of after the run completes.
Dispatch by Event Type
Which events arrive depends on the app type. See the event tables on Send Chat Message, Run Workflow, and Send Completion Message for the contract.
The typical minimum:
-
Concatenate reply chunks in order:
-
messageevents for Chatbot and Chatflow apps agent_messageevents for Legacy Agent and Agent apps
For Agent apps, a single closing message event repeats the complete answer; treat it as the final answer, not extra text to append.
- Close on the right terminal event:
message_endfor Chatbot, Legacy Agent, and Agent appsmessage_endthenworkflow_finished(both arrive, in that order) for Chatflow apps-
workflow_finishedfor Workflow apps -
Surface
error.
Handle Errors Mid-Stream
A failure after the stream opens doesn't change the HTTP status: the connection stays 200. How the failure surfaces depends on where it happens:
- A workflow node failure arrives as
node_finishedandworkflow_finishedevents withstatus: "failed". - Other failures end the stream with an
errorevent carryingstatus,code, andmessage.
Handle both, and treat either as terminal for that request.
Reconnect and Resume
Two identifiers matter, and they're easy to mix up:
task_idcontrols the in-flight generation and is what the stop endpoints (Stop Chat Message Generation / Stop Workflow Task) take.workflow_run_idnames the persistent run record.
Both arrive on the stream itself: every event except error carries task_id, and workflow and node events carry workflow_run_id. Save workflow_run_id as soon as it arrives: if the connection drops mid-run, it's the only handle you have for reconnecting or checking the outcome.
For workflow-backed runs (Workflow and Chatflow apps), a dropped connection isn't fatal. Reopen the stream with Stream Workflow Events, passing the workflow_run_id and the same user that started the run. A mismatch returns 404.
Add include_state_snapshot=true to first replay the status of nodes that already ran, and continue_on_pause=true to keep one stream open across multiple Human Input pauses.
After reconnecting to a still-running workflow, confirm completion with Get Workflow Run Detail rather than relying on the reconnected stream's final event alone.
Other replies have no resume endpoint: if the connection drops mid-reply, issue a new request. For chat-style apps, List Conversation Messages shows what was saved to the conversation.
Keep the Connection Alive
Set your client's read timeout comfortably above the 10-second ping interval so idle stretches between events don't kill the connection. The pings themselves need no handling beyond being skipped.
API for Workflow apps, covering workflow execution, run control and streaming, Human Input pauses, and run history
Workflow apps run in workflow mode, executing the published workflow once per call and returning its outputs. There's no conversation state between calls, so each run is independent of any previous one.
Authentication, the base URL, and the user field that scopes end-user data are covered in Get Started and End User Identity.
Run a Workflow
- Run Workflow: execute the app's currently published workflow with the input variables you provide.
Streaming mode delivers events live as nodes execute; blocking mode returns once the run finishes.
* Run Workflow by ID: execute a specific published version instead, identified by the workflow_id from an earlier run response or run detail lookup.
Follow and Control a Run
Whichever mode you run in, the response carries two IDs: task_id controls the run while it's active, and workflow_run_id identifies the persisted record afterward.
- Stop Workflow Task: cancel an active run by its
task_id. Works in streaming mode only; a blocking call has already finished by the time it returns. - Stream Workflow Events: resume a run's event stream from its
workflow_run_idafter a dropped connection or a pause.
Pass include_state_snapshot=true to replay the status of already-executed nodes first, or continue_on_pause=true to stay open across multiple Human Input pauses.
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 run's 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 to the run's finish.
For file-attached submissions and the full event sequence, see the Human Input Flow guide.
Inspect Past Runs
- Get Workflow Run Detail: a run's status and outputs, by its
workflow_run_id. - List Workflow Logs: run-level summaries covering status, token usage, step count, and timing, rather than a node-by-node execution log; filter by keyword, status, date range, or who triggered the run.
For node-level events, stream the run instead of listing its logs: call Run Workflow in streaming mode for a run you're starting, or Stream Workflow Events for one already in progress.
Work with Files
- Upload File: upload an image, document, audio, or video file, then pass the returned
idasupload_file_idin a file-type input variable when you run the workflow. Files are scoped to the uploading end user. - 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 an input value instead of typing it.
- Convert Text to Audio: synthesize a workflow's text output back into speech.
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.
API for Chatbot and Legacy Agent apps, covering chat messages, conversation management, file uploads, voice, and annotations
Chatbot apps (chat mode) and Legacy Agent apps (agent-chat mode) share the same endpoints to send messages, manage conversations, handle files, and retrieve app settings. Only the streamed reply differs: Chatbot apps stream the reply as message events, while Legacy Agent apps stream agent_thought and agent_message events.
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 Chatbot or Legacy Agent app. Blocking mode returns the full reply once it finishes; Legacy Agent apps support streaming mode only.
- 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
Conversations created through the API stay isolated from conversations started in the app's web app.
- 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.
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
- 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.
Manage Annotations
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.
API for Agent apps, covering streaming chat messages, conversation management, file uploads, and app configuration
Agent here means the new Agent app type (agent mode). The Legacy Agent app (agent-chat) is covered on Chatbot and Legacy Agent.
Agent apps run in agent mode: you send a message, stream the reply as it generates, and keep multi-turn context in conversations.
The model reasons and calls tools autonomously, and the stream shows that work: the reply text streams incrementally as agent_message events, with agent_thought events carrying each reasoning step and tool call alongside.
The turn closes with a single message event carrying the complete answer, then message_end. Render the agent_message deltas live and treat the closing message as the final answer rather than appending it.
Each agent_thought event carries the step's thought, the tool it called with its tool_input, and the tool's observation. The full stream shape is on Send Chat Message.
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 Agent app. Streaming mode only; blocking mode returns a 400
bad_requesterror.
Reply text streams as agent_message deltas, batched at roughly half-second intervals rather than token by token.
The closing message_end event reports token usage. It never includes knowledge-retrieval citations (retriever_resources).
Two limits end a run early, and either one closes the stream with the agent_run_limit_exceeded error code:
-
Time: a run is stopped after 1 hour by default.
For longer runs on self-hosted deployments, raise
APP_MAX_EXECUTION_TIME,WORKFLOW_MAX_EXECUTION_TIME, andDIFY_AGENT_RUN_TIMEOUT_SECONDSabove the duration you need. See Environment Variables for details. * Model requests: each run is capped at 500. -
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. Each message's
agent_thoughtsarray carries the reasoning steps for that turn. - Rename Conversation: set a conversation's name, or have one generated from its content.
- Delete Conversation: remove a conversation and its messages.
Upload Files
- Upload File: upload an image, document, audio, or video file, scoped to the uploading end user.
Files passed to Send Chat Message are surfaced to the agent as downloadable references it can fetch and inspect in its sandbox.
- 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.
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: app metadata; the
tool_iconsmap is empty for Agent apps. - Get App WebApp Settings: the web app's site configuration, theme, and customization options.
Manage tools that enable LLMs to interact with external services and APIs
Add tools to your apps so the LLM can call external services and APIs to access real-time data or perform actions, such as web searches, database queries, or content processing.
Use tools in:
- Workflow / Chatflow apps, as standalone Tool nodes or within Agent nodes
- Agent apps
- Legacy Agent apps
Manage all your tools from Integrations > Tools.
Tool Types
Ready-to-use tools from Dify and the community for common utilities and popular services. Built-in ones like Current Time work out of the box; install more from the [Marketplace](https://marketplace.dify.ai/).
Some tool plugins, such as Google and GitHub, need authentication first. Set workspace-level credentials in **Integrations** > **Tools** > **Tool Plugin**, or in the tool's settings inside an app or node.
Integrate a service that isn't available as a tool plugin by importing its OpenAPI (Swagger) specification.
Paste the schema, import it from a URL, or start from the provided example, and Dify generates the tool interface for you.
Turn any Workflow that starts with a User Input node into a tool, so you can reuse multi-step logic across apps. Chatflows cannot be used as tools.
Creating the tool publishes the workflow first, so the tool matches the workflow as it stands.
<img alt="Workflow as Tool" />
Connect an [MCP server](https://modelcontextprotocol.io/) to import its tools into Dify. An MCP server wraps external resources, such as databases, file systems, or APIs, and exposes them through a standard interface, so your apps can call them like any other tool.
To publish one of your own Dify apps *as* an MCP server instead, see [Publish as an MCP Server](https://docs.dify.ai/en/self-host/use-dify/publish/publish-mcp).
### Connect an MCP Server
Only MCP servers with [HTTP transport](https://modelcontextprotocol.io/docs/learn/architecture#transport-layer) are supported.
Add a server by providing its URL, a name, and a unique server identifier. Dify connects, authorizes if needed, and imports the server's tools so your apps can call them.
You can update the tool list later to pull the server's latest tools, though doing so can break an app if a tool it uses is removed or changed.
* Apps reference a server by its identifier. If you change it later, the server's tools stop working in apps that used the old one; re-add the tools in each affected app to restore them.
* Exported apps reference servers by identifier too, so to run one in another workspace, recreate the same servers there with matching identifiers.
### Authentication
**Dynamic Client Registration** (on by default) lets Dify obtain OAuth credentials from the server automatically, so you don't register an application yourself. Leave it on whenever the server supports it.
Turn it off when the server doesn't support automatic registration, or when you must use your team's existing OAuth application. Enter its **Client ID** and **Client Secret**, then register the redirect URL Dify shows.
### Advanced Options
#### Custom Headers
Send additional HTTP headers with every request to the server. Commonly used for servers that authenticate with a static token or API key (e.g., `Authorization: Bearer <token>`) rather than OAuth, but applicable whenever the server expects custom headers.
Header values can also be dynamic: `{{request.headers.X-Custom-Auth}}` is replaced at call time with the `X-Custom-Auth` header of the HTTP request that triggered the run (a Service API call, for example), letting you pass each caller's credentials through to the server.
A header the request doesn't carry resolves to an empty value; when a run has no originating HTTP request, the placeholder text is sent unchanged.
#### Timeouts
Control how long Dify waits on the server. Raise the request timeout when the server is slow to respond, and the SSE read timeout for long-running, streamed results. Change them only if you hit timeout errors.
Manage tools that enable LLMs to interact with external services and APIs
Add tools to your apps so the LLM can call external services and APIs to access real-time data or perform actions, such as web searches, database queries, or content processing.
Use tools in:
- Workflow / Chatflow apps, as standalone Tool nodes or within Agent nodes
- Agent apps
- Legacy Agent apps
Manage all your tools from Integrations > Tools.
Tool Types
Ready-to-use tools from Dify and the community for common utilities and popular services. Built-in ones like Current Time work out of the box; install more from the [Marketplace](https://marketplace.dify.ai/).
Some tool plugins, such as Google and GitHub, need authentication first. Set workspace-level credentials in **Integrations** > **Tools** > **Tool Plugin**, or in the tool's settings inside an app or node.
Integrate a service that isn't available as a tool plugin by importing its OpenAPI (Swagger) specification.
Paste the schema, import it from a URL, or start from the provided example, and Dify generates the tool interface for you.
Turn any Workflow that starts with a User Input node into a tool, so you can reuse multi-step logic across apps. Chatflows cannot be used as tools.
Creating the tool publishes the workflow first, so the tool matches the workflow as it stands.
<img alt="Workflow as Tool" />
Connect an [MCP server](https://modelcontextprotocol.io/) to import its tools into Dify. An MCP server wraps external resources, such as databases, file systems, or APIs, and exposes them through a standard interface, so your apps can call them like any other tool.
To publish one of your own Dify apps *as* an MCP server instead, see [Publish as an MCP Server](https://docs.dify.ai/en/cloud/use-dify/publish/publish-mcp).
### Connect an MCP Server
Only MCP servers with [HTTP transport](https://modelcontextprotocol.io/docs/learn/architecture#transport-layer) are supported.
Add a server by providing its URL, a name, and a unique server identifier. Dify connects, authorizes if needed, and imports the server's tools so your apps can call them.
You can update the tool list later to pull the server's latest tools, though doing so can break an app if a tool it uses is removed or changed.
* Apps reference a server by its identifier. If you change it later, the server's tools stop working in apps that used the old one; re-add the tools in each affected app to restore them.
* Exported apps reference servers by identifier too, so to run one in another workspace, recreate the same servers there with matching identifiers.
### Authentication
**Dynamic Client Registration** (on by default) lets Dify obtain OAuth credentials from the server automatically, so you don't register an application yourself. Leave it on whenever the server supports it.
Turn it off when the server doesn't support automatic registration, or when you must use your team's existing OAuth application. Enter its **Client ID** and **Client Secret**, then register the redirect URL Dify shows.
### Advanced Options
#### Custom Headers
Send additional HTTP headers with every request to the server. Commonly used for servers that authenticate with a static token or API key (e.g., `Authorization: Bearer <token>`) rather than OAuth, but applicable whenever the server expects custom headers.
Header values can also be dynamic: `{{request.headers.X-Custom-Auth}}` is replaced at call time with the `X-Custom-Auth` header of the HTTP request that triggered the run (a Service API call, for example), letting you pass each caller's credentials through to the server.
A header the request doesn't carry resolves to an empty value; when a run has no originating HTTP request, the placeholder text is sent unchanged.
#### Timeouts
Control how long Dify waits on the server. Raise the request timeout when the server is slow to respond, and the SSE read timeout for long-running, streamed results. Change them only if you hit timeout errors.
The error envelope, what each status class means, and which failures are worth retrying
Every documented error uses the same three-field JSON envelope:
{
"code": "invalid_param",
"message": "user is required",
"status": 400
}
status mirrors the HTTP status; code is the stable identifier to branch on; message is human-readable detail. Each endpoint page lists exactly which codes it can raise.
Status Classes at a Glance
| Status | Meaning | Typical codes |
|---|---|---|
| 400 | The request or the app's configuration is invalid | invalid_param, bad_request, app_unavailable, provider errors (below) |
| 401 | Missing or invalid API key | unauthorized |
| 403 | The key can't act here: access restrictions or plan limits | forbidden |
| 404 | The resource doesn't exist or isn't visible to this key or user |
not_found |
| 413 / 415 | A file is too large or of an unsupported type | file_too_large, unsupported_file_type |
| 429 | Too many requests right now, or a quota is exhausted | too_many_requests, rate_limit_error |
| 500 | Something failed on Dify's side | internal_server_error |
Provider Errors Are Configuration Errors
Four common 400 codes point at the app's model setup rather than your request:
provider_not_initialize: no valid model credentialsprovider_quota_exceeded: the model provider's own quota ran outmodel_currently_not_support: the model isn't currently supportedcompletion_request_error: an error occurred while making a completion request
For these errors, retrying won't help. Fix the app's model configuration in Dify.
Rate Limits and Quotas
The two 429 codes mean different things:
too_many_requestsis a concurrency ceiling—too many simultaneous requests for the app right now. Back off and retry.rate_limit_erroris a plan quota on Dify Cloud, such as workflow executions. Retrying won't clear it; it resets with the quota period or a plan change.
On Dify Cloud, knowledge write endpoints also enforce plan limits as 403 responses. These carry the same forbidden code as access restrictions—the message is what tells you it's a plan limit, so don't build a switch on code alone for 403s.
Errors Inside Streams
Once a stream opens, the HTTP status is already 200: failures arrive as an error event and end the stream. The event's code values are the same ones documented here—classify them with the same rules. See Consume Streaming Responses for details.
What to Retry
-
Retry with backoff:
too_many_requests,500, and network failures. -
Don't retry as-is: validation errors (fix the request first), authorization failures, or quota errors (they won't clear until the quota does).
-
Fix, don't retry: a
404from a resume call means the wronguseror a run that doesn't exist. Correct the identifier instead.
