├── src
├── main
│ └── java
│ │ └── ai
│ │ └── dify
│ │ └── javaclient
│ │ ├── http
│ │ └── DifyRoute.java
│ │ ├── constants
│ │ └── DifyServerConstants.java
│ │ ├── DifyClientException.java
│ │ ├── CompletionClient.java
│ │ ├── DifyClient.java
│ │ └── ChatClient.java
└── test
│ └── java
│ └── ai
│ └── dify
│ └── javaclient
│ ├── CompletionClientTest.java
│ ├── DifyClientTest.java
│ └── ChatClientTest.java
├── .gitignore
├── LICENSE
├── pom.xml
└── README.md
/src/main/java/ai/dify/javaclient/http/DifyRoute.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient.http;
2 |
3 | /**
4 | * @author Ziyao_Zhu
5 | */
6 | public class DifyRoute {
7 | public String method;
8 | public String url;
9 |
10 | public DifyRoute(String method, String url) {
11 | this.method = method;
12 | this.url = url;
13 | }
14 | }
--------------------------------------------------------------------------------
/src/main/java/ai/dify/javaclient/constants/DifyServerConstants.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient.constants;
2 |
3 | /**
4 | * This class contains constant values related to the Dify server configuration.
5 | * It provides a centralized place to manage server-related constants, such as the base URL of the Dify API.
6 | */
7 | public class DifyServerConstants {
8 | /**
9 | * The base URL of the Dify API.
10 | */
11 | public static final String BASE_URL = "https://api.dify.ai/v1";
12 | }
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | !**/src/main/**/target/
4 | !**/src/test/**/target/
5 | .mvn/
6 | mvnw
7 | mvnw.cmd
8 |
9 | .fleet/
10 | .DS_Store
11 |
12 | ### STS ###
13 | .apt_generated
14 | .classpath
15 | .factorypath
16 | .project
17 | .settings
18 | .springBeans
19 | .sts4-cache
20 |
21 | ### IntelliJ IDEA ###
22 | .idea
23 | *.iws
24 | *.iml
25 | *.ipr
26 |
27 | ### NetBeans ###
28 | /nbproject/private/
29 | /nbbuild/
30 | /dist/
31 | /nbdist/
32 | /.nb-gradle/
33 | build/
34 | !**/src/main/**/build/
35 | !**/src/test/**/build/
36 |
37 | ### VS Code ###
38 | .vscode/
39 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Katy Tao
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/main/java/ai/dify/javaclient/DifyClientException.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient;
2 |
3 | /**
4 | * This exception class represents a general exception that may occur while using the Dify API client.
5 | * It is used to handle errors related to the Dify API interactions.
6 | */
7 | public class DifyClientException extends Exception{
8 | /**
9 | * Constructs a new DifyClientException with the provided error message.
10 | *
11 | * @param message The error message describing the reason for the exception.
12 | */
13 | public DifyClientException(String message) {
14 | super(message);
15 | }
16 | }
17 | /**
18 | * This exception class represents an exception that occurs specifically during Dify API request operations.
19 | * It is used to handle errors related to sending requests to the Dify API.
20 | */
21 | class DifyRequestException extends DifyClientException {
22 | /**
23 | * Constructs a new DifyRequestException with the provided error message.
24 | *
25 | * @param message The error message describing the reason for the request exception.
26 | */
27 | public DifyRequestException(String message) {
28 | super(message);
29 | }
30 | }
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | ai.dify
8 | java-client
9 | 1.0.0
10 |
11 |
12 | 17
13 | 17
14 | UTF-8
15 |
16 |
17 |
18 | com.squareup.okhttp3
19 | okhttp
20 | 4.9.1
21 |
22 |
23 |
24 | com.alibaba.fastjson2
25 | fastjson2
26 | 2.0.34
27 |
28 |
29 | org.junit.jupiter
30 | junit-jupiter
31 | 5.8.1
32 | test
33 |
34 |
35 |
36 | org.mockito
37 | mockito-core
38 | 5.4.0
39 | test
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/src/main/java/ai/dify/javaclient/CompletionClient.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient;
2 |
3 | import okhttp3.*;
4 | import com.alibaba.fastjson2.JSONObject;
5 |
6 | /**
7 | * This class represents a client for interacting with the Dify Completion API.
8 | * It provides methods for creating completion messages using the API.
9 | */
10 | public class CompletionClient extends DifyClient {
11 | /**
12 | * Constructs a new CompletionClient with the provided API key.
13 | *
14 | * @param apiKey The API key to use for authentication.
15 | */
16 | public CompletionClient(String apiKey) {
17 | super(apiKey);
18 | }
19 | /**
20 | * Constructs a new CompletionClient with the provided API key and base URL.
21 | *
22 | * @param apiKey The API key to use for authentication.
23 | * @param baseUrl The base URL of the Dify API.
24 | */
25 | public CompletionClient(String apiKey, String baseUrl) {
26 | super(apiKey, baseUrl);
27 | }
28 |
29 | /**
30 | * Creates a new completion message.
31 | *
32 | * @param inputs The input text for which completion is requested.
33 | * @param query The query associated with the completion request.
34 | * @param user The user associated with the completion request.
35 | * @param stream Whether to use streaming response mode.
36 | * @return The HTTP response containing the result of the API request.
37 | * @throws DifyClientException If an error occurs while sending the request.
38 | */
39 | public Response createCompletionMessage(String inputs, String query, String user, boolean stream) throws DifyClientException {
40 | JSONObject json = new JSONObject();
41 | json.put("inputs", inputs);
42 | json.put("query", query);
43 | json.put("user", user);
44 | json.put("response_mode", stream ? "streaming" : "blocking");
45 |
46 | return sendRequest(CREATE_COMPLETION_MESSAGE, null, createJsonPayload(json));
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/test/java/ai/dify/javaclient/CompletionClientTest.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient;
2 |
3 | import okhttp3.*;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 | import org.mockito.Mock;
7 | import org.mockito.MockitoAnnotations;
8 |
9 | import java.io.IOException;
10 |
11 | import static org.mockito.Mockito.*;
12 |
13 | /**
14 | * This class contains unit tests for the CompletionClient class, focusing on its methods and interactions.
15 | */
16 | class CompletionClientTest {
17 |
18 | private static final String TEST_API_KEY = "testApiKey";
19 | private static final String TEST_BASE_URL = "http://testBaseUrl";
20 | private CompletionClient completionClient;
21 |
22 | @Mock
23 | private OkHttpClient mockClient;
24 |
25 | @Mock
26 | private Call mockCall;
27 |
28 | @Mock
29 | private Response mockResponse;
30 |
31 | /**
32 | * Sets up the test environment before each test case.
33 | *
34 | * @throws IOException If an I/O error occurs.
35 | */
36 | @BeforeEach
37 | public void setUp() throws IOException {
38 | MockitoAnnotations.openMocks(this);
39 | when(mockClient.newCall(any(Request.class))).thenReturn(mockCall);
40 | when(mockCall.execute()).thenReturn(mockResponse);
41 | completionClient = new CompletionClient(TEST_API_KEY, TEST_BASE_URL);
42 |
43 | // Inject mock OkHttpClient using reflection
44 | try {
45 | java.lang.reflect.Field clientField = DifyClient.class.getDeclaredField("client");
46 | clientField.setAccessible(true);
47 | clientField.set(completionClient, mockClient);
48 | } catch (Exception e) {
49 | throw new RuntimeException(e);
50 | }
51 | }
52 |
53 | /**
54 | * Tests the createCompletionMessage method of the CompletionClient class.
55 | *
56 | * @throws Exception If an error occurs during the test.
57 | */
58 | @Test
59 | public void testCreateCompletionMessage() throws Exception {
60 | when(mockResponse.isSuccessful()).thenReturn(true);
61 |
62 | completionClient.createCompletionMessage("testInputs", "testQuery", "testUser", true);
63 |
64 | verify(mockClient).newCall(any(Request.class));
65 | verify(mockCall).execute();
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/test/java/ai/dify/javaclient/DifyClientTest.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient;
2 |
3 | import okhttp3.*;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 | import org.mockito.Mock;
7 | import org.mockito.MockitoAnnotations;
8 |
9 | import java.io.IOException;
10 |
11 | import static org.mockito.Mockito.*;
12 |
13 | /**
14 | * This class contains unit tests for the DifyClient class, focusing on its methods and interactions.
15 | */
16 | class DifyClientTest {
17 |
18 | private static final String TEST_API_KEY = "testApiKey";
19 | private static final String TEST_BASE_URL = "http://testBaseUrl";
20 | private DifyClient difyClient;
21 |
22 | @Mock
23 | private OkHttpClient mockClient;
24 |
25 | @Mock
26 | private Call mockCall;
27 |
28 | @Mock
29 | private Response mockResponse;
30 |
31 | /**
32 | * Sets up the test environment before each test case.
33 | *
34 | * @throws IOException If an I/O error occurs.
35 | */
36 | @BeforeEach
37 | public void setUp() throws IOException {
38 | MockitoAnnotations.openMocks(this);
39 | when(mockClient.newCall(any(Request.class))).thenReturn(mockCall);
40 | when(mockCall.execute()).thenReturn(mockResponse);
41 | difyClient = new DifyClient(TEST_API_KEY, TEST_BASE_URL);
42 | // Use reflection to inject the mock client into the DifyClient
43 | // Alternatively, consider adding a constructor to accept the OkHttpClient
44 | try {
45 | java.lang.reflect.Field clientField = DifyClient.class.getDeclaredField("client");
46 | clientField.setAccessible(true);
47 | clientField.set(difyClient, mockClient);
48 | } catch (Exception e) {
49 | throw new RuntimeException(e);
50 | }
51 | }
52 |
53 | /**
54 | * Tests the getApplicationParameters method of the DifyClient class.
55 | *
56 | * @throws Exception If an error occurs during the test.
57 | */
58 | @Test
59 | public void testGetApplicationParameters() throws Exception {
60 | when(mockResponse.isSuccessful()).thenReturn(true);
61 | String testUser = "user123";
62 |
63 | difyClient.getApplicationParameters(testUser);
64 |
65 | verify(mockClient).newCall(any(Request.class));
66 | verify(mockCall).execute();
67 | }
68 |
69 | /**
70 | * Tests the messageFeedback method of the DifyClient class.
71 | *
72 | * @throws Exception If an error occurs during the test.
73 | */
74 | @Test
75 | public void testMessageFeedback() throws Exception {
76 | when(mockResponse.isSuccessful()).thenReturn(true);
77 |
78 | difyClient.messageFeedback("12345", "good", "user123");
79 |
80 | verify(mockClient).newCall(any(Request.class));
81 | verify(mockCall).execute();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Dify Java SDK
2 | This is the Java SDK for the Dify API, which allows you to seamlessly integrate Dify into your Java applications.
3 |
4 | ## Installation
5 |
6 | Please ensure that you have included the necessary dependencies in your project, such as `fastjson2`, `okhttp3`, etc. You can use Maven, Gradle, or any other dependency management tool of your choice. The SDK itself can be included once it is published to a package repository.
7 |
8 | For the sake of this README, let's assume the SDK is available on Maven Central:
9 |
10 | ```xml
11 |
12 | ai.dify
13 | java-client
14 | 1.0.0
15 |
16 | ```
17 |
18 | ## Usage
19 | Once the SDK is installed, you can use it in your project as follows:
20 |
21 | ```java
22 | import ai.dify.javaclient.DifyClient;
23 | import ai.dify.javaclient.ChatClient;
24 | import ai.dify.javaclient.CompletionClient;
25 | import okhttp3.Response;
26 |
27 | public class DifyApp {
28 |
29 | private static final String API_KEY = "your-api-key-here";
30 |
31 | public static void main(String[] args) {
32 | try {
33 | String user = "random-user-id";
34 | String inputs = "{\"name\":\"test name a\"}";
35 | String query = "Please tell me a short story in 10 words or less.";
36 | boolean responseMode = true;
37 |
38 | // Create a completion client
39 | CompletionClient completionClient = new CompletionClient(API_KEY);
40 | Response completionResponse = completionClient.createCompletionMessage(inputs, query, user, responseMode);
41 | System.out.println(completionResponse.body().string());
42 |
43 | // Create a chat client
44 | ChatClient chatClient = new ChatClient(API_KEY);
45 | // Create a chat message
46 | Response chatResponse = chatClient.createChatMessage(inputs, query, user, true, null);
47 | System.out.println(chatResponse.body().string());
48 |
49 | // Fetch conversations
50 | chatClient.getConversations(user);
51 | // Rename conversation
52 | String conversationId = "example-conversation-id";
53 | String name = "new-name";
54 | chatClient.renameConversation(conversationId, name, user);
55 |
56 | // And so on for other methods...
57 |
58 | DifyClient client = new DifyClient(API_KEY);
59 | // Fetch application parameters
60 | client.getApplicationParameters(user);
61 |
62 | // Provide feedback for a message
63 | String messageId = "your-message-id";
64 | String rating = "5";
65 | client.messageFeedback(messageId, rating, user);
66 |
67 | } catch (Exception e) {
68 | e.printStackTrace();
69 | }
70 | }
71 | }
72 | ```
73 |
74 | Replace `'your-api-key-here'` with your actual Dify API key.
75 |
76 | ## License
77 | This SDK is released under the MIT License.
78 |
--------------------------------------------------------------------------------
/src/test/java/ai/dify/javaclient/ChatClientTest.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient;
2 |
3 | import okhttp3.*;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 | import org.mockito.Mock;
7 | import org.mockito.MockitoAnnotations;
8 |
9 | import java.io.IOException;
10 |
11 | import static org.mockito.Mockito.*;
12 |
13 | /**
14 | * This class contains unit tests for the ChatClient class, focusing on its methods and interactions.
15 | */
16 | class ChatClientTest {
17 |
18 | private static final String TEST_API_KEY = "testApiKey";
19 | private static final String TEST_BASE_URL = "http://testBaseUrl";
20 | private ChatClient chatClient;
21 |
22 | @Mock
23 | private OkHttpClient mockClient;
24 |
25 | @Mock
26 | private Call mockCall;
27 |
28 | @Mock
29 | private Response mockResponse;
30 |
31 | /**
32 | * Sets up the test environment before each test case.
33 | *
34 | * @throws IOException If an I/O error occurs.
35 | */
36 | @BeforeEach
37 | public void setUp() throws IOException {
38 | MockitoAnnotations.openMocks(this);
39 | when(mockClient.newCall(any(Request.class))).thenReturn(mockCall);
40 | when(mockCall.execute()).thenReturn(mockResponse);
41 | chatClient = new ChatClient(TEST_API_KEY, TEST_BASE_URL);
42 |
43 | // Inject mock OkHttpClient using reflection
44 | try {
45 | java.lang.reflect.Field clientField = DifyClient.class.getDeclaredField("client");
46 | clientField.setAccessible(true);
47 | clientField.set(chatClient, mockClient);
48 | } catch (Exception e) {
49 | throw new RuntimeException(e);
50 | }
51 | }
52 |
53 | /**
54 | * Tests the createChatMessage method of the ChatClient class.
55 | *
56 | * @throws Exception If an error occurs during the test.
57 | */
58 | @Test
59 | public void testCreateChatMessage() throws Exception {
60 | when(mockResponse.isSuccessful()).thenReturn(true);
61 |
62 | chatClient.createChatMessage("testInputs", "testQuery", "testUser", true, "conversation123");
63 |
64 | verify(mockClient).newCall(any(Request.class));
65 | verify(mockCall).execute();
66 | }
67 |
68 | /**
69 | * Tests the getConversationMessages method of the ChatClient class.
70 | *
71 | * @throws Exception If an error occurs during the test.
72 | */
73 | @Test
74 | public void testGetConversationMessages() throws Exception {
75 | when(mockResponse.isSuccessful()).thenReturn(true);
76 |
77 | chatClient.getConversationMessages("testUser", "conversation123", "firstId123", 5);
78 |
79 | verify(mockClient).newCall(any(Request.class));
80 | verify(mockCall).execute();
81 | }
82 |
83 |
84 | /**
85 | * Tests the getConversations method of the ChatClient class.
86 | *
87 | * @throws Exception If an error occurs during the test.
88 | */
89 | @Test
90 | public void testGetConversations() throws Exception {
91 | when(mockResponse.isSuccessful()).thenReturn(true);
92 |
93 | chatClient.getConversations("testUser", "firstId123", 5, "yes");
94 |
95 | verify(mockClient).newCall(any(Request.class));
96 | verify(mockCall).execute();
97 | }
98 |
99 | /**
100 | * Tests the renameConversation method of the ChatClient class.
101 | *
102 | * @throws Exception If an error occurs during the test.
103 | */
104 | @Test
105 | public void testRenameConversation() throws Exception {
106 | when(mockResponse.isSuccessful()).thenReturn(true);
107 |
108 | chatClient.renameConversation("conversation123", "newName", "testUser");
109 |
110 | verify(mockClient).newCall(any(Request.class));
111 | verify(mockCall).execute();
112 | }
113 |
114 | /**
115 | * Tests the deleteConversation method of the ChatClient class.
116 | *
117 | * @throws Exception If an error occurs during the test.
118 | */
119 | @Test
120 | public void testDeleteConversation() throws Exception {
121 | when(mockResponse.isSuccessful()).thenReturn(true);
122 |
123 | chatClient.deleteConversation("conversation123", "testUser");
124 |
125 | verify(mockClient).newCall(any(Request.class));
126 | verify(mockCall).execute();
127 | }
128 |
129 | }
130 |
--------------------------------------------------------------------------------
/src/main/java/ai/dify/javaclient/DifyClient.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient;
2 |
3 | import ai.dify.javaclient.constants.DifyServerConstants;
4 | import ai.dify.javaclient.http.DifyRoute;
5 | import com.alibaba.fastjson2.JSONObject;
6 | import okhttp3.*;
7 |
8 | import java.io.IOException;
9 | /**
10 | * This class serves as a client for interacting with the Dify API.
11 | * It provides methods for sending various types of requests to the API.
12 | */
13 | public class DifyClient {
14 |
15 | // Constants representing different API routes
16 | public static final DifyRoute APPLICATION = new DifyRoute("GET", "/parameters?user=%s");
17 | public static final DifyRoute FEEDBACK = new DifyRoute("POST", "/messages/%s/feedbacks");
18 | public static final DifyRoute CREATE_COMPLETION_MESSAGE = new DifyRoute("POST", "/completion-messages");
19 | public static final DifyRoute CREATE_CHAT_MESSAGE = new DifyRoute("POST", "/chat-messages");
20 | public static final DifyRoute GET_CONVERSATION_MESSAGES = new DifyRoute("GET", "/messages?%s");
21 | public static final DifyRoute GET_CONVERSATIONS = new DifyRoute("GET", "/conversations");
22 | public static final DifyRoute RENAME_CONVERSATION = new DifyRoute("PATCH", "/conversations/%s");
23 | public static final DifyRoute DELETE_CONVERSATION = new DifyRoute("DELETE", "/conversations/%s");
24 |
25 | private String apiKey;
26 | private final String baseUrl;
27 | private final OkHttpClient client;
28 |
29 | /**
30 | * Constructs a new DifyClient with the provided API key and default base URL.
31 | *
32 | * @param apiKey The API key to use for authentication.
33 | */
34 | public DifyClient(String apiKey) {
35 | this(apiKey, DifyServerConstants.BASE_URL);
36 | }
37 |
38 | /**
39 | * Constructs a new DifyClient with the provided API key and base URL.
40 | *
41 | * @param apiKey The API key to use for authentication.
42 | * @param baseUrl The base URL of the Dify API.
43 | */
44 | public DifyClient(String apiKey, String baseUrl) {
45 | this.apiKey = apiKey;
46 | this.baseUrl = baseUrl;
47 | this.client = new OkHttpClient();
48 | }
49 |
50 | /**
51 | * Updates the API key used for authentication.
52 | *
53 | * @param apiKey The new API key.
54 | */
55 | public void updateApiKey(String apiKey) {
56 | this.apiKey = apiKey;
57 | }
58 |
59 |
60 | /**
61 | * Sends an HTTP request to the Dify API.
62 | *
63 | * @param route The API route to send the request to.
64 | * @param formatArgs Format arguments for route URL placeholders.
65 | * @param body The request body, if applicable.
66 | * @return The HTTP response containing the result of the API request.
67 | * @throws DifyClientException If an error occurs while sending the request.
68 | */
69 | public Response sendRequest(DifyRoute route, String[] formatArgs, RequestBody body) throws DifyClientException {
70 | try {
71 | String formattedURL = (formatArgs != null && formatArgs.length > 0)
72 | ? String.format(route.url, (Object[]) formatArgs)
73 | : route.url;
74 |
75 | Request request = new Request.Builder()
76 | .url(baseUrl + formattedURL)
77 | .method(route.method, body)
78 | .addHeader("Authorization", "Bearer " + apiKey)
79 | .addHeader("Content-Type", "application/json")
80 | .build();
81 |
82 | Response response = client.newCall(request).execute();
83 | if (!response.isSuccessful()) {
84 | throw new DifyRequestException("Request failed with status: " + response.code());
85 | }
86 | return response;
87 | } catch (IOException e) {
88 | throw new DifyClientException("Error occurred while sending request: " + e.getMessage());
89 | }
90 | }
91 |
92 |
93 | /**
94 | * Sends a message feedback to the Dify API.
95 | *
96 | * @param messageId The ID of the message to provide feedback for.
97 | * @param rating The feedback rating.
98 | * @param user The user providing the feedback.
99 | * @return The HTTP response containing the result of the API request.
100 | * @throws DifyClientException If an error occurs while sending the request.
101 | */
102 | public Response messageFeedback(String messageId, String rating, String user) throws DifyClientException {
103 | JSONObject json = new JSONObject();
104 | json.put("rating", rating);
105 | json.put("user", user);
106 |
107 | return sendRequest(FEEDBACK, new String[]{messageId}, createJsonPayload(json));
108 | }
109 |
110 | /**
111 | * Retrieves application parameters from the Dify API.
112 | *
113 | * @param user The user for whom the application parameters are retrieved.
114 | * @return The HTTP response containing the result of the API request.
115 | * @throws DifyClientException If an error occurs while sending the request.
116 | */
117 | public Response getApplicationParameters(String user) throws DifyClientException {
118 | return sendRequest(APPLICATION, new String[]{user}, null);
119 | }
120 |
121 | /**
122 | * Creates a request body with the given JSON object.
123 | *
124 | * @param jsonObject The JSON object to be used in the request body.
125 | * @return The created request body.
126 | */
127 | RequestBody createJsonPayload(JSONObject jsonObject) {
128 | return RequestBody.create(jsonObject.toJSONString(), MediaType.parse("application/json"));
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/src/main/java/ai/dify/javaclient/ChatClient.java:
--------------------------------------------------------------------------------
1 | package ai.dify.javaclient;
2 |
3 | import com.alibaba.fastjson2.JSONObject;
4 | import okhttp3.*;
5 |
6 | import java.util.ArrayList;
7 | import java.util.HashMap;
8 | import java.util.List;
9 | import java.util.Map;
10 |
11 | /**
12 | * This class represents a client for interacting with the Dify Chat API.
13 | * It provides methods for creating, retrieving, and managing chat messages and conversations.
14 | */
15 | public class ChatClient extends DifyClient {
16 |
17 | /**
18 | * Constructs a new ChatClient with the provided API key.
19 | *
20 | * @param apiKey The API key to use for authentication.
21 | */
22 | public ChatClient(String apiKey) {
23 | super(apiKey);
24 | }
25 |
26 | /**
27 | * Constructs a new ChatClient with the provided API key and base URL.
28 | *
29 | * @param apiKey The API key to use for authentication.
30 | * @param baseUrl The base URL of the Dify API.
31 | */
32 | public ChatClient(String apiKey, String baseUrl) {
33 | super(apiKey, baseUrl);
34 | }
35 |
36 | /**
37 | * Generates query parameters in the form of key-value pairs joined by "&".
38 | *
39 | * @param params The map of query parameter key-value pairs.
40 | * @return A string representation of the generated query parameters.
41 | */
42 | private String generateQueryParams(Map params) {
43 | List keyValuePairs = new ArrayList<>();
44 | for (Map.Entry entry : params.entrySet()) {
45 | keyValuePairs.add(entry.getKey() + "=" + entry.getValue());
46 | }
47 | return String.join("&", keyValuePairs);
48 | }
49 |
50 | /**
51 | * Creates a new chat message.
52 | *
53 | * @param inputs The chat message inputs.
54 | * @param query The query associated with the chat message.
55 | * @param user The user associated with the chat message.
56 | * @param stream Whether to use streaming response mode.
57 | * @param conversation_id The ID of the conversation, if applicable.
58 | * @return The HTTP response containing the result of the API request.
59 | * @throws DifyClientException If an error occurs while sending the request.
60 | */
61 | public Response createChatMessage(String inputs, String query, String user, boolean stream, String conversation_id) throws DifyClientException {
62 | JSONObject json = new JSONObject();
63 | json.put("inputs", inputs);
64 | json.put("query", query);
65 | json.put("user", user);
66 | json.put("response_mode", stream ? "streaming" : "blocking");
67 | if (conversation_id != null && !conversation_id.isEmpty()) {
68 | json.put("conversation_id", conversation_id);
69 | }
70 |
71 | return sendRequest(CREATE_CHAT_MESSAGE, null, createJsonPayload(json));
72 | }
73 |
74 | /**
75 | * Retrieves conversation messages.
76 | *
77 | * @param user The user associated with the conversation.
78 | * @param conversation_id The ID of the conversation.
79 | * @param first_id The ID of the first message to start fetching from.
80 | * @param limit The maximum number of messages to retrieve.
81 | * @return The HTTP response containing the result of the API request.
82 | * @throws DifyClientException If an error occurs while sending the request.
83 | */
84 | public Response getConversationMessages(String user, String conversation_id, String first_id, int limit) throws DifyClientException {
85 | Map queryParams = new HashMap<>();
86 | queryParams.put("user", user);
87 |
88 | if (conversation_id != null) {
89 | queryParams.put("conversation_id", conversation_id);
90 | }
91 | if (first_id != null) {
92 | queryParams.put("first_id", first_id);
93 | }
94 | if (limit > 0) {
95 | queryParams.put("limit", String.valueOf(limit));
96 | }
97 | String formattedQueryParams = generateQueryParams(queryParams);
98 |
99 | return sendRequest(GET_CONVERSATION_MESSAGES, new String[] {formattedQueryParams}, null);
100 | }
101 |
102 | /**
103 | * Retrieves conversations.
104 | *
105 | * @param user The user associated with the conversations.
106 | * @param first_id The ID of the first conversation to start fetching from.
107 | * @param limit The maximum number of conversations to retrieve.
108 | * @param pinned The pinned status of conversations to retrieve.
109 | * @return The HTTP response containing the result of the API request.
110 | * @throws DifyClientException If an error occurs while sending the request.
111 | */
112 | public Response getConversations(String user, String first_id, int limit, String pinned) throws DifyClientException {
113 | Map queryParams = new HashMap<>();
114 | queryParams.put("user", user);
115 | if (first_id != null && !first_id.isEmpty()) {
116 | queryParams.put("first_id", first_id);
117 | }
118 | if (limit > 0) {
119 | queryParams.put("limit", String.valueOf(limit));
120 | }
121 | if (pinned != null && !pinned.isEmpty()) {
122 | queryParams.put("pinned", pinned);
123 | }
124 | String formattedQueryParams = generateQueryParams(queryParams);
125 | return sendRequest(GET_CONVERSATIONS, new String[] {formattedQueryParams}, null);
126 | }
127 |
128 | /**
129 | * Renames a conversation.
130 | *
131 | * @param conversation_id The ID of the conversation to rename.
132 | * @param name The new name for the conversation.
133 | * @param user The user associated with the conversation.
134 | * @return The HTTP response containing the result of the API request.
135 | * @throws DifyClientException If an error occurs while sending the request.
136 | */
137 | public Response renameConversation(String conversation_id, String name, String user) throws DifyClientException {
138 | JSONObject json = new JSONObject();
139 | json.put("name", name);
140 | json.put("user", user);
141 |
142 | return sendRequest(RENAME_CONVERSATION, new String[]{conversation_id}, createJsonPayload(json));
143 | }
144 |
145 | /**
146 | * Deletes a conversation.
147 | *
148 | * @param conversation_id The ID of the conversation to delete.
149 | * @param user The user associated with the conversation.
150 | * @return The HTTP response containing the result of the API request.
151 | * @throws DifyClientException If an error occurs while sending the request.
152 | */
153 | public Response deleteConversation(String conversation_id, String user) throws DifyClientException {
154 | JSONObject json = new JSONObject();
155 | json.put("user", user);
156 |
157 | return sendRequest(DELETE_CONVERSATION, new String[]{conversation_id}, createJsonPayload(json));
158 | }
159 | }
160 |
161 |
--------------------------------------------------------------------------------