Multi dialogue & formate the response

Wangyanyixiang_branch
Lin 9 months ago
parent b77b3ebca3
commit 09bf09c0ac

@ -13,11 +13,15 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/C-_Program Files_Apache Software Foundation_Tomcat 9.0"/>
<classpathentry kind="lib" path="WebContent/WEB-INF/lib/commons-fileupload-1.4.jar"/>
<classpathentry kind="lib" path="WebContent/WEB-INF/lib/commons-io-2.6.jar"/>
<classpathentry kind="lib" path="WebContent/WEB-INF/lib/json-20240303.jar"/>
<classpathentry kind="lib" path="WebContent/WEB-INF/lib/mysql-connector-java-8.0.16.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v9.0"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

@ -21,7 +21,7 @@ function sendMessage() {
function addMessageToChat(sender, message) {
const messageElement = document.createElement('div');
messageElement.classList.add('message', `${sender}-message`);
messageElement.textContent = message;
messageElement.innerHTML = message; // 使用innerHTML以支持HTML格式
chatHistory.appendChild(messageElement);
chatHistory.scrollTop = chatHistory.scrollHeight;
}
@ -41,10 +41,13 @@ async function callAIAPI(prompt) {
}
const result = await response.json();
const aiResponse = result.output.text;
console.log('API响应:', result); // 添加这行来查看完整的响应
// 直接使用result.text因为服务器返回的JSON结构中text是在顶层
const aiResponse = result.text || '抱歉,我无法理解您的问题。';
addMessageToChat('ai', aiResponse);
} catch (error) {
console.error('Error:', error);
addMessageToChat('ai', '抱歉,出现了一些问题。请稍后再试。');
addMessageToChat('ai', '抱歉,出现了一些问题。请稍后再试123。');
}
}

@ -13,7 +13,7 @@ public class db_conn {
//数据库初始化连接
public db_conn() {
String URL="jdbc:mysql://localhost:3306/fly_ticket?useSSL=false&useUnicode=true&characterEncoding=UTF8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; //数据库名3306
String URL="jdbc:mysql://localhost:3307/fly_ticket?useSSL=false&useUnicode=true&characterEncoding=UTF8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; //数据库名3306
String USER="root"; //数据库用户名
String PWD="123456"; //数据库密码
try{

@ -11,13 +11,14 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONObject;
import java.util.logging.Logger;
import java.util.logging.Level;
public class ChatServlet extends HttpServlet {
private static final String API_KEY = "sk-0ad1eaf5194249439f82698893607bef"; // 请替换为您的实际 API 密钥
private static final String APP_ID = "1d2b00751a914efd84ea4b354fffd962"; // 请替换为您的实际应用 ID
private static final String API_KEY = "sk-0ad1eaf5194249439f82698893607bef"; // 请替换为您的实际 API 密钥
private static final String APP_ID = "1d2b00751a914efd84ea4b354fffd962"; // 请替换为您的实际应用 ID
private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/apps/" + APP_ID + "/completion";
private static final Logger LOGGER = Logger.getLogger(ChatServlet.class.getName());
@ -27,12 +28,17 @@ public class ChatServlet extends HttpServlet {
response.setCharacterEncoding("UTF-8");
String prompt = request.getParameter("prompt");
HttpSession session = request.getSession();
String sessionId = (String) session.getAttribute("chatSessionId");
try {
HttpClient client = HttpClient.newHttpClient();
JSONObject requestBody = new JSONObject();
JSONObject input = new JSONObject();
input.put("prompt", prompt);
if (sessionId != null) {
input.put("session_id", sessionId);
}
requestBody.put("input", input);
requestBody.put("parameters", new JSONObject());
@ -44,38 +50,44 @@ public class ChatServlet extends HttpServlet {
.build();
HttpResponse<String> apiResponse = client.send(apiRequest, HttpResponse.BodyHandlers.ofString());
/*
if (apiResponse.statusCode() == 200) {
PrintWriter out = response.getWriter();
out.print(apiResponse.body());
out.flush();
*/
if (apiResponse.statusCode() == 200) {
String responseBody = apiResponse.body();
String formattedResponse = formatResponse(responseBody); // 格式化响应
JSONObject jsonResponse = new JSONObject(responseBody);
String newSessionId = jsonResponse.getJSONObject("output").getString("session_id");
session.setAttribute("chatSessionId", newSessionId);
String formattedResponse = formatResponse(responseBody);
PrintWriter out = response.getWriter();
out.print(formattedResponse);
out.flush();
} else {
LOGGER.log(Level.SEVERE, "API request failed with status code: " + apiResponse.statusCode());
LOGGER.log(Level.SEVERE, "API请求失败,状态码: " + apiResponse.statusCode());
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("{\"error\":\"API请求失败\"}");
response.getWriter().write("{\"error\":\"API请求失败\"}");
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error in ChatServlet", e);
LOGGER.log(Level.SEVERE, "ChatServlet出错", e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("{\"error\":\"服务器错误: " + e.getMessage() + "\"}");
response.getWriter().write("{\"error\":\"服务器错误: " + e.getMessage() + "\"}");
}
}
// 格式化函数
// 格式化响应
private String formatResponse(String responseBody) {
// 假设responseBody是字符串形式的JSON您可能需要先解析它
// 这里简单示例对字符串进行替换和格式化
return responseBody
.replaceAll("\\*\\*(.*?)\\*\\*", "<strong>$1</strong>") // 加粗文本
.replaceAll("\\n", "<br>") // 替换换行符
.replaceAll("(\\d+\\. )", "<li>$1") // 列表项处理
.replaceAll("\\s+", " "); // 去除多余空白
JSONObject jsonResponse = new JSONObject(responseBody);
String text = jsonResponse.getJSONObject("output").getString("text");
// 格式化文本
text = text.replaceAll("\\*\\*(.*?)\\*\\*", "<strong>$1</strong>") // 加粗文本
.replaceAll("\\n", "<br>") // 替换换行符
.replaceAll("(\\d+\\. )", "<li>$1") // 列表项目
.replaceAll("\\s+", " "); // 去除多余空白
JSONObject formattedResponse = new JSONObject();
formattedResponse.put("text", text);
formattedResponse.put("session_id", jsonResponse.getJSONObject("output").getString("session_id"));
return formattedResponse.toString();
}
}

@ -1,4 +1,4 @@
Manifest-Version: 1.0
Build-Jdk-Spec: 22
Build-Jdk-Spec: 21
Created-By: Maven Integration for Eclipse

@ -1,7 +1,7 @@
#Generated by Maven Integration for Eclipse
#Tue Oct 22 14:56:12 CST 2024
#Sat Oct 26 20:26:49 CST 2024
artifactId=air_ticket_book
groupId=air_ticket_book
m2e.projectLocation=C\:\\Users\\RichardWang\\Desktop\\ai_agent
m2e.projectLocation=D\:\\college\\SE2\\air_ticket_book-master\\\u8F6F\u4EF6\u5DE5\u7A0B\u8BFE\u7A0B\u8BBE\u8BA1\\air_ticket_book
m2e.projectName=air_ticket_book
version=0.0.1-SNAPSHOT

Loading…
Cancel
Save