diff --git a/api_access/chat.en.mdx b/api_access/chat.en.mdx new file mode 100644 index 00000000..df56bbdc --- /dev/null +++ b/api_access/chat.en.mdx @@ -0,0 +1,1192 @@ +--- +title: Chat and Agent +--- + +Chat applications support session persistence, allowing previous chat history to be used as context for responses. This can be applicable for chatbot, customer service AI, etc. + +### Base URL + +```text +https://api.dify.ai/v1 +``` + +### Authentication + +The Service API uses `API-Key` authentication. + + + **Strongly recommend storing your API Key on the server-side, not shared or + stored on the client-side, to avoid possible API-Key leakage that can lead + to serious consequences.** + + +For all API requests, include your API Key in the `Authorization` HTTP Header, as shown below: + +```text +Authorization: Bearer {YOUR_API_KEY} +``` + +--- + +## POST /chat-messages Send Chat Message + +Send a request to the chat application. + +### Request Body + +- `query` (string): User Input/Question content. +- `inputs` (object, optional, default `{}`): Allows the entry of various variable values defined by the App. The `inputs` parameter contains multiple key/value pairs, with each key corresponding to a specific variable and each value being the specific value for that variable. +- `response_mode` (string): The mode of response return, supporting: + - `streaming`: Streaming mode (recommended), implements a typewriter-like output through SSE ([Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)). + - `blocking`: Blocking mode, returns result after execution is complete. (Requests may be interrupted if the process is long). Due to Cloudflare restrictions, the request will be interrupted without a return after 100 seconds. + Note: blocking mode is not supported in Agent Assistant mode. +- `user` (string): User identifier, used to define the identity of the end-user for retrieval and statistics. Should be uniquely defined by the developer within the application. +- `conversation_id` (string, optional): Conversation ID. To continue the conversation based on previous chat records, it is necessary to pass the previous message's `conversation_id`. +- `files` (array[object], optional): File list, suitable for inputting files (images) combined with text understanding and answering questions, available only when the model supports Vision capability. + - `type` (string): Supported type: `image` (currently only supports image type). + - `transfer_method` (string): Transfer method, `remote_url` for image URL / `local_file` for file upload. + - `url` (string, conditional): Image URL (when the transfer method is `remote_url`). + - `upload_file_id` (string, conditional): Uploaded file ID, which must be obtained by uploading through the File Upload API in advance (when the transfer method is `local_file`). +- `auto_generate_name` (bool, optional, default `true`): Auto-generate title. If set to `false`, can achieve async title generation by calling the conversation rename API and setting `auto_generate` to `true`. + +### Response + +When `response_mode` is `blocking`, returns a `ChatCompletionResponse` object. +When `response_mode` is `streaming`, returns a `ChunkChatCompletionResponse` stream. + +#### ChatCompletionResponse + +Returns the complete App result, `Content-Type` is `application/json`. + +- `event` (string): Event type, fixed as `message`. +- `task_id` (string): Task ID, used for request tracking and the Stop Generate API. +- `id` (string): Unique ID. +- `message_id` (string): Unique message ID. +- `conversation_id` (string): Conversation ID. +- `mode` (string): App mode, fixed as `chat`. +- `answer` (string): Complete response content. +- `metadata` (object): Metadata. + - `usage` (Usage): Model usage information. + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List. +- `created_at` (int): Message creation timestamp, e.g., `1705395332`. + +#### ChunkChatCompletionResponse + +Returns the stream chunks outputted by the App, `Content-Type` is `text/event-stream`. +Each streaming chunk starts with `data:`, separated by two newline characters `\n\n`, as shown below: + +```streaming +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +The structure of the streaming chunks varies depending on the `event`: + +- `event: message`: LLM returns text chunk event, i.e., the complete text is output in a chunked fashion. + - `task_id` (string): Task ID, used for request tracking and the below Stop Generate API. + - `message_id` (string): Unique message ID. + - `conversation_id` (string): Conversation ID. + - `answer` (string): LLM returned text chunk content. + - `created_at` (int): Creation timestamp, e.g., `1705395332`. +- `event: agent_message`: LLM returns text chunk event, i.e., with Agent Assistant enabled, the complete text is output in a chunked fashion (Only supported in Agent mode). + - `task_id` (string): Task ID. + - `message_id` (string): Unique message ID. + - `conversation_id` (string): Conversation ID. + - `answer` (string): LLM returned text chunk content. + - `created_at` (int): Creation timestamp. +- `event: tts_message`: TTS audio stream event. Speech synthesis output. Content is an audio block in Mp3 format, base64 encoded. Decode base64 and feed to player. (Available only when auto-play is enabled). + - `task_id` (string): Task ID. + - `message_id` (string): Unique message ID. + - `audio` (string): Base64 encoded audio content. + - `created_at` (int): Creation timestamp. +- `event: tts_message_end`: TTS audio stream end event. + - `task_id` (string): Task ID. + - `message_id` (string): Unique message ID. + - `audio` (string): Empty string for this event. + - `created_at` (int): Creation timestamp. +- `event: agent_thought`: Thought of Agent, contains LLM thought, tool call input/output (Only supported in Agent mode). + - `id` (string): Agent thought ID. + - `task_id` (string): Task ID. + - `message_id` (string): Unique message ID. + - `position` (int): Position of current agent thought. + - `thought` (string): What LLM is thinking. + - `observation` (string): Response from tool calls. + - `tool` (string): List of tools called, separated by `;`. + - `tool_input` (string): JSON formatted tool input. E.g., `{"dalle3": {"prompt": "a cute cat"}}`. + - `created_at` (int): Creation timestamp. + - `message_files` (array[string]): File IDs. + - `file_id` (string): File ID. + - `conversation_id` (string): Conversation ID. +- `event: message_file`: Message file event, a new file created by a tool. + - `id` (string): File unique ID. + - `type` (string): File type, currently only "image". + - `belongs_to` (string): Belongs to, will only be 'assistant' here. + - `url` (string): Remote URL of the file. + - `conversation_id` (string): Conversation ID. +- `event: message_end`: Message end event, streaming has ended. + - `task_id` (string): Task ID. + - `message_id` (string): Unique message ID. + - `conversation_id` (string): Conversation ID. + - `metadata` (object): Metadata. + - `usage` (Usage): Model usage information. + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List. +- `event: message_replace`: Message content replacement event. If content moderation flags content, it's replaced via this event. + - `task_id` (string): Task ID. + - `message_id` (string): Unique message ID. + - `conversation_id` (string): Conversation ID. + - `answer` (string): Replacement content. + - `created_at` (int): Creation timestamp. +- `event: error`: Exceptions during streaming. Reception ends the stream. + - `task_id` (string): Task ID. + - `message_id` (string): Unique message ID. + - `status` (int): HTTP status code. + - `code` (string): Error code. + - `message` (string): Error message. +- `event: ping`: Ping event every 10 seconds to keep the connection alive. + +### Errors + +- 404, Conversation does not exist. +- 400, `invalid_param`, abnormal parameter input. +- 400, `app_unavailable`, App configuration unavailable. +- 400, `provider_not_initialize`, no available model credential configuration. +- 400, `provider_quota_exceeded`, model invocation quota insufficient. +- 400, `model_currently_not_support`, current model unavailable. +- 400, `completion_request_error`, text generation failed. +- 500, internal server error. + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {}, + "query": "What are the specs of the iPhone 13 Pro Max?", + "response_mode": "streaming", + "conversation_id": "", + "user": "abc-123", + "files": [ + { + "type": "image", + "transfer_method": "remote_url", + "url": "https://cloud.dify.ai/logo/logo-site.png" + } + ] +}' +``` + + + +```json "Blocking Mode Response" +{ + "event": "message", + "task_id": "c3800678-a077-43df-a102-53f23ed20b88", + "id": "9da23599-e713-473b-982c-4328d4f5c78a", + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", + "mode": "chat", + "answer": "iPhone 13 Pro Max specs are listed here:...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + }, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ] + }, + "created_at": 1705407629 +} +``` +```streaming "Streaming (Basic Assistant)" + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} + data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` +```streaming "Streaming (Agent Assistant)" +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} +data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} +data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} +data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} +data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} +data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +--- + +## POST /files/upload File Upload + +Upload a file (currently only images are supported) for use when sending messages, enabling multimodal understanding of images and text. +Supports png, jpg, jpeg, webp, gif formats. +Uploaded files are for use by the current end-user only. + +### Request Body + +This interface requires a `multipart/form-data` request. + +- `file` (File, Required): The file to be uploaded. +- `user` (string, Required): User identifier, defined by the developer's rules, must be unique within the application. + +### Response + +After a successful upload, the server will return the file's ID and related information. + +- `id` (uuid): ID. +- `name` (string): File name. +- `size` (int): File size (bytes). +- `extension` (string): File extension. +- `mime_type` (string): File mime-type. +- `created_by` (uuid): End-user ID. +- `created_at` (timestamp): Creation timestamp, e.g., `1705395332`. + +### Errors + +- 400, `no_file_uploaded`, a file must be provided. +- 400, `too_many_files`, currently only one file is accepted. +- 400, `unsupported_preview`, the file does not support preview. +- 400, `unsupported_estimate`, the file does not support estimation. +- 413, `file_too_large`, the file is too large. +- 415, `unsupported_file_type`, unsupported extension. +- 503, `s3_connection_failed`, unable to connect to S3 service. +- 503, `s3_permission_denied`, no permission to upload files to S3. +- 503, `s3_file_too_large`, file exceeds S3 size limit. +- 500, internal server error. + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header + 'Authorization: Bearer {YOUR_API_KEY}' \ --form + 'file=@"/path/to/your/localfile.png";type=image/png' \ --form + 'user="abc-123"' ``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 +} +``` + + +--- + +## POST /chat-messages/:task_id/stop Stop Generate + +Only supported in streaming mode. + +### Path Parameters + +- `task_id` (string): Task ID, can be obtained from the streaming chunk return. + +### Request Body + +- `user` (string, Required): User identifier, used to define the identity of the end-user, must be consistent with the user passed in the send message interface. + +### Response + +- `result` (string): Always returns "success". + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages/:task_id/stop' \ +-H 'Authorization: Bearer {YOUR_API_KEY}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## POST /messages/:message_id/feedbacks Message Feedback + +End-users can provide feedback messages, facilitating application developers to optimize expected outputs. + +### Path Parameters + +- `message_id` (string): Message ID. + +### Request Body + +- `rating` (string): Upvote as `like`, downvote as `dislike`, revoke upvote/downvote as `null`. +- `user` (string): User identifier, defined by the developer's rules, must be unique within the application. +- `content` (string, optional): The specific content of message feedback. + +### Response + +- `result` (string): Always returns "success". + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/messages/:message_id/feedbacks' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## GET /messages/:message_id/suggested Next Suggested Questions + +Get next questions suggestions for the current message. + +### Path Parameters + +- `message_id` (string): Message ID. + +### Query Parameters + +- `user` (string): User identifier, used to define the identity of the end-user for retrieval and statistics. Should be uniquely defined by the developer within the application. + + + ```bash cURL curl --location --request GET 'https://api.dify.ai/v1/messages/ + {message_id}/suggested?user=abc-123' \ --header 'Authorization: Bearer { + YOUR_API_KEY + }' \ --header 'Content-Type: application/json' ``` + + + +```json Response +{ + "result": "success", + "data": [ + "a", + "b", + "c" + ] +} +``` + + +--- + +## GET /messages Get Conversation History Messages + +Returns historical chat records in a scrolling load format, with the first page returning the latest `{limit}` messages, i.e., in reverse order. + +### Query Parameters + +- `conversation_id` (string): Conversation ID. +- `user` (string): User identifier. +- `first_id` (string, optional): The ID of the first chat record on the current page, default is null. +- `limit` (int, optional, default `20`): How many chat history messages to return in one request. + +### Response + +- `data` (array[object]): Message list. + - `id` (string): Message ID. + - `conversation_id` (string): Conversation ID. + - `inputs` (object): User input parameters. + - `query` (string): User input / question content. + - `message_files` (array[object]): Message files. + - `id` (string): ID. + - `type` (string): File type, `image` for images. + - `url` (string): Preview image URL. + - `belongs_to` (string): Belongs to, `user` or `assistant`. + - `agent_thoughts` (array[object]): Agent thought (Empty if it's a Basic Assistant). + - `id` (string): Agent thought ID. + - `message_id` (string): Unique message ID. + - `position` (int): Position of current agent thought. + - `thought` (string): What LLM is thinking. + - `observation` (string): Response from tool calls. + - `tool` (string): List of tools called, separated by `;`. + - `tool_input` (string): JSON formatted tool input. + - `created_at` (int): Creation timestamp. + - `message_files` (array[string]): File IDs. + - `file_id` (string): File ID. + - `answer` (string): Response message content. + - `created_at` (timestamp): Creation timestamp. + - `feedback` (object, optional): Feedback information. + - `rating` (string): `like` / `dislike`. + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List. +- `has_more` (bool): Whether there is a next page. +- `limit` (int): Number of returned items. + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/messages?user=abc-123&conversation_id= + {YOUR_CONVERSATION_ID}' \ --header 'Authorization: Bearer {YOUR_API_KEY}' ``` + + + +```json "Basic Assistant Response" +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "a076a87f-31e5-48dc-b452-0061adbbc922", + "conversation_id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "inputs": { + "name": "dify" + }, + "query": "iphone 13 pro", + "answer": "The iPhone 13 Pro, released on September 24, 2021, features a 6.1-inch display...", + "message_files": [], + "feedback": null, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + // ... more retriever_resources fields + "content": "\"Model\",\"Release Date\",\"Display Size\"..." + } + ], + "agent_thoughts": [], + "created_at": 1705569239 + } + ] +} +``` +```json "Agent Assistant Response" +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "conversation_id": "957c068b-f258-4f89-ba10-6e8a0361c457", + "inputs": {}, + "query": "draw a cat", + "answer": "I have generated an image of a cat for you...", + "message_files": [ + { + "id": "976990d2-5294-47e6-8f14-7356ba9d2d76", + "type": "image", + "url": "http://127.0.0.1:5001/files/tools/...", + "belongs_to": "assistant" + } + ], + "feedback": null, + "retriever_resources": [], + "created_at": 1705988187, + "agent_thoughts": [ + { + "id": "592c84cf-07ee-441c-9dcc-ffc66c033469", + // ... more agent_thoughts fields + "files": [ + "976990d2-5294-47e6-8f14-7356ba9d2d76" + ] + }, + { + "id": "73ead60d-2370-4780-b5ed-532d2762b0e5", + // ... more agent_thoughts fields + "files": [] + } + ] + } + ] +} +``` + + +--- + +## GET /conversations Get Conversations + +Retrieve the conversation list for the current user, defaulting to the most recent 20 entries. + +### Query Parameters + +- `user` (string): User identifier. +- `last_id` (string, optional): The ID of the last record on the current page, default is null. +- `limit` (int, optional, default `20`, max `100`, min `1`): How many records to return. +- `sort_by` (string, optional, default `-updated_at`): Sorting Field. Available: `created_at`, `-created_at`, `updated_at`, `-updated_at`. `-` denotes descending. + +### Response + +- `data` (array[object]): List of conversations. + - `id` (string): Conversation ID. + - `name` (string): Conversation name. + - `inputs` (object): User input parameters. + - `status` (string): Conversation status. + - `introduction` (string): Introduction. + - `created_at` (timestamp): Creation timestamp. + - `updated_at` (timestamp): Update timestamp. +- `has_more` (bool): Whether there is a next page. +- `limit` (int): Number of entries returned. + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/conversations?user=abc-123&last_id=&limit=20' \ + --header 'Authorization: Bearer {YOUR_API_KEY}' ``` + + + +```json Response +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54", + "name": "New chat", + "inputs": { + "book": "book", + "myName": "Lucy" + }, + "status": "normal", + "created_at": 1679667915, + "updated_at": 1679667915 + }, + { + "id": "hSIhXBhNe8X1d8Et" + // ... + } + ] +} +``` + + +--- + +## DELETE /conversations/:conversation_id Delete Conversation + +Delete a conversation. + +### Path Parameters + +- `conversation_id` (string): Conversation ID. + +### Request Body + +- `user` (string): The user identifier. + +### Response + +- `204 No Content` + + +```bash cURL +curl -X DELETE 'https://api.dify.ai/v1/conversations/{conversation_id}' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + +```text Response 204 No Content ``` + +--- + +## POST /conversations/:conversation_id/name Conversation Rename + +Rename the session. The session name is used for display on clients that support multiple sessions. + +### Path Parameters + +- `conversation_id` (string): Conversation ID. + +### Request Body + +- `name` (string, optional): The name of the conversation. Can be omitted if `auto_generate` is `true`. +- `auto_generate` (bool, optional, default `false`): Automatically generate the title. +- `user` (string): The user identifier. + +### Response + +- `id` (string): Conversation ID. +- `name` (string): Conversation name. +- `inputs` (object): User input parameters. +- `status` (string): Conversation status. +- `introduction` (string): Introduction. +- `created_at` (timestamp): Creation timestamp. +- `updated_at` (timestamp): Update timestamp. + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/conversations/{conversation_id}/name' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name": "", + "auto_generate": true, + "user": "abc-123" +}' +``` + + + +```json Response +{ + "id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "name": "Chat vs AI", + "inputs": {}, + "status": "normal", + "introduction": "", + "created_at": 1705569238, + "updated_at": 1705569238 +} +``` + + +--- + +## GET /conversations/:conversation_id/variables Get Conversation Variables + +Retrieve variables from a specific conversation. Useful for extracting structured data captured during the conversation. + +### Path Parameters + +- `conversation_id` (string): The ID of the conversation. + +### Query Parameters + +- `user` (string): The user identifier. +- `last_id` (string, optional): The ID of the last record on the current page, default is null. +- `limit` (int, optional, default `20`, max `100`, min `1`): Number of records to return. +- `variable_name` (string, optional): Filter by a specific variable name. + +### Response + +- `limit` (int): Number of items per page. +- `has_more` (bool): Whether there is a next page. +- `data` (array[object]): List of variables. + - `id` (string): Variable ID. + - `name` (string): Variable name. + - `value_type` (string): Variable type (e.g., string, number, object). + - `value` (string): Variable value. + - `description` (string): Variable description. + - `created_at` (int): Creation timestamp. + - `updated_at` (int): Last update timestamp. + +### Errors + +- 404, `conversation_not_exists`, Conversation not found. + + + ```bash "Get all variables" curl -X GET + 'https://api.dify.ai/v1/conversations/{conversation_id} + /variables?user=abc-123' \ --header 'Authorization: Bearer {YOUR_API_KEY}' ``` + ```bash "Filter by variable name" curl -X GET 'https://api.dify.ai/v1/conversations/ + {conversation_id} + /variables?user=abc-123&variable_name=customer_name' \ --header + 'Authorization: Bearer {YOUR_API_KEY}' ``` + + + +```json Response +{ + "limit": 100, + "has_more": false, + "data": [ + { + "id": "variable-uuid-1", + "name": "customer_name", + "value_type": "string", + "value": "John Doe", + "description": "Customer name extracted from the conversation", + "created_at": 1650000000000, + "updated_at": 1650000000000 + }, + { + "id": "variable-uuid-2", + "name": "order_details", + "value_type": "json", + "value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}", + "description": "Order details from the customer", + "created_at": 1650000000000, + "updated_at": 1650000000000 + } + ] +} +``` + + +--- + +## POST /audio-to-text Speech to Text + +This endpoint requires a `multipart/form-data` request. + +### Request Body + +- `file` (file): Audio file. + Supported formats: `mp3, mp4, mpeg, mpga, m4a, wav, webm`. + File size limit: 15MB. +- `user` (string): User identifier. + +### Response + +- `text` (string): Output text. + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/audio-to-text' \ --header + 'Authorization: Bearer {YOUR_API_KEY}' \ --form + 'file=@"/path/to/your/audiofile.mp3";type=audio/mp3' \ --form + 'user="abc-123"' ``` + + + +```json Response +{ + "text": "Transcribed text from audio." +} +``` + + +--- + +## POST /text-to-audio Text to Audio + +Text to speech. + +### Request Body + +- `message_id` (string, optional): For text messages generated by Dify, pass the `message_id`. Backend uses it to find content for synthesis. Priority over `text` if both provided. +- `text` (string, optional): Speech content to generate. Required if `message_id` is not provided. +- `user` (string): The user identifier. + +### Response + +The response is an audio file stream. +**Headers:** + +- `Content-Type`: `audio/wav` (or other audio format depending on system configuration) + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "text": "Hello Dify", + "user": "abc-123" +}' \ +--output 'output.wav' +``` +To use `message_id`: +```bash cURL with message_id +curl --location --request POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", + "user": "abc-123" +}' \ +--output 'output.wav' +``` + + + + ```text "Response Headers" Content-Type: audio/wav // ... other headers ... + ``` ```text "Response Body" (Binary audio data) ``` + + +--- + +## GET /info Get Application Basic Information + +Used to get basic information about this application. + +### Response + +- `name` (string): Application name. +- `description` (string): Application description. +- `tags` (array[string]): Application tags. + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {YOUR_API_KEY}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## GET /parameters Get Application Parameters Information + +Used at the start of entering the page to obtain information such as features, input parameter names, types, and default values. + +### Query Parameters + +- `user` (string): User identifier. + +### Response + +- `opening_statement` (string): Opening statement. +- `suggested_questions` (array[string]): List of suggested questions for the opening. +- `suggested_questions_after_answer` (object): Suggest questions after enabling the answer. + - `enabled` (bool): Whether it is enabled. +- `speech_to_text` (object): Speech to text. + - `enabled` (bool): Whether it is enabled. +- `retriever_resource` (object): Citation and Attribution. + - `enabled` (bool): Whether it is enabled. +- `annotation_reply` (object): Annotation reply. + - `enabled` (bool): Whether it is enabled. +- `user_input_form` (array[object]): User input form configuration. + - `text-input` (object): Text input control. + - `label` (string): Variable display label name. + - `variable` (string): Variable ID. + - `required` (bool): Whether it is required. + - `default` (string): Default value. + - `paragraph` (object): Paragraph text input control. + - `label` (string): Variable display label name. + - `variable` (string): Variable ID. + - `required` (bool): Whether it is required. + - `default` (string): Default value. + - `select` (object): Dropdown control. + - `label` (string): Variable display label name. + - `variable` (string): Variable ID. + - `required` (bool): Whether it is required. + - `default` (string): Default value. + - `options` (array[string]): Option values. +- `file_upload` (object): File upload configuration. + - `image` (object): Image settings. Currently supports `png, jpg, jpeg, webp, gif`. + - `enabled` (bool): Whether it is enabled. + - `number_limits` (int): Image number limit (default 3). + - `transfer_methods` (array[string]): List of transfer methods (`remote_url`, `local_file`). +- `system_parameters` (object): System parameters. + - `file_size_limit` (int): Document upload size limit (MB). + - `image_file_size_limit` (int): Image file upload size limit (MB). + - `audio_file_size_limit` (int): Audio file upload size limit (MB). + - `video_file_size_limit` (int): Video file upload size limit (MB). + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters?user=abc-123' \ + --header 'Authorization: Bearer {YOUR_API_KEY}' ``` + + + +```json Response +{ + "opening_statement": "Hello!", + "suggested_questions_after_answer": { + "enabled": true + }, + "speech_to_text": { + "enabled": true + }, + "retriever_resource": { + "enabled": true + }, + "annotation_reply": { + "enabled": true + }, + "user_input_form": [ + { + "paragraph": { + "label": "Query", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + + +--- + +## GET /meta Get Application Meta Information + +Used to get icons of tools in this application. + +### Response + +- `tool_icons` (object): Tool icons. + - `tool_name` (string): Key is the tool name. + - `icon` (object|string): Icon can be an object or a URL string. + - (object) `background` (string): Background color in hex. + - (object) `content` (string): Emoji or icon character. + - (string) URL of the icon. + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/meta' \ -H 'Authorization: + Bearer {YOUR_API_KEY}' ``` + + + +```json Response +{ + "tool_icons": { + "dalle2": "https://cloud.dify.ai/console/api/workspaces/current/tool-provider/builtin/dalle/icon", + "api_tool": { + "background": "#252525", + "content": "\ud83d\ude01" + } + } +} +``` + + +--- + +## GET /apps/annotations Get Annotation List + +### Query Parameters + +- `page` (int, optional, default `1`): Page number. +- `limit` (int, optional, default `20`, range `1-100`): Number of items returned. + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotations?page=1&limit=20' \ --header + 'Authorization: Bearer {YOUR_API_KEY}' ``` + + + +```json Response +{ + "data": [ + { + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 + } + ], + "has_more": false, + "limit": 20, + "total": 1, + "page": 1 +} +``` + + +--- + +## POST /apps/annotations Create Annotation + +### Request Body + +- `question` (string): Question. +- `answer` (string): Answer. + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/apps/annotations' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your name?", + "answer": "I am Dify." +}' +``` + + + +```json Response +{ + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + + +--- + +## PUT /apps/annotations/:annotation_id Update Annotation + +### Path Parameters + +- `annotation_id` (string): Annotation ID. + +### Request Body + +- `question` (string, optional): Question. +- `answer` (string, optional): Answer. + + +```bash cURL +curl --location --request PUT 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your full name?", + "answer": "I am Dify, your AI assistant." +}' +``` + + + +```json Response +{ + "id": "{annotation_id}", + "question": "What is your full name?", + "answer": "I am Dify, your AI assistant.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + + +--- + +## DELETE /apps/annotations/:annotation_id Delete Annotation + +### Path Parameters + +- `annotation_id` (string): Annotation ID. + +### Response + +- `204 No Content` + + + ```bash cURL curl --location --request DELETE + 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ --header + 'Authorization: Bearer {YOUR_API_KEY}' ``` + + +```text Response 204 No Content ``` + +--- + +## POST /apps/annotation-reply/:action Initial Annotation Reply Settings + +### Path Parameters + +- `action` (string): Action, can only be `enable` or `disable`. + +### Request Body + +- `embedding_model_provider` (string, optional): Specified embedding model provider. Must be set up in the system. +- `embedding_model` (string, optional): Specified embedding model. +- `score_threshold` (number, optional): Similarity threshold for matching annotated replies. Only annotations with scores above this threshold will be recalled. (Required if enabling) + +**Note:** The provider and model name of the embedding model can be obtained through `v1/workspaces/current/models/model-types/text-embedding`. (Requires Dataset API Token for that endpoint). + + +```bash "Enable with specific model" +curl --location --request POST 'https://api.dify.ai/v1/apps/annotation-reply/enable' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "score_threshold": 0.9, + "embedding_model_provider": "zhipu", + "embedding_model": "embedding_3" +}' +``` +```bash "Disable" +curl --location --request POST 'https://api.dify.ai/v1/apps/annotation-reply/disable' \ +--header 'Authorization: Bearer {YOUR_API_KEY}' \ +--header 'Content-Type: application/json' +``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "waiting" +} +``` +This interface is executed asynchronously. Query the job status interface to get the final result. + + +--- + +## GET /apps/annotation-reply/:action/status/:job_id Query Initial Annotation Reply Settings Task Status + +### Path Parameters + +- `action` (string): Action, `enable` or `disable`. Must match the action in the initial settings call. +- `job_id` (string): Job ID from the initial settings call. + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotation-reply/enable/status/{job_id}' \ + --header 'Authorization: Bearer {YOUR_API_KEY}' ``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "succeeded", // or "waiting", "processing", "failed" + "error_msg": "" // Contains error message if job_status is "failed" +} +``` + diff --git a/api_access/chat.ja.mdx b/api_access/chat.ja.mdx new file mode 100644 index 00000000..94819033 --- /dev/null +++ b/api_access/chat.ja.mdx @@ -0,0 +1,980 @@ +--- +title: チャットアプリAPI +--- + +チャットアプリケーションはセッションの持続性をサポートしており、以前のチャット履歴を応答のコンテキストとして使用できます。これは、チャットボットやカスタマーサービス AI などに適用できます。 + +### ベース URL + +```text +https://api.dify.ai/v1 +``` + +### 認証 + +サービス API は`API-Key`認証を使用します。 + + + **APIキーの漏洩を防ぐため、APIキーはクライアント側で共有または保存せず、サーバー側で保存することを強くお勧めします。** + + +すべての API リクエストにおいて、以下のように`Authorization`HTTP ヘッダーに API キーを含めてください: + +``` +Authorization: Bearer {API_KEY} +``` + +--- + +## チャットメッセージを送信 `POST /chat-messages` + +チャットアプリケーションにリクエストを送信します。 + +### リクエストボディ + +- `query` (string, required): ユーザー入力/質問内容 +- `inputs` (object): アプリで定義されたさまざまな変数値の入力を許可します。`inputs`パラメータには複数のキー/値ペアが含まれ、各キーは特定の変数に対応し、各値はその変数の特定の値です。デフォルトは`{}` +- `response_mode` (string, required): 応答の返却モードを指定します。サポートされているモード: + - `streaming` ストリーミングモード(推奨)、SSE([Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events))を通じてタイプライターのような出力を実装します。 + - `blocking` ブロッキングモード、実行完了後に結果を返します。(プロセスが長い場合、リクエストが中断される可能性があります) + Cloudflare の制限により、100 秒後に応答がない場合、リクエストは中断されます。 + + 注:エージェントアシスタントモードではブロッキングモードはサポートされていません + +- `user` (string, required): ユーザー識別子、エンドユーザーのアイデンティティを定義するために使用されます。アプリケーション内で開発者によって一意に定義される必要があります。 +- `conversation_id` (string): 会話 ID、以前のチャット記録に基づいて会話を続けるには、前のメッセージの conversation_id を渡す必要があります。 +- `files` (array[object]): ファイルリスト、テキストの理解と質問への回答を組み合わせたファイル(画像)の入力に適しており、モデルがビジョン機能をサポートしている場合にのみ利用可能です。 + - `type` (string): サポートされているタイプ:`image`(現在は画像タイプのみサポート) + - `transfer_method` (string): 転送方法、画像 URL の場合は`remote_url` / ファイルアップロードの場合は`local_file` + - `url` (string): 画像 URL(転送方法が`remote_url`の場合) + - `upload_file_id` (string): アップロードされたファイル ID、事前にファイルアップロード API を通じて取得する必要があります(転送方法が`local_file`の場合) +- `auto_generate_name` (bool): タイトルを自動生成します。デフォルトは`true`です。 + +### 応答 + +`response_mode`がブロッキングの場合、`ChatCompletionResponse`オブジェクトを返します。 +`response_mode`がストリーミングの場合、`ChunkChatCompletionResponse`ストリームを返します。 + +#### ChatCompletionResponse + +完全なアプリ結果を返します。`Content-Type`は`application/json`です。 + +- `event` (string): イベントタイプ、固定で `message` +- `task_id` (string): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 +- `id` (string): ユニーク ID +- `message_id` (string): 一意のメッセージ ID +- `conversation_id` (string): 会話 ID +- `mode` (string): アプリモード、`chat`として固定 +- `answer` (string): 完全な応答内容 +- `metadata` (object): メタデータ + - `usage` (object): モデル使用情報 (詳細は Usage オブジェクトを参照) + - `retriever_resources` (array[object]): 引用と帰属リスト (詳細は RetrieverResource オブジェクトを参照) +- `created_at` (int): メッセージ作成タイムスタンプ、例:1705395332 + +#### ChunkChatCompletionResponse + +アプリによって出力されたストリームチャンクを返します。`Content-Type`は`text/event-stream`です。 +各ストリーミングチャンクは`data:`で始まり、2 つの改行文字`\n\n`で区切られます。以下のように表示されます: + + +```streaming 応答 +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +ストリーミングチャンクの構造は`event`に応じて異なります: +- `event: message`: LLMはテキストチャンクイベントを返します。つまり、完全なテキストがチャンク形式で出力されます。 + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `conversation_id` (string): 会話ID + - `answer` (string): LLMが返したテキストチャンク内容 + - `created_at` (int): 作成タイムスタンプ +- `event: agent_message`: LLMはテキストチャンクイベントを返します(エージェントモードでのみサポート)。 + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `conversation_id` (string): 会話ID + - `answer` (string): LLMが返したテキストチャンク内容 + - `created_at` (int): 作成タイムスタンプ +- `event: tts_message`: TTSオーディオストリームイベント。内容はMp3形式のオーディオブロックで、base64文字列としてエンコードされています。(自動再生が有効な場合のみ利用可能) + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `audio` (string): base64エンコードされたオーディオコンテンツ + - `created_at` (int): 作成タイムスタンプ +- `event: tts_message_end`: TTSオーディオストリーム終了イベント。 + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `audio` (string): 空の文字列 + - `created_at` (int): 作成タイムスタンプ +- `event: agent_thought`: エージェントの思考(エージェントモードでのみサポート)。 + - `id` (string): エージェント思考ID + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `position` (int): 現在のエージェント思考の位置 + - `thought` (string): LLMが考えていること + - `observation` (string): ツール呼び出しからの応答 + - `tool` (string): 呼び出されたツールのリスト(;で区切られる) + - `tool_input` (string): ツールの入力(JSON形式) + - `created_at` (int): 作成タイムスタンプ + - `message_files` (array[string]): この思考ステップに関連付けられたファイルIDのリスト。各IDは、対応する `message_file` イベントで詳細が提供されるファイルを参照します。 + - `conversation_id` (string): 会話ID +- `event: message_file`: メッセージファイルイベント。ツールによって新しいファイルが作成されました。 + - `id` (string): ファイル一意ID + - `type` (string): ファイルタイプ(現在は"image"のみ) + - `belongs_to` (string): 所属(ここでは'assistant'のみ) + - `url` (string): ファイルのリモートURL + - `conversation_id` (string): 会話ID +- `event: message_end`: メッセージ終了イベント。 + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `conversation_id` (string): 会話ID + - `metadata` (object): メタデータ + - `usage` (object): モデル使用情報 + - `retriever_resources` (array[object]): 引用と帰属リスト +- `event: message_replace`: メッセージ内容置換イベント。 + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `conversation_id` (string): 会話ID + - `answer` (string): 置換内容 + - `created_at` (int): 作成タイムスタンプ +- `event: error`: エラーイベント。 + - `task_id` (string): タスクID + - `message_id` (string): 一意のメッセージID + - `status` (int): HTTPステータスコード + - `code` (string): エラーコード + - `message` (string): エラーメッセージ +- `event: ping`: 接続維持のためのpingイベント(10秒ごと)。 + +### エラー + +- 404, 会話が存在しません +- 400, `invalid_param`, 異常なパラメータ入力 +- 400, `app_unavailable`, アプリ構成が利用できません +- 400, `provider_not_initialize`, 利用可能なモデル資格情報構成がありません +- 400, `provider_quota_exceeded`, モデル呼び出しクォータが不足しています +- 400, `model_currently_not_support`, 現在のモデルは利用できません +- 400, `completion_request_error`, テキスト生成に失敗しました +- 500, 内部サーバーエラー + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {}, + "query": "What are the specs of the iPhone 13 Pro Max?", + "response_mode": "streaming", + "conversation_id": "", + "user": "abc-123", + "files": [ + { + "type": "image", + "transfer_method": "remote_url", + "url": "https://cloud.dify.ai/logo/logo-site.png" + } + ] +}' +``` + + + +```json 応答 (ブロッキングモード) +{ + "event": "message", + "task_id": "c3800678-a077-43df-a102-53f23ed20b88", + "id": "9da23599-e713-473b-982c-4328d4f5c78a", + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", + "mode": "chat", + "answer": "iPhone 13 Pro Maxの仕様は次のとおりです:...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + }, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ] + }, + "created_at": 1705407629 +} +``` +```streaming 応答 (ストリーミングモード - 基本アシスタント) +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} +data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} +data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} +data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} +data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} +data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` +```streaming 応答 (エージェントアシスタント) +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} +data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} +data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} +data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} +data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} +data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +--- + +## ファイルアップロード `POST /files/upload` + +メッセージ送信時に使用するためのファイルをアップロードします(現在は画像のみサポート)。画像とテキストのマルチモーダル理解を可能にします。 +png、jpg、jpeg、webp、gif 形式をサポートしています。 +アップロードされたファイルは現在のエンドユーザーのみが使用できます。 + +### リクエストボディ + +このインターフェースは`multipart/form-data`リクエストを必要とします。 + +- `file` (File, required): アップロードするファイル。 +- `user` (string, required): ユーザー識別子、開発者のルールで定義され、アプリケーション内で一意でなければなりません。 + +### 応答 + +アップロードが成功すると、サーバーはファイルの ID と関連情報を返します。 + +- `id` (uuid): ID +- `name` (string): ファイル名 +- `size` (int): ファイルサイズ(バイト) +- `extension` (string): ファイル拡張子 +- `mime_type` (string): ファイルの MIME タイプ +- `created_by` (uuid): エンドユーザー ID +- `created_at` (timestamp): 作成タイムスタンプ、例:1705395332 + +### エラー + +- 400, `no_file_uploaded`, ファイルが提供されなければなりません +- 400, `too_many_files`, 現在は 1 つのファイルのみ受け付けます +- 400, `unsupported_preview`, ファイルはプレビューをサポートしていません +- 400, `unsupported_estimate`, ファイルは推定をサポートしていません +- 413, `file_too_large`, ファイルが大きすぎます +- 415, `unsupported_file_type`, サポートされていない拡張子、現在はドキュメントファイルのみ受け付けます +- 503, `s3_connection_failed`, S3 サービスに接続できません +- 503, `s3_permission_denied`, S3 にファイルをアップロードする権限がありません +- 503, `s3_file_too_large`, ファイルが S3 のサイズ制限を超えています +- 500, 内部サーバーエラー + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header + 'Authorization: Bearer {api_key}' \ --form + 'file=@/path/to/your/image.png;type=image/png' \ --form 'user=abc-123' ``` + + + +```json 応答 +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 +} +``` + + +--- + +## 生成停止 `POST /chat-messages/:task_id/stop` + +ストリーミングモードでのみサポートされています。 + +### パスパラメータ + +- `task_id` (string, required): タスク ID、ストリーミングチャンクの返り値から取得できます。 + +### リクエストボディ + +- `user` (string, required): ユーザー識別子、エンドユーザーのアイデンティティを定義するために使用され、メッセージ送信インターフェースで渡されたユーザーと一致している必要があります。 + +### 応答 + +- `result` (string): 常に"success"を返します。 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages/your_task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json 応答 +{ + "result": "success" +} +``` + + +--- + +## メッセージフィードバック `POST /messages/:message_id/feedbacks` + +エンドユーザーはフィードバックメッセージを提供でき、アプリケーション開発者が期待される出力を最適化するのに役立ちます。 + +### パスパラメータ + +- `message_id` (string, required): メッセージ ID + +### リクエストボディ + +- `rating` (string): アップボートは`like`、ダウンボートは`dislike`、アップボートの取り消しは`null`。 +- `user` (string, required): ユーザー識別子、開発者のルールで定義され、アプリケーション内で一意でなければなりません。 +- `content` (string): メッセージのフィードバックです。 + +### 応答 + +- `result` (string): 常に"success"を返します。 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/messages/your_message_id/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json 応答 +{ + "result": "success" +} +``` + + +--- + +## 次の推奨質問 `GET /messages/{message_id}/suggested` + +現在のメッセージに対する次の質問の提案を取得します。 + +### パスパラメータ + +- `message_id` (string, required): メッセージ ID + +### クエリパラメータ + +- `user` (string, required): ユーザー識別子、エンドユーザーのアイデンティティを定義するために使用され、統計のために使用されます。アプリケーション内で開発者によって一意に定義される必要があります。 + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/messages/your_message_id/suggested?user=abc-123' \ + --header 'Authorization: Bearer {api_key}' \ --header 'Content-Type: + application/json' ``` + + + +```json 応答 +{ + "result": "success", + "data": [ + "a", + "b", + "c" + ] +} +``` + + +--- + +## 会話履歴メッセージを取得 `GET /messages` + +スクロールロード形式で過去のチャット記録を返し、最初のページは最新の`{limit}`メッセージを返します。つまり、逆順です。 + +### クエリパラメータ + +- `conversation_id` (string, required): 会話 ID +- `user` (string, required): ユーザー識別子 +- `first_id` (string): 現在のページの最初のチャット記録の ID、デフォルトは null です。 +- `limit` (int): 1 回のリクエストで返すチャット履歴メッセージの数、デフォルトは 20 です。 + +### 応答 + +- `data` (array[object]): メッセージリスト + - `id` (string): メッセージ ID + - `conversation_id` (string): 会話 ID + - `inputs` (object): ユーザー入力パラメータ + - `query` (string): ユーザー入力/質問内容 + - `message_files` (array[object]): メッセージファイル + - `id` (string): ID + - `type` (string): ファイルタイプ(例: `image`) + - `url` (string): プレビュー画像 URL + - `belongs_to` (string): 所属(`user` または `assistant`) + - `agent_thoughts` (array[object]): エージェントの思考(基本アシスタントの場合は空) + - `id` (string): エージェント思考 ID + - `message_id` (string): 一意のメッセージ ID + - `position` (int): 現在のエージェント思考の位置 + - `thought` (string): LLM が考えていること + - `observation` (string): ツール呼び出しからの応答 + - `tool` (string): 呼び出されたツールのリスト(;で区切られる) + - `tool_input` (string): ツールの入力(JSON 形式) + - `created_at` (int): 作成タイムスタンプ + - `message_files` (array[string]): この思考ステップに関連付けられたファイル ID のリスト。 + - `answer` (string): 応答メッセージ内容 + - `created_at` (timestamp): 作成タイムスタンプ + - `feedback` (object): フィードバック情報 + - `rating` (string): `like` / `dislike` + - `retriever_resources` (array[object]): 引用と帰属リスト +- `has_more` (bool): 次のページがあるかどうか +- `limit` (int): 返されたアイテムの数 + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/messages?user=abc-123&conversation_id=your_conversation_id' + \ --header 'Authorization: Bearer {api_key}' ``` + + + +```json 応答 (基本アシスタント) +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "a076a87f-31e5-48dc-b452-0061adbbc922", + "conversation_id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "inputs": { + "name": "dify" + }, + "query": "iphone 13 pro", + "answer": "iPhone 13 Proは2021年9月24日に発売され、6.1インチのディスプレイと1170 x 2532の解像度を備えています。Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)プロセッサ、6 GBのRAMを搭載し、128 GB、256 GB、512 GB、1 TBのストレージオプションを提供します。カメラは12 MP、バッテリー容量は3095 mAhで、iOS 15を搭載しています。", + "message_files": [], + "feedback": null, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ], + "agent_thoughts": [], + "created_at": 1705569239 + } + ] +} +``` +```json 応答 (エージェントアシスタント) +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "conversation_id": "957c068b-f258-4f89-ba10-6e8a0361c457", + "inputs": {}, + "query": "draw a cat", + "answer": "猫の画像を生成しました。メッセージを確認して画像を表示してください。", + "message_files": [ + { + "id": "976990d2-5294-47e6-8f14-7356ba9d2d76", + "type": "image", + "url": "http://127.0.0.1:5001/files/tools/976990d2-5294-47e6-8f14-7356ba9d2d76.png?timestamp=1705988524&nonce=55df3f9f7311a9acd91bf074cd524092&sign=z43nMSO1L2HBvoqADLkRxr7Biz0fkjeDstnJiCK1zh8=", + "belongs_to": "assistant" + } + ], + "feedback": null, + "retriever_resources": [], + "created_at": 1705988187, + "agent_thoughts": [ + { + "id": "592c84cf-07ee-441c-9dcc-ffc66c033469", + "chain_id": null, + "message_id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "position": 1, + "thought": "", + "tool": "dalle2", + "tool_input": "{\"dalle2\": {\"prompt\": \"cat\"}}", + "created_at": 1705988186, + "observation": "画像はすでに作成され、ユーザーに送信されました。今すぐユーザーに確認するように伝えてください。", + "files": [ + "976990d2-5294-47e6-8f14-7356ba9d2d76" + ] + }, + { + "id": "73ead60d-2370-4780-b5ed-532d2762b0e5", + "chain_id": null, + "message_id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "position": 2, + "thought": "猫の画像を生成しました。メッセージを確認して画像を表示してください。", + "tool": "", + "tool_input": "", + "created_at": 1705988199, + "observation": "", + "files": [] + } + ] + } + ] +} +``` + + +--- + +## 会話を取得 `GET /conversations` + +現在のユーザーの会話リストを取得し、デフォルトで最新の 20 件を返します。 + +### クエリパラメータ + +- `user` (string, required): ユーザー識別子 +- `last_id` (string, optional): 現在のページの最後のレコードの ID、デフォルトは null です。 +- `limit` (int, optional): 1 回のリクエストで返すレコードの数、デフォルトは最新の 20 件です。最大 100、最小 1。 +- `sort_by` (string, optional): ソートフィールド、デフォルト:`-updated_at`(更新時間で降順にソート)。利用可能な値:`created_at`, `-created_at`, `updated_at`, `-updated_at`。フィールドの前の記号は順序または逆順を表し、`-`は逆順を表します。 + +### 応答 + +- `data` (array[object]): 会話のリスト + - `id` (string): 会話 ID + - `name` (string): 会話名 + - `inputs` (object): ユーザー入力パラメータ + - `introduction` (string): 紹介 + - `created_at` (timestamp): 作成タイムスタンプ + - `updated_at` (timestamp): 更新タイムスタンプ +- `has_more` (bool): さらにレコードがあるか +- `limit` (int): 返されたエントリの数 + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/conversations?user=abc-123&last_id=&limit=20' \ + --header 'Authorization: Bearer {api_key}' ``` + + + +```json 応答 +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54", + "name": "新しいチャット", + "inputs": { + "book": "book", + "myName": "Lucy" + }, + "status": "normal", + "created_at": 1679667915, + "updated_at": 1679667915 + }, + { + "id": "hSIhXBhNe8X1d8Et" + // ... + } + ] +} +``` + + +--- + +## 会話を削除 `DELETE /conversations/:conversation_id` + +会話を削除します。 + +### パスパラメータ + +- `conversation_id` (string, required): 会話 ID + +### リクエストボディ + +- `user` (string, required): ユーザー識別子、開発者によって定義され、アプリケーション内で一意である必要があります。 + +### 応答 + +- `204 No Content`: 成功を示す HTTP ステータス。 + + +```bash cURL +curl -X DELETE 'https://api.dify.ai/v1/conversations/your_conversation_id' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + +```text 応答 204 No Content ``` + +--- + +## 会話の名前を変更 `POST /conversations/:conversation_id/name` + +セッションの名前を変更します。セッション名は、複数のセッションをサポートするクライアントでの表示に使用されます。 + +### パスパラメータ + +- `conversation_id` (string, required): 会話 ID + +### リクエストボディ + +- `name` (string, optional): 会話の名前。このパラメータは、`auto_generate`が`true`に設定されている場合、省略できます。 +- `auto_generate` (bool, optional): タイトルを自動生成します。デフォルトは`false`です。 +- `user` (string, required): ユーザー識別子、開発者によって定義され、アプリケーション内で一意である必要があります。 + +### 応答 + +- `id` (string): 会話 ID +- `name` (string): 会話名 +- `inputs` (object): ユーザー入力パラメータ +- `status` (string): 会話状態 +- `introduction` (string): 紹介 +- `created_at` (timestamp): 作成タイムスタンプ +- `updated_at` (timestamp): 更新タイムスタンプ + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/conversations/your_conversation_id/name' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name": "新しい会話名", + "auto_generate": false, + "user": "abc-123" +}' +``` + + + +```json 応答 +{ + "id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "name": "Chat vs AI", + "inputs": {}, + "introduction": "", + "created_at": 1705569238, + "updated_at": 1705569238 +} +``` + + +--- + +## 会話変数の取得 `GET /conversations/:conversation_id/variables` + +特定の会話から変数を取得します。このエンドポイントは、会話中に取得された構造化データを抽出するのに役立ちます。 + +### パスパラメータ + +- `conversation_id` (string, required): 変数を取得する会話の ID。 + +### クエリパラメータ + +- `user` (string, required): ユーザー識別子。開発者によって定義されたルールに従い、アプリケーション内で一意である必要があります。 +- `last_id` (string, optional): 現在のページの最後のレコードの ID、デフォルトは null です。 +- `limit` (int, optional): 1 回のリクエストで返すレコードの数、デフォルトは最新の 20 件です。最大 100、最小 1。 + +### 応答 + +- `limit` (int): ページごとのアイテム数 +- `has_more` (bool): さらにアイテムがあるかどうか +- `data` (array[object]): 変数のリスト + - `id` (string): 変数 ID + - `name` (string): 変数名 + - `value_type` (string): 変数タイプ(文字列、数値、真偽値など) + - `value` (string): 変数値 + - `description` (string): 変数の説明 + - `created_at` (int): 作成タイムスタンプ + - `updated_at` (int): 最終更新タイムスタンプ + +### エラー + +- 404, `conversation_not_exists`, 会話が見つかりません + + + ```bash cURL (全変数) curl -X GET + 'https://api.dify.ai/v1/conversations/your_conversation_id/variables?user=abc-123' + \ --header 'Authorization: Bearer {api_key}' ``` ```bash cURL + (変数名でフィルタ) curl -X GET + 'https://api.dify.ai/v1/conversations/your_conversation_id/variables?user=abc-123&variable_name=customer_name' + \ --header 'Authorization: Bearer {api_key}' ``` + + + +```json 応答 +{ + "limit": 100, + "has_more": false, + "data": [ + { + "id": "variable-uuid-1", + "name": "customer_name", + "value_type": "string", + "value": "John Doe", + "description": "会話から抽出された顧客名", + "created_at": 1650000000000, + "updated_at": 1650000000000 + }, + { + "id": "variable-uuid-2", + "name": "order_details", + "value_type": "json", + "value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}", + "description": "顧客の注文詳細", + "created_at": 1650000000000, + "updated_at": 1650000000000 + } + ] +} +``` + + +--- + +## 音声からテキストへ `POST /audio-to-text` + +このエンドポイントは`multipart/form-data`リクエストを必要とします。 + +### リクエストボディ + +- `file` (file, required): オーディオファイル。サポートされている形式:`['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm']`。ファイルサイズ制限:15MB。 +- `user` (string, required): ユーザー識別子、開発者のルールで定義され、アプリケーション内で一意でなければなりません。 + +### 応答 + +- `text` (string): 出力テキスト + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/audio-to-text' \ --header + 'Authorization: Bearer {api_key}' \ --form + 'file=@/path/to/your/audio.mp3;type=audio/mp3' \ --form 'user=abc-123' ``` + + + +```json 応答 +{ + "text": "変換されたテキストがここに入ります。" +} +``` + + +--- + +## テキストから音声へ `POST /text-to-audio` + +テキストを音声に変換します。 + +### リクエストボディ + +- `message_id` (string, optional): Dify によって生成されたテキストメッセージの場合、生成されたメッセージ ID を直接渡します。バックエンドはメッセージ ID を使用して対応するコンテンツを検索し、音声情報を直接合成します。`message_id`と`text`が同時に提供される場合、`message_id`が優先されます。 +- `text` (string, optional): 音声生成コンテンツ。`message_id` がない場合は必須です。 +- `user` (string, required): ユーザー識別子、開発者によって定義され、アプリ内で一意である必要があります。 + +### 応答 + +成功すると、レスポンスボディは `audio/wav` 形式の音声データを含みます。 + + + ```bash cURL curl --location --request POST + 'https://api.dify.ai/v1/text-to-audio' \ --header 'Authorization: Bearer{' '} + {api_key}' \ --form 'text=Hello Dify' \ --form 'user=abc-123' # --form + 'message_id=your_message_id' # message_id を使用する場合 ``` + + +```http Headers Content-Type: audio/wav ``` + +--- + +## アプリケーションの基本情報を取得 `GET /info` + +このアプリケーションの基本情報を取得するために使用されます。 + +### 応答 + +- `name` (string): アプリケーションの名前 +- `description` (string): アプリケーションの説明 +- `tags` (array[string]): アプリケーションのタグ + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json 応答 +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## アプリケーションのパラメータ情報を取得 `GET /parameters` + +ページに入る際に、機能、入力パラメータ名、タイプ、デフォルト値などの情報を取得するために使用されます。 + +### 応答 + +- `opening_statement` (string): 開始文 +- `suggested_questions` (array[string]): 開始時の推奨質問のリスト +- `suggested_questions_after_answer` (object): 答えを有効にした後の質問を提案します。 + - `enabled` (bool): 有効かどうか +- `speech_to_text` (object): 音声からテキストへ + - `enabled` (bool): 有効かどうか +- `retriever_resource` (object): 引用と帰属 + - `enabled` (bool): 有効かどうか +- `annotation_reply` (object): 注釈返信 + - `enabled` (bool): 有効かどうか +- `user_input_form` (array[object]): ユーザー入力フォームの構成 + - `text-input` (object): テキスト入力コントロール + - `label` (string): 変数表示ラベル名 + - `variable` (string): 変数 ID + - `required` (bool): 必須かどうか + - `default` (string): デフォルト値 + - `paragraph` (object): 段落テキスト入力コントロール + - `label` (string): 変数表示ラベル名 + - `variable` (string): 変数 ID + - `required` (bool): 必須かどうか + - `default` (string): デフォルト値 + - `select` (object): ドロップダウンコントロール + - `label` (string): 変数表示ラベル名 + - `variable` (string): 変数 ID + - `required` (bool): 必須かどうか + - `default` (string): デフォルト値 + - `options` (array[string]): オプション値 +- `file_upload` (object): ファイルアップロード構成 + - `image` (object): 画像設定。現在サポートされている画像タイプ:`png`, `jpg`, `jpeg`, `webp`, `gif` + - `enabled` (bool): 有効かどうか + - `number_limits` (int): 画像数の制限、デフォルトは 3 + - `transfer_methods` (array[string]): 転送方法のリスト(`remote_url`, `local_file`)。いずれかを選択する必要があります。 +- `system_parameters` (object): システムパラメータ + - `file_size_limit` (int): ドキュメントアップロードサイズ制限(MB) + - `image_file_size_limit` (int): 画像ファイルアップロードサイズ制限(MB) + - `audio_file_size_limit` (int): オーディオファイルアップロードサイズ制限(MB) + - `video_file_size_limit` (int): ビデオファイルアップロードサイズ制限(MB) + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json 応答 +{ + "opening_statement": "こんにちは!", + "suggested_questions_after_answer": { + "enabled": true + }, + "speech_to_text": { + "enabled": true + }, + "retriever_resource": { + "enabled": true + }, + "annotation_reply": { + "enabled": true + }, + "user_input_form": [ + { + "paragraph": { + "label": "クエリ", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + + +--- + +## アプリケーションのメタ情報を取得 `GET /meta` + +このアプリケーションのツールのアイコンを取得するために使用されます。 + +### 応答 + +- `tool_icons` (object): ツールのアイコン。キーはツール名です。 + - `[tool_name]` (string | object): アイコンの定義。 + - 文字列の場合: アイコンの URL。 + - オブジェクトの場合: + - `background` (string): 背景色 (16 進数形式)。 + - `content` (string): 絵文字。 + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/meta' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json 応答 +{ + "tool_icons": { + "dalle2": "https://cloud.dify.ai/console/api/workspaces/current/tool-provider/builtin/dalle/icon", + "api_tool": { + "background": "#252525", + "content": "\ud83d\ude01" + } + } +} +``` + diff --git a/api_access/chat.zh.mdx b/api_access/chat.zh.mdx new file mode 100644 index 00000000..fe72a022 --- /dev/null +++ b/api_access/chat.zh.mdx @@ -0,0 +1,1025 @@ +--- +title: 对话型应用 API +--- + +对话应用支持会话持久化,可将之前的聊天记录作为上下文进行回答,可适用于聊天/客服 AI 等。 + +### 基础 URL + +```text +https://api.dify.ai/v1 +``` + +### 鉴权 + +Service API 使用 `API-Key` 进行鉴权。 + + + **强烈建议开发者把 `API-Key` 放在后端存储,而非分享或者放在客户端存储,以免 + `API-Key` 泄露,导致财产损失。** + +所有 API 请求都应在 **`Authorization`** HTTP Header 中包含您的 `API-Key`,如下所示: + +```javascript +Authorization: Bearer {API_KEY} +``` + +--- + +## 发送对话消息 + +POST `/chat-messages` + +创建会话消息。 + +### Request Body + +- `query` (string): 用户输入/提问内容。 +- `inputs` (object): 允许传入 App 定义的各变量值。 inputs 参数包含了多组键值对(Key/Value pairs),每组的键对应一个特定变量,每组的值则是该变量的具体值。默认 `{}` +- `response_mode` (string): + - `streaming` 流式模式(推荐)。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现类似打字机输出方式的流式返回。 + - `blocking` 阻塞模式,等待执行完毕后返回结果。(请求若流程较长可能会被中断)。 + 由于 Cloudflare 限制,请求会在 100 秒超时无返回后中断。 + 注:Agent模式下不允许blocking。 +- `user` (string): 用户标识,用于定义终端用户的身份,方便检索、统计。 由开发者定义规则,需保证用户标识在应用内唯一。 +- `conversation_id` (string): (选填)会话 ID,需要基于之前的聊天记录继续对话,必须传之前消息的 conversation_id。 +- `files` (array[object]): 上传的文件。 + - `type` (string): 支持类型:图片 `image`(目前仅支持图片格式)。 + - `transfer_method` (string): 传递方式: + - `remote_url`: 图片地址。 + - `local_file`: 上传文件。 + - `url` (string): 图片地址。(仅当传递方式为 `remote_url` 时)。 + - `upload_file_id` (string): 上传文件 ID。(仅当传递方式为 `local_file` 时)。 +- `auto_generate_name` (bool): (选填)自动生成标题,默认 `true`。 若设置为 `false`,则可通过调用会话重命名接口并设置 `auto_generate` 为 `true` 实现异步生成标题。 + +### Response + +当 `response_mode` 为 `blocking` 时,返回 ChatCompletionResponse object。 +当 `response_mode` 为 `streaming`时,返回 ChunkChatCompletionResponse object 流式序列。 + +#### ChatCompletionResponse + +返回完整的 App 结果,`Content-Type` 为 `application/json`。 + +- `event` (string): 事件类型,固定为 `message` +- `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 +- `id` (string): 唯一 ID +- `message_id` (string): 消息唯一 ID +- `conversation_id` (string): 会话 ID +- `mode` (string): App 模式,固定为 chat +- `answer` (string): 完整回复内容 +- `metadata` (object): 元数据 + - `usage` (Usage): 模型用量信息 + - `retriever_resources` (array[RetrieverResource]): 引用和归属分段列表 +- `created_at` (int): 消息创建时间戳,如:1705395332 + +#### ChunkChatCompletionResponse + +返回 App 输出的流式块,`Content-Type` 为 `text/event-stream`。 +每个流式块均为 data: 开头,块之间以 \n\n 即两个换行符分隔,如下所示: + +```streaming {{ title: 'Response Stream Example' }} +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +流式块中根据 event 不同,结构也不同: + +- `event: message`: LLM 返回文本块事件,即:完整的文本以分块的方式输出。 + - `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `conversation_id` (string): 会话 ID + - `answer` (string): LLM 返回文本块内容 + - `created_at` (int): 创建时间戳,如:1705395332 +- `event: agent_message`: Agent 模式下返回文本块事件,即:在 Agent 模式下,文章的文本以分块的方式输出(仅 Agent 模式下使用) + - `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `conversation_id` (string): 会话 ID + - `answer` (string): LLM 返回文本块内容 + - `created_at` (int): 创建时间戳,如:1705395332 +- `event: agent_thought`: Agent 模式下有关 Agent 思考步骤的相关内容,涉及到工具调用(仅 Agent 模式下使用) + - `id` (string): agent_thought ID,每一轮 Agent 迭代都会有一个唯一的 id + - `task_id` (string): 任务 ID,用于请求跟踪下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `position` (int): agent_thought 在消息中的位置,如第一轮迭代 position 为 1 + - `thought` (string): agent 的思考内容 + - `observation` (string): 工具调用的返回结果 + - `tool` (string): 使用的工具列表,以 ; 分割多个工具 + - `tool_input` (string): 工具的输入,JSON 格式的字符串(object)。如:`{"dalle3": {"prompt": "a cute cat"}}` + - `created_at` (int): 创建时间戳,如:1705395332 + - `message_files` (array[string]): 当前 `agent_thought` 关联的文件 ID + - `file_id` (string): 文件 ID + - `conversation_id` (string): 会话 ID +- `event: message_file`: 文件事件,表示有新文件需要展示 + - `id` (string): 文件唯一 ID + - `type` (string): 文件类型,目前仅为 image + - `belongs_to` (string): 文件归属,user 或 assistant,该接口返回仅为 `assistant` + - `url` (string): 文件访问地址 + - `conversation_id` (string): 会话 ID +- `event: message_end`: 消息结束事件,收到此事件则代表流式返回结束。 + - `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `conversation_id` (string): 会话 ID + - `metadata` (object): 元数据 + - `usage` (Usage): 模型用量信息 + - `retriever_resources` (array[RetrieverResource]): 引用和归属分段列表 +- `event: tts_message`: TTS 音频流事件,即:语音合成输出。内容是 Mp3 格式的音频块,使用 base64 编码后的字符串,播放的时候直接解码即可。(开启自动播放才有此消息) + - `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `audio` (string): 语音合成之后的音频块使用 Base64 编码之后的文本内容,播放的时候直接 base64 解码送入播放器即可 + - `created_at` (int): 创建时间戳,如:1705395332 +- `event: tts_message_end`: TTS 音频流结束事件,收到这个事件表示音频流返回结束。 + - `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `audio` (string): 结束事件是没有音频的,所以这里是空字符串 + - `created_at` (int): 创建时间戳,如:1705395332 +- `event: message_replace`: 消息内容替换事件。 开启内容审查和审查输出内容时,若命中了审查条件,则会通过此事件替换消息内容为预设回复。 + - `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `conversation_id` (string): 会话 ID + - `answer` (string): 替换内容(直接替换 LLM 所有回复文本) + - `created_at` (int): 创建时间戳,如:1705395332 +- `event: error`: 流式输出过程中出现的异常会以 stream event 形式输出,收到异常事件后即结束。 + - `task_id` (string): 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string): 消息唯一 ID + - `status` (int): HTTP 状态码 + - `code` (string): 错误码 + - `message` (string): 错误消息 +- `event: ping`: 每 10s 一次的 ping 事件,保持连接存活。 + +### Errors + +- 404,对话不存在 +- 400,`invalid_param`,传入参数异常 +- 400,`app_unavailable`,App 配置不可用 +- 400,`provider_not_initialize`,无可用模型凭据配置 +- 400,`provider_quota_exceeded`,模型调用额度不足 +- 400,`model_currently_not_support`,当前模型不可用 +- 400,`completion_request_error`,文本生成失败 +- 500,服务内部异常 + + +```bash {{ title: 'cURL' }} +curl -X POST 'https://api.dify.ai/v1/chat-messages' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "inputs": { + "name": "dify" + }, + "query": "What are the specs of the iPhone 13 Pro Max?", + "conversation_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "response_mode": "streaming", + "user": "abc-123", + "files": [ + { + "type": "image", + "transfer_method": "remote_url", + "url": "https://cloud.dify.ai/logo/logo-site.png" + } + ] +}' +``` + + + +```json {{ title: '阻塞模式 Response' }} +{ + "event": "message", + "task_id": "c3800678-a077-43df-a102-53f23ed20b88", + "id": "9da23599-e713-473b-982c-4328d4f5c78a", + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", + "mode": "chat", + "answer": "iPhone 13 Pro Max specs are listed here:...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + }, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ] + }, + "created_at": 1705407629 +} +``` +```streaming {{ title: '流式模式(基础助手) Response' }} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} + data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` +```streaming {{ title: '流式模式(智能助手) Response' }} + data: {"event": "agent_thought", "id": "8dcf3648-fbad-407a-85dd-73a6f43aeb9f", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "position": 1, "thought": "", "observation": "", "tool": "", "tool_input": "", "created_at": 1705639511, "message_files": [], "conversation_id": "c216c595-2d89-438c-b33c-aae5ddddd142"} + data: {"event": "agent_thought", "id": "8dcf3648-fbad-407a-85dd-73a6f43aeb9f", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "position": 1, "thought": "", "observation": "", "tool": "dalle3", "tool_input": "{\"dalle3\": {\"prompt\": \"cute Japanese anime girl with white hair, blue eyes, bunny girl suit\"}}", "created_at": 1705639511, "message_files": [], "conversation_id": "c216c595-2d89-438c-b33c-aae5ddddd142"} + data: {"event": "message_file", "id": "d75b7a5c-ce5e-442e-ab1b-d6a5e5b557b0", "type": "image", "belongs_to": "assistant", "url": "http://127.0.0.1:5001/files/tools/d75b7a5c-ce5e-442e-ab1b-d6a5e5b557b0.png?timestamp=1705639526&nonce=70423256c60da73a9c96d1385ff78487&sign=7B5fKV9890YJuqchQvrABvW4AIupDvDvxGdu1EOJT94=", "conversation_id": "c216c595-2d89-438c-b33c-aae5ddddd142"} + data: {"event": "agent_thought", "id": "8dcf3648-fbad-407a-85dd-73a6f43aeb9f", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "position": 1, "thought": "", "observation": "image has been created and sent to user already, you should tell user to check it now.", "tool": "dalle3", "tool_input": "{\"dalle3\": {\"prompt\": \"cute Japanese anime girl with white hair, blue eyes, bunny girl suit\"}}", "created_at": 1705639511, "message_files": ["d75b7a5c-ce5e-442e-ab1b-d6a5e5b557b0"], "conversation_id": "c216c595-2d89-438c-b33c-aae5ddddd142"} + data: {"event": "agent_thought", "id": "67a99dc1-4f82-42d3-b354-18d4594840c8", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "position": 2, "thought": "", "observation": "", "tool": "", "tool_input": "", "created_at": 1705639511, "message_files": [], "conversation_id": "c216c595-2d89-438c-aae5ddddd142"} + data: {"event": "agent_message", "id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "answer": "I have created an image of a cute Japanese", "created_at": 1705639511, "conversation_id": "c216c595-2d89-438c-aae5ddddd142"} + data: {"event": "agent_message", "id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "answer": " anime girl with white hair and blue", "created_at": 1705639511, "conversation_id": "c216c595-2d89-438c-aae5ddddd142"} + data: {"event": "agent_message", "id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "answer": " eyes wearing a bunny girl" ,"created_at": 1705639511, "conversation_id": "c216c595-2d89-438c-aae5ddddd142"} + data: {"event": "agent_message", "id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "answer": " suit .", "created_at": 1705639511, "conversation_id": "c216c595-2d89-438c-aae5ddddd142"} + data: {"event": "agent_thought", "id": "67a99dc1-4f82-42d3-b354-18d4594840c8", "task_id": "9cf1ddd7-f94b-459b-b942-b77b26c59e9b", "message_id": "1fb10045-55fd-4040-99e6-d048d07cbad3", "position": 2, "thought": "I have created an image of a cute Japanese anime girl with white hair and blue eyes wearing a bunny girl suit.", "observation": "", "tool": "", "tool_input": "", "created_at": 1705639511, "message_files": [], "conversation_id": "c216c595-2d89-438c-aae5ddddd142"} + data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +--- + +## 上传文件 + +POST `/files/upload` + +上传文件(目前仅支持图片)并在发送消息时使用,可实现图文多模态理解。 +支持 png, jpg, jpeg, webp, gif 格式。 + +上传的文件仅供当前终端用户使用。 + +### Request Body + +该接口需使用 `multipart/form-data` 进行请求。 + +- `file` (file): 要上传的文件。 +- `user` (string): 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response + +成功上传后,服务器会返回文件的 ID 和相关信息。 + +- `id` (uuid): ID +- `name` (string): 文件名 +- `size` (int): 文件大小(byte) +- `extension` (string): 文件后缀 +- `mime_type` (string): 文件 mime-type +- `created_by` (uuid): 上传人 ID +- `created_at` (timestamp): 上传时间 + +### Errors + +- 400,`no_file_uploaded`,必须提供文件 +- 400,`too_many_files`,目前只接受一个文件 +- 400,`unsupported_preview`,该文件不支持预览 +- 400,`unsupported_estimate`,该文件不支持估算 +- 413,`file_too_large`,文件太大 +- 415,`unsupported_file_type`,不支持的扩展名,当前只接受文档类文件 +- 503,`s3_connection_failed`,无法连接到 S3 服务 +- 503,`s3_permission_denied`,无权限上传文件到 S3 +- 503,`s3_file_too_large`,文件超出 S3 大小限制 + + + ```bash {{ title: 'cURL' }} + curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header 'Authorization: + Bearer {api_key}' \ --form 'file=@"/path/to/file"' \ --form 'user=abc-123' ``` + + + +```json {{ title: 'Response' }} +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": 123, + "created_at": 1577836800 +} +``` + +--- +## 停止响应 + +POST `/chat-messages/:task_id/stop` + +仅支持流式模式。 + +### Path Parameters + +- `task_id` (string): 任务 ID,可在流式返回 Chunk 中获取 + +### Request Body + +- `user` (string) Required: 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response + +- `result` (string): 固定返回 success + + +```bash {{ title: 'cURL' }} +curl -X POST 'https://api.dify.ai/v1/chat-messages/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json {{ title: 'Response' }} +{ + "result": "success" +} +``` + +--- + +## 消息反馈(点赞) + +POST `/messages/:message_id/feedbacks` + +消息终端用户反馈、点赞,方便应用开发者优化输出预期。 + +### Path Params + +- `message_id` (string): 消息 ID + +### Request Body + +- `rating` (string): 点赞 like, 点踩 dislike, 撤销点赞 null +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 +- `content` (string): 消息反馈的具体信息。 + +### Response + +- `result` (string): 固定返回 success + + +```bash {{ title: 'cURL' }} +curl -X POST 'https://api.dify.ai/v1/messages/:message_id/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json {{ title: 'Response' }} +{ + "result": "success" +} +``` + + +--- + +## 获取下一轮建议问题列表 + +GET `/messages/{message_id}/suggested` + +获取下一轮建议问题列表。 + +### Path Params + +- `message_id` (string): Message ID + +### Query Parameters + +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + + + ```bash {{ title: 'cURL' }} + curl --location --request GET 'https://api.dify.ai/v1/messages/{message_id}/suggested?user=abc-123' + \ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \ --header 'Content-Type: + application/json' ``` + + + +```json {{ title: 'Response' }} +{ + "result": "success", + "data": [ + "a", + "b", + "c" + ] +} +``` + + +--- + +--- + +## 获取会话历史消息 + +GET `/messages` + +滚动加载形式返回历史聊天记录,第一页返回最新 `limit` 条,即:倒序返回。 + +### Query Parameters + +- `conversation_id` (string): 会话 ID +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 +- `first_id` (string): 当前页第一条聊天记录的 ID,默认 null +- `limit` (int): 一次请求返回多少条聊天记录,默认 20 条。 + +### Response + +- `data` (array[object]): 消息列表 + - `id` (string): 消息 ID + - `conversation_id` (string): 会话 ID + - `inputs` (object): 用户输入参数。 + - `query` (string): 用户输入 / 提问内容。 + - `message_files` (array[object]): 消息文件 + - `id` (string): ID + - `type` (string): 文件类型,image 图片 + - `url` (string): 预览图片地址 + - `belongs_to` (string): 文件归属方,user 或 assistant + - `agent_thoughts` (array[object]): Agent 思考内容(仅 Agent 模式下不为空) + - `id` (string): agent_thought ID,每一轮 Agent 迭代都会有一个唯一的 id + - `message_id` (string): 消息唯一 ID + - `position` (int): agent_thought 在消息中的位置,如第一轮迭代 position 为 1 + - `thought` (string): agent 的思考内容 + - `observation` (string): 工具调用的返回结果 + - `tool` (string): 使用的工具列表,以 ; 分割多个工具 + - `tool_input` (string): 工具的输入,JSON 格式的字符串(object)。如:`{"dalle3": {"prompt": "a cute cat"}}` + - `created_at` (int): 创建时间戳,如:1705395332 + - `message_files` (array[string]): 当前 agent_thought 关联的文件 ID + - `file_id` (string): 文件 ID + - `conversation_id` (string): 会话 ID + - `answer` (string): 回答消息内容 + - `created_at` (timestamp): 创建时间 + - `feedback` (object): 反馈信息 + - `rating` (string): 点赞 like / 点踩 dislike + - `retriever_resources` (array[RetrieverResource]): 引用和归属分段列表 +- `has_more` (bool): 是否存在下一页 +- `limit` (int): 返回条数,若传入超过系统限制,返回系统限制数量 + + + ```bash {{ title: 'cURL' }} + curl -X GET 'https://api.dify.ai/v1/messages?user=abc-123&conversation_id={ + conversation_id + }' \ --header 'Authorization: Bearer {api_key}' ``` + + + +```json {{ title: '基础助手 Response Example' }} +{ +"limit": 20, +"has_more": false, +"data": [ + { + "id": "a076a87f-31e5-48dc-b452-0061adbbc922", + "conversation_id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "inputs": { + "name": "dify" + }, + "query": "iphone 13 pro", + "answer": "The iPhone 13 Pro, released on September 24, 2021, features a 6.1-inch display with a resolution of 1170 x 2532. It is equipped with a Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard) processor, 6 GB of RAM, and offers storage options of 128 GB, 256 GB, 512 GB, and 1 TB. The camera is 12 MP, the battery capacity is 3095 mAh, and it runs on iOS 15.", + "message_files": [], + "feedback": null, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ], + "agent_thoughts": [], + "created_at": 1705569239 + } + ] +} +``` +```json {{ title: '智能助手 Response Example' }} +{ +"limit": 20, +"has_more": false, +"data": [ + { + "id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "conversation_id": "957c068b-f258-4f89-ba10-6e8a0361c457", + "inputs": {}, + "query": "draw a cat", + "answer": "I have generated an image of a cat for you. Please check your messages to view the image.", + "message_files": [ + { + "id": "976990d2-5294-47e6-8f14-7356ba9d2d76", + "type": "image", + "url": "http://127.0.0.1:5001/files/tools/976990d2-5294-47e6-8f14-7356ba9d2d76.png?timestamp=1705988524&nonce=55df3f9f7311a9acd91bf074cd524092&sign=z43nMSO1L2HBvoqADLkRxr7Biz0fkjeDstnJiCK1zh8=", + "belongs_to": "assistant" + } + ], + "feedback": null, + "retriever_resources": [], + "created_at": 1705988187, + "agent_thoughts": [ + { + "id": "592c84cf-07ee-441c-9dcc-ffc66c033469", + "chain_id": null, + "message_id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "position": 1, + "thought": "", + "tool": "dalle2", + "tool_input": "{\"dalle2\": {\"prompt\": \"cat\"}}", + "created_at": 1705988186, + "observation": "image has been created and sent to user already, you should tell user to check it now.", + "files": [ + "976990d2-5294-47e6-8f14-7356ba9d2d76" + ] + }, + { + "id": "73ead60d-2370-4780-b5ed-532d2762b0e5", + "chain_id": null, + "message_id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "position": 2, + "thought": "I have generated an image of a cat for you. Please check your messages to view the image.", + "tool": "", + "tool_input": "", + "created_at": 1705988199, + "observation": "", + "files": [] + } + ] + } + ] +} +``` + + +--- + +## 获取会话列表 + +GET `/conversations` + +获取当前用户的会话列表,默认返回最近的 20 条。 + +### Query Parameters + +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 +- `last_id` (string): (选填)当前页最后面一条记录的 ID,默认 null +- `limit` (int): (选填)一次请求返回多少条记录,默认 20 条,最大 100 条,最小 1 条。 +- `sort_by` (string): (选填)排序字段,默认 -updated_at(按更新时间倒序排列) + - 可选值:created_at, -created_at, updated_at, -updated_at + - 字段前面的符号代表顺序或倒序,-代表倒序 + +### Response + +- `data` (array[object]): 会话列表 + - `id` (string): 会话 ID + - `name` (string): 会话名称,默认为会话中用户最开始问题的截取。 + - `inputs` (object): 用户输入参数。 + - `status` (string): 会话状态 + - `introduction` (string): 开场白 + - `created_at` (timestamp): 创建时间 + - `updated_at` (timestamp): 更新时间 +- `has_more` (bool): 是否有更多 +- `limit` (int): 返回条数,若传入超过系统限制,返回系统限制数量 + + + ```bash {{ title: 'cURL' }} + curl -X GET 'https://api.dify.ai/v1/conversations?user=abc-123&last_id=&limit=20' + \ --header 'Authorization: Bearer {api_key}' ``` + + + +```json {{ title: 'Response' }} +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54", + "name": "New chat", + "inputs": { + "book": "book", + "myName": "Lucy" + }, + "status": "normal", + "created_at": 1679667915, + "updated_at": 1679667915 + }, + { + "id": "hSIhXBhNe8X1d8Et" + // ... + } + ] +} +``` + +--- +## 删除会话 + +DELETE `/conversations/:conversation_id` + +删除会话。 + +### Path Parameters + +- `conversation_id` (string): 会话 ID + +### Request Body + +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +- `result` (string): 固定返回 success (实际通常为 204 No Content) + + +```bash {{ title: 'cURL' }} +curl -X DELETE 'https://api.dify.ai/v1/conversations/{conversation_id}' \ +--header 'Content-Type: application/json' \ +--header 'Accept: application/json' \ +--header 'Authorization: Bearer {api_key}' \ +--data '{ + "user": "abc-123" +}' +``` + + + + ```text {{ title: 'Response' }} + 204 No Content ``` + +--- + +## 会话重命名 + +POST `/conversations/:conversation_id/name` + +对会话进行重命名,会话名称用于显示在支持多会话的客户端上。 + +### Path Parameters + +- `conversation_id` (string): 会话 ID + +### Request Body + +- `name` (string): (选填)名称,若 `auto_generate` 为 `true` 时,该参数可不传。 +- `auto_generate` (bool): (选填)自动生成标题,默认 false。 +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +- `id` (string): 会话 ID +- `name` (string): 会话名称 +- `inputs` (object): 用户输入参数 +- `status` (string): 会话状态 +- `introduction` (string): 开场白 +- `created_at` (timestamp): 创建时间 +- `updated_at` (timestamp): 更新时间 + + +```bash {{ title: 'cURL' }} +curl -X POST 'https://api.dify.ai/v1/conversations/{conversation_id}/name' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name": "", + "auto_generate": true, + "user": "abc-123" +}' +``` + + + +```json {{ title: 'Response' }} +{ + "id": "34d511d5-56de-4f16-a997-57b379508443", + "name": "hello", + "inputs": {}, + "status": "normal", + "introduction": "", + "created_at": 1732731141, + "updated_at": 1732734510 +} +``` + + +--- + +## 获取对话变量 + +GET `/conversations/:conversation_id/variables` + +从特定对话中检索变量。此端点对于提取对话过程中捕获的结构化数据非常有用。 + +### 路径参数 + +- `conversation_id` (string): 要从中检索变量的对话 ID。 + +### 查询参数 + +- `user` (string): 用户标识符,由开发人员定义的规则,在应用程序内必须唯一。 +- `last_id` (string): (选填)当前页最后面一条记录的 ID,默认 null +- `limit` (int): (选填)一次请求返回多少条记录,默认 20 条,最大 100 条,最小 1 条。 + +### 响应 + +- `limit` (int): 每页项目数 +- `has_more` (bool): 是否有更多项目 +- `data` (array[object]): 变量列表 + - `id` (string): 变量 ID + - `name` (string): 变量名称 + - `value_type` (string): 变量类型(字符串、数字、布尔等) + - `value` (string): 变量值 + - `description` (string): 变量描述 + - `created_at` (int): 创建时间戳 + - `updated_at` (int): 最后更新时间戳 + +### 错误 + +- 404, `conversation_not_exists`, 对话不存在 + + + ```bash {{ title: 'Request' }} + curl -X GET 'https://api.dify.ai/v1/conversations/{conversation_id}/variables?user=abc-123' + \ --header 'Authorization: Bearer {api_key}' ``` ```bash {{ + title: 'Request with variable name filter', + }} + curl -X GET 'https://api.dify.ai/v1/conversations/{conversation_id} + /variables?user=abc-123&variable_name=customer_name' \ --header 'Authorization: + Bearer {api_key}' ``` + + + +```json {{ title: 'Response' }} +{ + "limit": 100, + "has_more": false, + "data": [ + { + "id": "variable-uuid-1", + "name": "customer_name", + "value_type": "string", + "value": "John Doe", + "description": "客户名称(从对话中提取)", + "created_at": 1650000000000, + "updated_at": 1650000000000 + }, + { + "id": "variable-uuid-2", + "name": "order_details", + "value_type": "json", + "value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}", + "description": "客户的订单详情", + "created_at": 1650000000000, + "updated_at": 1650000000000 + } + ] +} +``` + + +--- + +## 语音转文字 + +POST `/audio-to-text` + +### Request Body + +该接口需使用 `multipart/form-data` 进行请求。 + +- `file` (file): 语音文件。支持格式:`['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm']` 文件大小限制:15MB +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +- `text` (string): 输出文字 + + + ```bash {{ title: 'cURL' }} + curl -X POST 'https://api.dify.ai/v1/audio-to-text' \ --header 'Authorization: + Bearer {api_key}' \ --form 'file=@localfile.mp3;type=audio/mp3' \ --form 'user=abc-123' + ``` + + + +```json {{ title: 'Response' }} +{ + "text": "hello" +} +``` + + +--- + +## 文字转语音 + +POST `/text-to-audio` + +文字转语音。 + +### Request Body + +- `message_id` (string): Dify 生成的文本消息,那么直接传递生成的 message-id 即可,后台会通过 message_id 查找相应的内容直接合成语音信息。如果同时传 message_id 和 text,优先使用 message_id。 +- `text` (string): 语音生成内容。如果没有传 message-id 的话,则会使用这个字段的内容 +- `user` (string): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + + + ```bash {{ title: 'cURL' }} + curl --location --request POST 'https://api.dify.ai/v1/text-to-audio' \ --header + 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' \ --form 'text=你好Dify' \ --form + 'user=abc-123' \ --form 'message_id=5ad4cb98-f0c7-4085-b384-88c403be6290' ``` + + + +```json {{ title: 'Headers Example (Response is audio file)' }} +{ + "Content-Type": "audio/wav" +} +``` + +--- + +## 获取应用基本信息 + +GET `/info` + +用于获取应用的基本信息 + +### Response + +- `name` (string): 应用名称 +- `description` (string): 应用描述 +- `tags` (array[string]): 应用标签 + + + ```bash {{ title: 'cURL' }} + curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: Bearer { + api_key + }' ``` + + + +```json {{ title: 'Response' }} +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## 获取应用参数 + +GET `/parameters` + +用于进入页面一开始,获取功能开关、输入参数名称、类型及默认值等使用。 + +### Response + +- `opening_statement` (string): 开场白 +- `suggested_questions` (array[string]): 开场推荐问题列表 +- `suggested_questions_after_answer` (object): 启用回答后给出推荐问题。 + - `enabled` (bool): 是否开启 +- `speech_to_text` (object): 语音转文本 + - `enabled` (bool): 是否开启 +- `retriever_resource` (object): 引用和归属 + - `enabled` (bool): 是否开启 +- `annotation_reply` (object): 标记回复 + - `enabled` (bool): 是否开启 +- `user_input_form` (array[object]): 用户输入表单配置 + - `text-input` (object): 文本输入控件 + - `label` (string): 控件展示标签名 + - `variable` (string): 控件 ID + - `required` (bool): 是否必填 + - `default` (string): 默认值 + - `paragraph` (object): 段落文本输入控件 + - `label` (string): 控件展示标签名 + - `variable` (string): 控件 ID + - `required` (bool): 是否必填 + - `default` (string): 默认值 + - `select` (object): 下拉控件 + - `label` (string): 控件展示标签名 + - `variable` (string): 控件 ID + - `required` (bool): 是否必填 + - `default` (string): 默认值 + - `options` (array[string]): 选项值 +- `file_upload` (object): 文件上传配置 + - `image` (object): 图片设置 当前仅支持图片类型:`png`, `jpg`, `jpeg`, `webp`, `gif` + - `enabled` (bool): 是否开启 + - `number_limits` (int): 图片数量限制,默认 3 + - `transfer_methods` (array[string]): 传递方式列表,remote_url , local_file,必选一个 +- `system_parameters` (object): 系统参数 + - `file_size_limit` (int): 文档上传大小限制 (MB) + - `image_file_size_limit` (int): 图片文件上传大小限制(MB) + - `audio_file_size_limit` (int): 音频文件上传大小限制 (MB) + - `video_file_size_limit` (int): 视频文件上传大小限制 (MB) + + + ```bash {{ title: 'cURL' }} + curl -X GET 'https://api.dify.ai/v1/parameters' \ --header 'Authorization: Bearer{' '} + {api_key}' ``` + + + +```json {{ title: 'Response' }} +{ + "introduction": "nice to meet you", + "user_input_form": [ + { + "text-input": { + "label": "a", + "variable": "a", + "required": true, + "max_length": 48, + "default": "" + } + }, + { + // ... + } + ], + "file_upload": { + "image": { + "enabled": true, + "number_limits": 3, + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + + +--- + +## 获取应用 Meta 信息 + +GET `/meta` + +用于获取工具 icon + +### Response + +- `tool_icons`(object[string]): 工具图标 + - `工具名称` (string) + - `icon` (object|string) + - (object) 图标 + - `background` (string): hex 格式的背景色 + - `content`(string): emoji + - (string) 图标 URL + + + ```bash {{ title: 'cURL' }} + curl -X GET 'https://api.dify.ai/v1/meta' \ -H 'Authorization: Bearer { + api_key + }' ``` + + + +```json {{ title: 'Response' }} +{ + "tool_icons": { + "dalle2": "https://cloud.dify.ai/console/api/workspaces/current/tool-provider/builtin/dalle/icon", + "api_tool": { + "background": "#252525", + "content": "\ud83d\ude01" + } + } +} +``` + diff --git a/api_access/chatflow.en.mdx b/api_access/chatflow.en.mdx new file mode 100644 index 00000000..09a3950e --- /dev/null +++ b/api_access/chatflow.en.mdx @@ -0,0 +1,1147 @@ +--- +title: Advanced Chat App API +--- + +Chat applications support session persistence, allowing previous chat history to be used as context for responses. This can be applicable for chatbot, customer service AI, etc. + +### Base URL + +```text +https://api.dify.ai/v1 +``` + +### Authentication + +The Service API uses `API-Key` authentication. + + + **Strongly recommend storing your API Key on the server-side, not shared or + stored on the client-side, to avoid possible API-Key leakage that can lead + to serious consequences.** + + +For all API requests, include your API Key in the `Authorization`HTTP Header, as shown below: + +```javascript +Authorization: Bearer {API_KEY} +``` + +--- + +## POST /chat-messages Send Chat Message + +Send a request to the chat application. + +### Request Body + +- `query` (`string`): User Input/Question content +- `inputs` (`object`): Allows the entry of various variable values defined by the App. The `inputs` parameter contains multiple key/value pairs, with each key corresponding to a specific variable and each value being the specific value for that variable. If the variable is of file type, specify an object that has the keys described in `files` below. Default `{}` +- `response_mode` (`string`): The mode of response return, supporting: + - `streaming` Streaming mode (recommended), implements a typewriter-like output through SSE ([Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)). + - `blocking` Blocking mode, returns result after execution is complete. (Requests may be interrupted if the process is long) + Due to Cloudflare restrictions, the request will be interrupted without a return after 100 seconds. +- `user` (`string`): User identifier, used to define the identity of the end-user for retrieval and statistics. Should be uniquely defined by the developer within the application. +- `conversation_id` (`string`): Conversation ID, to continue the conversation based on previous chat records, it is necessary to pass the previous message's conversation_id. +- `files` (`array[object]`): File list, suitable for inputting files combined with text understanding and answering questions, available only when the model supports Vision capability. + - `type` (`string`): Supported type: + - `document` ('TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB') + - `image` ('JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG') + - `audio` ('MP3', 'M4A', 'WAV', 'WEBM', 'AMR') + - `video` ('MP4', 'MOV', 'MPEG', 'MPGA') + - `custom` (Other file types) + - `transfer_method` (`string`): Transfer method, `remote_url` for image URL / `local_file` for file upload + - `url` (`string`): Image URL (when the transfer method is `remote_url`) + - `upload_file_id` (`string`): Uploaded file ID, which must be obtained by uploading through the File Upload API in advance (when the transfer method is `local_file`) +- `auto_generate_name` (`bool`): Auto-generate title, default is `true`. If set to `false`, can achieve async title generation by calling the conversation rename API and setting `auto_generate` to `true`. + +### Response + +When response_mode is blocking, return a CompletionResponse object. +When response_mode is streaming, return a ChunkCompletionResponse stream. + +#### ChatCompletionResponse + +Returns the complete App result, `Content-Type` is `application/json`. + +- `event` (`string`): Event type, fixed to `message` +- `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API +- `id` (`string`): unique ID +- `message_id` (`string`): Unique message ID +- `conversation_id` (`string`): Conversation ID +- `mode` (`string`): App mode, fixed as `chat` +- `answer` (`string`): Complete response content +- `metadata` (`object`): Metadata + - `usage` (Usage): Model usage information + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List +- `created_at` (`int`): Message creation timestamp, e.g., 1705395332 + +#### ChunkChatCompletionResponse + +Returns the stream chunks outputted by the App, `Content-Type` is `text/event-stream`. +Each streaming chunk starts with `data:`, separated by two newline characters `\n\n`, as shown below: + +```text Response +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +The structure of the streaming chunks varies depending on the `event`: + +- `event: message` LLM returns text chunk event, i.e., the complete text is output in a chunked fashion. + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `message_id` (`string`): Unique message ID + - `conversation_id` (`string`): Conversation ID + - `answer` (`string`): LLM returned text chunk content + - `created_at` (`int`): Creation timestamp, e.g., 1705395332 +- `event: message_file` Message file event, a new file has created by tool + - `id` (`string`): File unique ID + - `type` (`string`): File type,only allow "image" currently + - `belongs_to` (`string`): Belongs to, it will only be an 'assistant' here + - `url` (`string`): Remote url of file + - `conversation_id` (`string`): Conversation ID +- `event: message_end` Message end event, receiving this event means streaming has ended. + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `message_id` (`string`): Unique message ID + - `conversation_id` (`string`): Conversation ID + - `metadata` (`object`): Metadata + - `usage` (Usage): Model usage information + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List +- `event: tts_message` TTS audio stream event, that is, speech synthesis output. The content is an audio block in Mp3 format, encoded as a base64 string. When playing, simply decode the base64 and feed it into the player. (This message is available only when auto-play is enabled) + - `task_id` (`string`): Task ID, used for request tracking and the stop response interface below + - `message_id` (`string`): Unique message ID + - `audio` (`string`): The audio after speech synthesis, encoded in base64 text content, when playing, simply decode the base64 and feed it into the player + - `created_at` (`int`): Creation timestamp, e.g.: 1705395332 +- `event: tts_message_end` TTS audio stream end event, receiving this event indicates the end of the audio stream. + - `task_id` (`string`): Task ID, used for request tracking and the stop response interface below + - `message_id` (`string`): Unique message ID + - `audio` (`string`): The end event has no audio, so this is an empty string + - `created_at` (`int`): Creation timestamp, e.g.: 1705395332 +- `event: message_replace` Message content replacement event. + When output content moderation is enabled, if the content is flagged, then the message content will be replaced with a preset reply through this event. + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `message_id` (`string`): Unique message ID + - `conversation_id` (`string`): Conversation ID + - `answer` (`string`): Replacement content (directly replaces all LLM reply text) + - `created_at` (`int`): Creation timestamp, e.g., 1705395332 +- `event: workflow_started` workflow starts execution + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (`string`): Unique ID of workflow execution + - `event` (`string`): fixed to `workflow_started` + - `data` (`object`): detail + - `id` (`string`): Unique ID of workflow execution + - `workflow_id` (`string`): ID of related workflow + - `sequence_number` (`int`): Self-increasing serial number, self-increasing in the App, starting from 1 + - `created_at` (`timestamp`): Creation timestamp, e.g., 1705395332 +- `event: node_started` node execution started + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (`string`): Unique ID of workflow execution + - `event` (`string`): fixed to `node_started` + - `data` (`object`): detail + - `id` (`string`): Unique ID of workflow execution + - `node_id` (`string`): ID of node + - `node_type` (`string`): type of node + - `title` (`string`): name of node + - `index` (`int`): Execution sequence number, used to display Tracing Node sequence + - `predecessor_node_id` (`string`): optional Prefix node ID, used for canvas display execution path + - `inputs` (`object`): Contents of all preceding node variables used in the node + - `created_at` (`timestamp`): timestamp of start, e.g., 1705395332 +- `event: node_finished` node execution ends, success or failure in different states in the same event + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (`string`): Unique ID of workflow execution + - `event` (`string`): fixed to `node_finished` + - `data` (`object`): detail + - `id` (`string`): Unique ID of workflow execution + - `node_id` (`string`): ID of node + - `node_type` (`string`): type of node + - `title` (`string`): name of node + - `index` (`int`): Execution sequence number, used to display Tracing Node sequence + - `predecessor_node_id` (`string`): optional Prefix node ID, used for canvas display execution path + - `inputs` (`object`): Contents of all preceding node variables used in the node + - `process_data` (`json`): Optional node process data + - `outputs` (`json`): Optional content of output + - `status` (`string`): status of execution, `running` / `succeeded` / `failed` / `stopped` + - `error` (`string`): Optional reason of error + - `elapsed_time` (`float`): Optional total seconds to be used + - `execution_metadata` (`json`): meta data + - `total_tokens` (`int`): optional tokens to be used + - `total_price` (`decimal`): optional Total cost + - `currency` (`string`): optional e.g. `USD` / `RMB` + - `created_at` (`timestamp`): timestamp of start, e.g., 1705395332 +- `event: workflow_finished` workflow execution ends, success or failure in different states in the same event + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (`string`): Unique ID of workflow execution + - `event` (`string`): fixed to `workflow_finished` + - `data` (`object`): detail + - `id` (`string`): ID of workflow execution + - `workflow_id` (`string`): ID of related workflow + - `status` (`string`): status of execution, `running` / `succeeded` / `failed` / `stopped` + - `outputs` (`json`): Optional content of output + - `error` (`string`): Optional reason of error + - `elapsed_time` (`float`): Optional total seconds to be used + - `total_tokens` (`int`): Optional tokens to be used + - `total_steps` (`int`): default 0 + - `created_at` (`timestamp`): start time + - `finished_at` (`timestamp`): end time +- `event: error` + Exceptions that occur during the streaming process will be output in the form of stream events, and reception of an error event will end the stream. + - `task_id` (`string`): Task ID, used for request tracking and the below Stop Generate API + - `message_id` (`string`): Unique message ID + - `status` (`int`): HTTP status code + - `code` (`string`): Error code + - `message` (`string`): Error message +- `event: ping` Ping event every 10 seconds to keep the connection alive. + +### Errors + +- 404, Conversation does not exists +- 400, `invalid_param`, abnormal parameter input +- 400, `app_unavailable`, App configuration unavailable +- 400, `provider_not_initialize`, no available model credential configuration +- 400, `provider_quota_exceeded`, model invocation quota insufficient +- 400, `model_currently_not_support`, current model unavailable +- 400, `completion_request_error`, text generation failed +- 500, internal server error + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {}, + "query": "What are the specs of the iPhone 13 Pro Max?", + "response_mode": "streaming", + "conversation_id": "", + "user": "abc-123", + "files": [ + { + "type": "image", + "transfer_method": "remote_url", + "url": "https://cloud.dify.ai/logo/logo-site.png" + } + ] +}' +``` + + + +```json Blocking Mode Response +{ + "event": "message", + "task_id": "c3800678-a077-43df-a102-53f23ed20b88", + "id": "9da23599-e713-473b-982c-4328d4f5c78a", + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", + "mode": "chat", + "answer": "iPhone 13 Pro Max specs are listed here:...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + }, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ] + }, + "created_at": 1705407629 +} +``` +```text Streaming Mode Response + data: {"event": "workflow_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "sequence_number": 1, "created_at": 1679586595}} + data: {"event": "node_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "created_at": 1679586595}} + data: {"event": "node_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "execution_metadata": {"total_tokens": 63127864, "total_price": 2.378, "currency": "USD"}, "created_at": 1679586595}} + data: {"event": "workflow_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "total_tokens": 63127864, "total_steps": "1", "created_at": 1679586595, "finished_at": 1679976595}} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} + data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +--- + +## POST /files/upload File Upload + +Upload a file for use when sending messages, enabling multimodal understanding of images and text. +Supports any formats that are supported by your application. +Uploaded files are for use by the current end-user only. + +### Request Body + +This interface requires a `multipart/form-data` request. + +- `file` (File) Required: The file to be uploaded. +- `user` (string) Required: User identifier, defined by the developer's rules, must be unique within the application. + +### Response + +After a successful upload, the server will return the file's ID and related information. + +- `id` (uuid): ID +- `name` (string): File name +- `size` (int): File size (bytes) +- `extension` (string): File extension +- `mime_type` (string): File mime-type +- `created_by` (uuid): End-user ID +- `created_at` (timestamp): Creation timestamp, e.g., 1705395332 + +### Errors + +- 400, `no_file_uploaded`, a file must be provided +- 400, `too_many_files`, currently only one file is accepted +- 400, `unsupported_preview`, the file does not support preview +- 400, `unsupported_estimate`, the file does not support estimation +- 413, `file_too_large`, the file is too large +- 415, `unsupported_file_type`, unsupported extension, currently only document files are accepted +- 503, `s3_connection_failed`, unable to connect to S3 service +- 503, `s3_permission_denied`, no permission to upload files to S3 +- 503, `s3_file_too_large`, file exceeds S3 size limit +- 500, internal server error + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header + 'Authorization: Bearer {api_key}' \ --form 'file=@"/path/to/file"' \ --form + 'user=abc-123' ``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 +} +``` + +--- + +## POST /chat-messages/:task_id/stop Stop Generate + +Only supported in streaming mode. + +### Path + +- `task_id` (`string`): Task ID, can be obtained from the streaming chunk return + +### Request Body + +- `user` (`string`) Required: User identifier, used to define the identity of the end-user, must be consistent with the user passed in the send message interface. + +### Response + +- `result` (`string`): Always returns "success" + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## POST /messages/:message_id/feedbacks Message Feedback + +End-users can provide feedback messages, facilitating application developers to optimize expected outputs. + +### Path Parameters + +- `message_id` (`string`): Message ID + +### Request Body + +- `rating` (`string`): Upvote as `like`, downvote as `dislike`, revoke upvote as `null` +- `user` (`string`): User identifier, defined by the developer's rules, must be unique within the application. +- `content` (`string`): The specific content of message feedback. + +### Response + +- `result` (`string`): Always returns "success" + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/messages/:message_id/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## GET /messages/{message_id}/suggested Next Suggested Questions + +Get next questions suggestions for the current message + +### Path Parameters + +- `message_id` (`string`): Message ID + +### Query Parameters + +- `user` (`string`): User identifier, used to define the identity of the end-user for retrieval and statistics. Should be uniquely defined by the developer within the application. + + + ```bash cURL curl --location --request GET 'https://api.dify.ai/v1/messages/ + {message_id}/suggested?user=abc-123' \ --header 'Authorization: Bearer { + api_key + }' \ --header 'Content-Type: application/json' ``` + + + +```json Response +{ + "result": "success", + "data": [ + "a", + "b", + "c" + ] +} +``` + + +--- + +## GET /messages Get Conversation History Messages + +Returns historical chat records in a scrolling load format, with the first page returning the latest `{limit}` messages, i.e., in reverse order. + +### Query Parameters + +- `conversation_id` (`string`): Conversation ID +- `user` (`string`): User identifier, used to define the identity of the end-user for retrieval and statistics. Should be uniquely defined by the developer within the application. +- `first_id` (`string`): The ID of the first chat record on the current page, default is null. +- `limit` (`int`): How many chat history messages to return in one request, default is 20. + +### Response + +- `data` (`array[object]`): Message list + - `id` (`string`): Message ID + - `conversation_id` (`string`): Conversation ID + - `inputs` (`object`): User input parameters. + - `query` (`string`): User input / question content. + - `message_files` (`array[object]`): Message files + - `id` (`string`): ID + - `type` (`string`): File type, image for images + - `url` (`string`): Preview image URL + - `belongs_to` (`string`): belongs to,user or assistant + - `answer` (`string`): Response message content + - `created_at` (`timestamp`): Creation timestamp, e.g., 1705395332 + - `feedback` (`object`): Feedback information + - `rating` (`string`): Upvote as `like` / Downvote as `dislike` + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List +- `has_more` (`bool`): Whether there is a next page +- `limit` (`int`): Number of returned items, if input exceeds system limit, returns system limit amount + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/messages?user=abc-123&conversation_id=' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "a076a87f-31e5-48dc-b452-0061adbbc922", + "conversation_id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "inputs": { + "name": "dify" + }, + "query": "iphone 13 pro", + "answer": "The iPhone 13 Pro, released on September 24, 2021, features a 6.1-inch display with a resolution of 1170 x 2532. It is equipped with a Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard) processor, 6 GB of RAM, and offers storage options of 128 GB, 256 GB, 512 GB, and 1 TB. The camera is 12 MP, the battery capacity is 3095 mAh, and it runs on iOS 15.", + "message_files": [], + "feedback": null, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ], + "created_at": 1705569239 + } + ] +} +``` + + +--- + +## GET /conversations Get Conversations + +Retrieve the conversation list for the current user, defaulting to the most recent 20 entries. + +### Query Parameters + +- `user` (`string`): User identifier, used to define the identity of the end-user for retrieval and statistics. Should be uniquely defined by the developer within the application. +- `last_id` (`string`, Optional): The ID of the last record on the current page, default is null. +- `limit` (`int`, Optional): How many records to return in one request, default is the most recent 20 entries. Maximum 100, minimum 1. +- `sort_by` (`string`, Optional): Sorting Field, Default: -updated_at (sorted in descending order by update time) + - Available Values: created_at, -created_at, updated_at, -updated_at + - The symbol before the field represents the order or reverse, "-" represents reverse order. + +### Response + +- `data` (`array[object]`): List of conversations + - `id` (`string`): Conversation ID + - `name` (`string`): Conversation name, by default, is generated by LLM. + - `inputs` (`object`): User input parameters. + - `status` (`string`): Conversation status + - `introduction` (`string`): Introduction + - `created_at` (`timestamp`): Creation timestamp, e.g., 1705395332 + - `updated_at` (`timestamp`): Update timestamp, e.g., 1705395332 +- `has_more` (`bool`): Whether there is a next page. +- `limit` (`int`): Number of entries returned, if input exceeds system limit, system limit number is returned. + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/conversations?user=abc-123&last_id=&limit=20' \ + --header 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54", + "name": "New chat", + "inputs": { + "book": "book", + "myName": "Lucy" + }, + "status": "normal", + "created_at": 1679667915, + "updated_at": 1679667915 + }, + { + "id": "hSIhXBhNe8X1d8Et" + // ... + } + ] +} +``` + + +--- + +## DELETE /conversations/:conversation_id Delete Conversation + +Delete a conversation. + +### Path Parameters + +- `conversation_id` (`string`): Conversation ID + +### Request Body + +- `user` (`string`): The user identifier, defined by the developer, must ensure uniqueness within the application. + +### Response + +- `result` (`string`): Always returns "success" (Note: HTTP 204 No Content is typical for successful DELETE operations). + + +```bash cURL +curl -X DELETE 'https://api.dify.ai/v1/conversations/{conversation_id}' \ +--header 'Content-Type: application/json' \ +--header 'Accept: application/json' \ +--header 'Authorization: Bearer {api_key}' \ +--data '{ + "user": "abc-123" +}' +``` + + +```text Response 204 No Content ``` + +--- + +## POST /conversations/:conversation_id/name Conversation Rename + +Rename the session, the session name is used for display on clients that support multiple sessions. + +### Path Parameters + +- `conversation_id` (`string`): Conversation ID + +### Request Body + +- `name` (`string`, Optional): The name of the conversation. This parameter can be omitted if `auto_generate` is set to `true`. +- `auto_generate` (`bool`, Optional): Automatically generate the title, default is `false`. +- `user` (`string`): The user identifier, defined by the developer, must ensure uniqueness within the application. + +### Response + +- `id` (`string`): Conversation ID +- `name` (`string`): Conversation name +- `inputs` (`object`): User input parameters +- `status` (`string`): Conversation status +- `introduction` (`string`): Introduction +- `created_at` (`timestamp`): Creation timestamp, e.g., 1705395332 +- `updated_at` (`timestamp`): Update timestamp, e.g., 1705395332 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/conversations/{conversation_id}/name' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer {api_key}' \ +--data-raw '{ + "name": "", + "auto_generate": true, + "user": "abc-123" +}' +``` + + + +```json Response +{ + "id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "name": "Chat vs AI", + "inputs": {}, + "status": "normal", + "introduction": "", + "created_at": 1705569238, + "updated_at": 1705569238 +} +``` + + +--- + +## GET /conversations/:conversation_id/variables Get Conversation Variables + +Retrieve variables from a specific conversation. This endpoint is useful for extracting structured data that was captured during the conversation. + +### Path Parameters + +- `conversation_id` (`string`): The ID of the conversation to retrieve variables from. + +### Query Parameters + +- `user` (`string`): The user identifier, defined by the developer, must ensure uniqueness within the application. +- `last_id` (`string`, Optional): The ID of the last record on the current page, default is null. +- `limit` (`int`, Optional): How many records to return in one request, default is the most recent 20 entries. Maximum 100, minimum 1. + +### Response + +- `limit` (`int`): Number of items per page +- `has_more` (`bool`): Whether there is a next page +- `data` (`array[object]`): List of variables + - `id` (`string`): Variable ID + - `name` (`string`): Variable name + - `value_type` (`string`): Variable type (string, number, object, etc.) + - `value` (`string`): Variable value + - `description` (`string`): Variable description + - `created_at` (`int`): Creation timestamp + - `updated_at` (`int`): Last update timestamp + +### Errors + +- 404, `conversation_not_exists`, Conversation not found + + + ```bash Get All Variables curl -X GET 'https://api.dify.ai/v1/conversations/ + {conversation_id}/variables?user=abc-123' \ --header 'Authorization: Bearer { + api_key + }' ``` ```bash Filter by Variable Name curl -X GET 'https://api.dify.ai/v1/conversations/ + {conversation_id} + /variables?user=abc-123&variable_name=customer_name' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "limit": 100, + "has_more": false, + "data": [ + { + "id": "variable-uuid-1", + "name": "customer_name", + "value_type": "string", + "value": "John Doe", + "description": "Customer name extracted from the conversation", + "created_at": 1650000000000, + "updated_at": 1650000000000 + }, + { + "id": "variable-uuid-2", + "name": "order_details", + "value_type": "json", + "value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}", + "description": "Order details from the customer", + "created_at": 1650000000000, + "updated_at": 1650000000000 + } + ] +} +``` + + +--- + +## POST /audio-to-text Speech to Text + +This endpoint requires a multipart/form-data request. + +### Request Body + +- `file` (`file`): Audio file. + Supported formats: `['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm']` + File size limit: 15MB +- `user` (`string`): User identifier, defined by the developer's rules, must be unique within the application. + +### Response + +- `text` (`string`): Output text + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/audio-to-text' \ --header + 'Authorization: Bearer {api_key}' \ --form 'file=@localfile;type=audio/mp3' + \ --form 'user=abc-123' ``` + + + +```json Response +{ + "text": "" +} +``` + + +--- + +## POST /text-to-audio Text to Audio + +Text to speech. + +### Request Body + +- `message_id` (`str`): For text messages generated by Dify, simply pass the generated message-id directly. The backend will use the message-id to look up the corresponding content and synthesize the voice information directly. If both message_id and text are provided simultaneously, the message_id is given priority. +- `text` (`str`): Speech generated content. +- `user` (`string`): The user identifier, defined by the developer, must ensure uniqueness within the app. + + +```bash cURL +curl -o text-to-audio.mp3 -X POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", + "text": "Hello Dify", + "user": "abc-123", + "streaming": false +}' +``` + + + + ```http Response Headers Content-Type: audio/wav ``` ```text Response Body # + The response body is the audio data. # The example cURL command saves it to + text-to-audio.mp3 (or .wav depending on actual server response type) ``` + +--- + +## GET /info Get Application Basic Information + +Used to get basic information about this application + +### Response + +- `name` (`string`): application name +- `description` (`string`): application description +- `tags` (`array[string]`): application tags + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## GET /parameters Get Application Parameters Information + +Used at the start of entering the page to obtain information such as features, input parameter names, types, and default values. + +### Response + +- `opening_statement` (`string`): Opening statement +- `suggested_questions` (`array[string]`): List of suggested questions for the opening +- `suggested_questions_after_answer` (`object`): Suggest questions after enabling the answer. + - `enabled` (`bool`): Whether it is enabled +- `speech_to_text` (`object`): Speech to text + - `enabled` (`bool`): Whether it is enabled +- `retriever_resource` (`object`): Citation and Attribution + - `enabled` (`bool`): Whether it is enabled +- `annotation_reply` (`object`): Annotation reply + - `enabled` (`bool`): Whether it is enabled +- `user_input_form` (`array[object]`): User input form configuration + - `text-input` (`object`): Text input control + - `label` (`string`): Variable display label name + - `variable` (`string`): Variable ID + - `required` (`bool`): Whether it is required + - `default` (`string`): Default value + - `paragraph` (`object`): Paragraph text input control + - `label` (`string`): Variable display label name + - `variable` (`string`): Variable ID + - `required` (`bool`): Whether it is required + - `default` (`string`): Default value + - `select` (`object`): Dropdown control + - `label` (`string`): Variable display label name + - `variable` (`string`): Variable ID + - `required` (`bool`): Whether it is required + - `default` (`string`): Default value + - `options` (`array[string]`): Option values +- `file_upload` (`object`): File upload configuration + - `image` (`object`): Image settings + Currently only supports image types: `png`, `jpg`, `jpeg`, `webp`, `gif` + - `enabled` (`bool`): Whether it is enabled + - `number_limits` (`int`): Image number limit, default is 3 + - `transfer_methods` (`array[string]`): List of transfer methods, remote_url, local_file, must choose one +- `system_parameters` (`object`): System parameters + - `file_size_limit` (`int`): Document upload size limit (MB) + - `image_file_size_limit` (`int`): Image file upload size limit (MB) + - `audio_file_size_limit` (`int`): Audio file upload size limit (MB) + - `video_file_size_limit` (`int`): Video file upload size limit (MB) + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "opening_statement": "Hello!", + "suggested_questions_after_answer": { + "enabled": true + }, + "speech_to_text": { + "enabled": true + }, + "retriever_resource": { + "enabled": true + }, + "annotation_reply": { + "enabled": true + }, + "user_input_form": [ + { + "paragraph": { + "label": "Query", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + +--- + +## GET /meta Get Application Meta Information + +Used to get icons of tools in this application + +### Response + +- `tool_icons`(`object[string]`): tool icons + - `tool_name` (`string`) + - `icon` (`object`|`string`) + - (`object`) icon object + - `background` (`string`): background color in hex format + - `content`(`string`): emoji + - (`string`) url of icon + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/meta' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "tool_icons": { + "dalle2": "https://cloud.dify.ai/console/api/workspaces/current/tool-provider/builtin/dalle/icon", + "api_tool": { + "background": "#252525", + "content": "\ud83d\ude01" + } + } +} +``` + +--- + +## GET /apps/annotations Get Annotation List + +### Query Parameters + +- `page` (`string`): Page number +- `limit` (`string`): Number of items returned, default 20, range 1-100 + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotations?page=1&limit=20' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "data": [ + { + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 + } + ], + "has_more": false, + "limit": 20, + "total": 1, + "page": 1 +} +``` + +--- + +## POST /apps/annotations Create Annotation + +### Request Body + +- `question` (`string`): Question +- `answer` (`string`): Answer + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/apps/annotations' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your name?", + "answer": "I am Dify." +}' +``` + + + +```json Response +{ + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + +--- + +## PUT /apps/annotations/{annotation_id} Update Annotation + +### Path Parameters + +- `annotation_id` (`string`): Annotation ID + +### Request Body + +- `question` (`string`): Question +- `answer` (`string`): Answer + + +```bash cURL +curl --location --request PUT 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your name?", + "answer": "I am Dify." +}' +``` + + + +```json Response +{ + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + +--- + +## DELETE /apps/annotations/{annotation_id} Delete Annotation + +### Path Parameters + +- `annotation_id` (`string`): Annotation ID + + + ```bash cURL curl --location --request DELETE + 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ --header + 'Authorization: Bearer {api_key}' ``` + + +## `text Response 204 No Content ` + +## POST /apps/annotation-reply/{action} Initial Annotation Reply Settings + +### Path Parameters + +- `action` (`string`): Action, can only be 'enable' or 'disable' + +### Request Body + +- `embedding_provider_name` (`string`, Optional): Specified embedding model provider, must be set up in the system first, corresponding to the provider field. +- `embedding_model_name` (`string`, Optional): Specified embedding model, corresponding to the model field. +- `score_threshold` (`number`): The similarity threshold for matching annotated replies. Only annotations with scores above this threshold will be recalled. + +The provider and model name of the embedding model can be obtained through the following interface: `v1/workspaces/current/models/model-types/text-embedding`. For specific instructions, see: Maintain Knowledge Base via API. The Authorization used is the Dataset API Token. + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/apps/annotation-reply/{action}' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "score_threshold": 0.9, + "embedding_provider_name": "zhipu", + "embedding_model_name": "embedding_3" +}' +``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "waiting" +} +``` + +This interface is executed asynchronously, so it will return a job_id. You can get the final execution result by querying the job status interface. +--- + +## GET /apps/annotation-reply/{action}/status/{job_id} Query Initial Annotation Reply Settings Task Status + +### Path Parameters + +- `action` (`string`): Action, can only be 'enable' or 'disable', must be the same as the action in the initial annotation reply settings interface +- `job_id` (`string`): Job ID, obtained from the initial annotation reply settings interface + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotation-reply/{action}/status/{job_id}' \ + --header 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "waiting", + "error_msg": "" +} +``` + diff --git a/api_access/chatflow.ja.mdx b/api_access/chatflow.ja.mdx new file mode 100644 index 00000000..7cdea22e --- /dev/null +++ b/api_access/chatflow.ja.mdx @@ -0,0 +1,1004 @@ +--- +title: 高度なチャットアプリAPI +--- + +チャットアプリケーションはセッションの持続性をサポートしており、以前のチャット履歴を応答のコンテキストとして使用できます。これは、チャットボットやカスタマーサービス AI などに適用できます。 + +### ベース URL + +```text +https://api.dify.ai/v1 +``` + +### 認証 + +サービス API は`API-Key`認証を使用します。 + + + **APIキーはサーバー側に保存し、クライアント側で共有または保存しないことを強くお勧めします。APIキーの漏洩は深刻な結果を招く可能性があります。** + + +すべての API リクエストには、以下のように`Authorization`HTTP ヘッダーに API キーを含めてください: + +```text +Authorization: Bearer {API_KEY} +``` + +--- + +## POST /chat-messages + +### チャットメッセージを送信 + +チャットアプリケーションにリクエストを送信します。 + +### リクエストボディ + +**`query`** (`string`): +ユーザー入力/質問内容 + +**`inputs`** (`object`, デフォルト: `{}`): +アプリによって定義されたさまざまな変数値の入力を許可します。 +`inputs`パラメータには複数のキー/値ペアが含まれ、各キーは特定の変数に対応し、各値はその変数の特定の値です。 +変数がファイルタイプの場合、以下の`files`で説明されているキーを持つオブジェクトを指定します。 + +**`response_mode`** (`string`): +応答の返却モードを指定します。サポートされているモード: + +- `streaming` ストリーミングモード(推奨)、SSE([サーバー送信イベント](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events))を通じてタイプライターのような出力を実装します。 +- `blocking` ブロッキングモード、実行完了後に結果を返します。(プロセスが長い場合、リクエストが中断される可能性があります) + Cloudflare の制限により、リクエストは 100 秒後に返答なしで中断されます。 + +**`user`** (`string`): +ユーザー識別子、エンドユーザーの身元を定義するために使用され、統計のために使用されます。 +アプリケーション内で開発者によって一意に定義されるべきです。 + +**`conversation_id`** (`string`): +会話 ID、以前のチャット記録に基づいて会話を続けるには、以前のメッセージの conversation_id を渡す必要があります。 + +**`files`** (`array[object]`): +ファイルリスト、テキストの理解と質問への回答を組み合わせたファイルの入力に適しており、モデルがビジョン機能をサポートしている場合にのみ利用可能です。 +各オブジェクトは以下のフィールドを持ちます: + +- **`type`** (`string`): サポートされているタイプ: + - `document` ('TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB') + - `image` ('JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG') + - `audio` ('MP3', 'M4A', 'WAV', 'WEBM', 'AMR') + - `video` ('MP4', 'MOV', 'MPEG', 'MPGA') + - `custom` (他のファイルタイプ) +- **`transfer_method`** (`string`): 転送方法、画像 URL の場合は`remote_url` / ファイルアップロードの場合は`local_file` +- **`url`** (`string`): 画像 URL(転送方法が`remote_url`の場合) +- **`upload_file_id`** (`string`): アップロードされたファイル ID、事前にファイルアップロード API を通じて取得する必要があります(転送方法が`local_file`の場合) + +**`auto_generate_name`** (`bool`, デフォルト: `true`): +タイトルを自動生成。 +`false`に設定すると、会話のリネーム API を呼び出し、`auto_generate`を`true`に設定することで非同期タイトル生成を実現できます。 + +### 応答 + +response_mode がブロッキングの場合、CompletionResponse オブジェクトを返します。 +response_mode がストリーミングの場合、ChunkCompletionResponse ストリームを返します。 + +#### ChatCompletionResponse + +完全なアプリ結果を返します。`Content-Type`は`application/json`です。 + +- **`event`** (`string`): イベントタイプ、固定で `message` +- **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 +- **`id`** (`string`): ユニーク ID +- **`message_id`** (`string`): 一意のメッセージ ID +- **`conversation_id`** (`string`): 会話 ID +- **`mode`** (`string`): アプリモード、`chat`として固定 +- **`answer`** (`string`): 完全な応答内容 +- **`metadata`** (`object`): メタデータ + - **`usage`** (`Usage`): モデル使用情報 + - **`retriever_resources`** (`array[RetrieverResource]`): 引用と帰属リスト +- **`created_at`** (`int`): メッセージ作成タイムスタンプ、例:1705395332 + +#### ChunkChatCompletionResponse + +アプリによって出力されたストリームチャンクを返します。`Content-Type`は`text/event-stream`です。 +各ストリーミングチャンクは`data:`で始まり、2 つの改行文字`\n\n`で区切られます。以下のように表示されます: + +```streaming Streaming Response Example +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +ストリーミングチャンクの構造は`event`に応じて異なります: + +- **`event: message`**: LLM がテキストチャンクイベントを返します。つまり、完全なテキストがチャンク形式で出力されます。 + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`message_id`** (`string`): 一意のメッセージ ID + - **`conversation_id`** (`string`): 会話 ID + - **`answer`** (`string`): LLM が返したテキストチャンク内容 + - **`created_at`** (`int`): 作成タイムスタンプ、例:1705395332 +- **`event: message_file`**: メッセージファイルイベント、ツールによって新しいファイルが作成されました + - **`id`** (`string`): ファイル一意 ID + - **`type`** (`string`): ファイルタイプ、現在は"image"のみ許可 + - **`belongs_to`** (`string`): 所属、ここでは'assistant'のみ + - **`url`** (`string`): ファイルのリモート URL + - **`conversation_id`** (`string`): 会話 ID +- **`event: message_end`**: メッセージ終了イベント、このイベントを受信するとストリーミングが終了したことを意味します。 + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`message_id`** (`string`): 一意のメッセージ ID + - **`conversation_id`** (`string`): 会話 ID + - **`metadata`** (`object`): メタデータ + - **`usage`** (`Usage`): モデル使用情報 + - **`retriever_resources`** (`array[RetrieverResource]`): 引用と帰属リスト +- **`event: tts_message`**: TTS オーディオストリームイベント、つまり音声合成出力。内容は Mp3 形式のオーディオブロックで、base64 文字列としてエンコードされています。再生時には、base64 をデコードしてプレーヤーに入力するだけです。(このメッセージは自動再生が有効な場合にのみ利用可能) + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下のストップ応答インターフェースに使用 + - **`message_id`** (`string`): 一意のメッセージ ID + - **`audio`** (`string`): 音声合成後のオーディオ、base64 テキストコンテンツとしてエンコードされており、再生時には base64 をデコードしてプレーヤーに入力するだけです + - **`created_at`** (`int`): 作成タイムスタンプ、例:1705395332 +- **`event: tts_message_end`**: TTS オーディオストリーム終了イベント、このイベントを受信するとオーディオストリームが終了したことを示します。 + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下のストップ応答インターフェースに使用 + - **`message_id`** (`string`): 一意のメッセージ ID + - **`audio`** (`string`): 終了イベントにはオーディオがないため、これは空の文字列です + - **`created_at`** (`int`): 作成タイムスタンプ、例:1705395332 +- **`event: message_replace`**: メッセージ内容置換イベント。 + 出力内容のモデレーションが有効な場合、内容がフラグ付けされると、このイベントを通じてメッセージ内容がプリセットの返信に置き換えられます。 + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`message_id`** (`string`): 一意のメッセージ ID + - **`conversation_id`** (`string`): 会話 ID + - **`answer`** (`string`): 置換内容(すべての LLM 返信テキストを直接置き換えます) + - **`created_at`** (`int`): 作成タイムスタンプ、例:1705395332 +- **`event: workflow_started`**: ワークフローが実行を開始 + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`workflow_run_id`** (`string`): ワークフロー実行の一意 ID + - **`event`** (`string`): `workflow_started`に固定 + - **`data`** (`object`): 詳細 + - **`id`** (`string`): ワークフロー実行の一意 ID + - **`workflow_id`** (`string`): 関連ワークフローの ID + - **`sequence_number`** (`int`): 自己増加シリアル番号、アプリ内で自己増加し、1 から始まります + - **`created_at`** (`timestamp`): 作成タイムスタンプ、例:1705395332 +- **`event: node_started`**: ノード実行が開始 + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`workflow_run_id`** (`string`): ワークフロー実行の一意 ID + - **`event`** (`string`): `node_started`に固定 + - **`data`** (`object`): 詳細 + - **`id`** (`string`): ワークフロー実行の一意 ID + - **`node_id`** (`string`): ノードの ID + - **`node_type`** (`string`): ノードのタイプ + - **`title`** (`string`): ノードの名前 + - **`index`** (`int`): 実行シーケンス番号、トレースノードシーケンスを表示するために使用 + - **`predecessor_node_id`** (`string`): オプションのプレフィックスノード ID、キャンバス表示実行パスに使用 + - **`inputs`** (`object`): ノードで使用されるすべての前のノード変数の内容 + - **`created_at`** (`timestamp`): 開始のタイムスタンプ、例:1705395332 +- **`event: node_finished`**: ノード実行が終了、成功または失敗は同じイベント内で異なる状態で示されます + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`workflow_run_id`** (`string`): ワークフロー実行の一意 ID + - **`event`** (`string`): `node_finished`に固定 + - **`data`** (`object`): 詳細 + - **`id`** (`string`): ワークフロー実行の一意 ID + - **`node_id`** (`string`): ノードの ID + - **`node_type`** (`string`): ノードのタイプ + - **`title`** (`string`): ノードの名前 + - **`index`** (`int`): 実行シーケンス番号、トレースノードシーケンスを表示するために使用 + - **`predecessor_node_id`** (`string`): オプションのプレフィックスノード ID、キャンバス表示実行パスに使用 + - **`inputs`** (`object`): ノードで使用されるすべての前のノード変数の内容 + - **`process_data`** (`json`): オプションのノードプロセスデータ + - **`outputs`** (`json`): オプションの出力内容 + - **`status`** (`string`): 実行の状態、`running` / `succeeded` / `failed` / `stopped` + - **`error`** (`string`): オプションのエラー理由 + - **`elapsed_time`** (`float`): オプションの使用される合計秒数 + - **`execution_metadata`** (`json`): メタデータ + - **`total_tokens`** (`int`): オプションの使用されるトークン数 + - **`total_price`** (`decimal`): オプションの合計コスト + - **`currency`** (`string`): オプション、例:`USD` / `RMB` + - **`created_at`** (`timestamp`): 開始のタイムスタンプ、例:1705395332 +- **`event: workflow_finished`**: ワークフロー実行が終了、成功または失敗は同じイベント内で異なる状態で示されます + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`workflow_run_id`** (`string`): ワークフロー実行の一意 ID + - **`event`** (`string`): `workflow_finished`に固定 + - **`data`** (`object`): 詳細 + - **`id`** (`string`): ワークフロー実行の ID + - **`workflow_id`** (`string`): 関連ワークフローの ID + - **`status`** (`string`): 実行の状態、`running` / `succeeded` / `failed` / `stopped` + - **`outputs`** (`json`): オプションの出力内容 + - **`error`** (`string`): オプションのエラー理由 + - **`elapsed_time`** (`float`): オプションの使用される合計秒数 + - **`total_tokens`** (`int`): オプションの使用されるトークン数 + - **`total_steps`** (`int`): デフォルト 0 + - **`created_at`** (`timestamp`): 開始時間 + - **`finished_at`** (`timestamp`): 終了時間 +- **`event: error`**: + ストリーミングプロセス中に発生する例外はストリームイベントの形式で出力され、エラーイベントを受信するとストリームが終了します。 + - **`task_id`** (`string`): タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - **`message_id`** (`string`): 一意のメッセージ ID + - **`status`** (`int`): HTTP ステータスコード + - **`code`** (`string`): エラーコード + - **`message`** (`string`): エラーメッセージ +- **`event: ping`**: 接続を維持するために 10 秒ごとに ping イベントが発生します。 + +### エラー + +- 404, 会話が存在しません +- 400, `invalid_param`, 異常なパラメータ入力 +- 400, `app_unavailable`, アプリ構成が利用できません +- 400, `provider_not_initialize`, 利用可能なモデル資格情報構成がありません +- 400, `provider_quota_exceeded`, モデル呼び出しクォータが不足しています +- 400, `model_currently_not_support`, 現在のモデルが利用できません +- 400, `completion_request_error`, テキスト生成に失敗しました +- 500, 内部サーバーエラー + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {}, + "query": "iPhone 13 Pro Maxの仕様は何ですか?", + "response_mode": "streaming", + "conversation_id": "", + "user": "abc-123", + "files": [ + { + "type": "image", + "transfer_method": "remote_url", + "url": "https://cloud.dify.ai/logo/logo-site.png" + } + ] +}' +``` + + + +```json Blocking Mode Response +{ + "event": "message", + "task_id": "c3800678-a077-43df-a102-53f23ed20b88", + "id": "9da23599-e713-473b-982c-4328d4f5c78a", + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", + "mode": "chat", + "answer": "iPhone 13 Pro Maxの仕様は次のとおりです:...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + }, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ] + }, + "created_at": 1705407629 +} +``` +```streaming Streaming Mode Response + data: {"event": "workflow_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "sequence_number": 1, "created_at": 1679586595}} + data: {"event": "node_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "created_at": 1679586595}} + data: {"event": "node_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "execution_metadata": {"total_tokens": 63127864, "total_price": 2.378, "currency": "USD"}, "created_at": 1679586595}} + data: {"event": "workflow_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "total_tokens": 63127864, "total_steps": "1", "created_at": 1679586595, "finished_at": 1679976595}} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} + data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + +--- + +## POST /files/upload + +### ファイルアップロード + +メッセージ送信時に使用するファイルをアップロードし、画像とテキストのマルチモーダル理解を可能にします。 +アプリケーションでサポートされている形式をサポートします。 +アップロードされたファイルは現在のエンドユーザーのみが使用できます。 + +### リクエストボディ + +このインターフェースは`multipart/form-data`リクエストを必要とします。 + +- **`file`** (`File`): 必須。アップロードするファイル。 +- **`user`** (`string`): 必須。ユーザー識別子、開発者のルールによって定義され、アプリケーション内で一意でなければなりません。 + +### 応答 + +アップロードが成功すると、サーバーはファイルの ID と関連情報を返します。 + +- **`id`** (`uuid`): ID +- **`name`** (`string`): ファイル名 +- **`size`** (`int`): ファイルサイズ(バイト) +- **`extension`** (`string`): ファイル拡張子 +- **`mime_type`** (`string`): ファイルの MIME タイプ +- **`created_by`** (`uuid`): エンドユーザー ID +- **`created_at`** (`timestamp`): 作成タイムスタンプ、例:1705395332 + +### エラー + +- 400, `no_file_uploaded`, ファイルが提供されなければなりません +- 400, `too_many_files`, 現在は 1 つのファイルのみ受け付けます +- 400, `unsupported_preview`, ファイルはプレビューをサポートしていません +- 400, `unsupported_estimate`, ファイルは推定をサポートしていません +- 413, `file_too_large`, ファイルが大きすぎます +- 415, `unsupported_file_type`, サポートされていない拡張子、現在はドキュメントファイルのみ受け付けます +- 503, `s3_connection_failed`, S3 サービスに接続できません +- 503, `s3_permission_denied`, S3 にファイルをアップロードする権限がありません +- 503, `s3_file_too_large`, ファイルが S3 のサイズ制限を超えています +- 500, 内部サーバーエラー + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header + 'Authorization: Bearer {api_key}' \ --form 'file=@"/path/to/file"' \ --form + 'user="abc-123"' ``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 +} +``` + +--- + +## POST /chat-messages/:task_id/stop + +### 生成を停止 + +ストリーミングモードでのみサポートされています。 + +### パスパラメータ + +- **`task_id`** (`string`): タスク ID、ストリーミングチャンクの返り値から取得できます + +### リクエストボディ + +- **`user`** (`string`): 必須。ユーザー識別子、エンドユーザーの身元を定義するために使用され、送信メッセージインターフェースで渡されたユーザーと一致している必要があります。 + +### 応答 + +- **`result`** (`string`): 常に"success"を返します + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + +--- + +## POST /messages/:message_id/feedbacks + +### メッセージフィードバック + +エンドユーザーはフィードバックメッセージを提供でき、アプリケーション開発者が期待される出力を最適化するのを支援します。 + +### パスパラメータ + +- **`message_id`** (`string`): メッセージ ID + +### リクエストボディ + +- **`rating`** (`string`): アップボートは`like`、ダウンボートは`dislike`、アップボートの取り消しは`null` +- **`user`** (`string`): ユーザー識別子、開発者のルールによって定義され、アプリケーション内で一意でなければなりません。 +- **`content`** (`string`): メッセージのフィードバックです。 + +### 応答 + +- **`result`** (`string`): 常に"success"を返します + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/messages/:message_id/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + +--- + +## GET /messages/{message_id}/suggested + +### 次の推奨質問 + +現在のメッセージに対する次の質問の提案を取得します + +### パスパラメータ + +- **`message_id`** (`string`): メッセージ ID + +### クエリパラメータ + +- **`user`** (`string`): ユーザー識別子、エンドユーザーの身元を定義するために使用され、統計のために使用されます。アプリケーション内で開発者によって一意に定義されるべきです。 + + + ```bash cURL curl --location --request GET 'https://api.dify.ai/v1/messages/ + {message_id}/suggested?user=abc-123' \ --header 'Authorization: Bearer ENTER-YOUR-SECRET-KEY' + \ --header 'Content-Type: application/json' ``` + + + +```json Response +{ + "result": "success", + "data": [ + "a", + "b", + "c" + ] +} +``` + +--- + +## GET /messages + +### 会話履歴メッセージを取得 + +スクロールロード形式で履歴チャット記録を返し、最初のページは最新の`{limit}`メッセージを返します。つまり、逆順です。 + +### クエリパラメータ + +- **`conversation_id`** (`string`): 会話 ID +- **`user`** (`string`): ユーザー識別子、エンドユーザーの身元を定義するために使用され、統計のために使用されます。アプリケーション内で開発者によって一意に定義されるべきです。 +- **`first_id`** (`string`): 現在のページの最初のチャット記録の ID、デフォルトは null です。 +- **`limit`** (`int`): 1 回のリクエストで返すチャット履歴メッセージの数、デフォルトは 20 です。 + +### 応答 + +- **`data`** (`array[object]`): メッセージリスト + - **`id`** (`string`): メッセージ ID + - **`conversation_id`** (`string`): 会話 ID + - **`inputs`** (`object`): ユーザー入力パラメータ。 + - **`query`** (`string`): ユーザー入力/質問内容。 + - **`message_files`** (`array[object]`): メッセージファイル + - **`id`** (`string`): ID + - **`type`** (`string`): ファイルタイプ、画像の場合は image + - **`url`** (`string`): プレビュー画像 URL + - **`belongs_to`** (`string`): 所属、user または assistant + - **`answer`** (`string`): 応答メッセージ内容 + - **`created_at`** (`timestamp`): 作成タイムスタンプ、例:1705395332 + - **`feedback`** (`object`): フィードバック情報 + - **`rating`** (`string`): アップボートは`like` / ダウンボートは`dislike` + - **`retriever_resources`** (`array[RetrieverResource]`): 引用と帰属リスト +- **`has_more`** (`bool`): 次のページがあるかどうか +- **`limit`** (`int`): 返された項目数、入力がシステム制限を超える場合、システム制限数を返します + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/messages?user=abc-123&conversation_id=' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "a076a87f-31e5-48dc-b452-0061adbbc922", + "conversation_id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "inputs": { + "name": "dify" + }, + "query": "iphone 13 pro", + "answer": "iPhone 13 Proは2021年9月24日に発売され、6.1インチのディスプレイと1170 x 2532の解像度を備えています。Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)プロセッサ、6 GBのRAMを搭載し、128 GB、256 GB、512 GB、1 TBのストレージオプションを提供します。カメラは12 MP、バッテリー容量は3095 mAhで、iOS 15を搭載しています。", + "message_files": [], + "feedback": null, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ], + "created_at": 1705569239 + } + ] +} +``` + +--- + +## GET /conversations + +### 会話を取得 + +現在のユーザーの会話リストを取得し、デフォルトで最新の 20 件を返します。 + +### クエリパラメータ + +- **`user`** (`string`): ユーザー識別子、エンドユーザーの身元を定義するために使用され、統計のために使用されます。アプリケーション内で開発者によって一意に定義されるべきです。 +- **`last_id`** (`string`, Optional): 現在のページの最後の記録の ID、デフォルトは null です。 +- **`limit`** (`int`, Optional): 1 回のリクエストで返す記録の数、デフォルトは最新の 20 件です。最大 100、最小 1。 +- **`sort_by`** (`string`, Optional): ソートフィールド、デフォルト:`-updated_at`(更新時間で降順にソート) + - 利用可能な値:`created_at`, `-created_at`, `updated_at`, `-updated_at` + - フィールドの前の記号は順序または逆順を表し、`-`は逆順を表します。 + +### 応答 + +- **`data`** (`array[object]`): 会話のリスト + - **`id`** (`string`): 会話 ID + - **`name`** (`string`): 会話名、デフォルトでは LLM によって生成されます。 + - **`inputs`** (`object`): ユーザー入力パラメータ。 + - **`introduction`** (`string`): 紹介 + - **`created_at`** (`timestamp`): 作成タイムスタンプ、例:1705395332 + - **`updated_at`** (`timestamp`): 更新タイムスタンプ、例:1705395332 +- **`has_more`** (`bool`) +- **`limit`** (`int`): 返されたエントリ数、入力がシステム制限を超える場合、システム制限数が返されます + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/conversations?user=abc-123&last_id=&limit=20' \ + --header 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54", + "name": "新しいチャット", + "inputs": { + "book": "book", + "myName": "Lucy" + }, + "status": "normal", + "created_at": 1679667915, + "updated_at": 1679667915 + }, + { + "id": "hSIhXBhNe8X1d8Et" + // ... + } + ] +} +``` + +--- + +## DELETE /conversations/:conversation_id + +### 会話を削除 + +会話を削除します。 + +### パスパラメータ + +- **`conversation_id`** (`string`): 会話 ID + +### リクエストボディ + +- **`user`** (`string`): ユーザー識別子、開発者によって定義され、アプリケーション内で一意であることを保証しなければなりません。 + +### 応答 + +- `204 No Content` + + +```bash cURL +curl -X DELETE 'https://api.dify.ai/v1/conversations/{conversation_id}' \ +--header 'Content-Type: application/json' \ +--header 'Accept: application/json' \ +--header 'Authorization: Bearer {api_key}' \ +--data '{ + "user": "abc-123" +}' +``` + + +## `text Response 204 No Content ` + +## POST /conversations/:conversation_id/name + +### 会話の名前を変更 + +セッションの名前を変更します。セッション名は、複数のセッションをサポートするクライアントでの表示に使用されます。 + +### パスパラメータ + +- **`conversation_id`** (`string`): 会話 ID + +### リクエストボディ + +- **`name`** (`string`, Optional): 会話の名前。`auto_generate`が`true`に設定されている場合、このパラメータは省略できます。 +- **`auto_generate`** (`bool`, Optional, デフォルト: `false`): タイトルを自動生成 +- **`user`** (`string`): ユーザー識別子、開発者によって定義され、アプリケーション内で一意であることを保証しなければなりません。 + +### 応答 + +- **`id`** (`string`): 会話 ID +- **`name`** (`string`): 会話名 +- **`inputs`** (`object`): ユーザー入力パラメータ +- **`status`** (`string`): 会話状態 +- **`introduction`** (`string`): 紹介 +- **`created_at`** (`timestamp`): 作成タイムスタンプ、例:1705395332 +- **`updated_at`** (`timestamp`): 更新タイムスタンプ、例:1705395332 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/conversations/{conversation_id}/name' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer {api_key}' \ +--data-raw '{ + "name": "", + "auto_generate": true, + "user": "abc-123" +}' +``` + + + +```json Response +{ + "id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "name": "チャット vs AI", + "inputs": {}, + "status": "normal", + "introduction": "", + "created_at": 1705569238, + "updated_at": 1705569238 +} +``` + +--- + +## GET /conversations/:conversation_id/variables + +### 会話変数の取得 + +特定の会話から変数を取得します。このエンドポイントは、会話中に取得された構造化データを抽出するのに役立ちます。 + +### パスパラメータ + +- **`conversation_id`** (`string`): 変数を取得する会話の ID。 + +### クエリパラメータ + +- **`user`** (`string`): ユーザー識別子。開発者によって定義されたルールに従い、アプリケーション内で一意である必要があります。 +- **`last_id`** (`string`, Optional): 現在のページの最後の記録の ID、デフォルトは null です。 +- **`limit`** (`int`, Optional): 1 回のリクエストで返す記録の数、デフォルトは最新の 20 件です。最大 100、最小 1。 + +### レスポンス + +- **`limit`** (`int`): ページごとのアイテム数 +- **`has_more`** (`bool`): さらにアイテムがあるかどうか +- **`data`** (`array[object]`): 変数のリスト + - **`id`** (`string`): 変数 ID + - **`name`** (`string`): 変数名 + - **`value_type`** (`string`): 変数タイプ(文字列、数値、真偽値など) + - **`value`** (`string`): 変数値 + - **`description`** (`string`): 変数の説明 + - **`created_at`** (`int`): 作成タイムスタンプ + - **`updated_at`** (`int`): 最終更新タイムスタンプ + +### エラー + +- 404, `conversation_not_exists`, 会話が見つかりません + + +```bash cURL +curl -X GET 'https://api.dify.ai/v1/conversations/ + {conversation_id}/variables?user=abc-123' \ --header 'Authorization: Bearer {api_key}' +``` +```bash cURL with variable name filter +curl -X GET 'https://api.dify.ai/v1/conversations/ + {conversation_id}/variables?user=abc-123&variable_name=customer_name' \ --header 'Authorization: + Bearer {api_key}' + ``` + + + +```json Response +{ + "limit": 100, + "has_more": false, + "data": [ + { + "id": "variable-uuid-1", + "name": "customer_name", + "value_type": "string", + "value": "John Doe", + "description": "会話から抽出された顧客名", + "created_at": 1650000000000, + "updated_at": 1650000000000 + }, + { + "id": "variable-uuid-2", + "name": "order_details", + "value_type": "json", + "value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}", + "description": "顧客の注文詳細", + "created_at": 1650000000000, + "updated_at": 1650000000000 + } + ] +} +``` + +--- + +## POST /audio-to-text + +### 音声からテキストへ + +このエンドポイントは multipart/form-data リクエストを必要とします。 + +### リクエストボディ + +- **`file`** (`file`): オーディオファイル。 + サポートされている形式:`['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm']` + ファイルサイズ制限:15MB +- **`user`** (`string`): ユーザー識別子、開発者のルールによって定義され、アプリケーション内で一意でなければなりません。 + +### 応答 + +- **`text`** (`string`): 出力テキスト + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/audio-to-text' \ --header + 'Authorization: Bearer {api_key}' \ --form + 'file=@localfile.mp3;type=audio/mp3' \ --form 'user="abc-123"' ``` + + + +```json Response +{ + "text": "" +} +``` + +--- + +## POST /text-to-audio + +### テキストから音声へ + +テキストを音声に変換します。 + +### リクエストボディ + +- **`message_id`** (`str`): Dify によって生成されたテキストメッセージの場合、生成されたメッセージ ID を直接渡します。バックエンドはメッセージ ID を使用して対応する内容を検索し、音声情報を直接合成します。message_id と text が同時に提供される場合、message_id が優先されます。 +- **`text`** (`str`): 音声生成コンテンツ。 +- **`user`** (`string`): ユーザー識別子、開発者によって定義され、アプリ内で一意であることを保証しなければなりません。 + + +```bash cURL +curl -o text-to-audio.mp3 -X POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", + "text": "Hello Dify", + "user": "abc-123", + "streaming": false +}' +``` + + + + ```text Headers Content-Type: audio/wav ``` ```text Body (Binary audio data) + ``` + +--- + +## GET /info + +### アプリケーションの基本情報を取得 + +このアプリケーションの基本情報を取得するために使用されます + +### Response + +- **`name`** (`string`): アプリケーションの名前 +- **`description`** (`string`): アプリケーションの説明 +- **`tags`** (`array[string]`): アプリケーションのタグ + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + +--- + +## GET /parameters + +### アプリケーションのパラメータ情報を取得 + +ページに入る際に、機能、入力パラメータ名、タイプ、デフォルト値などの情報を取得するために使用されます。 + +### 応答 + +- **`opening_statement`** (`string`): 開始の挨拶 +- **`suggested_questions`** (`array[string]`): 開始時の推奨質問のリスト +- **`suggested_questions_after_answer`** (`object`): 答えを有効にした後の質問を提案します。 + - **`enabled`** (`bool`): 有効かどうか +- **`speech_to_text`** (`object`): 音声からテキストへ + - **`enabled`** (`bool`): 有効かどうか +- **`retriever_resource`** (`object`): 引用と帰属 + - **`enabled`** (`bool`): 有効かどうか +- **`annotation_reply`** (`object`): 注釈返信 + - **`enabled`** (`bool`): 有効かどうか +- **`user_input_form`** (`array[object]`): ユーザー入力フォームの設定 + - **`text-input`** (`object`): テキスト入力コントロール + - **`label`** (`string`): 変数表示ラベル名 + - **`variable`** (`string`): 変数 ID + - **`required`** (`bool`): 必須かどうか + - **`default`** (`string`): デフォルト値 + - **`paragraph`** (`object`): 段落テキスト入力コントロール + - **`label`** (`string`): 変数表示ラベル名 + - **`variable`** (`string`): 変数 ID + - **`required`** (`bool`): 必須かどうか + - **`default`** (`string`): デフォルト値 + - **`select`** (`object`): ドロップダウンコントロール + - **`label`** (`string`): 変数表示ラベル名 + - **`variable`** (`string`): 変数 ID + - **`required`** (`bool`): 必須かどうか + - **`default`** (`string`): デフォルト値 + - **`options`** (`array[string]`): オプション値 +- **`file_upload`** (`object`): ファイルアップロード設定 + - **`image`** (`object`): 画像設定 + 現在サポートされている画像タイプ:`png`, `jpg`, `jpeg`, `webp`, `gif` + - **`enabled`** (`bool`): 有効かどうか + - **`number_limits`** (`int`): 画像数の制限、デフォルトは 3 + - **`transfer_methods`** (`array[string]`): 転送方法のリスト、remote_url, local_file、いずれかを選択する必要があります +- **`system_parameters`** (`object`): システムパラメータ + - **`file_size_limit`** (`int`): ドキュメントアップロードサイズ制限(MB) + - **`image_file_size_limit`** (`int`): 画像ファイルアップロードサイズ制限(MB) + - **`audio_file_size_limit`** (`int`): オーディオファイルアップロードサイズ制限(MB) + - **`video_file_size_limit`** (`int`): ビデオファイルアップロードサイズ制限(MB) + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "opening_statement": "こんにちは!", + "suggested_questions_after_answer": { + "enabled": true + }, + "speech_to_text": { + "enabled": true + }, + "retriever_resource": { + "enabled": true + }, + "annotation_reply": { + "enabled": true + }, + "user_input_form": [ + { + "paragraph": { + "label": "クエリ", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + +--- + +## GET /meta + +### アプリケーションのメタ情報を取得 + +このアプリケーションのツールのアイコンを取得するために使用されます + +### 応答 + +- **`tool_icons`** (`object[string]`): ツールアイコン + - **`tool_name`** (`string`) + - **`icon`** (`object`|`string`) + - (`object`) アイコンオブジェクト + - **`background`** (`string`): 背景色(16 進数形式) + - **`content`** (`string`): 絵文字 + - (`string`) アイコンの URL + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/meta' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "tool_icons": { + "dalle2": "https://cloud.dify.ai/console/api/workspaces/current/tool-provider/builtin/dalle/icon", + "api_tool": { + "background": "#252525", + "content": "\ud83d\ude01" + } + } +} +``` + diff --git a/api_access/chatflow.zh.mdx b/api_access/chatflow.zh.mdx new file mode 100755 index 00000000..411ea352 --- /dev/null +++ b/api_access/chatflow.zh.mdx @@ -0,0 +1,1154 @@ +--- +title: 工作流编排对话型应用 API +--- + +对话应用支持会话持久化,可将之前的聊天记录作为上下文进行回答,可适用于聊天/客服 AI 等。 + +### 基础 URL + +```text +https://api.dify.ai/v1 +``` + +### 鉴权 + +Service API 使用 `API-Key` 进行鉴权。 + + + **强烈建议开发者把 `API-Key` 放在后端存储,而非分享或者放在客户端存储,以免 + `API-Key` 泄露,导致财产损失。** + +所有 API 请求都应在 **`Authorization`** HTTP Header 中包含您的 `API-Key`,如下所示: + +```text +Authorization: Bearer {API_KEY} +``` + +--- + +## 发送对话消息 + +创建会话消息。 + +### Request Body + +- `query` (`string`): 用户输入/提问内容。 +- `inputs` (`object`): 允许传入 App 定义的各变量值。inputs 参数包含了多组键值对(Key/Value pairs),每组的键对应一个特定变量,每组的值则是该变量的具体值。如果变量是文件类型,请指定一个包含以下 `files` 中所述键的对象。默认 `{}` +- `response_mode` (`string`): + - `streaming` 流式模式(推荐)。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现类似打字机输出方式的流式返回。 + - `blocking` 阻塞模式,等待执行完毕后返回结果。(请求若流程较长可能会被中断)。 + _由于 Cloudflare 限制,请求会在 100 秒超时无返回后中断。_ +- `user` (`string`): 用户标识,用于定义终端用户的身份,方便检索、统计。由开发者定义规则,需保证用户标识在应用内唯一。 +- `conversation_id` (`string`): (选填)会话 ID,需要基于之前的聊天记录继续对话,必须传之前消息的 conversation_id。 +- `files` (`array[object]`): 文件列表,适用于传入文件结合文本理解并回答问题,仅当模型支持 Vision 能力时可用。 + - `type` (`string`): 支持类型: + - `document`: 具体类型包含:'TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB' + - `image`: 具体类型包含:'JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG' + - `audio`: 具体类型包含:'MP3', 'M4A', 'WAV', 'WEBM', 'AMR' + - `video`: 具体类型包含:'MP4', 'MOV', 'MPEG', 'MPGA' + - `custom`: 具体类型包含:其他文件类型 + - `transfer_method` (`string`): 传递方式: + - `remote_url`: 图片地址。 + - `local_file`: 上传文件。 + - `url` (`string`): 图片地址。(仅当传递方式为 `remote_url` 时)。 + - `upload_file_id` (`string`): 上传文件 ID。(仅当传递方式为 `local_file` 时)。 +- `auto_generate_name` (`bool`): (选填)自动生成标题,默认 `true`。 若设置为 `false`,则可通过调用会话重命名接口并设置 `auto_generate` 为 `true` 实现异步生成标题。 + +### Response + +当 `response_mode` 为 `blocking` 时,返回 ChatCompletionResponse object。 +当 `response_mode` 为 `streaming`时,返回 ChunkChatCompletionResponse object 流式序列。 + +#### ChatCompletionResponse + +返回完整的 App 结果,`Content-Type` 为 `application/json`。 + +- `event` (`string`): 事件类型,固定为 `message` +- `task_id` (`string`): 任务 ID,用于请求跟踪和下方的停止响应接口 +- `id` (`string`): 唯一 ID +- `message_id` (`string`): 消息唯一 ID +- `conversation_id` (`string`): 会话 ID +- `mode` (`string`): App 模式,固定为 chat +- `answer` (`string`): 完整回复内容 +- `metadata` (`object`): 元数据 + - `usage` (Usage): 模型用量信息 + - `retriever_resources` (array[RetrieverResource]): 引用和归属分段列表 +- `created_at` (`int`): 消息创建时间戳,如:1705395332 + +#### ChunkChatCompletionResponse + +返回 App 输出的流式块,`Content-Type` 为 `text/event-stream`。 +每个流式块均为 data: 开头,块之间以 \n\n 即两个换行符分隔,如下所示: + +```text +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +流式块中根据 event 不同,结构也不同: + +- `event: message`: LLM 返回文本块事件,即:完整的文本以分块的方式输出。 + - `task_id` (`string`): 任务 ID + - `message_id` (`string`): 消息唯一 ID + - `conversation_id` (`string`): 会话 ID + - `answer` (`string`): LLM 返回文本块内容 + - `created_at` (`int`): 创建时间戳 +- `event: message_file`: 文件事件,表示有新文件需要展示 + - `id` (`string`): 文件唯一 ID + - `type` (`string`): 文件类型,目前仅为 image + - `belongs_to` (`string`): 文件归属,user 或 assistant,该接口返回仅为 `assistant` + - `url` (`string`): 文件访问地址 + - `conversation_id` (`string`): 会话 ID +- `event: message_end`: 消息结束事件 + - `task_id` (`string`): 任务 ID + - `message_id` (`string`): 消息唯一 ID + - `conversation_id` (`string`): 会话 ID + - `metadata` (`object`): 元数据 (包含 `usage` 和 `retriever_resources`) +- `event: tts_message`: TTS 音频流事件 + - `task_id` (`string`): 任务 ID + - `message_id` (`string`): 消息唯一 ID + - `audio` (`string`): Base64 编码的音频块 + - `created_at` (`int`): 创建时间戳 +- `event: tts_message_end`: TTS 音频流结束事件 + - `task_id` (`string`): 任务 ID + - `message_id` (`string`): 消息唯一 ID + - `audio` (`string`): 空字符串 + - `created_at` (`int`): 创建时间戳 +- `event: message_replace`: 消息内容替换事件 + - `task_id` (`string`): 任务 ID + - `message_id` (`string`): 消息唯一 ID + - `conversation_id` (`string`): 会话 ID + - `answer` (`string`): 替换内容 + - `created_at` (`int`): 创建时间戳 +- `event: workflow_started`: workflow 开始执行 + - `task_id` (`string`): 任务 ID + - `workflow_run_id` (`string`): workflow 执行 ID + - `event` (`string`): 固定为 `workflow_started` + - `data` (`object`): 详细内容 (id, workflow_id, sequence_number, created_at) +- `event: node_started`: node 开始执行 + - `task_id` (`string`): 任务 ID + - `workflow_run_id` (`string`): workflow 执行 ID + - `event` (`string`): 固定为 `node_started` + - `data` (`object`): 详细内容 (id, node_id, node_type, title, index, predecessor_node_id, inputs, created_at) +- `event: node_finished`: node 执行结束 + - `task_id` (`string`): 任务 ID + - `workflow_run_id` (`string`): workflow 执行 ID + - `event` (`string`): 固定为 `node_finished` + - `data` (`object`): 详细内容 (id, node_id, index, predecessor_node_id, inputs, process_data, outputs, status, error, elapsed_time, execution_metadata, created_at) +- `event: workflow_finished`: workflow 执行结束 + - `task_id` (`string`): 任务 ID + - `workflow_run_id` (`string`): workflow 执行 ID + - `event` (`string`): 固定为 `workflow_finished` + - `data` (`object`): 详细内容 (id, workflow_id, status, outputs, error, elapsed_time, total_tokens, total_steps, created_at, finished_at) +- `event: error`: 错误事件 + - `task_id` (`string`): 任务 ID + - `message_id` (`string`): 消息唯一 ID + - `status` (`int`): HTTP 状态码 + - `code` (`string`): 错误码 + - `message` (`string`): 错误消息 +- `event: ping`: 每 10s 一次的 ping 事件。 + +### Errors + +- 404: 对话不存在 +- 400, `invalid_param`: 传入参数异常 +- 400, `app_unavailable`: App 配置不可用 +- 400, `provider_not_initialize`: 无可用模型凭据配置 +- 400, `provider_quota_exceeded`: 模型调用额度不足 +- 400, `model_currently_not_support`: 当前模型不可用 +- 400, `completion_request_error`: 文本生成失败 +- 500: 服务内部异常 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "inputs": { + "name": "dify" + }, + "query": "What are the specs of the iPhone 13 Pro Max?", + "conversation_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "response_mode": "streaming", + "user": "abc-123", + "files": [ + { + "type": "image", + "transfer_method": "remote_url", + "url": "https://cloud.dify.ai/logo/logo-site.png" + } + ] +}' +``` + + + +```json Blocking Response +{ + "event": "message", + "task_id": "c3800678-a077-43df-a102-53f23ed20b88", + "id": "9da23599-e713-473b-982c-4328d4f5c78a", + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", + "mode": "chat", + "answer": "iPhone 13 Pro Max specs are listed here:...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + }, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ] + }, + "created_at": 1705407629 +} +``` +```text Streaming Response +data: {"event": "workflow_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "sequence_number": 1, "created_at": 1679586595}} + +data: {"event": "node_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "created_at": 1679586595}} + +data: {"event": "node_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "execution_metadata": {"total_tokens": 63127864, "total_price": 2.378, "currency": "USD"}, "created_at": 1679586595}} + +data: {"event": "workflow_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "total_tokens": 63127864, "total_steps": "1", "created_at": 1679586595, "finished_at": 1679976595}} + +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595} + +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": "'m", "created_at": 1679586595} + +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " glad", "created_at": 1679586595} + +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " to", "created_at": 1679586595} + +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " meet", "created_at": 1679586595} + +data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " you", "created_at": 1679586595} + +data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}, "retriever_resources": [{"position": 1, "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", "dataset_name": "iPhone", "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", "document_name": "iPhone List", "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", "score": 0.98457545, "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\""}]}} + +data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + +data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} + +```` + + +--- + +## 上传文件 POST /files/upload + +上传文件并在发送消息时使用,可实现图文多模态理解。 +支持您的应用程序所支持的所有格式。 +*上传的文件仅供当前终端用户使用。* + +### Request Body +该接口需使用 `multipart/form-data` 进行请求。 +- `file` (`file`): 要上传的文件。 +- `user` (`string`): 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response +成功上传后,服务器会返回文件的 ID 和相关信息。 +- `id` (`uuid`): ID +- `name` (`string`): 文件名 +- `size` (`int`): 文件大小(byte) +- `extension` (`string`): 文件后缀 +- `mime_type` (`string`): 文件 mime-type +- `created_by` (`uuid`): 上传人 ID +- `created_at` (`timestamp`): 上传时间 + +### Errors +- 400, `no_file_uploaded`: 必须提供文件 +- 400, `too_many_files`: 目前只接受一个文件 +- 400, `unsupported_preview`: 该文件不支持预览 +- 400, `unsupported_estimate`: 该文件不支持估算 +- 413, `file_too_large`: 文件太大 +- 415, `unsupported_file_type`: 不支持的扩展名,当前只接受文档类文件 +- 503, `s3_connection_failed`: 无法连接到 S3 服务 +- 503, `s3_permission_denied`: 无权限上传文件到 S3 +- 503, `s3_file_too_large`: 文件超出 S3 大小限制 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/files/upload' \ +--header 'Authorization: Bearer {api_key}' \ +--form 'file=@"/path/to/file"' \ +--form 'user="abc-123"' +```` + + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "user-id-123", + "created_at": 1577836800 +} +``` + + +--- + +## 停止响应 POST /chat-messages/:task_id/stop + +仅支持流式模式。 + +### Path Parameters + +- `task_id` (`string`): 任务 ID,可在流式返回 Chunk 中获取 + +### Request Body + +- `user` (`string`): Required. 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response + +- `result` (`string`): 固定返回 success + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/chat-messages/{task_id}/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## 消息反馈(点赞) POST /messages/:message_id/feedbacks + +消息终端用户反馈、点赞,方便应用开发者优化输出预期。 + +### Path Parameters + +- `message_id` (`string`): 消息 ID + +### Request Body + +- `rating` (`string`): 点赞 like, 点踩 dislike, 撤销点赞 null +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 +- `content` (`string`): 消息反馈的具体信息。 + +### Response + +- `result` (`string`): 固定返回 success + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/messages/{message_id}/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## 获取下一轮建议问题列表 GET /messages/{message_id}/suggested + +获取下一轮建议问题列表。 + +### Path Parameters + +- `message_id` (`string`): Message ID + +### Query Parameters + +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + + + ```bash cURL curl --location --request GET 'https://api.dify.ai/v1/messages/ + {message_id}/suggested?user=abc-123' \ --header 'Authorization: Bearer{' '} + {api_key}' \ --header 'Content-Type: application/json' ``` + + + +```json Response +{ + "result": "success", + "data": [ + "a", + "b", + "c" + ] +} +``` + + +--- + +## 获取会话历史消息 GET /messages + +滚动加载形式返回历史聊天记录,第一页返回最新 `limit` 条,即:倒序返回。 + +### Query Parameters + +- `conversation_id` (`string`): 会话 ID +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 +- `first_id` (`string`): 当前页第一条聊天记录的 ID,默认 null +- `limit` (`int`): 一次请求返回多少条聊天记录,默认 20 条。 + +### Response + +- `data` (`array[object]`): 消息列表 + - `id` (`string`): 消息 ID + - `conversation_id` (`string`): 会话 ID + - `inputs` (`object`): 用户输入参数。 + - `query` (`string`): 用户输入 / 提问内容。 + - `message_files` (`array[object]`): 消息文件 + - `id` (`string`): ID + - `type` (`string`): 文件类型,image 图片 + - `url` (`string`): 预览图片地址 + - `belongs_to` (`string`): 文件归属方,user 或 assistant + - `answer` (`string`): 回答消息内容 + - `created_at` (`timestamp`): 创建时间 + - `feedback` (`object`): 反馈信息 + - `rating` (`string`): 点赞 like / 点踩 dislike + - `retriever_resources` (array[RetrieverResource]): 引用和归属分段列表 +- `has_more` (`bool`): 是否存在下一页 +- `limit` (`int`): 返回条数,若传入超过系统限制,返回系统限制数量 + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/messages?user=abc-123&conversation_id= + {conversation_id}' \ --header 'Authorization: Bearer {api_key}' ``` + + + +```json Default Response +{ +"limit": 20, +"has_more": false, +"data": [ + { + "id": "a076a87f-31e5-48dc-b452-0061adbbc922", + "conversation_id": "cd78daf6-f9e4-4463-9ff2-54257230a0ce", + "inputs": { + "name": "dify" + }, + "query": "iphone 13 pro", + "answer": "The iPhone 13 Pro, released on September 24, 2021, features a 6.1-inch display with a resolution of 1170 x 2532. It is equipped with a Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard) processor, 6 GB of RAM, and offers storage options of 128 GB, 256 GB, 512 GB, and 1 TB. The camera is 12 MP, the battery capacity is 3095 mAh, and it runs on iOS 15.", + "message_files": [], + "feedback": null, + "retriever_resources": [ + { + "position": 1, + "dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb", + "dataset_name": "iPhone", + "document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00", + "document_name": "iPhone List", + "segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a", + "score": 0.98457545, + "content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\"\n\"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"" + } + ], + "created_at": 1705569239 + } + ] +} +``` +```json Response (智能助手) +{ +"limit": 20, +"has_more": false, +"data": [ + { + "id": "d35e006c-7c4d-458f-9142-be4930abdf94", + "conversation_id": "957c068b-f258-4f89-ba10-6e8a0361c457", + "inputs": {}, + "query": "draw a cat", + "answer": "I have generated an image of a cat for you. Please check your messages to view the image.", + "message_files": [ + { + "id": "976990d2-5294-47e6-8f14-7356ba9d2d76", + "type": "image", + "url": "http://127.0.0.1:5001/files/tools/976990d2-5294-47e6-8f14-7356ba9d2d76.png?timestamp=1705988524&nonce=55df3f9f7311a9acd91bf074cd524092&sign=z43nMSO1L2HBvoqADLkRxr7Biz0fkjeDstnJiCK1zh8=", + "belongs_to": "assistant" + } + ], + "feedback": null, + "retriever_resources": [], + "created_at": 1705988187 + } + ] +} +``` + + +--- + +## 获取会话列表 GET /conversations + +获取当前用户的会话列表,默认返回最近的 20 条。 + +### Query Parameters + +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 +- `last_id` (`string`): (选填)当前页最后面一条记录的 ID,默认 null +- `limit` (`int`): (选填)一次请求返回多少条记录,默认 20 条,最大 100 条,最小 1 条。 +- `sort_by` (`string`): (选填)排序字段,默认 -updated_at(按更新时间倒序排列) + - 可选值:created_at, -created_at, updated_at, -updated_at + - 字段前面的符号代表顺序或倒序,-代表倒序 + +### Response + +- `data` (`array[object]`): 会话列表 + - `id` (`string`): 会话 ID + - `name` (`string`): 会话名称,默认由大语言模型生成。 + - `inputs` (`object`): 用户输入参数。 + - `status` (`string`): 会话状态 + - `introduction` (`string`): 开场白 + - `created_at` (`timestamp`): 创建时间 + - `updated_at` (`timestamp`): 更新时间 +- `has_more` (`bool`): 是否有更多记录 +- `limit` (`int`): 返回条数 + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/conversations?user=abc-123&last_id=&limit=20' \ + --header 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "limit": 20, + "has_more": false, + "data": [ + { + "id": "10799fb8-64f7-4296-bbf7-b42bfbe0ae54", + "name": "New chat", + "inputs": { + "book": "book", + "myName": "Lucy" + }, + "status": "normal", + "introduction": "Hello there!", + "created_at": 1679667915, + "updated_at": 1679667915 + }, + { + "id": "hSIhXBhNe8X1d8Et" + // ... + } + ] +} +``` + + +--- + +## 删除会话 DELETE /conversations/:conversation_id + +删除会话。 + +### Path Parameters + +- `conversation_id` (`string`): 会话 ID + +### Request Body + +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +- `result` (`string`): 固定返回 success (Note: HTTP 204 No Content is typical for successful DELETE) + + +```bash cURL +curl -X DELETE 'https://api.dify.ai/v1/conversations/{conversation_id}' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + +```text Response 204 No Content ``` + +--- + +## 会话重命名 POST /conversations/:conversation_id/name + +对会话进行重命名,会话名称用于显示在支持多会话的客户端上。 + +### Path Parameters + +- `conversation_id` (`string`): 会话 ID + +### Request Body + +- `name` (`string`): (选填)名称,若 `auto_generate` 为 `true` 时,该参数可不传。 +- `auto_generate` (`bool`): (选填)自动生成标题,默认 false。 +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +- `id` (`string`): 会话 ID +- `name` (`string`): 会话名称 +- `inputs` (`object`): 用户输入参数 +- `status` (`string`): 会话状态 +- `introduction` (`string`): 开场白 +- `created_at` (`timestamp`): 创建时间 +- `updated_at` (`timestamp`): 更新时间 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/conversations/{conversation_id}/name' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "name": "", + "auto_generate": true, + "user": "abc-123" +}' +``` + + + +```json Response +{ + "id": "34d511d5-56de-4f16-a997-57b379508443", + "name": "hello", + "inputs": {}, + "status": "normal", + "introduction": "", + "created_at": 1732731141, + "updated_at": 1732734510 +} +``` + + +--- + +## 获取对话变量 GET /conversations/:conversation_id/variables + +从特定对话中检索变量。此端点对于提取对话过程中捕获的结构化数据非常有用。 + +### 路径参数 + +- `conversation_id` (`string`): 要从中检索变量的对话 ID。 + +### 查询参数 + +- `user` (`string`): 用户标识符,由开发人员定义的规则,在应用程序内必须唯一。 +- `last_id` (`string`): (选填)当前页最后面一条记录的 ID,默认 null +- `limit` (`int`): (选填)一次请求返回多少条记录,默认 20 条,最大 100 条,最小 1 条。 + +### 响应 + +- `limit` (`int`): 每页项目数 +- `has_more` (`bool`): 是否有更多项目 +- `data` (`array[object]`): 变量列表 + - `id` (`string`): 变量 ID + - `name` (`string`): 变量名称 + - `value_type` (`string`): 变量类型(字符串、数字、布尔等) + - `value` (`string`): 变量值 + - `description` (`string`): 变量描述 + - `created_at` (`int`): 创建时间戳 + - `updated_at` (`int`): 最后更新时间戳 + +### 错误 + +- 404, `conversation_not_exists`: 对话不存在 + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/conversations/ + {conversation_id}/variables?user=abc-123' \ --header 'Authorization: Bearer{' '} + {api_key}' ``` ```bash cURL (with variable name filter) curl -X GET + 'https://api.dify.ai/v1/conversations/{conversation_id} + /variables?user=abc-123&variable_name=customer_name' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "limit": 100, + "has_more": false, + "data": [ + { + "id": "variable-uuid-1", + "name": "customer_name", + "value_type": "string", + "value": "John Doe", + "description": "客户名称(从对话中提取)", + "created_at": 1650000000000, + "updated_at": 1650000000000 + }, + { + "id": "variable-uuid-2", + "name": "order_details", + "value_type": "json", + "value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}", + "description": "客户的订单详情", + "created_at": 1650000000000, + "updated_at": 1650000000000 + } + ] +} +``` + + +--- + +## 语音转文字 POST /audio-to-text + +### Request Body + +该接口需使用 `multipart/form-data` 进行请求。 + +- `file` (`file`): 语音文件。支持格式:`['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm']` 文件大小限制:15MB +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +- `text` (`string`): 输出文字 + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/audio-to-text' \ --header + 'Authorization: Bearer {api_key}' \ --form + 'file=@localfile.mp3;type=audio/mp3' \ --form 'user="abc-123"' ``` + + + +```json Response +{ + "text": "hello" +} +``` + + +--- + +## 文字转语音 POST /text-to-audio + +文字转语音。 + +### Request Body + +- `message_id` (`str`): Dify 生成的文本消息,那么直接传递生成的 message-id 即可,后台会通过 message_id 查找相应的内容直接合成语音信息。如果同时传 message_id 和 text,优先使用 message_id。 +- `text` (`str`): 语音生成内容。如果没有传 message-id 的话,则会使用这个字段的内容 +- `user` (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +API 直接返回音频数据。客户端应将响应内容保存为音频文件(例如 .mp3 或 .wav,具体取决于 `Content-Type` header)。 + +**Response Headers:** + +```json +{ + "Content-Type": "audio/wav" +} +``` + + +```bash cURL +curl -o text-to-audio.mp3 -X POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", + "text": "你好Dify", + "user": "abc-123" +}' +``` + + +--- + +## 获取应用基本信息 GET /info + +用于获取应用的基本信息 + +### Response + +- `name` (`string`): 应用名称 +- `description` (`string`): 应用描述 +- `tags` (`array[string]`): 应用标签 + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## 获取应用参数 GET /parameters + +用于进入页面一开始,获取功能开关、输入参数名称、类型及默认值等使用。 + +### Response + +- `opening_statement` (`string`): 开场白 +- `suggested_questions` (`array[string]`): 开场推荐问题列表 +- `suggested_questions_after_answer` (`object`): 启用回答后给出推荐问题。 + - `enabled` (`bool`): 是否开启 +- `speech_to_text` (`object`): 语音转文本 + - `enabled` (`bool`): 是否开启 +- `retriever_resource` (`object`): 引用和归属 + - `enabled` (`bool`): 是否开启 +- `annotation_reply` (`object`): 标记回复 + - `enabled` (`bool`): 是否开启 +- `user_input_form` (`array[object]`): 用户输入表单配置 + - `text-input` (`object`): 文本输入控件 + - `label` (`string`): 控件展示标签名 + - `variable` (`string`): 控件 ID + - `required` (`bool`): 是否必填 + - `default` (`string`): 默认值 + - `paragraph` (`object`): 段落文本输入控件 + - `label` (`string`): 控件展示标签名 + - `variable` (`string`): 控件 ID + - `required` (`bool`): 是否必填 + - `default` (`string`): 默认值 + - `select` (`object`): 下拉控件 + - `label` (`string`): 控件展示标签名 + - `variable` (`string`): 控件 ID + - `required` (`bool`): 是否必填 + - `default` (`string`): 默认值 + - `options` (`array[string]`): 选项值 +- `file_upload` (`object`): 文件上传配置 + - `image` (`object`): 图片设置 (当前仅支持图片类型:`png`, `jpg`, `jpeg`, `webp`, `gif`) + - `enabled` (`bool`): 是否开启 + - `number_limits` (`int`): 图片数量限制,默认 3 + - `transfer_methods` (`array[string]`): 传递方式列表,remote_url , local_file,必选一个 +- `system_parameters` (`object`): 系统参数 + - `file_size_limit` (`int`): Document upload size limit (MB) + - `image_file_size_limit` (`int`): Image file upload size limit (MB) + - `audio_file_size_limit` (`int`): Audio file upload size limit (MB) + - `video_file_size_limit` (`int`): Video file upload size limit (MB) + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "opening_statement": "nice to meet you", + "suggested_questions": [], + "suggested_questions_after_answer": { + "enabled": false + }, + "speech_to_text": { + "enabled": false + }, + "retriever_resource": { + "enabled": false + }, + "annotation_reply": { + "enabled": false + }, + "user_input_form": [ + { + "text-input": { + "label": "a", + "variable": "a", + "required": true, + "max_length": 48, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": true, + "number_limits": 3, + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + + +--- + +## 获取应用 Meta 信息 GET /meta + +用于获取工具 icon + +### Response + +- `tool_icons` (`object[string]`): 工具图标 + - `工具名称` (`string`): + - `icon` (`object`|`string`): + - (`object`) 图标: + - `background` (`string`): hex 格式的背景色 + - `content` (`string`): emoji + - (`string`) 图标 URL + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/meta' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "tool_icons": { + "dalle2": "https://cloud.dify.ai/console/api/workspaces/current/tool-provider/builtin/dalle/icon", + "api_tool": { + "background": "#252525", + "content": "\ud83d\ude01" + } + } +} +``` + + +--- + +## 获取标注列表 GET /apps/annotations + +### Query Parameters + +- `page` (`string`): 页码 +- `limit` (`string`): 每页数量 + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotations?page=1&limit=20' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "data": [ + { + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 + } + ], + "has_more": false, + "limit": 20, + "total": 1, + "page": 1 +} +``` + + +--- + +## 创建标注 POST /apps/annotations + +### Request Body + +- `question` (`string`): 问题 +- `answer` (`string`): 答案内容 + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/apps/annotations' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your name?", + "answer": "I am Dify." +}' +``` + + + +```json Response +{ + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + + +--- + +## 更新标注 PUT /apps/annotations/{annotation_id} + +### Path Parameters + +- `annotation_id` (`string`): 标注 ID + +### Request Body + +- `question` (`string`): 问题 +- `answer` (`string`): 答案内容 + + +```bash cURL +curl --location --request PUT 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your name?", + "answer": "I am Dify." +}' +``` + + + +```json Response +{ + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + + +--- + +## 删除标注 DELETE /apps/annotations/{annotation_id} + +### Path Parameters + +- `annotation_id` (`string`): 标注 ID + + + ```bash cURL curl --location --request DELETE + 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ --header + 'Authorization: Bearer {api_key}' ``` + + +```text Response 204 No Content ``` + +--- + +## 标注回复初始设置 POST /apps/annotation-reply/{action} + +### Path Parameters + +- `action` (`string`): 动作,只能是 'enable' 或 'disable' + +### Request Body + +- `embedding_provider_name` (`string`): 指定的嵌入模型提供商, 必须先在系统内设定好接入的模型,对应的是 provider 字段 +- `embedding_model_name` (`string`): 指定的嵌入模型,对应的是 model 字段 +- `score_threshold` (`number`): 相似度阈值,当相似度大于该阈值时,系统会自动回复,否则不回复 + +嵌入模型的提供商和模型名称可以通过以下接口获取:`v1/workspaces/current/models/model-types/text-embedding`, 具体见:通过 API 维护知识库。 使用的 Authorization 是 Dataset 的 API Token。 + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/apps/annotation-reply/{action}' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "score_threshold": 0.9, + "embedding_provider_name": "zhipu", + "embedding_model_name": "embedding_3" +}' +``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "waiting" +} +``` + +该接口是异步执行,所以会返回一个job_id,通过查询job状态接口可以获取到最终的执行结果。 + +--- + +## 查询标注回复初始设置任务状态 GET /apps/annotation-reply/{action}/status/{job_id} + +### Path Parameters + +- `action` (`string`): 动作,只能是 'enable' 或 'disable',并且必须和标注回复初始设置接口的动作一致 +- `job_id` (`string`): 任务 ID,从标注回复初始设置接口返回的 job_id + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotation-reply/{action}/status/{job_id}' \ + --header 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "waiting", + "error_msg": "" +} +``` + diff --git a/api_access/completion.en.mdx b/api_access/completion.en.mdx new file mode 100755 index 00000000..b386c743 --- /dev/null +++ b/api_access/completion.en.mdx @@ -0,0 +1,495 @@ +--- +title: Completion App API +--- + +The text generation application offers non-session support and is ideal for translation, article writing, summarization AI, and more. + +### Base URL + +```text +https://api.dify.ai/v1 +``` + +### Authentication + +The Service API uses `API-Key` authentication. + + + **Strongly recommend storing your API Key on the server-side, not shared or + stored on the client-side, to avoid possible API-Key leakage that can lead + to serious consequences.** + + +For all API requests, include your API Key in the `Authorization` HTTP Header, as shown below: + +```http +Authorization: Bearer {API_KEY} +``` + +--- + +## POST /completion-messages + +Create Completion Message + +Send a request to the text generation application. + +### Request Body + +- `inputs` (object): Allows the entry of various variable values defined by the App. + The `inputs` parameter contains multiple key/value pairs, with each key corresponding to a specific variable and each value being the specific value for that variable. + The text generation application requires at least one key/value pair to be inputted. + - `query` (string, Required): The input text, the content to be processed. +- `response_mode` (string): The mode of response return, supporting: + - `streaming`: Streaming mode (recommended), implements a typewriter-like output through SSE ([Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)). + - `blocking`: Blocking mode, returns result after execution is complete. (Requests may be interrupted if the process is long) + + Due to Cloudflare restrictions, the request will be interrupted + without a return after 100 seconds. + +- `user` (string): User identifier, used to define the identity of the end-user for retrieval and statistics. Should be uniquely defined by the developer within the application. +- `files` (array[object]): File list, suitable for inputting files (images) combined with text understanding and answering questions, available only when the model supports Vision capability. + - `type` (string): Supported type: `image` (currently only supports image type). + - `transfer_method` (string): Transfer method, `remote_url` for image URL / `local_file` for file upload. + - `url` (string): Image URL (when the transfer method is `remote_url`). + - `upload_file_id` (string): Uploaded file ID, which must be obtained by uploading through the File Upload API in advance (when the transfer method is `local_file`). + +### Response + +When `response_mode` is `blocking`, return a CompletionResponse object. +When `response_mode` is `streaming`, return a ChunkCompletionResponse stream. + +#### ChatCompletionResponse + +Returns the complete App result, `Content-Type` is `application/json`. + +- `message_id` (string): Unique message ID. +- `mode` (string): App mode, fixed as `completion`. +- `answer` (string): Complete response content. +- `metadata` (object): Metadata. + - `usage` (Usage): Model usage information. + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List. +- `created_at` (int): Message creation timestamp, e.g., 1705395332. + +#### ChunkChatCompletionResponse + +Returns the stream chunks outputted by the App, `Content-Type` is `text/event-stream`. +Each streaming chunk starts with `data:`, separated by two newline characters `\n\n`, as shown below: + +```streaming Response +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +The structure of the streaming chunks varies depending on the `event`: + +- `event: message`: LLM returns text chunk event, i.e., the complete text is output in a chunked fashion. + - `task_id` (string): Task ID, used for request tracking and the below Stop Generate API. + - `message_id` (string): Unique message ID. + - `answer` (string): LLM returned text chunk content. + - `created_at` (int): Creation timestamp, e.g., 1705395332. +- `event: message_end`: Message end event, receiving this event means streaming has ended. + - `task_id` (string): Task ID, used for request tracking and the below Stop Generate API. + - `message_id` (string): Unique message ID. + - `metadata` (object): Metadata. + - `usage` (Usage): Model usage information. + - `retriever_resources` (array[RetrieverResource]): Citation and Attribution List. +- `event: tts_message`: TTS audio stream event, that is, speech synthesis output. The content is an audio block in Mp3 format, encoded as a base64 string. When playing, simply decode the base64 and feed it into the player. (This message is available only when auto-play is enabled). + - `task_id` (string): Task ID, used for request tracking and the stop response interface below. + - `message_id` (string): Unique message ID. + - `audio` (string): The audio after speech synthesis, encoded in base64 text content, when playing, simply decode the base64 and feed it into the player. + - `created_at` (int): Creation timestamp, e.g.: 1705395332. +- `event: tts_message_end`: TTS audio stream end event, receiving this event indicates the end of the audio stream. + - `task_id` (string): Task ID, used for request tracking and the stop response interface below. + - `message_id` (string): Unique message ID. + - `audio` (string): The end event has no audio, so this is an empty string. + - `created_at` (int): Creation timestamp, e.g.: 1705395332. +- `event: message_replace`: Message content replacement event. + When output content moderation is enabled, if the content is flagged, then the message content will be replaced with a preset reply through this event. + - `task_id` (string): Task ID, used for request tracking and the below Stop Generate API. + - `message_id` (string): Unique message ID. + - `answer` (string): Replacement content (directly replaces all LLM reply text). + - `created_at` (int): Creation timestamp, e.g., 1705395332. +- `event: error`: Exceptions that occur during the streaming process will be output in the form of stream events, and reception of an error event will end the stream. + - `task_id` (string): Task ID, used for request tracking and the below Stop Generate API. + - `message_id` (string): Unique message ID. + - `status` (int): HTTP status code. + - `code` (string): Error code. + - `message` (string): Error message. +- `event: ping`: Ping event every 10 seconds to keep the connection alive. + +### Errors + +- 404, Conversation does not exists +- 400, `invalid_param`, abnormal parameter input +- 400, `app_unavailable`, App configuration unavailable +- 400, `provider_not_initialize`, no available model credential configuration +- 400, `provider_quota_exceeded`, model invocation quota insufficient +- 400, `model_currently_not_support`, current model unavailable +- 400, `completion_request_error`, text generation failed +- 500, internal server error + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/completion-messages' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {"query": "Hello, world!"}, + "response_mode": "streaming", + "user": "abc-123" +}' +``` + + + +```json Blocking Mode Response +{ + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "mode": "completion", + "answer": "Hello World!...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + } + }, + "created_at": 1705407629 +} +``` +```streaming Streaming Mode Response + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": "'m", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " glad", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " to", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " meet", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " you", "created_at": 1679586595} + data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +--- + +## POST /files/upload + +File Upload + +Upload a file (currently only images are supported) for use when sending messages, enabling multimodal understanding of images and text. +Supports png, jpg, jpeg, webp, gif formats. +Uploaded files are for use by the current end-user only. + +### Request Body + +This interface requires a `multipart/form-data` request. + +- `file` (File, Required): The file to be uploaded. +- `user` (string, Required): User identifier, defined by the developer's rules, must be unique within the application. + +### Response + +After a successful upload, the server will return the file's ID and related information. + +- `id` (uuid): ID. +- `name` (string): File name. +- `size` (int): File size (bytes). +- `extension` (string): File extension. +- `mime_type` (string): File mime-type. +- `created_by` (uuid): End-user ID. +- `created_at` (timestamp): Creation timestamp, e.g., 1705395332. + +### Errors + +- 400, `no_file_uploaded`, a file must be provided. +- 400, `too_many_files`, currently only one file is accepted. +- 400, `unsupported_preview`, the file does not support preview. +- 400, `unsupported_estimate`, the file does not support estimation. +- 413, `file_too_large`, the file is too large. +- 415, `unsupported_file_type`, unsupported extension, currently only document files are accepted. +- 503, `s3_connection_failed`, unable to connect to S3 service. +- 503, `s3_permission_denied`, no permission to upload files to S3. +- 503, `s3_file_too_large`, file exceeds S3 size limit. +- 500, internal server error. + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header + 'Authorization: Bearer {api_key}' \ --form + 'file=@"/path/to/file";type=image/png' \ --form 'user="abc-123"' ``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 +} +``` + + +--- + +## POST /completion-messages/:task_id/stop + +Stop Generate + +Only supported in streaming mode. + +### Path Parameters + +- `task_id` (string): Task ID, can be obtained from the streaming chunk return. + +### Request Body + +- `user` (string, Required): User identifier, used to define the identity of the end-user, must be consistent with the user passed in the send message interface. + +### Response + +- `result` (string): Always returns "success". + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/completion-messages/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## POST /messages/:message_id/feedbacks + +Message Feedback + +End-users can provide feedback messages, facilitating application developers to optimize expected outputs. + +### Path Parameters + +- `message_id` (string): Message ID. + +### Request Body + +- `rating` (string): Upvote as `like`, downvote as `dislike`, revoke upvote as `null`. +- `user` (string): User identifier, defined by the developer's rules, must be unique within the application. +- `content` (string): The specific content of message feedback. + +### Response + +- `result` (string): Always returns "success". + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/messages/:message_id/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## POST /text-to-audio + +Text to Audio + +Text to speech. + +### Request Body + +- `message_id` (string): For text messages generated by Dify, simply pass the generated message-id directly. The backend will use the message-id to look up the corresponding content and synthesize the voice information directly. If both `message_id` and `text` are provided simultaneously, the `message_id` is given priority. +- `text` (string): Speech generated content. +- `user` (string): The user identifier, defined by the developer, must ensure uniqueness within the app. + +### Response + +The response is an audio file stream. +**Headers:** + +- `Content-Type`: `audio/wav` (or other audio format depending on system configuration) + + +```bash cURL +curl -o text-to-audio.mp3 -X POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", + "text": "Hello Dify", + "user": "abc-123" +}' +``` + + + + ```text Response Headers Content-Type: audio/wav ``` ```text Response Body + (Binary audio data) ``` + + +--- + +## GET /info + +Get Application Basic Information + +Used to get basic information about this application. + +### Response + +- `name` (string): application name. +- `description` (string): application description. +- `tags` (array[string]): application tags. + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## GET /parameters + +Get Application Parameters Information + +Used at the start of entering the page to obtain information such as features, input parameter names, types, and default values. + +### Response + +- `opening_statement` (string): Opening statement. +- `suggested_questions` (array[string]): List of suggested questions for the opening. +- `suggested_questions_after_answer` (object): Suggest questions after enabling the answer. + - `enabled` (bool): Whether it is enabled. +- `speech_to_text` (object): Speech to text. + - `enabled` (bool): Whether it is enabled. +- `retriever_resource` (object): Citation and Attribution. + - `enabled` (bool): Whether it is enabled. +- `annotation_reply` (object): Annotation reply. + - `enabled` (bool): Whether it is enabled. +- `user_input_form` (array[object]): User input form configuration. + - `text-input` (object): Text input control. + - `label` (string): Variable display label name. + - `variable` (string): Variable ID. + - `required` (bool): Whether it is required. + - `default` (string): Default value. + - `paragraph` (object): Paragraph text input control. + - `label` (string): Variable display label name. + - `variable` (string): Variable ID. + - `required` (bool): Whether it is required. + - `default` (string): Default value. + - `select` (object): Dropdown control. + - `label` (string): Variable display label name. + - `variable` (string): Variable ID. + - `required` (bool): Whether it is required. + - `default` (string): Default value. + - `options` (array[string]): Option values. +- `file_upload` (object): File upload configuration. + - `image` (object): Image settings. Currently only supports image types: `png`, `jpg`, `jpeg`, `webp`, `gif`. + - `enabled` (bool): Whether it is enabled. + - `number_limits` (int): Image number limit, default is 3. + - `transfer_methods` (array[string]): List of transfer methods, `remote_url`, `local_file`, must choose one. +- `system_parameters` (object): System parameters. + - `file_size_limit` (int): Document upload size limit (MB). + - `image_file_size_limit` (int): Image file upload size limit (MB). + - `audio_file_size_limit` (int): Audio file upload size limit (MB). + - `video_file_size_limit` (int): Video file upload size limit (MB). + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "opening_statement": "Hello!", + "suggested_questions_after_answer": { + "enabled": true + }, + "speech_to_text": { + "enabled": true + }, + "retriever_resource": { + "enabled": true + }, + "annotation_reply": { + "enabled": true + }, + "user_input_form": [ + { + "paragraph": { + "label": "Query", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + diff --git a/api_access/completion.ja.mdx b/api_access/completion.ja.mdx new file mode 100755 index 00000000..130b4b28 --- /dev/null +++ b/api_access/completion.ja.mdx @@ -0,0 +1,496 @@ +--- +title: Completion アプリ API +--- + +テキスト生成アプリケーションはセッションレスをサポートし、翻訳、記事作成、要約 AI 等に最適です。 + +### ベース URL + +```text +https://api.dify.ai/v1 +``` + +### 認証 + +サービス API は`API-Key`認証を使用します。 +**_API キーの漏洩による重大な結果を避けるため、API キーはサーバーサイドに保存し、クライアントサイドでは共有や保存しないことを強く推奨します。_** + +すべての API リクエストで、以下のように`Authorization` HTTP ヘッダーに API キーを含めてください: + +```text +Authorization: Bearer {API_KEY} +``` + +--- + +## 完了メッセージの作成 `POST /completion-messages` + +テキスト生成アプリケーションにリクエストを送信します。 + +### リクエストボディ + +- `inputs` (object) + アプリで定義された各種変数値を入力できます。 + `inputs`パラメータには複数のキー/値ペアが含まれ、各キーは特定の変数に対応し、各値はその変数の具体的な値となります。 + テキスト生成アプリケーションでは、少なくとも 1 つのキー/値ペアの入力が必要です。 + - `query` (string) 必須 + 入力テキスト、処理される内容。 +- `response_mode` (string) + レスポンス返却モード、以下をサポート: + - `streaming` ストリーミングモード(推奨)、SSE([Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events))によるタイプライター風の出力を実装。 + - `blocking` ブロッキングモード、実行完了後に結果を返却。(処理が長い場合はリクエストが中断される可能性があります) + _Cloudflare の制限により、100 秒後に返却なしで中断されます。_ +- `user` (string) + ユーザー識別子、エンドユーザーの身元を定義し、取得や統計に使用します。 + アプリケーション内で開発者が一意に定義する必要があります。 +- `files` (array[object]) + ファイルリスト、モデルが Vision 機能をサポートしている場合のみ、テキスト理解と質問応答を組み合わせたファイル(画像)の入力に適しています。 + - `type` (string) サポートされるタイプ:`image`(現在は画像タイプのみサポート) + - `transfer_method` (string) 転送方法、画像 URL の場合は`remote_url` / ファイルアップロードの場合は`local_file` + - `url` (string) 画像 URL(転送方法が`remote_url`の場合) + - `upload_file_id` (string) アップロードされたファイル ID、事前にファイルアップロード API を通じてアップロードする必要があります(転送方法が`local_file`の場合) + +### レスポンス + +`response_mode`が`blocking`の場合、CompletionResponse オブジェクトを返却します。 +`response_mode`が`streaming`の場合、ChunkCompletionResponse ストリームを返却します。 + +#### ChatCompletionResponse + +アプリの完全な結果を返却、`Content-Type`は`application/json`です。 + +- `message_id` (string) 一意のメッセージ ID +- `mode` (string) アプリモード、固定で`chat` +- `answer` (string) 完全な応答内容 +- `metadata` (object) メタデータ + - `usage` (Usage) モデル使用情報 + - `retriever_resources` (array[RetrieverResource]) 引用と帰属のリスト +- `created_at` (int) メッセージ作成タイムスタンプ、例:1705395332 + +#### ChunkChatCompletionResponse + +アプリが出力するストリームチャンクを返却、`Content-Type`は`text/event-stream`です。 +各ストリーミングチャンクは`data:`で始まり、2 つの改行文字`\n\n`で区切られます: + +```streaming +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +ストリーミングチャンクの構造は`event`によって異なります: + +- `event: message` LLM がテキストチャンクを返すイベント、つまり完全なテキストがチャンク形式で出力されます。 + - `task_id` (string) タスク ID、リクエストの追跡と以下の生成停止 API に使用 + - `message_id` (string) 一意のメッセージ ID + - `answer` (string) LLM が返したテキストチャンクの内容 + - `created_at` (int) 作成タイムスタンプ、例:1705395332 +- `event: message_end` メッセージ終了イベント、このイベントを受信するとストリーミングが終了したことを意味します。 + - `task_id` (string) タスク ID、リクエストの追跡と以下の生成停止 API に使用 + - `message_id` (string) 一意のメッセージ ID + - `metadata` (object) メタデータ + - `usage` (Usage) モデル使用情報 + - `retriever_resources` (array[RetrieverResource]) 引用と帰属のリスト +- `event: tts_message` TTS 音声ストリームイベント、つまり音声合成出力。内容は Mp3 形式の音声ブロックで、base64 文字列としてエンコードされています。再生時は単に base64 をデコードしてプレーヤーに供給するだけです。(このメッセージは自動再生が有効な場合のみ利用可能) + - `task_id` (string) タスク ID、リクエストの追跡と以下の応答停止インターフェースに使用 + - `message_id` (string) 一意のメッセージ ID + - `audio` (string) 音声合成後の音声、base64 テキストコンテンツとしてエンコード、再生時は単に base64 をデコードしてプレーヤーに供給 + - `created_at` (int) 作成タイムスタンプ、例:1705395332 +- `event: tts_message_end` TTS 音声ストリーム終了イベント、このイベントを受信すると音声ストリームが終了したことを示します。 + - `task_id` (string) タスク ID、リクエストの追跡と以下の応答停止インターフェースに使用 + - `message_id` (string) 一意のメッセージ ID + - `audio` (string) 終了イベントには音声がないため、空文字列 + - `created_at` (int) 作成タイムスタンプ、例:1705395332 +- `event: message_replace` メッセージ内容置換イベント。 + 出力内容のモデレーションが有効な場合、コンテンツがフラグ付けされると、このイベントを通じてメッセージ内容が事前設定された返信に置き換えられます。 + - `task_id` (string) タスク ID、リクエストの追跡と以下の生成停止 API に使用 + - `message_id` (string) 一意のメッセージ ID + - `answer` (string) 置換内容(LLM の返信テキストすべてを直接置換) + - `created_at` (int) 作成タイムスタンプ、例:1705395332 +- `event: error` + ストリーミング処理中に発生した例外は、ストリームイベントの形式で出力され、エラーイベントを受信するとストリームが終了します。 + - `task_id` (string) タスク ID、リクエストの追跡と以下の生成停止 API に使用 + - `message_id` (string) 一意のメッセージ ID + - `status` (int) HTTP ステータスコード + - `code` (string) エラーコード + - `message` (string) エラーメッセージ +- `event: ping` 接続を維持するため 10 秒ごとの Ping イベント。 + +### エラー + +- 404, 会話が存在しません +- 400, `invalid_param`, パラメータ入力異常 +- 400, `app_unavailable`, アプリ設定が利用できません +- 400, `provider_not_initialize`, 利用可能なモデル認証情報設定がありません +- 400, `provider_quota_exceeded`, モデル呼び出しクォータ不足 +- 400, `model_currently_not_support`, 現在のモデルは利用できません +- 400, `completion_request_error`, テキスト生成に失敗しました +- 500, 内部サーバーエラー + + +```bash Request +curl -X POST 'https://api.dify.ai/v1/completion-messages' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {"query": "Hello, world!"}, + "response_mode": "streaming", + "user": "abc-123" +}' +``` + + +#### ブロッキングモード + + +```json Response +{ + "event": "message", + "message_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "mode": "completion", + "answer": "Hello World!...", + "metadata": { + "usage": { + "prompt_tokens": 1033, + "prompt_unit_price": "0.001", + "prompt_price_unit": "0.001", + "prompt_price": "0.0010330", + "completion_tokens": 128, + "completion_unit_price": "0.002", + "completion_price_unit": "0.001", + "completion_price": "0.0002560", + "total_tokens": 1161, + "total_price": "0.0012890", + "currency": "USD", + "latency": 0.7682376249867957 + } + }, + "created_at": 1705407629 +} +``` + + +#### ストリーミングモード + + +```streaming Response + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": "'m", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " glad", "created_at": 1679586595} + data: {"event": "message", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " to", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " meet", "created_at": 1679586595} + data: {"event": "message", "message_id" : "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " you", "created_at": 1679586595} + data: {"event": "message_end", "id": "5e52ce04-874b-4d27-9045-b3bc80def685", "metadata": {"usage": {"prompt_tokens": 1033, "prompt_unit_price": "0.001", "prompt_price_unit": "0.001", "prompt_price": "0.0010330", "completion_tokens": 135, "completion_unit_price": "0.002", "completion_price_unit": "0.001", "completion_price": "0.0002700", "total_tokens": 1168, "total_price": "0.0013030", "currency": "USD", "latency": 1.381760165997548}}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +--- + +## ファイルアップロード `POST /files/upload` + +メッセージ送信時に使用するファイル(現在は画像のみ対応)をアップロードし、画像とテキストのマルチモーダルな理解を可能にします。 +png、jpg、jpeg、webp、gif 形式に対応しています。 +_アップロードされたファイルは、現在のエンドユーザーのみが使用できます。_ + +### リクエストボディ + +このインターフェースは`multipart/form-data`リクエストが必要です。 + +- `file` (File) 必須 + アップロードするファイル。 +- `user` (string) 必須 + 開発者のルールで定義されたユーザー識別子。アプリケーション内で一意である必要があります。 + +### レスポンス + +アップロードが成功すると、サーバーはファイルの ID と関連情報を返します。 + +- `id` (uuid) ID +- `name` (string) ファイル名 +- `size` (int) ファイルサイズ(バイト) +- `extension` (string) ファイル拡張子 +- `mime_type` (string) ファイルの MIME タイプ +- `created_by` (uuid) エンドユーザー ID +- `created_at` (timestamp) 作成タイムスタンプ、例:1705395332 + +### エラー + +- 400, `no_file_uploaded`, ファイルを提供する必要があります +- 400, `too_many_files`, 現在は 1 つのファイルのみ受け付けています +- 400, `unsupported_preview`, ファイルがプレビューに対応していません +- 400, `unsupported_estimate`, ファイルが推定に対応していません +- 413, `file_too_large`, ファイルが大きすぎます +- 415, `unsupported_file_type`, サポートされていない拡張子です。現在はドキュメントファイルのみ受け付けています +- 503, `s3_connection_failed`, S3 サービスに接続できません +- 503, `s3_permission_denied`, S3 へのファイルアップロード権限がありません +- 503, `s3_file_too_large`, ファイルが S3 のサイズ制限を超えています +- 500, 内部サーバーエラー + + + ```bash Request curl -X POST 'https://api.dify.ai/v1/files/upload' \ + --header 'Authorization: Bearer {api_key}' \ --form + 'file=@"/path/to/your/image.png";type=image/png' \ --form 'user=abc-123' ``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 +} +``` + +--- + +## 生成の停止 `POST /completion-messages/:task_id/stop` + +ストリーミングモードでのみサポートされています。 + +### パスパラメータ + +- `task_id` (string) タスク ID、ストリーミングチャンクの返信から取得可能 + +### リクエストボディ + +- `user` (string) 必須 + ユーザー識別子。エンドユーザーの身元を定義するために使用され、メッセージ送信インターフェースで渡されたユーザーと一致する必要があります。 + +### レスポンス + +- `result` (string) 常に"success"を返します + + +```bash Request +curl -X POST 'https://api.dify.ai/v1/completion-messages/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## メッセージフィードバック `POST /messages/:message_id/feedbacks` + +エンドユーザーはフィードバックメッセージを提供でき、アプリケーション開発者が期待される出力を最適化するのに役立ちます。 + +### パスパラメータ + +- `message_id` (string) + メッセージ ID + +### リクエストボディ + +- `rating` (string) + 高評価は`like`、低評価は`dislike`、高評価の取り消しは`null` +- `user` (string) + 開発者のルールで定義されたユーザー識別子。アプリケーション内で一意である必要があります。 +- `content` (string) + メッセージのフィードバックです。 + +### レスポンス + +- `result` (string) 常に"success"を返します + + +```bash Request +curl -X POST 'https://api.dify.ai/v1/messages/:message_id/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + +--- + +## テキストから音声 `POST /text-to-audio` + +テキストを音声に変換します。 + +### リクエストボディ + +- `message_id` (str) + Dify が生成したテキストメッセージの場合、生成された message-id を直接渡すだけです。バックエンドは message-id を使用して対応するコンテンツを検索し、音声情報を直接合成します。message_id と text の両方が同時に提供された場合、message_id が優先されます。 +- `text` (str) + 音声生成コンテンツ。 +- `user` (string) + 開発者が定義したユーザー識別子。アプリ内で一意性を確保する必要があります。 + +### レスポンス + +レスポンスは音声ファイルです(例: `audio/wav`)。 +レスポンスヘッダーの例: + +```json +{ + "Content-Type": "audio/wav" +} +``` + + +```bash Request +curl -o text-to-audio.mp3 -X POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", + "text": "Hello Dify", + "user": "abc-123" +}' +``` + + +--- + +## アプリケーションの基本情報を取得 `GET /info` + +このアプリケーションの基本情報を取得するために使用されます + +### レスポンス + +- `name` (string) アプリケーションの名前 +- `description` (string) アプリケーションの説明 +- `tags` (array[string]) アプリケーションのタグ + + + ```bash Request curl -X GET 'https://api.dify.ai/v1/info' \ -H + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## アプリケーションのパラメータ情報を取得 `GET /parameters` + +ページ開始時に、機能、入力パラメータ名、タイプ、デフォルト値などの情報を取得するために使用されます。 + +### レスポンス + +- `opening_statement` (string) 開始文 +- `suggested_questions` (array[string]) 開始時の提案質問リスト +- `suggested_questions_after_answer` (object) 回答後の提案質問を有効にします。 + - `enabled` (bool) 有効かどうか +- `speech_to_text` (object) 音声からテキスト + - `enabled` (bool) 有効かどうか +- `retriever_resource` (object) 引用と帰属 + - `enabled` (bool) 有効かどうか +- `annotation_reply` (object) 注釈付き返信 + - `enabled` (bool) 有効かどうか +- `user_input_form` (array[object]) ユーザー入力フォーム設定 + - `text-input` (object) テキスト入力コントロール + - `label` (string) 変数表示ラベル名 + - `variable` (string) 変数 ID + - `required` (bool) 必須かどうか + - `default` (string) デフォルト値 + - `paragraph` (object) 段落テキスト入力コントロール + - `label` (string) 変数表示ラベル名 + - `variable` (string) 変数 ID + - `required` (bool) 必須かどうか + - `default` (string) デフォルト値 + - `select` (object) ドロップダウンコントロール + - `label` (string) 変数表示ラベル名 + - `variable` (string) 変数 ID + - `required` (bool) 必須かどうか + - `default` (string) デフォルト値 + - `options` (array[string]) オプション値 +- `file_upload` (object) ファイルアップロード設定 + - `image` (object) 画像設定 + 現在は画像タイプのみ対応:`png`、`jpg`、`jpeg`、`webp`、`gif` + - `enabled` (bool) 有効かどうか + - `number_limits` (int) 画像数制限、デフォルトは 3 + - `transfer_methods` (array[string]) 転送方法リスト、remote_url、local_file、いずれかを選択 +- `system_parameters` (object) システムパラメータ + - `file_size_limit` (int) ドキュメントアップロードサイズ制限(MB) + - `image_file_size_limit` (int) 画像ファイルアップロードサイズ制限(MB) + - `audio_file_size_limit` (int) 音声ファイルアップロードサイズ制限(MB) + - `video_file_size_limit` (int) 動画ファイルアップロードサイズ制限(MB) + + + ```bash Request curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "opening_statement": "Hello!", + "suggested_questions_after_answer": { + "enabled": true + }, + "speech_to_text": { + "enabled": true + }, + "retriever_resource": { + "enabled": true + }, + "annotation_reply": { + "enabled": true + }, + "user_input_form": [ + { + "paragraph": { + "label": "Query", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + diff --git a/api_access/completion.zh.mdx b/api_access/completion.zh.mdx new file mode 100755 index 00000000..3f3991d6 --- /dev/null +++ b/api_access/completion.zh.mdx @@ -0,0 +1,658 @@ +--- +title: 文本生成型应用 API +--- + +文本生成应用无会话支持,适合用于翻译/文章写作/总结 AI 等等。 + +### 基础 URL + +```text +https://api.dify.ai/v1 +``` + +### 鉴权 + +Dify Service API 使用 `API-Key` 进行鉴权。 +_强烈建议开发者把 `API-Key` 放在后端存储,而非分享或者放在客户端存储,以免 `API-Key` 泄露,导致财产损失。_ +所有 API 请求都应在 **`Authorization`** HTTP Header 中包含您的 `API-Key`,如下所示: + +```text +Authorization: Bearer {API_KEY} +``` + +--- + +## 发送消息 + +**POST** `/completion-messages` + +发送请求给文本生成型应用。 + +### Request Body + +- **`inputs`** (`object`): (选填) 允许传入 App 定义的各变量值。inputs 参数包含了多组键值对(Key/Value pairs),每组的键对应一个特定变量,每组的值则是该变量的具体值。文本生成型应用要求至少传入一组键值对。 + - **`query`** (`string`): 必填. 用户输入的文本内容。 +- **`response_mode`** (`string`): + - `streaming`: 流式模式(推荐)。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现类似打字机输出方式的流式返回。 + - `blocking`: 阻塞模式,等待执行完毕后返回结果。(请求若流程较长可能会被中断)。 + _由于 Cloudflare 限制,请求会在 100 秒超时无返回后中断。_ +- **`user`** (`string`): 用户标识,用于定义终端用户的身份,方便检索、统计。由开发者定义规则,需保证用户标识在应用内唯一。 +- **`files`** (`array[object]`): 上传的文件。 + - **`type`** (`string`): 支持类型:图片 `image`(目前仅支持图片格式)。 + - **`transfer_method`** (`string`): 传递方式: + - `remote_url`: 图片地址。 + - `local_file`: 上传文件。 + - **`url`** (`string`): 图片地址。(仅当传递方式为 `remote_url` 时)。 + - **`upload_file_id`** (`string`): 上传文件 ID。(仅当传递方式为 `local_file` 时)。 + +### Response + +当 `response_mode` 为 `blocking` 时,返回 ChatCompletionResponse object。 +当 `response_mode` 为 `streaming`时,返回 ChunkChatCompletionResponse object 流式序列。 + +#### ChatCompletionResponse + +返回完整的 App 结果,`Content-Type` 为 `application/json`。 + +- **`message_id`** (`string`): 消息唯一 ID +- **`mode`** (`string`): App 模式,固定为 chat +- **`answer`** (`string`): 完整回复内容 +- **`metadata`** (`object`): 元数据 + - **`usage`** (`Usage`): 模型用量信息 + - **`retriever_resources`** (`array[RetrieverResource]`): 引用和归属分段列表 +- **`created_at`** (`int`): 消息创建时间戳,如:1705395332 + +#### ChunkChatCompletionResponse + +返回 App 输出的流式块,`Content-Type` 为 `text/event-stream`。 +每个流式块均为 data: 开头,块之间以 `\n\n` 即两个换行符分隔,如下所示: + +```text +data: {"event": "message", "task_id": "900bbd43-dc0b-4383-a372-aa6e6c414227", "id": "663c5084-a254-4040-8ad3-51f2a3c1a77c", "answer": "Hi", "created_at": 1705398420}\n\n +``` + +流式块中根据 `event` 不同,结构也不同: + +- `event: message`: LLM 返回文本块事件,即:完整的文本以分块的方式输出。 + - **`task_id`** (`string`): 任务 ID,用于请求跟踪和下方的停止响应接口 + - **`message_id`** (`string`): 消息唯一 ID + - **`answer`** (`string`): LLM 返回文本块内容 + - **`created_at`** (`int`): 创建时间戳,如:1705395332 +- `event: message_end`: 消息结束事件,收到此事件则代表文本流式返回结束。 + - **`task_id`** (`string`): 任务 ID,用于请求跟踪和下方的停止响应接口 + - **`message_id`** (`string`): 消息唯一 ID + - **`metadata`** (`object`): 元数据 + - **`usage`** (`Usage`): 模型用量信息 + - **`retriever_resources`** (`array[RetrieverResource]`): 引用和归属分段列表 +- `event: tts_message`: TTS 音频流事件,即:语音合成输出。内容是 Mp3 格式的音频块,使用 base64 编码后的字符串,播放的时候直接解码即可。(开启自动播放才有此消息) + - **`task_id`** (`string`): 任务 ID,用于请求跟踪和下方的停止响应接口 + - **`message_id`** (`string`): 消息唯一 ID + - **`audio`** (`string`): 语音合成之后的音频块使用 Base64 编码之后的文本内容,播放的时候直接 base64 解码送入播放器即可 + - **`created_at`** (`int`): 创建时间戳,如:1705395332 +- `event: tts_message_end`: TTS 音频流结束事件,收到这个事件表示音频流返回结束。 + - **`task_id`** (`string`): 任务 ID,用于请求跟踪和下方的停止响应接口 + - **`message_id`** (`string`): 消息唯一 ID + - **`audio`** (`string`): 结束事件是没有音频的,所以这里是空字符串 + - **`created_at`** (`int`): 创建时间戳,如:1705395332 +- `event: message_replace`: 消息内容替换事件。 + 开启内容审查和审查输出内容时,若命中了审查条件,则会通过此事件替换消息内容为预设回复。 + - **`task_id`** (`string`): 任务 ID,用于请求跟踪和下方的停止响应接口 + - **`message_id`** (`string`): 消息唯一 ID + - **`answer`** (`string`): 替换内容(直接替换 LLM 所有回复文本) + - **`created_at`** (`int`): 创建时间戳,如:1705395332 +- `event: error`: + 流式输出过程中出现的异常会以 stream event 形式输出,收到异常事件后即结束。 + - **`task_id`** (`string`): 任务 ID,用于请求跟踪和下方的停止响应接口 + - **`message_id`** (`string`): 消息唯一 ID + - **`status`** (`int`): HTTP 状态码 + - **`code`** (`string`): 错误码 + - **`message`** (`string`): 错误消息 +- `event: ping`: 每 10s 一次的 ping 事件,保持连接存活。 + +### Errors + +- 404,对话不存在 +- 400,`invalid_param`,传入参数异常 +- 400,`app_unavailable`,App 配置不可用 +- 400,`provider_not_initialize`,无可用模型凭据配置 +- 400,`provider_quota_exceeded`,模型调用额度不足 +- 400,`model_currently_not_support`,当前模型不可用 +- 400,`completion_request_error`,文本生成失败 +- 500,服务内部异常 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/completion-messages' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": { + "query": "Hello, world!" + }, + "response_mode": "streaming", + "user": "abc-123" +}' +``` + + + +```json Blocking +{ + "id": "0b089b9a-24d9-48cc-94f8-762677276261", + "answer": "how are you?", + "created_at": 1679586667 +} +``` + +```text Streaming +data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595} +data: {"id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I", "created_at": 1679586595} +data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} +data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + + +--- + +## 上传文件 + +**POST** `/files/upload` + +上传文件(目前仅支持图片)并在发送消息时使用,可实现图文多模态理解。 +支持 png, jpg, jpeg, webp, gif 格式。 +_上传的文件仅供当前终端用户使用。_ + +### Request Body + +该接口需使用 `multipart/form-data` 进行请求。 + +- **`file`** (`file`): 要上传的文件。 +- **`user`** (`string`): 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response + +成功上传后,服务器会返回文件的 ID 和相关信息。 + +- **`id`** (`uuid`): ID +- **`name`** (`string`): 文件名 +- **`size`** (`int`): 文件大小(byte) +- **`extension`** (`string`): 文件后缀 +- **`mime_type`** (`string`): 文件 mime-type +- **`created_by`** (`uuid`): 上传人 ID +- **`created_at`** (`timestamp`): 上传时间 + +### Errors + +- 400,`no_file_uploaded`,必须提供文件 +- 400,`too_many_files`,目前只接受一个文件 +- 400,`unsupported_preview`,该文件不支持预览 +- 400,`unsupported_estimate`,该文件不支持估算 +- 413,`file_too_large`,文件太大 +- 415,`unsupported_file_type`,不支持的扩展名,当前只接受文档类文件 +- 503,`s3_connection_failed`,无法连接到 S3 服务 +- 503,`s3_permission_denied`,无权限上传文件到 S3 +- 503,`s3_file_too_large`,文件超出 S3 大小限制 + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header + 'Authorization: Bearer {api_key}' \ --form 'file=@"/path/to/file"' \ --form + 'user="abc-123"' ``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "123", + "created_at": 1577836800 +} +``` + + +--- + +## 停止响应 + +**POST** `/completion-messages/:task_id/stop` + +仅支持流式模式。 + +### Path Parameters + +- **`task_id`** (`string`): 任务 ID,可在流式返回 Chunk 中获取 + +### Request Body + +- **`user`** (`string`): Required. 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response + +- **`result`** (`string`): 固定返回 success + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/completion-messages/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## 消息反馈(点赞) + +**POST** `/messages/:message_id/feedbacks` + +消息终端用户反馈、点赞,方便应用开发者优化输出预期。 + +### Path Parameters + +- **`message_id`** (`string`): 消息 ID + +### Request Body + +- **`rating`** (`string`): 点赞 `like`, 点踩 `dislike`, 撤销点赞 `null` +- **`user`** (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 +- **`content`** (`string`): 消息反馈的具体信息。 + +### Response + +- **`result`** (`string`): 固定返回 success + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/messages/:message_id/feedbacks' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "rating": "like", + "user": "abc-123", + "content": "message feedback information" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## 文字转语音 + +**POST** `/text-to-audio` + +文字转语音。 + +### Request Body + +- **`message_id`** (`string`): Dify 生成的文本消息,那么直接传递生成的 message-id 即可,后台会通过 message_id 查找相应的内容直接合成语音信息。如果同时传 message_id 和 text,优先使用 message_id。 +- **`text`** (`string`): 语音生成内容。如果没有传 message-id 的话,则会使用这个字段的内容 +- **`user`** (`string`): 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 + +### Response + +响应体为 `audio/wav` 格式的音频文件。 + + +```bash cURL +curl -o text-to-audio.mp3 -X POST 'https://api.dify.ai/v1/text-to-audio' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", + "text": "你好Dify", + "user": "abc-123", + "streaming": false +}' +``` + + + +```text Headers +Content-Type: audio/wav +``` + +```text Body +(Binary audio data) +``` + + + +--- + +## 获取应用基本信息 + +**GET** `/info` + +用于获取应用的基本信息。 + +### Response + +- **`name`** (`string`): 应用名称 +- **`description`** (`string`): 应用描述 +- **`tags`** (`array[string]`): 应用标签 + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {api_key}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## 获取应用参数 + +**GET** `/parameters` + +用于进入页面一开始,获取功能开关、输入参数名称、类型及默认值等使用。 + +### Response + +- **`opening_statement`** (`string`): 开场白 +- **`suggested_questions`** (`array[string]`): 开场推荐问题列表 +- **`suggested_questions_after_answer`** (`object`): 启用回答后给出推荐问题。 + - **`enabled`** (`bool`): 是否开启 +- **`speech_to_text`** (`object`): 语音转文本 + - **`enabled`** (`bool`): 是否开启 +- **`retriever_resource`** (`object`): 引用和归属 + - **`enabled`** (`bool`): 是否开启 +- **`annotation_reply`** (`object`): 标记回复 + - **`enabled`** (`bool`): 是否开启 +- **`user_input_form`** (`array[object]`): 用户输入表单配置 + - **`text-input`** (`object`): 文本输入控件 + - **`label`** (`string`): 控件展示标签名 + - **`variable`** (`string`): 控件 ID + - **`required`** (`bool`): 是否必填 + - **`default`** (`string`): 默认值 + - **`paragraph`** (`object`): 段落文本输入控件 + - **`label`** (`string`): 控件展示标签名 + - **`variable`** (`string`): 控件 ID + - **`required`** (`bool`): 是否必填 + - **`default`** (`string`): 默认值 + - **`select`** (`object`): 下拉控件 + - **`label`** (`string`): 控件展示标签名 + - **`variable`** (`string`): 控件 ID + - **`required`** (`bool`): 是否必填 + - **`default`** (`string`): 默认值 + - **`options`** (`array[string]`): 选项值 +- **`file_upload`** (`object`): 文件上传配置 + - **`image`** (`object`): 图片设置 + 当前仅支持图片类型:`png`, `jpg`, `jpeg`, `webp`, `gif` + - **`enabled`** (`bool`): 是否开启 + - **`number_limits`** (`int`): 图片数量限制,默认 3 + - **`transfer_methods`** (`array[string]`): 传递方式列表,`remote_url` , `local_file`,必选一个 +- **`system_parameters`** (`object`): 系统参数 + - **`file_size_limit`** (`int`): 文档上传大小限制 (MB) + - **`image_file_size_limit`** (`int`): 图片文件上传大小限制(MB) + - **`audio_file_size_limit`** (`int`): 音频文件上传大小限制 (MB) + - **`video_file_size_limit`** (`int`): 视频文件上传大小限制 (MB) + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "introduction": "nice to meet you", + "user_input_form": [ + { + "text-input": { + "label": "a", + "variable": "a", + "required": true, + "max_length": 48, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": true, + "number_limits": 3, + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + + +--- + +## 获取标注列表 + +**GET** `/apps/annotations` + +### Query Parameters + +- **`page`** (`string`): 页码 +- **`limit`** (`string`): 每页数量 + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotations?page=1&limit=20' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "data": [ + { + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 + } + ], + "has_more": false, + "limit": 20, + "total": 1, + "page": 1 +} +``` + + +--- + +## 创建标注 + +**POST** `/apps/annotations` + +### Request Body + +- **`question`** (`string`): 问题 +- **`answer`** (`string`): 答案内容 + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/apps/annotations' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your name?", + "answer": "I am Dify." +}' +``` + + + +```json Response +{ + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + + +--- + +## 更新标注 + +**PUT** `/apps/annotations/{annotation_id}` + +### Path Parameters + +- **`annotation_id`** (`string`): 标注 ID + +### Request Body + +- **`question`** (`string`): 问题 +- **`answer`** (`string`): 答案内容 + + +```bash cURL +curl --location --request PUT 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "question": "What is your name?", + "answer": "I am Dify." +}' +``` + + + +```json Response +{ + "id": "69d48372-ad81-4c75-9c46-2ce197b4d402", + "question": "What is your name?", + "answer": "I am Dify.", + "hit_count": 0, + "created_at": 1735625869 +} +``` + + +--- + +## 删除标注 + +**DELETE** `/apps/annotations/{annotation_id}` + +### Path Parameters + +- **`annotation_id`** (`string`): 标注 ID + + + ```bash cURL curl --location --request DELETE + 'https://api.dify.ai/v1/apps/annotations/{annotation_id}' \ --header + 'Authorization: Bearer {api_key}' ``` + + +```text Response 204 No Content ``` + +--- + +## 标注回复初始设置 + +**POST** `/apps/annotation-reply/{action}` + +### Path Parameters + +- **`action`** (`string`): 动作,只能是 `enable` 或 `disable` + +### Request Body + +- **`embedding_provider_name`** (`string`): 指定的嵌入模型提供商, 必须先在系统内设定好接入的模型,对应的是 provider 字段 +- **`embedding_model_name`** (`string`): 指定的嵌入模型,对应的是 model 字段 +- **`score_threshold`** (`number`): 相似度阈值,当相似度大于该阈值时,系统会自动回复,否则不回复 + +嵌入模型的提供商和模型名称可以通过以下接口获取:`v1/workspaces/current/models/model-types/text-embedding`, 具体见:通过 API 维护知识库。 使用的 Authorization 是 Dataset 的 API Token。 +该接口是异步执行,所以会返回一个 job_id,通过查询 job 状态接口可以获取到最终的执行结果。 + + +```bash cURL +curl --location --request POST 'https://api.dify.ai/v1/apps/annotation-reply/{action}' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "score_threshold": 0.9, + "embedding_provider_name": "zhipu", + "embedding_model_name": "embedding_3" +}' +``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "waiting" +} +``` + + +--- + +## 查询标注回复初始设置任务状态 + +**GET** `/apps/annotation-reply/{action}/status/{job_id}` + +### Path Parameters + +- **`action`** (`string`): 动作,只能是 `enable` 或 `disable`,并且必须和标注回复初始设置接口的动作一致 +- **`job_id`** (`string`): 任务 ID,从标注回复初始设置接口返回的 job_id + + + ```bash cURL curl --location --request GET + 'https://api.dify.ai/v1/apps/annotation-reply/{action}/status/{job_id}' \ + --header 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "job_id": "b15c8f68-1cf4-4877-bf21-ed7cf2011802", + "job_status": "waiting", + "error_msg": "" +} +``` + diff --git a/api_access/workflow.en.mdx b/api_access/workflow.en.mdx new file mode 100644 index 00000000..8c38f317 --- /dev/null +++ b/api_access/workflow.en.mdx @@ -0,0 +1,668 @@ +--- +title: Workflow App API +--- + +Workflow applications offers non-session support and is ideal for translation, article writing, summarization AI, and more. + +### Base URL + +The Base URL for the API is: + +```text +https://api.dify.ai/v1 +``` + +### Authentication + +The Service API uses `API-Key` authentication. + + + **Strongly recommend storing your API Key on the server-side, not shared or + stored on the client-side, to avoid possible API-Key leakage that can lead + to serious consequences.** + + +For all API requests, include your API Key in the `Authorization` HTTP Header, as shown below: + +```text Authorization Header +Authorization: Bearer {API_KEY} +``` + +--- + +## Execute Workflow (POST /workflows/run) + +Execute workflow, cannot be executed without a published workflow. + + + ```bash cURL + curl -X POST 'https://api.dify.ai/v1/workflows/run' \ + --header 'Authorization: Bearer {api_key}' \ + --header 'Content-Type: application/json' \ + --data-raw '{ + "inputs": {"your_key": "your_value"}, + "response_mode": "streaming", + "user": "abc-123" + }' + ``` + + +### Request Body + +- `inputs` (object) Required + Allows the entry of various variable values defined by the App. + The `inputs` parameter contains multiple key/value pairs, with each key corresponding to a specific variable and each value being the specific value for that variable. + The workflow application requires at least one key/value pair to be inputted. The variable can be of File Array type. + File Array type variable is suitable for inputting files combined with text understanding and answering questions, available only when the model supports file parsing and understanding capability. + If the variable is of File Array type, the corresponding value should be a list whose elements contain following attributions: + + - `type` (string) Supported type: + - `document` ('TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB') + - `image` ('JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG') + - `audio` ('MP3', 'M4A', 'WAV', 'WEBM', 'AMR') + - `video` ('MP4', 'MOV', 'MPEG', 'MPGA') + - `custom` (Other file types) + - `transfer_method` (string) Transfer method, `remote_url` for image URL / `local_file` for file upload + - `url` (string) Image URL (when the transfer method is `remote_url`) + - `upload_file_id` (string) Uploaded file ID, which must be obtained by uploading through the File Upload API in advance (when the transfer method is `local_file`) + +- `response_mode` (string) Required + The mode of response return, supporting: + - `streaming` Streaming mode (recommended), implements a typewriter-like output through SSE ([Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)). + - `blocking` Blocking mode, returns result after execution is complete. (Requests may be interrupted if the process is long) + + Due to Cloudflare restrictions, the request will be interrupted + without a return after 100 seconds. + +- `user` (string) Required + User identifier, used to define the identity of the end-user for retrieval and statistics. + Should be uniquely defined by the developer within the application. + +#### Example: file array as an input variable + +```json "File variable example" +{ + "inputs": { + "{variable_name}": [ + { + "transfer_method": "local_file", + "upload_file_id": "{upload_file_id}", + "type": "{document_type}" + } + ] + } +} +``` + +### Responses + +When `response_mode` is `blocking`, return a CompletionResponse object. +When `response_mode` is `streaming`, return a ChunkCompletionResponse stream. + + + + ```json "Blocking Mode Response" + { + "workflow_run_id": "djflajgkldjgd", + "task_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "data": { + "id": "fdlsjfjejkghjda", + "workflow_id": "fldjaslkfjlsda", + "status": "succeeded", + "outputs": { + "text": "Nice to meet you." + }, + "error": null, + "elapsed_time": 0.875, + "total_tokens": 3562, + "total_steps": 8, + "created_at": 1705407629, + "finished_at": 1727807631 + } + } + ``` + ```streaming "Streaming Mode Response" + data: {"event": "workflow_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "sequence_number": 1, "created_at": 1679586595}} + data: {"event": "node_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "created_at": 1679586595}} + data: {"event": "node_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "execution_metadata": {"total_tokens": 63127864, "total_price": 2.378, "currency": "USD"}, "created_at": 1679586595}} + data: {"event": "workflow_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "total_tokens": 63127864, "total_steps": "1", "created_at": 1679586595, "finished_at": 1679976595}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} + ``` + + + +#### CompletionResponse + +Returns the App result, `Content-Type` is `application/json`. + +- `workflow_run_id` (string) Unique ID of workflow execution +- `task_id` (string) Task ID, used for request tracking and the below Stop Generate API +- `data` (object) detail of result + - `id` (string) ID of workflow execution + - `workflow_id` (string) ID of related workflow + - `status` (string) status of execution, `running` / `succeeded` / `failed` / `stopped` + - `outputs` (json) Optional content of output + - `error` (string) Optional reason of error + - `elapsed_time` (float) Optional total seconds to be used + - `total_tokens` (int) Optional tokens to be used + - `total_steps` (int) default 0 + - `created_at` (timestamp) start time + - `finished_at` (timestamp) end time + +#### ChunkCompletionResponse + +Returns the stream chunks outputted by the App, `Content-Type` is `text/event-stream`. +Each streaming chunk starts with `data:`, separated by two newline characters `\n\n`, as shown below: + +```streaming Response +data: {"event": "text_chunk", "workflow_run_id": "b85e5fc5-751b-454d-b14e-dc5f240b0a31", "task_id": "bd029338-b068-4d34-a331-fc85478922c2", "data": {"text": "\u4e3a\u4e86", "from_variable_selector": ["1745912968134", "text"]}}\n\n +``` + +The structure of the streaming chunks varies depending on the `event`: + +- `event: workflow_started` workflow starts execution + - `task_id` (string) Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (string) Unique ID of workflow execution + - `event` (string) fixed to `workflow_started` + - `data` (object) detail + - `id` (string) Unique ID of workflow execution + - `workflow_id` (string) ID of related workflow + - `sequence_number` (int) Self-increasing serial number, self-increasing in the App, starting from 1 + - `created_at` (timestamp) Creation timestamp, e.g., 1705395332 +- `event: node_started` node execution started + - `task_id` (string) Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (string) Unique ID of workflow execution + - `event` (string) fixed to `node_started` + - `data` (object) detail + - `id` (string) Unique ID of workflow execution + - `node_id` (string) ID of node + - `node_type` (string) type of node + - `title` (string) name of node + - `index` (int) Execution sequence number, used to display Tracing Node sequence + - `predecessor_node_id` (string) optional Prefix node ID, used for canvas display execution path + - `inputs` (object) Contents of all preceding node variables used in the node + - `created_at` (timestamp) timestamp of start, e.g., 1705395332 +- `event: text_chunk` Text fragment + - `task_id` (string) Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (string) Unique ID of workflow execution + - `event` (string) fixed to `text_chunk` + - `data` (object) detail + - `text` (string) Text content + - `from_variable_selector` (array) Text source path, helping developers understand which node and variable generated the text +- `event: node_finished` node execution ends, success or failure in different states in the same event + - `task_id` (string) Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (string) Unique ID of workflow execution + - `event` (string) fixed to `node_finished` + - `data` (object) detail + - `id` (string) Unique ID of workflow execution + - `node_id` (string) ID of node + - `node_type` (string) type of node + - `title` (string) name of node + - `index` (int) Execution sequence number, used to display Tracing Node sequence + - `predecessor_node_id` (string) optional Prefix node ID, used for canvas display execution path + - `inputs` (object) Contents of all preceding node variables used in the node + - `process_data` (json) Optional node process data + - `outputs` (json) Optional content of output + - `status` (string) status of execution, `running` / `succeeded` / `failed` / `stopped` + - `error` (string) Optional reason of error + - `elapsed_time` (float) Optional total seconds to be used + - `execution_metadata` (json) meta data + - `total_tokens` (int) optional tokens to be used + - `total_price` (decimal) optional Total cost + - `currency` (string) optional e.g. `USD` / `RMB` + - `created_at` (timestamp) timestamp of start, e.g., 1705395332 +- `event: workflow_finished` workflow execution ends, success or failure in different states in the same event + - `task_id` (string) Task ID, used for request tracking and the below Stop Generate API + - `workflow_run_id` (string) Unique ID of workflow execution + - `event` (string) fixed to `workflow_finished` + - `data` (object) detail + - `id` (string) ID of workflow execution + - `workflow_id` (string) ID of related workflow + - `status` (string) status of execution, `running` / `succeeded` / `failed` / `stopped` + - `outputs` (json) Optional content of output + - `error` (string) Optional reason of error + - `elapsed_time` (float) Optional total seconds to be used + - `total_tokens` (int) Optional tokens to be used + - `total_steps` (int) default 0 + - `created_at` (timestamp) start time + - `finished_at` (timestamp) end time +- `event: tts_message` TTS audio stream event, that is, speech synthesis output. The content is an audio block in Mp3 format, encoded as a base64 string. When playing, simply decode the base64 and feed it into the player. (This message is available only when auto-play is enabled) + - `task_id` (string) Task ID, used for request tracking and the stop response interface below + - `message_id` (string) Unique message ID + - `audio` (string) The audio after speech synthesis, encoded in base64 text content, when playing, simply decode the base64 and feed it into the player + - `created_at` (int) Creation timestamp, e.g.: 1705395332 +- `event: tts_message_end` TTS audio stream end event, receiving this event indicates the end of the audio stream. + - `task_id` (string) Task ID, used for request tracking and the stop response interface below + - `message_id` (string) Unique message ID + - `audio` (string) The end event has no audio, so this is an empty string + - `created_at` (int) Creation timestamp, e.g.: 1705395332 +- `event: ping` Ping event every 10 seconds to keep the connection alive. + +### Errors + +- 400, `invalid_param`, abnormal parameter input +- 400, `app_unavailable`, App configuration unavailable +- 400, `provider_not_initialize`, no available model credential configuration +- 400, `provider_quota_exceeded`, model invocation quota insufficient +- 400, `model_currently_not_support`, current model unavailable +- 400, `workflow_request_error`, workflow execution failed +- 500, internal server error + +### File upload sample code + +```python "File upload sample code" +import requests +import json + +def upload_file(file_path, user): + upload_url = "https://api.dify.ai/v1/files/upload" # Assuming this is the correct upload URL + headers = { + "Authorization": "Bearer app-xxxxxxxx", # Replace with your app-specific API key for file upload if different + } + + try: + print("Upload file...") + with open(file_path, 'rb') as file: + files = { + 'file': (file_path, file, 'text/plain') # Make sure the file is uploaded with the appropriate MIME type + } + data = { + "user": user, + # "type": "TXT" # Type might be part of file metadata or not needed for generic upload API + } + + response = requests.post(upload_url, headers=headers, files=files, data=data) + if response.status_code == 201: # 201 means creation is successful + print("File uploaded successfully") + return response.json().get("id") # Get the uploaded file ID + else: + print(f"File upload failed, status code: {response.status_code}, message: {response.text}") + return None + except Exception as e: + print(f"Error occurred: {str(e)}") + return None + +def run_workflow(file_id, user, response_mode="blocking"): + workflow_url = "https://api.dify.ai/v1/workflows/run" + headers = { + "Authorization": "Bearer app-xxxxxxxxx", # Replace with your workflow execution API key + "Content-Type": "application/json" + } + + data = { + "inputs": { + "orig_mail": [{ # Assuming "orig_mail" is your variable name + "transfer_method": "local_file", + "upload_file_id": file_id, + "type": "document" # Ensure this matches the expected type for the variable + }] + }, + "response_mode": response_mode, + "user": user + } + + try: + print("Run Workflow...") + response = requests.post(workflow_url, headers=headers, json=data) + if response.status_code == 200: + print("Workflow execution successful") + return response.json() + else: + print(f"Workflow execution failed, status code: {response.status_code}, message: {response.text}") + return {"status": "error", "message": f"Failed to execute workflow, status code: {response.status_code}, response: {response.text}"} + except Exception as e: + print(f"Error occurred: {str(e)}") + return {"status": "error", "message": str(e)} + +# Usage Examples +# file_path = "{your_file_path}" # e.g., "/path/to/your/file.txt" +# user = "difyuser" + +# # Upload files +# file_id = upload_file(file_path, user) +# if file_id: +# # The file was uploaded successfully, and the workflow continues to run +# result = run_workflow(file_id, user) +# print(result) +# else: +# print("File upload failed and workflow cannot be executed") +``` + +--- + +## Get Workflow Run Detail (GET /workflows/run/:workflow_id) + +Retrieve the current execution results of a workflow task based on the workflow execution ID. + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/workflows/run/{workflow_id} + ' \ -H 'Authorization: Bearer {api_key}' \ -H 'Content-Type: + application/json' ``` + + +### Path Parameters + +- `workflow_id` (string) Workflow ID, can be obtained from the streaming chunk return + +### Response + +- `id` (string) ID of workflow execution +- `workflow_id` (string) ID of related workflow +- `status` (string) status of execution, `running` / `succeeded` / `failed` / `stopped` +- `inputs` (json) content of input +- `outputs` (json) content of output +- `error` (string) reason of error +- `total_steps` (int) total steps of task +- `total_tokens` (int) total tokens to be used +- `created_at` (timestamp) start time +- `finished_at` (timestamp) end time +- `elapsed_time` (float) total seconds to be used + + + ```json Response + { + "id": "b1ad3277-089e-42c6-9dff-6820d94fbc76", + "workflow_id": "19eff89f-ec03-4f75-b0fc-897e7effea02", + "status": "succeeded", + "inputs": "{\"sys.files\": [], \"sys.user_id\": \"abc-123\"}", + "outputs": null, + "error": null, + "total_steps": 3, + "total_tokens": 0, + "created_at": 1705407629, + "finished_at": 1727807631, + "elapsed_time": 30.098514399956912 + } + ``` + + +--- + +## Stop Generate (POST /workflows/tasks/:task_id/stop) + +Only supported in streaming mode. + + + ```bash cURL + curl -X POST 'https://api.dify.ai/v1/workflows/tasks/{task_id}/stop' \ + -H 'Authorization: Bearer {api_key}' \ + -H 'Content-Type: application/json' \ + --data-raw '{ + "user": "abc-123" + }' + ``` + + +### Path Parameters + +- `task_id` (string) Task ID, can be obtained from the streaming chunk return + +### Request Body + +- `user` (string) Required + User identifier, used to define the identity of the end-user, must be consistent with the user passed in the send message interface. + +### Response + +- `result` (string) Always returns "success" + + + ```json Response + { + "result": "success" + } + ``` + + +--- + +## File Upload (POST /files/upload) + +Upload a file for use when sending messages, enabling multimodal understanding of images and text. +Supports any formats that are supported by your workflow. +Uploaded files are for use by the current end-user only. + + + ```bash cURL curl -X POST 'https://api.dify.ai/v1/files/upload' \ --header + 'Authorization: Bearer {api_key}' \ --form 'file=@"/path/to/file"' \ --form + 'user="abc-123"' ``` + + +### Request Body + +This interface requires a `multipart/form-data` request. + +- `file` (File) Required + The file to be uploaded. +- `user` (string) Required + User identifier, defined by the developer's rules, must be unique within the application. + +### Response + +After a successful upload, the server will return the file's ID and related information. + +- `id` (uuid) ID +- `name` (string) File name +- `size` (int) File size (bytes) +- `extension` (string) File extension +- `mime_type` (string) File mime-type +- `created_by` (uuid) End-user ID +- `created_at` (timestamp) Creation timestamp, e.g., 1705395332 + + + ```json Response + { + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 + } + ``` + + +### Errors + +- 400, `no_file_uploaded`, a file must be provided +- 400, `too_many_files`, currently only one file is accepted +- 400, `unsupported_preview`, the file does not support preview +- 400, `unsupported_estimate`, the file does not support estimation +- 413, `file_too_large`, the file is too large +- 415, `unsupported_file_type`, unsupported extension, currently only document files are accepted +- 503, `s3_connection_failed`, unable to connect to S3 service +- 503, `s3_permission_denied`, no permission to upload files to S3 +- 503, `s3_file_too_large`, file exceeds S3 size limit +- 500, internal server error + +--- + +## Get Workflow Logs (GET /workflows/logs) + +Returns workflow logs, with the first page returning the latest `{limit}` messages, i.e., in reverse order. + + + ```bash cURL curl -X GET + 'https://api.dify.ai/v1/workflows/logs?limit=1&page=1&status=succeeded&keyword=mysearch' + \ --header 'Authorization: Bearer {api_key}' ``` + + +### Query Parameters + +- `keyword` (string, optional): Keyword to search. +- `status` (string, optional): Filter by status: `succeeded` / `failed` / `stopped`. +- `page` (int, optional): Current page, default is 1. +- `limit` (int, optional): How many chat history messages to return in one request, default is 20. + +### Response + +- `page` (int) Current page +- `limit` (int) Number of returned items, if input exceeds system limit, returns system limit amount +- `total` (int) Number of total items +- `has_more` (bool) Whether there is a next page +- `data` (array[object]) Log list + - `id` (string) ID + - `workflow_run` (object) Workflow run + - `id` (string) ID + - `version` (string) Version + - `status` (string) status of execution, `running` / `succeeded` / `failed` / `stopped` + - `error` (string) Optional reason of error + - `elapsed_time` (float) total seconds to be used + - `total_tokens` (int) tokens to be used + - `total_steps` (int) default 0 + - `created_at` (timestamp) start time + - `finished_at` (timestamp) end time + - `created_from` (string) Created from + - `created_by_role` (string) Created by role + - `created_by_account` (string) Optional Created by account + - `created_by_end_user` (object) Created by end user + - `id` (string) ID + - `type` (string) Type + - `is_anonymous` (bool) Is anonymous + - `session_id` (string) Session ID + - `created_at` (timestamp) create time + + + ```json Response + { + "page": 1, + "limit": 1, + "total": 7, + "has_more": true, + "data": [ + { + "id": "e41b93f1-7ca2-40fd-b3a8-999aeb499cc0", + "workflow_run": { + "id": "c0640fc8-03ef-4481-a96c-8a13b732a36e", + "version": "2024-08-01 12:17:09.771832", + "status": "succeeded", + "error": null, + "elapsed_time": 1.3588523610014818, + "total_tokens": 0, + "total_steps": 3, + "created_at": 1726139643, + "finished_at": 1726139644 + }, + "created_from": "service-api", + "created_by_role": "end_user", + "created_by_account": null, + "created_by_end_user": { + "id": "7f7d9117-dd9d-441d-8970-87e5e7e687a3", + "type": "service_api", + "is_anonymous": false, + "session_id": "abc-123" + }, + "created_at": 1726139644 + } + ] + } + ``` + + +--- + +## Get Application Basic Information (GET /info) + +Used to get basic information about this application. + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/info' \ -H 'Authorization: + Bearer {api_key}' ``` + + +### Response + +- `name` (string) application name +- `description` (string) application description +- `tags` (array[string]) application tags + + + ```json Response + { + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] + } + ``` + + +--- + +## Get Application Parameters Information (GET /parameters) + +Used at the start of entering the page to obtain information such as features, input parameter names, types, and default values. + + + ```bash cURL curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + +### Response + +- `user_input_form` (array[object]) User input form configuration + - `text-input` (object) Text input control + - `label` (string) Variable display label name + - `variable` (string) Variable ID + - `required` (bool) Whether it is required + - `default` (string) Default value + - `paragraph` (object) Paragraph text input control + - `label` (string) Variable display label name + - `variable` (string) Variable ID + - `required` (bool) Whether it is required + - `default` (string) Default value + - `select` (object) Dropdown control + - `label` (string) Variable display label name + - `variable` (string) Variable ID + - `required` (bool) Whether it is required + - `default` (string) Default value + - `options` (array[string]) Option values +- `file_upload` (object) File upload configuration + - `image` (object) Image settings + Currently only supports image types: `png`, `jpg`, `jpeg`, `webp`, `gif` + - `enabled` (bool) Whether it is enabled + - `number_limits` (int) Image number limit, default is 3 + - `transfer_methods` (array[string]) List of transfer methods, remote_url, local_file, must choose one +- `system_parameters` (object) System parameters + - `file_size_limit` (int) Document upload size limit (MB) + - `image_file_size_limit` (int) Image file upload size limit (MB) + - `audio_file_size_limit` (int) Audio file upload size limit (MB) + - `video_file_size_limit` (int) Video file upload size limit (MB) + + + ```json Response + { + "user_input_form": [ + { + "paragraph": { + "label": "Query", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } + } + ``` + diff --git a/api_access/workflow.ja.mdx b/api_access/workflow.ja.mdx new file mode 100644 index 00000000..43795596 --- /dev/null +++ b/api_access/workflow.ja.mdx @@ -0,0 +1,665 @@ +--- +title: ワークフローアプリAPI +--- + +ワークフローアプリケーションは、セッションをサポートせず、翻訳、記事作成、要約 AI などに最適です。 + +### ベース URL + +```text +https://api.dify.ai/v1 +``` + +### 認証 + +サービス API は`API-Key`認証を使用します。 + + + **APIキーの漏洩を防ぐため、APIキーはクライアント側で共有または保存せず、サーバー側で保存することを強くお勧めします。** + + +すべての API リクエストにおいて、以下のように`Authorization`HTTP ヘッダーに API キーを含めてください: + +```text +Authorization: Bearer {API_KEY} +``` + +--- + +## POST /workflows/run ワークフローを実行 + +ワークフローを実行します。公開されたワークフローがないと実行できません。 + +### リクエストボディ + +- `inputs` (object) 必須 + アプリで定義されたさまざまな変数値の入力を許可します。 + `inputs`パラメータには複数のキー/値ペアが含まれ、各キーは特定の変数に対応し、各値はその変数の特定の値です。 + ワークフローアプリケーションは少なくとも 1 つのキー/値ペアの入力を必要とします。値はファイルリストである場合もあります。 + ファイルリストは、テキスト理解と質問への回答を組み合わせたファイルの入力に適しています。モデルがファイルの解析と理解機能をサポートしている場合にのみ使用できます。 + + 変数がファイルリストの場合、リストの各要素は以下の属性を持つ必要があります。 + + - `type` (string) サポートされているタイプ: + - `document` ('TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB') + - `image` ('JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG') + - `audio` ('MP3', 'M4A', 'WAV', 'WEBM', 'AMR') + - `video` ('MP4', 'MOV', 'MPEG', 'MPGA') + - `custom` (他のファイルタイプ) + - `transfer_method` (string) 転送方法、画像 URL の場合は`remote_url` / ファイルアップロードの場合は`local_file` + - `url` (string) 画像 URL(転送方法が`remote_url`の場合) + - `upload_file_id` (string) アップロードされたファイル ID、事前にファイルアップロード API を通じて取得する必要があります(転送方法が`local_file`の場合) + +- `response_mode` (string) 必須 + 応答の返却モードを指定します。サポートされているモード: + - `streaming` ストリーミングモード(推奨)、SSE([Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events))を通じてタイプライターのような出力を実装します。 + - `blocking` ブロッキングモード、実行完了後に結果を返します。(プロセスが長い場合、リクエストが中断される可能性があります) + + Cloudflareの制限により、100秒後に応答がない場合、リクエストは中断されます。 + +- `user` (string) 必須 + ユーザー識別子、エンドユーザーのアイデンティティを定義するために使用されます。 + アプリケーション内で開発者によって一意に定義される必要があります。 +- `files` (array[object]) オプション + +### 応答 + +`response_mode`が`blocking`の場合、CompletionResponse オブジェクトを返します。 +`response_mode`が`streaming`の場合、ChunkCompletionResponse ストリームを返します。 + +#### CompletionResponse + +アプリの結果を返します。`Content-Type`は`application/json`です。 + +- `workflow_run_id` (string) ワークフロー実行の一意の ID +- `task_id` (string) タスク ID、リクエスト追跡と以下の Stop Generate API に使用 +- `data` (object) 結果の詳細 + - `id` (string) ワークフロー実行の ID + - `workflow_id` (string) 関連するワークフローの ID + - `status` (string) 実行のステータス、`running` / `succeeded` / `failed` / `stopped` + - `outputs` (json) オプションの出力内容 + - `error` (string) オプションのエラー理由 + - `elapsed_time` (float) オプションの使用時間(秒) + - `total_tokens` (int) オプションの使用トークン数 + - `total_steps` (int) デフォルト 0 + - `created_at` (timestamp) 開始時間 + - `finished_at` (timestamp) 終了時間 + +#### ChunkCompletionResponse + +アプリによって出力されたストリームチャンクを返します。`Content-Type`は`text/event-stream`です。 +各ストリーミングチャンクは`data:`で始まり、2 つの改行文字`\n\n`で区切られます。以下のように表示されます: + +```text +data: {"event": "text_chunk", "workflow_run_id": "b85e5fc5-751b-454d-b14e-dc5f240b0a31", "task_id": "bd029338-b068-4d34-a331-fc85478922c2", "data": {"text": "\u4e3a\u4e86", "from_variable_selector": ["1745912968134", "text"]}}\n\n +``` + +ストリーミングチャンクの構造は`event`に応じて異なります: + +- `event: workflow_started` ワークフローが実行を開始 + - `task_id` (string) タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - `workflow_run_id` (string) ワークフロー実行の一意の ID + - `event` (string) `workflow_started`に固定 + - `data` (object) 詳細 + - `id` (string) ワークフロー実行の一意の ID + - `workflow_id` (string) 関連するワークフローの ID + - `sequence_number` (int) 自己増加シリアル番号、アプリ内で自己増加し、1 から始まります + - `created_at` (timestamp) 作成タイムスタンプ、例:1705395332 +- `event: node_started` ノード実行開始 + - `task_id` (string) タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - `workflow_run_id` (string) ワークフロー実行の一意の ID + - `event` (string) `node_started`に固定 + - `data` (object) 詳細 + - `id` (string) ワークフロー実行の一意の ID + - `node_id` (string) ノードの ID + - `node_type` (string) ノードのタイプ + - `title` (string) ノードの名前 + - `index` (int) 実行シーケンス番号、トレースノードシーケンスを表示するために使用 + - `predecessor_node_id` (string) オプションのプレフィックスノード ID、キャンバス表示実行パスに使用 + - `inputs` (object) ノードで使用されるすべての前のノード変数の内容 + - `created_at` (timestamp) 開始のタイムスタンプ、例:1705395332 +- `event: text_chunk` テキストフラグメント + - `task_id` (string) タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - `workflow_run_id` (string) ワークフロー実行の一意の ID + - `event` (string) `text_chunk`に固定 + - `data` (object) 詳細 + - `text` (string) テキスト内容 + - `from_variable_selector` (array) テキスト生成元パス(開発者がどのノードのどの変数から生成されたかを理解するための情報) +- `event: node_finished` ノード実行終了、同じイベントで異なる状態で成功または失敗 + - `task_id` (string) タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - `workflow_run_id` (string) ワークフロー実行の一意の ID + - `event` (string) `node_finished`に固定 + - `data` (object) 詳細 + - `id` (string) ワークフロー実行の一意の ID + - `node_id` (string) ノードの ID + - `node_type` (string) ノードのタイプ + - `title` (string) ノードの名前 + - `index` (int) 実行シーケンス番号、トレースノードシーケンスを表示するために使用 + - `predecessor_node_id` (string) オプションのプレフィックスノード ID、キャンバス表示実行パスに使用 + - `inputs` (object) ノードで使用されるすべての前のノード変数の内容 + - `process_data` (json) オプションのノードプロセスデータ + - `outputs` (json) オプションの出力内容 + - `status` (string) 実行のステータス、`running` / `succeeded` / `failed` / `stopped` + - `error` (string) オプションのエラー理由 + - `elapsed_time` (float) オプションの使用時間(秒) + - `execution_metadata` (json) メタデータ + - `total_tokens` (int) オプションの使用トークン数 + - `total_price` (decimal) オプションの総コスト + - `currency` (string) オプション 例:`USD` / `RMB` + - `created_at` (timestamp) 開始のタイムスタンプ、例:1705395332 +- `event: workflow_finished` ワークフロー実行終了、同じイベントで異なる状態で成功または失敗 + - `task_id` (string) タスク ID、リクエスト追跡と以下の Stop Generate API に使用 + - `workflow_run_id` (string) ワークフロー実行の一意の ID + - `event` (string) `workflow_finished`に固定 + - `data` (object) 詳細 + - `id` (string) ワークフロー実行の ID + - `workflow_id` (string) 関連するワークフローの ID + - `status` (string) 実行のステータス、`running` / `succeeded` / `failed` / `stopped` + - `outputs` (json) オプションの出力内容 + - `error` (string) オプションのエラー理由 + - `elapsed_time` (float) オプションの使用時間(秒) + - `total_tokens` (int) オプションの使用トークン数 + - `total_steps` (int) デフォルト 0 + - `created_at` (timestamp) 開始時間 + - `finished_at` (timestamp) 終了時間 +- `event: tts_message` TTS オーディオストリームイベント、つまり音声合成出力。内容は Mp3 形式のオーディオブロックで、base64 文字列としてエンコードされています。再生時には、base64 をデコードしてプレーヤーに入力するだけです。(このメッセージは自動再生が有効な場合にのみ利用可能) + - `task_id` (string) タスク ID、リクエスト追跡と以下の停止応答インターフェースに使用 + - `message_id` (string) 一意のメッセージ ID + - `audio` (string) 音声合成後のオーディオ、base64 テキストコンテンツとしてエンコードされており、再生時には base64 をデコードしてプレーヤーに入力するだけです + - `created_at` (int) 作成タイムスタンプ、例:1705395332 +- `event: tts_message_end` TTS オーディオストリーム終了イベント。このイベントを受信すると、オーディオストリームの終了を示します。 + - `task_id` (string) タスク ID、リクエスト追跡と以下の停止応答インターフェースに使用 + - `message_id` (string) 一意のメッセージ ID + - `audio` (string) 終了イベントにはオーディオがないため、これは空の文字列です + - `created_at` (int) 作成タイムスタンプ、例:1705395332 +- `event: ping` 接続を維持するために 10 秒ごとに送信される Ping イベント。 + +### エラー + +- 400, `invalid_param`, 異常なパラメータ入力 +- 400, `app_unavailable`, アプリの設定が利用できません +- 400, `provider_not_initialize`, 利用可能なモデル資格情報の設定がありません +- 400, `provider_quota_exceeded`, モデル呼び出しのクォータが不足しています +- 400, `model_currently_not_support`, 現在のモデルは利用できません +- 400, `workflow_request_error`, ワークフロー実行に失敗しました +- 500, 内部サーバーエラー + + +```bash Request +curl -X POST 'https://api.dify.ai/v1/workflows/run' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {}, + "response_mode": "streaming", + "user": "abc-123" +}' +``` + + +### ファイル変数の例 + +```json example.json +{ + "inputs": { + "{variable_name}": [ + { + "transfer_method": "local_file", + "upload_file_id": "{upload_file_id}", + "type": "{document_type}" + } + ] + } +} +``` + + +#### ブロッキングモード応答 +```json Response +{ + "workflow_run_id": "djflajgkldjgd", + "task_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "data": { + "id": "fdlsjfjejkghjda", + "workflow_id": "fldjaslkfjlsda", + "status": "succeeded", + "outputs": { + "text": "Nice to meet you." + }, + "error": null, + "elapsed_time": 0.875, + "total_tokens": 3562, + "total_steps": 8, + "created_at": 1705407629, + "finished_at": 1727807631 + } +} +``` +#### ストリーミングモード応答 +```text StreamingResponse + data: {"event": "workflow_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "sequence_number": 1, "created_at": 1679586595}} + data: {"event": "node_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "created_at": 1679586595}} + data: {"event": "node_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "execution_metadata": {"total_tokens": 63127864, "total_price": 2.378, "currency": "USD"}, "created_at": 1679586595}} + data: {"event": "workflow_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "total_tokens": 63127864, "total_steps": "1", "created_at": 1679586595, "finished_at": 1679976595}} + data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} + data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +### ファイルアップロードのサンプルコード + +```python example_upload.py +import requests +import json + +def upload_file(file_path, user): + upload_url = "https://api.dify.ai/v1/files/upload" + headers = { + "Authorization": "Bearer app-xxxxxxxx", # あなたのAPIキーに置き換えてください + } + + try: + print("ファイルをアップロードしています...") + with open(file_path, 'rb') as file: + files = { + 'file': (file_path, file, 'text/plain') # ファイルが適切な MIME タイプでアップロードされていることを確認してください + } + data = { + "user": user, + "type": "TXT" # ファイルタイプをTXTに設定します (必要に応じて変更) + } + + response = requests.post(upload_url, headers=headers, files=files, data=data) + if response.status_code == 201: # 201 は作成が成功したことを意味します + print("ファイルが正常にアップロードされました") + return response.json().get("id") # アップロードされたファイルIDを取得する + else: + print(f"ファイルのアップロードに失敗しました。ステータス コード: {response.status_code}, 応答: {response.text}") + return None + except Exception as e: + print(f"エラーが発生しました: {str(e)}") + return None + +def run_workflow(file_id, user, response_mode="blocking"): + workflow_url = "https://api.dify.ai/v1/workflows/run" + headers = { + "Authorization": "Bearer app-xxxxxxxxx", # あなたのAPIキーに置き換えてください + "Content-Type": "application/json" + } + + # `orig_mail` はワークフローで定義された変数名です。実際の変数名に置き換えてください。 + data = { + "inputs": { + "orig_mail": [{ # このキーはワークフローの入力変数名と一致する必要があります + "transfer_method": "local_file", + "upload_file_id": file_id, + "type": "document" # アップロードしたファイルのタイプに合わせてください + }] + }, + "response_mode": response_mode, + "user": user + } + + try: + print("ワークフローを実行...") + response = requests.post(workflow_url, headers=headers, json=data) + if response.status_code == 200: + print("ワークフローが正常に実行されました") + return response.json() + else: + print(f"ワークフローの実行がステータス コードで失敗しました: {response.status_code}, 応答: {response.text}") + return {"status": "error", "message": f"Failed to execute workflow, status code: {response.status_code}, response: {response.text}"} + except Exception as e: + print(f"エラーが発生しました: {str(e)}") + return {"status": "error", "message": str(e)} + +# 使用例 +# file_path = "{your_file_path}" # アップロードするファイルのパスに置き換えてください +# user = "difyuser" # ユーザーIDに置き換えてください + +# # ファイルをアップロードする +# file_id = upload_file(file_path, user) +# if file_id: +# # ファイルは正常にアップロードされました。ワークフローの実行を続行します +# result = run_workflow(file_id, user) +# print(result) +# else: +# print("ファイルのアップロードに失敗し、ワークフローを実行できません") +``` + +--- + +## GET /workflows/run/:workflow_id ワークフロー実行詳細を取得 + +ワークフロー実行 ID に基づいて、ワークフロータスクの現在の実行結果を取得します。 + +### パスパラメータ + +- `workflow_id` (string) ワークフロー ID、ストリーミングチャンクの返り値から取得可能 + +### 応答 + +- `id` (string) ワークフロー実行の ID +- `workflow_id` (string) 関連するワークフローの ID +- `status` (string) 実行のステータス、`running` / `succeeded` / `failed` / `stopped` +- `inputs` (json) 入力内容 +- `outputs` (json) 出力内容 +- `error` (string) エラー理由 +- `total_steps` (int) タスクの総ステップ数 +- `total_tokens` (int) 使用されるトークンの総数 +- `created_at` (timestamp) 開始時間 +- `finished_at` (timestamp) 終了時間 +- `elapsed_time` (float) 使用される総秒数 + + + ```bash Request curl -X GET + 'https://api.dify.ai/v1/workflows/run/:workflow_id' \ -H 'Authorization: + Bearer {api_key}' \ -H 'Content-Type: application/json' ``` + + + +```json Response +{ + "id": "b1ad3277-089e-42c6-9dff-6820d94fbc76", + "workflow_id": "19eff89f-ec03-4f75-b0fc-897e7effea02", + "status": "succeeded", + "inputs": "{\"sys.files\": [], \"sys.user_id\": \"abc-123\"}", + "outputs": null, + "error": null, + "total_steps": 3, + "total_tokens": 0, + "created_at": 1705407629, + "finished_at": 1727807631, + "elapsed_time": 30.098514399956912 +} +``` + + +--- + +## POST /workflows/tasks/:task_id/stop 生成を停止 + +ストリーミングモードでのみサポートされています。 + +### パスパラメータ + +- `task_id` (string) タスク ID、ストリーミングチャンクの返り値から取得可能 + +### リクエストボディ + +- `user` (string) 必須 + ユーザー識別子、エンドユーザーのアイデンティティを定義するために使用され、送信メッセージインターフェースで渡されたユーザーと一致している必要があります。 + +### 応答 + +- `result` (string) 常に"success"を返します + + +```bash Request +curl -X POST 'https://api.dify.ai/v1/workflows/tasks/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## POST /files/upload ファイルアップロード + +メッセージ送信時に使用するためのファイルをアップロードし、画像とテキストのマルチモーダル理解を可能にします。 +ワークフローでサポートされている任意の形式をサポートします。 +アップロードされたファイルは、現在のエンドユーザーのみが使用できます。 + +### リクエストボディ + +このインターフェースは`multipart/form-data`リクエストを必要とします。 + +- `file` (File) 必須 + アップロードするファイル。 +- `user` (string) 必須 + ユーザー識別子、開発者のルールで定義され、アプリケーション内で一意でなければなりません。 + +### 応答 + +アップロードが成功すると、サーバーはファイルの ID と関連情報を返します。 + +- `id` (uuid) ID +- `name` (string) ファイル名 +- `size` (int) ファイルサイズ(バイト) +- `extension` (string) ファイル拡張子 +- `mime_type` (string) ファイルの MIME タイプ +- `created_by` (uuid) エンドユーザー ID +- `created_at` (timestamp) 作成タイムスタンプ、例:1705395332 + +### エラー + +- 400, `no_file_uploaded`, ファイルが提供されていません +- 400, `too_many_files`, 現在は 1 つのファイルのみ受け付けています +- 400, `unsupported_preview`, ファイルはプレビューをサポートしていません +- 400, `unsupported_estimate`, ファイルは推定をサポートしていません +- 413, `file_too_large`, ファイルが大きすぎます +- 415, `unsupported_file_type`, サポートされていない拡張子、現在はドキュメントファイルのみ受け付けています +- 503, `s3_connection_failed`, S3 サービスに接続できません +- 503, `s3_permission_denied`, S3 にファイルをアップロードする権限がありません +- 503, `s3_file_too_large`, ファイルが S3 のサイズ制限を超えています +- 500, 内部サーバーエラー + + + ```bash Request curl -X POST 'https://api.dify.ai/v1/files/upload' \ + --header 'Authorization: Bearer {api_key}' \ --form + 'file=@"/path/to/your/file.txt"' \ --form 'user="abc-123"' ``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "6ad1ab0a-73ff-4ac1-b9e4-cdb312f71f13", + "created_at": 1577836800 +} +``` + + +--- + +## GET /workflows/logs ワークフローログを取得 + +ワークフローログを返します。最初のページは最新の`{limit}`メッセージを返します。つまり、逆順です。 + +### クエリパラメータ + +- `keyword` (string, optional): 検索するキーワード +- `status` (string, optional): フィルタリングするステータス (`succeeded`/`failed`/`stopped`) +- `page` (int, optional): 現在のページ、デフォルトは 1。 +- `limit` (int, optional): 1 回のリクエストで返すチャット履歴メッセージの数、デフォルトは 20。 + +### 応答 + +- `page` (int) 現在のページ +- `limit` (int) 返されたアイテムの数、入力がシステム制限を超える場合、システム制限量を返します +- `total` (int) 合計アイテム数 +- `has_more` (bool) 次のページがあるかどうか +- `data` (array[object]) ログリスト + - `id` (string) ID + - `workflow_run` (object) ワークフロー実行 + - `id` (string) ID + - `version` (string) バージョン + - `status` (string) 実行のステータス、`running` / `succeeded` / `failed` / `stopped` + - `error` (string) オプションのエラー理由 + - `elapsed_time` (float) 使用される総秒数 + - `total_tokens` (int) 使用されるトークン数 + - `total_steps` (int) デフォルト 0 + - `created_at` (timestamp) 開始時間 + - `finished_at` (timestamp) 終了時間 + - `created_from` (string) 作成元 + - `created_by_role` (string) 作成者の役割 + - `created_by_account` (string) オプションの作成者アカウント + - `created_by_end_user` (object) エンドユーザーによって作成 + - `id` (string) ID + - `type` (string) タイプ + - `is_anonymous` (bool) 匿名かどうか + - `session_id` (string) セッション ID + - `created_at` (timestamp) 作成時間 + + + ```bash Request curl -X GET 'https://api.dify.ai/v1/workflows/logs?limit=1' + \ --header 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "page": 1, + "limit": 1, + "total": 7, + "has_more": true, + "data": [ + { + "id": "e41b93f1-7ca2-40fd-b3a8-999aeb499cc0", + "workflow_run": { + "id": "c0640fc8-03ef-4481-a96c-8a13b732a36e", + "version": "2024-08-01 12:17:09.771832", + "status": "succeeded", + "error": null, + "elapsed_time": 1.3588523610014818, + "total_tokens": 0, + "total_steps": 3, + "created_at": 1726139643, + "finished_at": 1726139644 + }, + "created_from": "service-api", + "created_by_role": "end_user", + "created_by_account": null, + "created_by_end_user": { + "id": "7f7d9117-dd9d-441d-8970-87e5e7e687a3", + "type": "service_api", + "is_anonymous": false, + "session_id": "abc-123" + }, + "created_at": 1726139644 + } + ] +} +``` + + +--- + +## GET /info アプリケーションの基本情報を取得 + +このアプリケーションの基本情報を取得するために使用されます + +### 応答 + +- `name` (string) アプリケーションの名前 +- `description` (string) アプリケーションの説明 +- `tags` (array[string]) アプリケーションのタグ + + + ```bash Request curl -X GET 'https://api.dify.ai/v1/info' \ -H + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## GET /parameters アプリケーションのパラメータ情報を取得 + +ページに入る際に、機能、入力パラメータ名、タイプ、デフォルト値などの情報を取得するために使用されます。 + +### 応答 + +- `user_input_form` (array[object]) ユーザー入力フォームの設定 + - `text-input` (object) テキスト入力コントロール + - `label` (string) 変数表示ラベル名 + - `variable` (string) 変数 ID + - `required` (bool) 必須かどうか + - `default` (string) デフォルト値 + - `paragraph` (object) 段落テキスト入力コントロール + - `label` (string) 変数表示ラベル名 + - `variable` (string) 変数 ID + - `required` (bool) 必須かどうか + - `default` (string) デフォルト値 + - `select` (object) ドロップダウンコントロール + - `label` (string) 変数表示ラベル名 + - `variable` (string) 変数 ID + - `required` (bool) 必須かどうか + - `default` (string) デフォルト値 + - `options` (array[string]) オプション値 +- `file_upload` (object) ファイルアップロード設定 + - `image` (object) 画像設定 + 現在サポートされている画像タイプのみ:`png`, `jpg`, `jpeg`, `webp`, `gif` + - `enabled` (bool) 有効かどうか + - `number_limits` (int) 画像数の制限、デフォルトは 3 + - `transfer_methods` (array[string]) 転送方法のリスト、remote_url, local_file、いずれかを選択する必要があります +- `system_parameters` (object) システムパラメータ + - `file_size_limit` (int) ドキュメントアップロードサイズ制限(MB) + - `image_file_size_limit` (int) 画像ファイルアップロードサイズ制限(MB) + - `audio_file_size_limit` (int) オーディオファイルアップロードサイズ制限(MB) + - `video_file_size_limit` (int) ビデオファイルアップロードサイズ制限(MB) + + + ```bash Request curl -X GET 'https://api.dify.ai/v1/parameters' \ --header + 'Authorization: Bearer {api_key}' ``` + + + +```json Response +{ + "user_input_form": [ + { + "paragraph": { + "label": "Query", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + diff --git a/api_access/workflow.zh.mdx b/api_access/workflow.zh.mdx new file mode 100644 index 00000000..4aaa804e --- /dev/null +++ b/api_access/workflow.zh.mdx @@ -0,0 +1,651 @@ +--- +title: Workflow 应用 API +--- + +Workflow 应用无会话支持,适合用于翻译/文章写作/总结 AI 等等。 + +### Base URL + +```text +https://api.dify.ai/v1 +``` + +### Authentication + +Dify Service API 使用 `API-Key` 进行鉴权。 +**强烈建议开发者把 `API-Key` 放在后端存储,而非分享或者放在客户端存储,以免 `API-Key` 泄露,导致财产损失。** +所有 API 请求都应在 **`Authorization`** HTTP Header 中包含您的 `API-Key`,如下所示: + +```text +Authorization: Bearer {API_KEY} +``` + +--- + +## 执行 workflow + +`POST /workflows/run` + +执行 workflow,没有已发布的 workflow,不可执行。 + +### Request Body + - `inputs` (object) Required + 允许传入 App 定义的各变量值。 + inputs 参数包含了多组键值对(Key/Value pairs),每组的键对应一个特定变量,每组的值则是该变量的具体值。变量可以是文件列表类型。 + 文件列表类型变量适用于传入文件结合文本理解并回答问题,仅当模型支持该类型文件解析能力时可用。如果该变量是文件列表类型,该变量对应的值应是列表格式,其中每个元素应包含以下内容: + - `type` (string) 支持类型: + - `document` 具体类型包含:'TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB' + - `image` 具体类型包含:'JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG' + - `audio` 具体类型包含:'MP3', 'M4A', 'WAV', 'WEBM', 'AMR' + - `video` 具体类型包含:'MP4', 'MOV', 'MPEG', 'MPGA' + - `custom` 具体类型包含:其他文件类型 + - `transfer_method` (string) 传递方式,`remote_url` 图片地址 / `local_file` 上传文件 + - `url` (string) 图片地址(仅当传递方式为 `remote_url` 时) + - `upload_file_id` (string) 上传文件 ID(仅当传递方式为 `local_file` 时) + - `response_mode` (string) Required + 返回响应模式,支持: + - `streaming` 流式模式(推荐)。基于 SSE(**[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)**)实现类似打字机输出方式的流式返回。 + - `blocking` 阻塞模式,等待执行完毕后返回结果。(请求若流程较长可能会被中断)。 + 由于 Cloudflare 限制,请求会在 100 秒超时无返回后中断。 + - `user` (string) Required + 用户标识,用于定义终端用户的身份,方便检索、统计。 + 由开发者定义规则,需保证用户标识在应用内唯一。 + + +### Response +当 `response_mode` 为 `blocking` 时,返回 CompletionResponse object。 +当 `response_mode` 为 `streaming`时,返回 ChunkCompletionResponse object 流式序列。 + +### CompletionResponse +返回完整的 App 结果,`Content-Type` 为 `application/json` 。 +- `workflow_run_id` (string) workflow 执行 ID +- `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 +- `data` (object) 详细内容 + - `id` (string) workflow 执行 ID + - `workflow_id` (string) 关联 Workflow ID + - `status` (string) 执行状态, `running` / `succeeded` / `failed` / `stopped` + - `outputs` (json) Optional 输出内容 + - `error` (string) Optional 错误原因 + - `elapsed_time` (float) Optional 耗时(s) + - `total_tokens` (int) Optional 总使用 tokens + - `total_steps` (int) 总步数(冗余),默认 0 + - `created_at` (timestamp) 开始时间 + - `finished_at` (timestamp) 结束时间 + +### ChunkCompletionResponse +返回 App 输出的流式块,`Content-Type` 为 `text/event-stream`。 +每个流式块均为 data: 开头,块之间以 `\n\n` 即两个换行符分隔,如下所示: + +```text +data: {"event": "text_chunk", "workflow_run_id": "b85e5fc5-751b-454d-b14e-dc5f240b0a31", "task_id": "bd029338-b068-4d34-a331-fc85478922c2", "data": {"text": "\u4e3a\u4e86", "from_variable_selector": ["1745912968134", "text"]}}\n\n +``` + +流式块中根据 `event` 不同,结构也不同,包含以下类型: +- `event: workflow_started` workflow 开始执行 + - `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 + - `workflow_run_id` (string) workflow 执行 ID + - `event` (string) 固定为 `workflow_started` + - `data` (object) 详细内容 + - `id` (string) workflow 执行 ID + - `workflow_id` (string) 关联 Workflow ID + - `sequence_number` (int) 自增序号,App 内自增,从 1 开始 + - `created_at` (timestamp) 开始时间 +- `event: node_started` node 开始执行 + - `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 + - `workflow_run_id` (string) workflow 执行 ID + - `event` (string) 固定为 `node_started` + - `data` (object) 详细内容 + - `id` (string) workflow 执行 ID + - `node_id` (string) 节点 ID + - `node_type` (string) 节点类型 + - `title` (string) 节点名称 + - `index` (int) 执行序号,用于展示 Tracing Node 顺序 + - `predecessor_node_id` (string) 前置节点 ID,用于画布展示执行路径 + - `inputs` (object) 节点中所有使用到的前置节点变量内容 + - `created_at` (timestamp) 开始时间 +- `event: text_chunk` 文本片段 + - `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 + - `workflow_run_id` (string) workflow 执行 ID + - `event` (string) 固定为 `text_chunk` + - `data` (object) 详细内容 + - `text` (string) 文本内容 + - `from_variable_selector` (array) 文本来源路径,帮助开发者了解文本是由哪个节点的哪个变量生成的 +- `event: node_finished` node 执行结束,成功失败同一事件中不同状态 + - `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 + - `workflow_run_id` (string) workflow 执行 ID + - `event` (string) 固定为 `node_finished` + - `data` (object) 详细内容 + - `id` (string) node 执行 ID + - `node_id` (string) 节点 ID + - `index` (int) 执行序号,用于展示 Tracing Node 顺序 + - `predecessor_node_id` (string) optional 前置节点 ID,用于画布展示执行路径 + - `inputs` (object) 节点中所有使用到的前置节点变量内容 + - `process_data` (json) Optional 节点过程数据 + - `outputs` (json) Optional 输出内容 + - `status` (string) 执行状态 `running` / `succeeded` / `failed` / `stopped` + - `error` (string) Optional 错误原因 + - `elapsed_time` (float) Optional 耗时(s) + - `execution_metadata` (json) 元数据 + - `total_tokens` (int) optional 总使用 tokens + - `total_price` (decimal) optional 总费用 + - `currency` (string) optional 货币,如 `USD` / `RMB` + - `created_at` (timestamp) 开始时间 +- `event: workflow_finished` workflow 执行结束,成功失败同一事件中不同状态 + - `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 + - `workflow_run_id` (string) workflow 执行 ID + - `event` (string) 固定为 `workflow_finished` + - `data` (object) 详细内容 + - `id` (string) workflow 执行 ID + - `workflow_id` (string) 关联 Workflow ID + - `status` (string) 执行状态 `running` / `succeeded` / `failed` / `stopped` + - `outputs` (json) Optional 输出内容 + - `error` (string) Optional 错误原因 + - `elapsed_time` (float) Optional 耗时(s) + - `total_tokens` (int) Optional 总使用 tokens + - `total_steps` (int) 总步数(冗余),默认 0 + - `created_at` (timestamp) 开始时间 + - `finished_at` (timestamp) 结束时间 +- `event: tts_message` TTS 音频流事件,即:语音合成输出。内容是Mp3格式的音频块,使用 base64 编码后的字符串,播放的时候直接解码即可。(开启自动播放才有此消息) + - `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string) 消息唯一 ID + - `audio` (string) 语音合成之后的音频块使用 Base64 编码之后的文本内容,播放的时候直接 base64 解码送入播放器即可 + - `created_at` (int) 创建时间戳,如:1705395332 +- `event: tts_message_end` TTS 音频流结束事件,收到这个事件表示音频流返回结束。 + - `task_id` (string) 任务 ID,用于请求跟踪和下方的停止响应接口 + - `message_id` (string) 消息唯一 ID + - `audio` (string) 结束事件是没有音频的,所以这里是空字符串 + - `created_at` (int) 创建时间戳,如:1705395332 +- `event: ping` 每 10s 一次的 ping 事件,保持连接存活。 + +### Errors +- 400,`invalid_param`,传入参数异常 +- 400,`app_unavailable`,App 配置不可用 +- 400,`provider_not_initialize`,无可用模型凭据配置 +- 400,`provider_quota_exceeded`,模型调用额度不足 +- 400,`model_currently_not_support`,当前模型不可用 +- 400,`workflow_request_error`,workflow 执行失败 +- 500,服务内部异常 + +#### 文件变量示例 + +```json +{ + "inputs": { + "{variable_name}": [ + { + "transfer_method": "local_file", + "upload_file_id": "{upload_file_id}", + "type": "{document_type}" + } + ] + } +} +``` + +#### 文件上传Python示例代码 + +```python +import requests +import json + +def upload_file(file_path, user): + upload_url = "https://api.dify.ai/v1/files/upload" + headers = { + "Authorization": "Bearer app-xxxxxxxx", # 请替换为您的 API Key + } + + try: + print("上传文件中...") + with open(file_path, 'rb') as file: + files = { + 'file': (file_path, file, 'text/plain') # 确保文件以适当的MIME类型上传 + } + data = { + "user": user, + # "type": "TXT" # type 参数在 v0.6 已废弃,由后端自动判断 + } + + response = requests.post(upload_url, headers=headers, files=files, data=data) + if response.status_code == 201: # 201 表示创建成功 + print("文件上传成功") + return response.json().get("id") # 获取上传的文件 ID + else: + print(f"文件上传失败,状态码: {response.status_code}, 错误: {response.text}") + return None + except Exception as e: + print(f"发生错误: {str(e)}") + return None + +def run_workflow(file_id, user, response_mode="blocking"): + workflow_url = "https://api.dify.ai/v1/workflows/run" + headers = { + "Authorization": "Bearer app-xxxxxxxxx", # 请替换为您的 API Key + "Content-Type": "application/json" + } + + data = { + "inputs": { + "orig_mail": [{ # "orig_mail" 是示例变量名,请替换为您 workflow 中定义的变量名 + "transfer_method": "local_file", + "upload_file_id": file_id, + "type": "document" # 根据实际文件类型填写 'document', 'image', 'audio', 'video', 'custom' + }] + }, + "response_mode": response_mode, + "user": user + } + + try: + print("运行工作流...") + response = requests.post(workflow_url, headers=headers, json=data) + if response.status_code == 200: + print("工作流执行成功") + return response.json() + else: + print(f"工作流执行失败,状态码: {response.status_code}, 错误: {response.text}") + return {"status": "error", "message": f"Failed to execute workflow, status code: {response.status_code}, error: {response.text}"} + except Exception as e: + print(f"发生错误: {str(e)}") + return {"status": "error", "message": str(e)} + +# 使用示例 +# file_path = "{your_file_path}" # 替换为您的文件路径 +# user = "difyuser" # 替换为您的用户标识 + +# 上传文件 +# file_id = upload_file(file_path, user) +# if file_id: +# # 文件上传成功,继续运行工作流 +# result = run_workflow(file_id, user) +# print(result) +# else: +# print("文件上传失败,无法执行工作流") +``` + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/workflows/run' \ +--header 'Authorization: Bearer {api_key}' \ +--header 'Content-Type: application/json' \ +--data-raw '{ + "inputs": {}, + "response_mode": "streaming", + "user": "abc-123" +}' +``` + + + +```json Blocking +{ + "workflow_run_id": "djflajgkldjgd", + "task_id": "9da23599-e713-473b-982c-4328d4f5c78a", + "data": { + "id": "fdlsjfjejkghjda", + "workflow_id": "fldjaslkfjlsda", + "status": "succeeded", + "outputs": { + "text": "Nice to meet you." + }, + "error": null, + "elapsed_time": 0.875, + "total_tokens": 3562, + "total_steps": 8, + "created_at": 1705407629, + "finished_at": 1727807631 + } +} +``` + +```text Streaming +data: {"event": "workflow_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "sequence_number": 1, "created_at": 1679586595}} +data: {"event": "node_started", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "created_at": 1679586595}} +data: {"event": "node_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "node_id": "dfjasklfjdslag", "node_type": "start", "title": "Start", "index": 0, "predecessor_node_id": "fdljewklfklgejlglsd", "inputs": {}, "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "execution_metadata": {"total_tokens": 63127864, "total_price": 2.378, "currency": "USD"}, "created_at": 1679586595}} +data: {"event": "workflow_finished", "task_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "workflow_run_id": "5ad498-f0c7-4085-b384-88cbe6290", "data": {"id": "5ad498-f0c7-4085-b384-88cbe6290", "workflow_id": "dfjasklfjdslag", "outputs": {}, "status": "succeeded", "elapsed_time": 0.324, "total_tokens": 63127864, "total_steps": "1", "created_at": 1679586595, "finished_at": 1679976595}} +data: {"event": "tts_message", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"} +data: {"event": "tts_message_end", "conversation_id": "23dd85f3-1a41-4ea0-b7a9-062734ccfaf9", "message_id": "a8bdc41c-13b2-4c18-bfd9-054b9803038c", "created_at": 1721205487, "task_id": "3bf8a0bb-e73b-4690-9e66-4e429bad8ee7", "audio": ""} +``` + + +--- + +## 获取workflow执行情况 + +`GET /workflows/run/:workflow_run_id` + +根据 workflow 执行 ID 获取 workflow 任务当前执行结果 + +### Path +- `workflow_run_id` (string) workflow_run_id,可在流式返回 Chunk 中获取 + +### Response +- `id` (string) workflow 执行 ID +- `workflow_id` (string) 关联的 Workflow ID +- `status` (string) 执行状态 `running` / `succeeded` / `failed` / `stopped` +- `inputs` (json) 任务输入内容 +- `outputs` (json) 任务输出内容 +- `error` (string) 错误原因 +- `total_steps` (int) 任务执行总步数 +- `total_tokens` (int) 任务执行总 tokens +- `created_at` (timestamp) 任务开始时间 +- `finished_at` (timestamp) 任务结束时间 +- `elapsed_time` (float) 耗时(s) + + +```bash cURL +curl -X GET 'https://api.dify.ai/v1/workflows/run/:workflow_run_id' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' +``` + + + +```json Response +{ + "id": "b1ad3277-089e-42c6-9dff-6820d94fbc76", + "workflow_id": "19eff89f-ec03-4f75-b0fc-897e7effea02", + "status": "succeeded", + "inputs": "{\"sys.files\": [], \"sys.user_id\": \"abc-123\"}", + "outputs": null, + "error": null, + "total_steps": 3, + "total_tokens": 0, + "created_at": 1705407629, + "finished_at": 1727807631, + "elapsed_time": 30.098514399956912 +} +``` + + +--- + +## 停止响应 + +`POST /workflows/tasks/:task_id/stop` + +仅支持流式模式。 + +### Path +- `task_id` (string) 任务 ID,可在流式返回 Chunk 中获取 + +### Request Body +- `user` (string) Required + 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response +- `result` (string) 固定返回 "success" + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/workflows/tasks/:task_id/stop' \ +-H 'Authorization: Bearer {api_key}' \ +-H 'Content-Type: application/json' \ +--data-raw '{ + "user": "abc-123" +}' +``` + + + +```json Response +{ + "result": "success" +} +``` + + +--- + +## 上传文件 + +`POST /files/upload` + +上传文件并在发送消息时使用,可实现图文多模态理解。 +支持您的工作流程所支持的任何格式。 +上传的文件仅供当前终端用户使用。 + +### Request Body +该接口需使用 `multipart/form-data` 进行请求。 +- `file` (file): 要上传的文件。 +- `user` (string): 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 + +### Response +成功上传后,服务器会返回文件的 ID 和相关信息。 +- `id` (uuid) ID +- `name` (string) 文件名 +- `size` (int) 文件大小(byte) +- `extension` (string) 文件后缀 +- `mime_type` (string) 文件 mime-type +- `created_by` (uuid) 上传人 ID +- `created_at` (timestamp) 上传时间 + +### Errors +- 400,`no_file_uploaded`,必须提供文件 +- 400,`too_many_files`,目前只接受一个文件 +- 400,`unsupported_preview`,该文件不支持预览 +- 400,`unsupported_estimate`,该文件不支持估算 +- 413,`file_too_large`,文件太大 +- 415,`unsupported_file_type`,不支持的扩展名,当前只接受文档类文件 +- 503,`s3_connection_failed`,无法连接到 S3 服务 +- 503,`s3_permission_denied`,无权限上传文件到 S3 +- 503,`s3_file_too_large`,文件超出 S3 大小限制 + + +```bash cURL +curl -X POST 'https://api.dify.ai/v1/files/upload' \ +--header 'Authorization: Bearer {api_key}' \ +--form 'file=@"/path/to/file"' \ +--form 'user="abc-123"' +``` + + + +```json Response +{ + "id": "72fa9618-8f89-4a37-9b33-7e1178a24a67", + "name": "example.png", + "size": 1024, + "extension": "png", + "mime_type": "image/png", + "created_by": "abc-123", + "created_at": 1577836800 +} +``` + + +--- + +## 获取 workflow 日志 + +`GET /workflows/logs` + +倒序返回workflow日志 + +### Query +- `keyword` (string): 关键字 +- `status` (string): 执行状态 succeeded/failed/stopped +- `page` (int): 当前页码, 默认1. +- `limit` (int): 每页条数, 默认20. + +### Response +- `page` (int) 当前页码 +- `limit` (int) 每页条数 +- `total` (int) 总条数 +- `has_more` (bool) 是否还有更多数据 +- `data` (array[object]) 当前页码的数据 + - `id` (string) 标识 + - `workflow_run` (object) Workflow 执行日志 + - `id` (string) 标识 + - `version` (string) 版本 + - `status` (string) 执行状态, `running` / `succeeded` / `failed` / `stopped` + - `error` (string) (可选) 错误 + - `elapsed_time` (float) 耗时,单位秒 + - `total_tokens` (int) 消耗的token数量 + - `total_steps` (int) 执行步骤长度 + - `created_at` (timestamp) 开始时间 + - `finished_at` (timestamp) 结束时间 + - `created_from` (string) 来源 + - `created_by_role` (string) 角色 + - `created_by_account` (string) (可选) 帐号 + - `created_by_end_user` (object) 用户 + - `id` (string) 标识 + - `type` (string) 类型 + - `is_anonymous` (bool) 是否匿名 + - `session_id` (string) 会话标识 + - `created_at` (timestamp) 创建时间 + + +```bash cURL +curl -X GET 'https://api.dify.ai/v1/workflows/logs?limit=1' \ +--header 'Authorization: Bearer {api_key}' +``` + + + +```json Response +{ + "page": 1, + "limit": 1, + "total": 7, + "has_more": true, + "data": [ + { + "id": "e41b93f1-7ca2-40fd-b3a8-999aeb499cc0", + "workflow_run": { + "id": "c0640fc8-03ef-4481-a96c-8a13b732a36e", + "version": "2024-08-01 12:17:09.771832", + "status": "succeeded", + "error": null, + "elapsed_time": 1.3588523610014818, + "total_tokens": 0, + "total_steps": 3, + "created_at": 1726139643, + "finished_at": 1726139644 + }, + "created_from": "service-api", + "created_by_role": "end_user", + "created_by_account": null, + "created_by_end_user": { + "id": "7f7d9117-dd9d-441d-8970-87e5e7e687a3", + "type": "service_api", + "is_anonymous": false, + "session_id": "abc-123" + }, + "created_at": 1726139644 + } + ] +} +``` + + +--- + +## 获取应用基本信息 + +`GET /info` + +用于获取应用的基本信息 + +### Response +- `name` (string) 应用名称 +- `description` (string) 应用描述 +- `tags` (array[string]) 应用标签 + + +```bash cURL +curl -X GET 'https://api.dify.ai/v1/info' \ +-H 'Authorization: Bearer {api_key}' +``` + + + +```json Response +{ + "name": "My App", + "description": "This is my app.", + "tags": [ + "tag1", + "tag2" + ] +} +``` + + +--- + +## 获取应用参数 + +`GET /parameters` + +用于进入页面一开始,获取功能开关、输入参数名称、类型及默认值等使用。 + +### Response +- `user_input_form` (array[object]) 用户输入表单配置 + - `text-input` (object) 文本输入控件 + - `label` (string) 控件展示标签名 + - `variable` (string) 控件 ID + - `required` (bool) 是否必填 + - `default` (string) 默认值 + - `paragraph` (object) 段落文本输入控件 + - `label` (string) 控件展示标签名 + - `variable` (string) 控件 ID + - `required` (bool) 是否必填 + - `default` (string) 默认值 + - `select` (object) 下拉控件 + - `label` (string) 控件展示标签名 + - `variable` (string) 控件 ID + - `required` (bool) 是否必填 + - `default` (string) 默认值 + - `options` (array[string]) 选项值 +- `file_upload` (object) 文件上传配置 + - `image` (object) 图片设置 + 当前仅支持图片类型:`png`, `jpg`, `jpeg`, `webp`, `gif` + - `enabled` (bool) 是否开启 + - `number_limits` (int) 图片数量限制,默认 3 + - `transfer_methods` (array[string]) 传递方式列表,remote_url , local_file,必选一个 +- `system_parameters` (object) 系统参数 + - `file_size_limit` (int) 文档上传大小限制 (MB) + - `image_file_size_limit` (int) 图片文件上传大小限制(MB) + - `audio_file_size_limit` (int) 音频文件上传大小限制 (MB) + - `video_file_size_limit` (int) 视频文件上传大小限制 (MB) + + +```bash cURL +curl -X GET 'https://api.dify.ai/v1/parameters' \ +--header 'Authorization: Bearer {api_key}' +``` + + + +```json Response +{ + "user_input_form": [ + { + "paragraph": { + "label": "Query", + "variable": "query", + "required": true, + "default": "" + } + } + ], + "file_upload": { + "image": { + "enabled": false, + "number_limits": 3, + "detail": "high", + "transfer_methods": [ + "remote_url", + "local_file" + ] + } + }, + "system_parameters": { + "file_size_limit": 15, + "image_file_size_limit": 10, + "audio_file_size_limit": 50, + "video_file_size_limit": 100 + } +} +``` + diff --git a/docs.json b/docs.json index 87170ac6..a3e77b63 100644 --- a/docs.json +++ b/docs.json @@ -594,6 +594,15 @@ "pages": [ "en/termbase/termbase" ] + }, + { + "tab": "API Access", + "pages": [ + "api_access/chat.en", + "api_access/chatflow.en", + "api_access/completion.en", + "api_access/workflow.en" + ] } ] }, @@ -1215,6 +1224,15 @@ "pages": [ "zh-hans/termbase/termbase" ] + }, + { + "tab": "访问 API", + "pages": [ + "api_access/chat.zh", + "api_access/chatflow.zh", + "api_access/completion.zh", + "api_access/workflow.zh" + ] } ] }, @@ -1678,6 +1696,15 @@ "pages": [ "ja-jp/termbase/termbase" ] + }, + { + "tab": "APIアクセス", + "pages": [ + "api_access/chat.ja", + "api_access/chatflow.ja", + "api_access/completion.ja", + "api_access/workflow.ja" + ] } ] },