Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Dify Java Client 是一个用于与 Dify 平台进行交互的 Java 客户端库。它提供了对 Dify 应用 API 和知识库 API 的完整支持,让 Java 开发者能够轻松地将 Dify 的生成式 AI 能力集成到自己的应用中。

License

NotificationsYou must be signed in to change notification settings

imfangs/dify-java-client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Maven CentralLicenseJava

English | 简体中文 |日本語

Dify Java Client 是一个用于与Dify 平台进行交互的 Java 客户端库。它提供了对 Dify 应用 API 和知识库 API 的完整支持,让 Java 开发者能够轻松地将 Dify 的生成式 AI 能力集成到自己的应用中。

功能特性

Dify Java Client 提供以下核心功能:

1. 多种应用类型支持

  • 对话型应用 (Chat): 通过DifyChatClient 调用对话型应用,支持会话管理、消息反馈等功能
  • 文本生成应用 (Completion): 通过DifyCompletionClient 调用文本生成型应用
  • 工作流编排对话 (Chatflow): 通过DifyChatflowClient 调用工作流编排对话型应用
  • 工作流应用 (Workflow): 通过DifyWorkflowClient 调用工作流应用
  • 知识库管理 (Datasets): 通过DifyDatasetsClient 管理知识库、文档和检索

2. 丰富的交互模式

  • 阻塞模式: 同步调用API,等待完整响应
  • 流式模式: 通过回调接收实时生成的内容,支持打字机效果
  • 文件处理: 支持文件上传、语音转文字、文字转语音等多媒体功能

3. 完整的会话管理

  • 创建和管理会话
  • 获取历史消息
  • 会话重命名
  • 消息反馈(点赞/点踩)
  • 获取建议问题

4. 知识库全流程支持

  • 创建和管理知识库
  • 上传和管理文档
  • 文档分段管理
  • 语义检索

5. 灵活的配置选项

  • 自定义连接超时
  • 自定义读写超时
  • 自定义HTTP客户端

安装

系统要求

  • Java 8 或更高版本
  • Maven 3.x 或 Gradle 4.x 以上

Maven

<dependency>    <groupId>io.github.imfangs</groupId>    <artifactId>dify-java-client</artifactId>    <version>1.2.3</version></dependency>

Gradle

implementation'io.github.imfangs:dify-java-client:1.2.3'

快速开始

创建客户端

// 创建完整的 Dify 客户端DifyClientclient =DifyClientFactory.createClient("https://api.dify.ai/v1","your-api-key");// 创建特定类型的客户端DifyChatClientchatClient =DifyClientFactory.createChatClient("https://api.dify.ai/v1","your-api-key");DifyCompletionClientcompletionClient =DifyClientFactory.createCompletionClient("https://api.dify.ai/v1","your-api-key");DifyChatflowClientchatflowClient =DifyClientFactory.createChatWorkflowClient("https://api.dify.ai/v1","your-api-key");DifyWorkflowClientworkflowClient =DifyClientFactory.createWorkflowClient("https://api.dify.ai/v1","your-api-key");DifyDatasetsClientdatasetsClient =DifyClientFactory.createDatasetsClient("https://api.dify.ai/v1","your-api-key");// 使用自定义配置创建客户端DifyConfigconfig =DifyConfig.builder()    .baseUrl("https://api.dify.ai/v1")    .apiKey("your-api-key")    .connectTimeout(5000)    .readTimeout(60000)    .writeTimeout(30000)    .build();DifyClientclientWithConfig =DifyClientFactory.createClient(config);

使用示例

1. 对话型应用 (Chat)

阻塞模式

// 创建聊天客户端DifyChatClientchatClient =DifyClientFactory.createChatClient("https://api.dify.ai/v1","your-api-key");// 创建聊天消息ChatMessagemessage =ChatMessage.builder()    .query("你好,请介绍一下自己")    .user("user-123")    .responseMode(ResponseMode.BLOCKING)    .build();// 发送消息并获取响应ChatMessageResponseresponse =chatClient.sendChatMessage(message);System.out.println("回复: " +response.getAnswer());System.out.println("会话ID: " +response.getConversationId());System.out.println("消息ID: " +response.getMessageId());

流式模式

// 创建聊天消息ChatMessagemessage =ChatMessage.builder()    .query("请给我讲一个简短的故事")    .user("user-123")    .responseMode(ResponseMode.STREAMING)    .build();// 发送流式消息chatClient.sendChatMessageStream(message,newChatStreamCallback() {@OverridepublicvoidonMessage(MessageEventevent) {System.out.println("收到消息片段: " +event.getAnswer());    }@OverridepublicvoidonMessageEnd(MessageEndEventevent) {System.out.println("消息结束,完整消息ID: " +event.getMessageId());    }@OverridepublicvoidonError(ErrorEventevent) {System.err.println("错误: " +event.getMessage());    }@OverridepublicvoidonException(Throwablethrowable) {System.err.println("异常: " +throwable.getMessage());    }});

会话管理

// 获取会话历史消息MessageListResponsemessages =chatClient.getMessages(conversationId,"user-123",null,10);// 获取会话列表ConversationListResponseconversations =chatClient.getConversations("user-123",null,10,"-updated_at");// 重命名会话ConversationrenamedConversation =chatClient.renameConversation(conversationId,"新会话名称",false,"user-123");// 删除会话SimpleResponsedeleteResponse =chatClient.deleteConversation(conversationId,"user-123");

消息反馈

// 发送消息反馈(点赞)SimpleResponsefeedbackResponse =chatClient.feedbackMessage(messageId,"like","user-123","这是一个很好的回答");// 获取建议问题SuggestedQuestionsResponsesuggestedQuestions =chatClient.getSuggestedQuestions(messageId,"user-123");

语音转换

// 语音转文字AudioToTextResponsetextResponse =chatClient.audioToText(audioFile,"user-123");System.out.println("转换后的文本: " +textResponse.getText());// 文字转语音byte[]audioData =chatClient.textToAudio(null,"这是一段测试文本","user-123");

2. 文本生成应用 (Completion)

阻塞模式

// 创建文本生成客户端DifyCompletionClientcompletionClient =DifyClientFactory.createCompletionClient("https://api.dify.ai/v1","your-api-key");// 创建请求Map<String,Object>inputs =newHashMap<>();inputs.put("content","茄子");CompletionRequestrequest =CompletionRequest.builder()    .inputs(inputs)    .responseMode(ResponseMode.BLOCKING)    .user("user-123")    .build();// 发送请求并获取响应CompletionResponseresponse =completionClient.sendCompletionMessage(request);System.out.println("生成的文本: " +response.getAnswer());

流式模式

// 创建请求Map<String,Object>inputs =newHashMap<>();inputs.put("content","茄子");CompletionRequestrequest =CompletionRequest.builder()    .inputs(inputs)    .responseMode(ResponseMode.STREAMING)    .user("user-123")    .build();// 发送流式请求completionClient.sendCompletionMessageStream(request,newCompletionStreamCallback() {@OverridepublicvoidonMessage(MessageEventevent) {System.out.println("收到消息片段: " +event.getAnswer());    }@OverridepublicvoidonMessageEnd(MessageEndEventevent) {System.out.println("消息结束,完整消息ID: " +event.getMessageId());    }@OverridepublicvoidonError(ErrorEventevent) {System.err.println("错误: " +event.getMessage());    }@OverridepublicvoidonException(Throwablethrowable) {System.err.println("异常: " +throwable.getMessage());    }});

停止生成

// 停止文本生成SimpleResponsestopResponse =completionClient.stopCompletion(taskId,"user-123");

3. 工作流应用 (Workflow)

阻塞模式

// 创建工作流客户端DifyWorkflowClientworkflowClient =DifyClientFactory.createWorkflowClient("https://api.dify.ai/v1","your-api-key");// 创建工作流请求Map<String,Object>inputs =newHashMap<>();inputs.put("content","请介绍一下人工智能的应用场景");WorkflowRunRequestrequest =WorkflowRunRequest.builder()    .inputs(inputs)    .responseMode(ResponseMode.BLOCKING)    .user("user-123")    .build();// 执行工作流并获取响应WorkflowRunResponseresponse =workflowClient.runWorkflow(request);System.out.println("工作流执行ID: " +response.getTaskId());// 输出结果if (response.getData() !=null) {for (Map.Entry<String,Object>entry :response.getData().getOutputs().entrySet()) {System.out.println(entry.getKey() +": " +entry.getValue());    }}

流式模式

// 创建工作流请求Map<String,Object>inputs =newHashMap<>();inputs.put("content","请详细介绍一下机器学习的基本原理");WorkflowRunRequestrequest =WorkflowRunRequest.builder()    .inputs(inputs)    .responseMode(ResponseMode.STREAMING)    .user("user-123")    .build();// 执行工作流流式请求workflowClient.runWorkflowStream(request,newWorkflowStreamCallback() {@OverridepublicvoidonWorkflowStarted(WorkflowStartedEventevent) {System.out.println("工作流开始: " +event);    }@OverridepublicvoidonNodeStarted(NodeStartedEventevent) {System.out.println("节点开始: " +event);    }@OverridepublicvoidonNodeFinished(NodeFinishedEventevent) {System.out.println("节点完成: " +event);    }@OverridepublicvoidonWorkflowFinished(WorkflowFinishedEventevent) {System.out.println("工作流完成: " +event);    }@OverridepublicvoidonError(ErrorEventevent) {System.err.println("错误: " +event.getMessage());    }@OverridepublicvoidonException(Throwablethrowable) {System.err.println("异常: " +throwable.getMessage());    }});

工作流管理

// 停止工作流WorkflowStopResponsestopResponse =workflowClient.stopWorkflow(taskId,"user-123");// 获取工作流执行情况WorkflowRunStatusResponsestatusResponse =workflowClient.getWorkflowRun(workflowRunId);// 获取工作流日志WorkflowLogsResponselogsResponse =workflowClient.getWorkflowLogs(null,null,1,10);

4. 知识库管理 (Datasets)

创建和管理知识库

// 创建知识库客户端DifyDatasetsClientdatasetsClient =DifyClientFactory.createDatasetsClient("https://api.dify.ai/v1","your-api-key");// 创建知识库CreateDatasetRequestcreateRequest =CreateDatasetRequest.builder()    .name("测试知识库-" +System.currentTimeMillis())    .description("这是一个测试知识库")    .indexingTechnique("high_quality")    .permission("only_me")    .provider("vendor")    .build();DatasetResponsedataset =datasetsClient.createDataset(createRequest);System.out.println("创建的知识库ID: " +dataset.getId());// 获取知识库列表DatasetListResponsedatasetList =datasetsClient.getDatasets(1,10);System.out.println("知识库总数: " +datasetList.getTotal());

文档管理

// 通过文本创建文档 - 使用自动处理模式(推荐)CreateDocumentByTextRequestdocRequest =CreateDocumentByTextRequest.builder()    .name("测试文档-" +System.currentTimeMillis())    .text("这是一个测试文档的内容。\n这是第二行内容。\n这是第三行内容。")    .indexingTechnique("high_quality")    .docForm("text_model")    .docLanguage("Chinese")    .processRule(ProcessRule.builder()        .mode("automatic")// 使用自动处理模式        .build())    .build();DocumentResponsedocResponse =datasetsClient.createDocumentByText(datasetId,docRequest);System.out.println("创建的文档ID: " +docResponse.getDocument().getId());// 获取文档列表DocumentListResponsedocList =datasetsClient.getDocuments(datasetId,null,1,10);System.out.println("文档总数: " +docList.getTotal());// 删除文档SimpleResponsedeleteResponse =datasetsClient.deleteDocument(datasetId,documentId);

知识库检索

// 创建检索请求RetrievalModelretrievalModel =newRetrievalModel();retrievalModel.setTopK(3);retrievalModel.setScoreThreshold(0.5f);RetrieveRequestretrieveRequest =RetrieveRequest.builder()    .query("什么是人工智能")    .retrievalModel(retrievalModel)    .build();// 发送检索请求RetrieveResponseretrieveResponse =datasetsClient.retrieveDataset(datasetId,retrieveRequest);// 处理检索结果System.out.println("检索查询: " +retrieveResponse.getQuery().getContent());System.out.println("检索结果数量: " +retrieveResponse.getRecords().size());retrieveResponse.getRecords().forEach(record -> {System.out.println("分数: " +record.getScore());System.out.println("内容: " +record.getSegment().getContent());});

API 参考

客户端类型

客户端类型描述主要功能
DifyClient完整客户端支持所有API功能
DifyChatClient对话型应用客户端对话、会话管理、消息反馈
DifyCompletionClient文本生成型应用客户端文本生成、停止生成
DifyChatflowClient工作流编排对话型应用客户端工作流编排对话
DifyWorkflowClient工作流应用客户端执行工作流、工作流管理
DifyDatasetsClient知识库客户端知识库管理、文档管理、检索

响应模式

模式枚举值描述
阻塞模式ResponseMode.BLOCKING同步调用,等待完整响应
流式模式ResponseMode.STREAMING通过回调接收实时生成的内容

事件类型

事件类型描述
MessageEvent消息事件,包含生成的文本片段
MessageEndEvent消息结束事件,包含完整消息ID
MessageFileEvent文件消息事件,包含文件信息
TtsMessageEvent文字转语音事件
TtsMessageEndEvent文字转语音结束事件
MessageReplaceEvent消息替换事件
AgentMessageEventAgent消息事件
AgentThoughtEventAgent思考事件
WorkflowStartedEvent工作流开始事件
NodeStartedEvent节点开始事件
NodeFinishedEvent节点完成事件
WorkflowFinishedEvent工作流完成事件
ErrorEvent错误事件
PingEvent心跳事件

高级配置

自定义HTTP客户端

// 创建自定义配置DifyConfigconfig =DifyConfig.builder()    .baseUrl("https://api.dify.ai/v1")    .apiKey("your-api-key")    .connectTimeout(5000)// 连接超时(毫秒)    .readTimeout(60000)// 读取超时(毫秒)    .writeTimeout(30000)// 写入超时(毫秒)    .build();// 使用自定义配置创建客户端DifyClientclient =DifyClientFactory.createClient(config);

更多文档

贡献

欢迎贡献代码、报告问题或提出改进建议。请通过 GitHub Issues 或 Pull Requests 参与项目开发。

许可证

本项目采用Apache License 2.0 许可证。

相关链接

Star History

Star History Chart

About

Dify Java Client 是一个用于与 Dify 平台进行交互的 Java 客户端库。它提供了对 Dify 应用 API 和知识库 API 的完整支持,让 Java 开发者能够轻松地将 Dify 的生成式 AI 能力集成到自己的应用中。

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp