dify-spring-boot-starter
  • 介绍
  • 快速开始
  • 安装
  • 配置
  • 客户端构建器
  • 功能

    • Chat API
    • Workflow API
    • Dataset API
    • Server API
  • 事件

    • 介绍
    • 聊天事件
  • 使用配置
  • 自定义配置
  • v1.x-SNAPSHOT
  • v0.x
  • 更新日志
  • 简体中文
  • English
GitHub
  • 介绍
  • 快速开始
  • 安装
  • 配置
  • 客户端构建器
  • 功能

    • Chat API
    • Workflow API
    • Dataset API
    • Server API
  • 事件

    • 介绍
    • 聊天事件
  • 使用配置
  • 自定义配置
  • v1.x-SNAPSHOT
  • v0.x
  • 更新日志
  • 简体中文
  • English
GitHub
  • 指南

    • 介绍
    • 快速开始
    • 安装
    • 配置
    • 客户端构建器
  • 功能

    • Chat API
    • Workflow API
    • Dataset API
    • Server API
  • 事件

    • 介绍
    • 聊天事件

Chat API

接口概述

聊天服务接口提供完整的聊天功能集成能力,包含消息收发、会话管理、语音转换等核心功能。所有接口均需要有效的API密钥进行身份验证。 使用DifyChat接口实例。

1. 消息

1.1 发送消息

方法

ChatMessageSendResponse send(ChatMessageSendRequest sendRequest);

请求参数

ChatMessageSendRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
conversationIdString否聊天对话编号
contentString是消息内容
filesList<ChatMessageFile>否文件
inputsMap<String, Object>否自定义参数

ChatMessageFile 结构:

参数名类型描述
idString文件 ID
typeString文件类型,默认为 "image"
urlString预览图片地址
transferMethodString传输方式,默认为 "remote_url"
belongsToString文件归属方,user 或 assistant
uploadFileIdString上传文件ID

响应参数

ChatMessageSendResponse

参数名类型描述
conversationIdString会话 id
messageIdString消息id
createdAtLong创建时间戳
taskIdString任务 id
idStringid
answerString回答

1.2 发送流式消息

方法

Flux<ChatMessageSendCompletionResponse> sendChatMessageStream(ChatMessageSendRequest sendRequest);

请求参数

与发送消息接口相同

响应参数

返回消息流,包含以下结构:

ChatMessageSendCompletionResponse

参数名类型描述
workflowRunIdString工作流运行ID
dataCompletionData完成数据,根据事件类型不同而变化

其中 CompletionData 根据事件类型会具有不同的数据结构,可能的事件类型有:

事件类型描述对应数据类
workflow_started工作流开始WorkflowStartedData
node_started节点开始NodeStartedData
node_finished节点完成NodeFinishedData
workflow_finished工作流完成WorkflowFinishedData

1.3 终止消息流

方法

void stopMessagesStream(String apiKey, String taskId, String userId);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey
taskIdString是任务 id
userIdString是用户 id

1.4 消息反馈

方法

MessageFeedbackResponse messageFeedback(MessageFeedbackRequest messageFeedbackRequest);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
messageIdString是消息 id
ratingRating是评级
contentString是消息反馈的具体信息

响应参数

MessageFeedbackResponse

参数名类型描述
resultString固定返回 success

1.5 获取消息列表

方法

DifyPageResult<MessagesResponseVO> messages(MessagesRequest request);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
conversationIdString是会话 id
firstIdString否第一条记录 id
limitInteger否每页记录数,默认20条

响应参数

参数名类型描述
idString消息 ID
conversationIdString会话 ID
inputsMap<String, Object>用户输入参数
queryString用户输入/问题内容
messageFilesList<MessageFile>消息文件
answerString回答消息内容
createdAtLong创建时间戳
feedbackFeedback反馈信息

MessageFile 结构:

参数名类型描述
idString文件 ID
filenameString文件名
typeString文件类型,如 "image"
urlString预览图片地址
mimeTypeString文件 MIME 类型
sizeLong文件大小(字节)
transferMethodString传输方式
belongsToString文件归属方,"user" 或 "assistant"
uploadFileIdString上传文件ID
agentThoughtsList<MessageFileAgentThought>Agent思考内容(仅Agent模式下不为空)

MessageFileAgentThought 结构:

参数名类型描述
idStringagent_thought ID,每一轮Agent迭代都会有一个唯一的id
messageIdString消息唯一ID
positionIntegeragent_thought在消息中的位置,如第一轮迭代position为1
thoughtStringagent的思考内容
observationString工具调用的返回结果
toolString使用的工具列表,以 ; 分割多个工具
toolInputString工具的输入,JSON格式的字符串(object)。如:{"dalle3": {"prompt": "a cute cat"}}
createdAtLong创建时间戳,如:1705395332
messageFilesList<String>当前agent_thought 关联的文件ID
conversationIdString会话ID

Feedback 结构:

参数名类型描述
ratingString点赞/点踩 评级

1.6 获取建议回复

方法

List<String> messagesSuggested(String messageId, String apiKey, String userId);

请求参数

参数名类型是否必须描述
messageIdString是消息 id
apiKeyString是apiKey
userIdString是用户 id

响应参数

返回建议回复文本列表

1.7 获取应用反馈列表

方法

DifyPageResult<AppFeedbackResponse> feedbacks(AppFeedbackPageRequest request);

请求参数

AppFeedbackPageRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
pageInteger否页码,默认1
limitInteger否每页记录数,默认20,范围 1-100

响应参数

AppFeedbackResponse

参数名类型描述
idString反馈 id
appIdString应用 id
conversationIdString会话 id
messageIdString消息 id
ratingString评级 (like/dislike)
contentString反馈内容
fromSourceString来源
fromEndUserIdString终端用户 id
fromAccountIdString账户 id
createdAtLocalDateTime创建时间戳
updatedAtLocalDateTime更新时间戳

1.8 获取会话变量列表

方法

DifyPageResult<ConversationVariableResponse> conversationVariables(ConversationVariableRequest request);

请求参数

ConversationVariableRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
conversationIdString是会话 id
variableNameString否变量名称,为空则返回所有变量

响应参数

ConversationVariableResponse

参数名类型描述
idString变量 id
nameString变量名称
valueTypeString值类型 (string/json)
valueString变量值
descriptionString描述
createdAtLong创建时间戳 (时间戳)
updatedAtLong更新时间戳 (时间戳)

1.9 更新会话变量

方法

ConversationVariableResponse updateConversationVariable(UpdateConversationVariableRequest request);

请求参数

UpdateConversationVariableRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
conversationIdString是会话 id
variableIdString是变量 id
valueString是新的变量值

响应参数

ConversationVariableResponse

参数名类型描述
idString变量 id
nameString变量名称
valueTypeString值类型 (string/json)
valueString变量值
descriptionString描述
createdAtLong创建时间戳 (时间戳)
updatedAtLong更新时间戳 (时间戳)

2. 会话

2.1 获取会话列表

方法

DifyPageResult<MessageConversationsResponse> conversations(MessageConversationsRequest request);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
lastIdString否最后一条记录 id
limitInteger否每页记录数,默认20
sortByString否排序字段,默认-updated_at

响应参数

MessageConversationsResponse

参数名类型描述
idString会话 id
nameString会话名称
inputsMap<String,Object>输入参数
statusString会话状态
introductionString开场白
createdAtLong创建时间戳
updatedAtLong更新时间戳

2.2 删除会话

方法

void deleteConversation(String conversationId, String apiKey, String userId);

请求参数

参数名类型是否必须描述
conversationIdString是会话 id
apiKeyString是apiKey
userIdString是用户 id

2.3 会话重命名

方法

MessageConversationsResponse renameConversation(RenameConversationRequest renameConversationRequest);

请求参数

参数名类型是否必须描述
conversationIdString是会话 id
nameString是会话名称
autoGenerateString否自动生成标题,默认 false
apiKeyString是apiKey
userIdString是用户 id

响应参数

MessageConversationsResponse

参数名类型描述
idString会话 id
nameString会话名称
inputsMap<String,Object>输入参数
statusString会话状态
introductionString开场白
createdAtLong创建时间戳
updatedAtLong更新时间戳

3. 其他

3.1 文本转语音

方法

ResponseEntity<byte[]> textToAudio(TextToAudioRequest request);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
textString是转换文本
messageIdString否消息 id

响应参数

返回音频文件流

使用示例

import java.io.IOException;

private void textToAudio(TextToAudioRequest request, HttpServletResponse response) {
    try {
        ResponseEntity<byte[]> responseEntity = difyChat.textToAudio(request);

        String type = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        response.setContentType(type != null ? type : "audio/mpeg");

        String contentDisposition = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
        if (contentDisposition != null) {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        } else {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=audio.mp3");
        }

        if (responseEntity.getBody() != null) {
            response.getOutputStream().write(responseEntity.getBody());
            response.getOutputStream().flush();
        }

    } catch (Exception e) {
        log.error("textToAudio error: {}", e.getMessage());
        throw new RuntimeException("textToAudio error");
    }
}

3.2 语音转文本

方法

DifyTextVO audioToText(AudioToTextRequest request);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
fileMultipartFile是音频文件

响应参数

参数名类型描述
textString转换文本

3.3 获取应用参数

方法

AppParametersResponseVO parameters(String apiKey);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey

响应参数

AppParametersResponseVO

参数名类型描述
openingStatementString开场白
suggestedQuestionsList<String>开场推荐问题列表
suggestedQuestionsAfterAnswerEnabled启用回答后给出推荐问题
speechToTextEnabled语音转文本功能配置
textToSpeechTextToSpeech文本转语音功能配置
retrieverResourceEnabled引用和归属功能配置
annotationReplyEnabled标记回复功能配置
moreLikeThisEnabled更多类似功能配置
userInputFormList<UserInputForm>用户输入表单配置
sensitiveWordAvoidanceEnabled敏感词规避功能配置
fileUploadFileUpload文件上传配置
systemParametersFileUploadConfig系统参数配置

Enabled 对象结构:

参数名类型描述
enabledBoolean是否启用

TextToSpeech 对象结构:

参数名类型描述
enabledBoolean是否启用
voiceString语音类型

FileUpload 对象结构:

参数名类型描述
enabledBoolean是否启用文件上传功能
imageFileUploadImage图片上传配置
allowedFileTypesList<String>允许的文件类型列表
allowedFileExtensionsList<String>允许的文件扩展名列表
allowedFileUploadMethodsList<String>允许的文件上传方式列表
numberLimitsInteger文件数量限制
fileUploadConfigFileUploadConfig文件上传详细配置

FileUploadImage 对象结构:

参数名类型描述
enabledBoolean是否启用图片上传功能
numberLimitsInteger图片数量限制,默认3
transferMethodsList<String>传递方式列表,可选值:remote_url, local_file

FileUploadConfig 对象结构:

参数名类型描述
fileSizeLimitInteger文件大小限制(MB)
batchCountLimitInteger批量上传数量限制
imageFileSizeLimitInteger图片文件大小限制(MB)
videoFileSizeLimitInteger视频文件大小限制(MB)
audioFileSizeLimitInteger音频文件大小限制(MB)
workflowFileUploadLimitInteger工作流文件上传限制

UserInputForm 对象结构:

参数名类型描述
textInputTextInput文本输入控件配置
paragraphParagraph段落文本输入控件配置
selectSelect下拉控件配置

TextInput 对象结构:

参数名类型描述
labelString控件展示标签名
variableString控件ID
requiredBoolean是否必填
maxLengthInteger最大长度限制
defaultValueString默认值

Paragraph 对象结构: 继承自 TextInput,具有相同的字段结构

Select 对象结构:

参数名类型描述
labelString控件展示标签名
variableString控件ID
requiredBoolean是否必填
maxLengthInteger最大长度限制
defaultValueString默认值
typeString下拉类型
optionsList<String>选项列表

3.4 文件上传

方法

FileUploadResponse fileUpload(FileUploadRequest request);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
fileMultipartFile是上传文件

响应参数

FileUploadResponse

参数名类型描述
idString文件 id
nameString文件名称
sizeInteger文件大小(字节)
extensionString文件后缀
mimeTypeString文件MIME类型
createdByString创建人
createdAtLong创建时间戳

3.5 获取应用信息

方法

AppInfoResponse info(String apiKey);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey

响应参数

AppInfoResponse

参数名类型描述
nameString应用名称
descriptionString应用描述
tagsList<String>应用标签列表

3.6 获取应用元数据

方法

AppMetaResponse meta(String apiKey);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey

响应参数

AppMetaResponse

参数名类型描述
toolIconsMap<String, Object>工具图标映射

3.7 获取应用 WebApp 设置

方法

AppSiteResponse site(String apikey);

请求参数

参数名类型是否必须描述
apiKeyString是apiKey

响应参数

AppSiteResponse

参数名类型描述
titleStringWebApp 名称
chatColorThemeString聊天颜色主题,十六进制格式
chatColorThemeInvertedBoolean聊天颜色主题是否反转
iconTypeIconTypeEnum图标类型,emoji - 表情符号,image - 图片
iconString图标。如果是 emoji 类型,则为表情符号;如果是 image 类型,则为图片 URL
iconBackgroundString背景颜色,十六进制格式
iconUrlString图标 URL
descriptionString描述
copyrightString版权信息
privacyPolicyString隐私政策链接
customDisclaimerString自定义免责声明
defaultLanguageString默认语言
showWorkflowStepsBoolean是否显示工作流详情
useIconAsAnswerIconBoolean是否在聊天中用 WebApp 图标替换 🤖

3.8 文件预览

方法

ResponseEntity<byte[]> filePreview(FilePreviewRequest request);

请求参数

FilePreviewRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
fileIdString是要预览的文件的唯一标识符,从文件上传 API 响应中获得
asAttachmentBoolean否是否强制将文件作为附件下载。默认为 false(在浏览器中预览)

响应参数

返回带有适当浏览器显示或下载标头的文件内容。

响应头说明
  • Content-Type: 根据文件 MIME 类型设置
  • Content-Length: 文件大小(以字节为单位,如果可用)
  • Content-Disposition: 如果 asAttachment=true 则设置为 "attachment"
  • Cache-Control: 用于性能的缓存标头
  • Accept-Ranges: 对于音频/视频文件设置为 "bytes"

使用示例

基本使用
// 创建文件预览请求
FilePreviewRequest request = new FilePreviewRequest("file-id-123")
                .setApiKey("your-api-key")
                .setUserId("user-123");

// 执行文件预览
ResponseEntity<byte[]> response = difyChat.filePreview(request);

// 获取文件内容
byte[] fileContent = response.getBody();
预览文件(在浏览器中显示)
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

private void previewFile(String fileId, HttpServletResponse response) {
    try {
        FilePreviewRequest request = new FilePreviewRequest(fileId)
                .setApiKey("your-api-key")
                .setUserId("user-123")
                .setAsAttachment(false); // 在浏览器中预览

        ResponseEntity<byte[]> responseEntity = difyChat.filePreview(request);

        // 设置响应头
        String contentType = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        response.setContentType(contentType != null ? contentType : "application/octet-stream");

        String contentLength = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_LENGTH);
        if (contentLength != null) {
            response.setContentLength(Integer.parseInt(contentLength));
        }

        // 复制缓存控制头
        String cacheControl = responseEntity.getHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
        if (cacheControl != null) {
            response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControl);
        }

        // 写入文件内容
        if (responseEntity.getBody() != null) {
            response.getOutputStream().write(responseEntity.getBody());
            response.getOutputStream().flush();
        }

    } catch (Exception e) {
        log.error("File preview error: {}", e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
下载文件(作为附件)
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

private void downloadFile(String fileId, String filename, HttpServletResponse response) {
    try {
        FilePreviewRequest request = new FilePreviewRequest(fileId, true, "your-api-key", "user-123");

        ResponseEntity<byte[]> responseEntity = difyChat.filePreview(request);

        // 设置响应头
        String contentType = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        response.setContentType(contentType != null ? contentType : "application/octet-stream");

        String contentDisposition = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
        if (contentDisposition != null) {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        } else {
            // 设置自定义文件名
            String safeFilename = filename != null ? filename : "download";
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + safeFilename + "\"");
        }

        // 写入文件内容
        if (responseEntity.getBody() != null) {
            response.getOutputStream().write(responseEntity.getBody());
            response.getOutputStream().flush();
        }

    } catch (Exception e) {
        log.error("File download error: {}", e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

4. 应用标注

需要 Dify 1.2.0 或更高版本

4.1 获取应用标注列表

方法

DifyPageResult<AppAnnotationResponse> pageAppAnnotation(AppAnnotationPageRequest request);

请求参数

AppAnnotationPageRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
pageInteger否页码,默认1
limitInteger否每页记录数,默认20,范围 1-100

响应参数

AppAnnotationResponse

参数名类型描述
idString标注 id
questionString问题内容
answerString回答内容
hitCountInteger命中次数
createdAtLong创建时间戳

4.2 创建应用标注

方法

AppAnnotationResponse createAppAnnotation(AppAnnotationCreateRequest request);

请求参数

AppAnnotationCreateRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
questionString是问题内容
answerString是回答内容

响应参数

AppAnnotationResponse

参数名类型描述
idString标注 id
questionString问题内容
answerString回答内容
hitCountInteger命中次数
createdAtLong创建时间戳

4.3 更新应用标注

需要 Dify 1.3.1 或更高版本

方法

AppAnnotationResponse updateAppAnnotation(AppAnnotationUpdateRequest request);

请求参数

AppAnnotationUpdateRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
annotationIdString是标注 id
questionString是问题内容
answerString是回答内容

响应参数

AppAnnotationResponse

参数名类型描述
idString标注 id
questionString问题内容
answerString回答内容
hitCountInteger命中次数
createdAtLong创建时间戳

4.4 删除应用标注

方法

 void deleteAppAnnotation(String annotationId, String apiKey);

请求参数

参数名类型是否必须描述
annotationIdString是标注 id
apiKeyString是apiKey

响应参数

无

4.5 标注回复

方法

AppAnnotationReplyResponse annotationReply(AppAnnotationReplyRequest request);

请求参数

AppAnnotationReplyRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
actionAnnotationReplyActionEnum是回复动作类型
embeddingProviderNameString否嵌入模型提供商
embeddingModelNameString否嵌入模型名称
scoreThresholdFloat否评分阈值

AnnotationReplyActionEnum 可选值:

  • enable - 启用标注回复
  • disable - 禁用标注回复

响应参数

AppAnnotationReplyResponse

参数名类型描述
jobIdString任务 id
jobStatusString任务状态
errorMsgString错误信息

4.6 查询标注回复状态

方法

AppAnnotationReplyResponse queryAnnotationReply(AppAnnotationReplyQueryRequest request);

请求参数

AppAnnotationReplyQueryRequest

参数名类型是否必须描述
apiKeyString是apiKey
userIdString是用户 id
actionAnnotationReplyActionEnum是回复动作类型
jobIdString是需要查询的任务id

响应参数

AppAnnotationReplyResponse

参数名类型描述
jobIdString任务 id
jobStatusString任务状态
errorMsgString错误信息
在 GitHub 上编辑此页
上次更新: 2025/9/8 08:06
Next
Workflow API