From c1ae2790879ace37b69b4a902a011f9216e9d49f Mon Sep 17 00:00:00 2001 From: mengshuo Date: Mon, 15 Jul 2024 15:37:15 +0800 Subject: [PATCH] fix: DifyRequestException Request failed with status: 400 --- src/main/java/ai/dify/javaclient/ChatClient.java | 9 +++++++-- src/test/java/ai/dify/javaclient/ChatClientTest.java | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/ai/dify/javaclient/ChatClient.java b/src/main/java/ai/dify/javaclient/ChatClient.java index 9eae123..73efc71 100644 --- a/src/main/java/ai/dify/javaclient/ChatClient.java +++ b/src/main/java/ai/dify/javaclient/ChatClient.java @@ -1,5 +1,6 @@ package ai.dify.javaclient; +import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import okhttp3.*; @@ -50,7 +51,7 @@ private String generateQueryParams(Map params) { /** * Creates a new chat message. * - * @param inputs The chat message inputs. + * @param inputs The chat message inputs. Must be a valid JSON object str. * @param query The query associated with the chat message. * @param user The user associated with the chat message. * @param stream Whether to use streaming response mode. @@ -59,8 +60,12 @@ private String generateQueryParams(Map params) { * @throws DifyClientException If an error occurs while sending the request. */ public Response createChatMessage(String inputs, String query, String user, boolean stream, String conversation_id) throws DifyClientException { + assert JSON.isValidObject(inputs); + assert query != null && !query.isEmpty(); + assert user != null ; + JSONObject json = new JSONObject(); - json.put("inputs", inputs); + json.put("inputs", JSON.parseObject(inputs)); json.put("query", query); json.put("user", user); json.put("response_mode", stream ? "streaming" : "blocking"); diff --git a/src/test/java/ai/dify/javaclient/ChatClientTest.java b/src/test/java/ai/dify/javaclient/ChatClientTest.java index 9edc9eb..409878e 100644 --- a/src/test/java/ai/dify/javaclient/ChatClientTest.java +++ b/src/test/java/ai/dify/javaclient/ChatClientTest.java @@ -59,7 +59,7 @@ public void setUp() throws IOException { public void testCreateChatMessage() throws Exception { when(mockResponse.isSuccessful()).thenReturn(true); - chatClient.createChatMessage("testInputs", "testQuery", "testUser", true, "conversation123"); + chatClient.createChatMessage("{}", "testQuery", "testUser", true, "conversation123"); verify(mockClient).newCall(any(Request.class)); verify(mockCall).execute();