Commit d2f8d7c9 authored by 高如斌's avatar 高如斌

Merge branch 'develop_tmp' into 'feature/chat-form'

Develop tmp

See merge request !7
parents a2b3a8c8 1ff00b03
......@@ -338,6 +338,16 @@
<artifactId>lombok</artifactId>
</exclude>
</excludes>
<requiresUnpack>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>driver</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>driver-bundle</artifactId>
</dependency>
</requiresUnpack>
</configuration>
</plugin>
......
......@@ -125,29 +125,26 @@ public class DefaultReactExecutor implements ReactExecutor {
List<org.springframework.ai.chat.messages.Message> messages = new ArrayList<>();
messages.add(new SystemMessage(systemPrompt));
if (!newChat) {
if (agent != null) {
try {
// 如果没有提供用户ID,则尝试获取当前用户ID
if (userId == null) {
userId = UserUtils.getCurrentUserIdStatic();
}
String sessionId = memoryService.generateSessionId(agent, userId);
if (agent != null) {
try {
// 如果没有提供用户ID,则尝试获取当前用户ID
if (userId == null) {
userId = UserUtils.getCurrentUserIdStatic();
}
String sessionId = memoryService.generateSessionId(agent, userId);
int historyLength = agent.getHistoryLength() != null ? agent.getHistoryLength() : 10;
int historyLength = agent.getHistoryLength() != null ? agent.getHistoryLength() : 10;
List<org.springframework.ai.chat.messages.Message> historyMessages =
memoryService.getHistoryMessages(sessionId, historyLength);
if (!newChat) {
List<org.springframework.ai.chat.messages.Message> historyMessages =
memoryService.getHistoryMessages(sessionId, historyLength);
messages.addAll(historyMessages);
memoryService.addUserMessageToMemory(sessionId, userInput);
} catch (Exception e) {
log.warn("获取历史对话记录时发生错误: {}", e.getMessage());
}
memoryService.addUserMessageToMemory(sessionId, userInput);
} catch (Exception e) {
log.warn("获取历史对话记录时发生错误: {}", e.getMessage());
}
}
messages.add(new UserMessage(userInput));
for (Message message : messages) {
log.info("message is {}", message);
......@@ -179,13 +176,17 @@ public class DefaultReactExecutor implements ReactExecutor {
log.info("agentTools {}", agentTools);
if (agent.getId().compareToIgnoreCase("agent-8") == 0) {
if (!chatService.chatExists(tmpUserId, agent.getId())) {
log.info("new chat for {} {} ", userId, agent.getId());
prompt = buildPromptWithHistory(defaultSystemPrompt, userInput, agent, tmpUserId, true);
boolean chatExists = chatService.chatExists(tmpUserId, agent.getId());
String newChat = "yes";
if(chatExists){
newChat = "no";
}
// log.info("new chat for {} {} ", userId, agent.getId());
prompt = buildPromptWithHistory(agent.getSystemPrompt(), userInput, agent, tmpUserId, true);
//}
chatClient.prompt(prompt)
.tools(agentTools.toArray())
.toolContext(Map.of("emitterId", emitterId, "userId", sseTokenEmitter.getUserId(),"agentId",agent.getId()))
.toolContext(Map.of("emitterId", emitterId, "userId", sseTokenEmitter.getUserId(), "agentId", agent.getId(),"newChat",newChat))
.stream()
.chatResponse()
.subscribe(
......
......@@ -75,7 +75,7 @@ public class VisitorAppointmentTool {
// 登录状态有效期(毫秒),设置为30分钟
private static final long LOGIN_VALIDITY_PERIOD = 30 * 60 * 1000;
public VisitorAppointmentTool(UserTokenService userTokenService,AgentService agentService, InfoCollectorService infoCollectorService, UserSseService userSseService,ChatService chatService) {
public VisitorAppointmentTool(UserTokenService userTokenService, AgentService agentService, InfoCollectorService infoCollectorService, UserSseService userSseService, ChatService chatService) {
this.agentService = agentService;
this.infoCollectorService = infoCollectorService;
this.ssoToken = "33f667865c395f164d29487c15fe74bf76b463f2941ef6af55d14a35a11d60b1";
......@@ -141,10 +141,11 @@ public class VisitorAppointmentTool {
log.error("海信SSO认证工具的Playwright资源释放失败: ", e);
}
}
private String setAccessToken(ToolContext toolContext) {
String userId = toolContext.getContext().get("userId").toString();
log.info("start set access token for {}", userId);
UserToken userToken = userTokenService.getUserToken(userId,"pangea");
UserToken userToken = userTokenService.getUserToken(userId, "pangea");
Cookie tripCookie = new Cookie("jwtToken", userToken.getTokenValue());
tripCookie.setDomain("vrms-proxy.hisense.com");
tripCookie.setPath("/");
......@@ -165,8 +166,6 @@ public class VisitorAppointmentTool {
// .setSources(true));
log.info("submit apply info ");
String accessToken = setAccessToken(toolContext);
JSONArray jsonArray = infoCollectorService.getInfo(pageId);
......@@ -196,8 +195,8 @@ public class VisitorAppointmentTool {
log.info("json {}", obj);
String fieldName = obj.getString("field_name");
String fieldValue = infoCollectorService.getValue(obj.getString("code")).toString();
log.info("fieldName {} fieldValue {} ", fieldName,fieldValue);
String fieldValue = infoCollectorService.getValue(fieldName).toString();
log.info("fieldName {} fieldValue {} ", fieldName, fieldValue);
if (fieldName.compareToIgnoreCase("访问园区") == 0) {
parkValue = fieldValue;
continue;
......@@ -234,7 +233,7 @@ public class VisitorAppointmentTool {
for (JSONObject tmp : dateJson) {
String fieldName = tmp.getString("field_name");
String fieldValue = infoCollectorService.getValue(tmp.getString("code")).toString();
String fieldValue = infoCollectorService.getValue(fieldName).toString();
String[] values = fieldValue.split("-");
page.locator(".van-cell")
......@@ -308,7 +307,7 @@ public class VisitorAppointmentTool {
infoCollectorService.saveValue(key, infos.get(key));
});
infoCollectorService.saveDefaultValue(pageId);
Map<String,String> keys = infoCollectorService.findLackInfo(pageId);
Map<String, String> keys = infoCollectorService.findLackInfo(pageId);
if (!keys.isEmpty()) {
JSONArray jsonArray = infoCollectorService.getInfo(pageId);
JSONArray lackJson = new JSONArray();
......@@ -316,8 +315,12 @@ public class VisitorAppointmentTool {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject tmp = jsonArray.getJSONObject(i);
JSONObject pangeJson = tmp.getJSONObject("pangea_json");
if(infoCollectorService.getValue(tmp.getString("code")) != null){
pangeJson.getJSONObject("props").put("value", infoCollectorService.getValue(tmp.getString("code")).toString());
if (infoCollectorService.getValue(tmp.getString("field_name")) != null) {
pangeJson.getJSONObject("props").put("value", infoCollectorService.getValue(tmp.getString("field_name")).toString());
}
if (tmp.getString("field_name").compareToIgnoreCase("接访员工手机号") == 0
|| tmp.getString("field_name").compareToIgnoreCase("接访员工姓名") == 0) {
continue;
}
lackJson.add(pangeJson);
}
......@@ -331,18 +334,15 @@ public class VisitorAppointmentTool {
} else {
sb.append("用户还有以下信息未提交:");
sb.append("\n");
for (Map.Entry<String,String> key : keys.entrySet()) {
for (Map.Entry<String, String> key : keys.entrySet()) {
sb.append(key.getValue());
sb.append("(");
sb.append(key);
sb.append(")");
sb.append(",");
sb.append("\n");
}
sb.append("\n");
sb.append("提示用户继续提交信息");
}
log.info("notice {}",sb.toString());
log.info("notice {}", sb.toString());
return sb.toString();
}
......@@ -367,14 +367,22 @@ public class VisitorAppointmentTool {
JSONArray lackJson = new JSONArray();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject tmp = jsonArray.getJSONObject(i);
if (tmp.getString("field_name").compareToIgnoreCase("接访员工手机号") == 0
|| tmp.getString("field_name").compareToIgnoreCase("接访员工姓名") == 0) {
continue;
}
lackJson.add(tmp.getJSONObject("pangea_json"));
}
JSONObject formMessage = new JSONObject();
formMessage.put("coms", lackJson);
try {
sendFormMessage(formMessage, toolContext);
} catch (Exception e) {
e.printStackTrace();
boolean newChat = toolContext.getContext().get("newChat").toString().compareToIgnoreCase("yes") == 0;
log.info("new chat {}", newChat);
if (newChat) {
try {
sendFormMessage(formMessage, toolContext);
} catch (Exception e) {
e.printStackTrace();
}
}
stringBuilder.append(formMessage.toJSONString());
stringBuilder.append("提示用户以json格式提交信息;如果用户已提供部分信息,需要将这些信息与`props.name`属性的值进行匹配,并将匹配之后的信息以json格式提交到`applyInfoSave`以保存信息");
......@@ -420,8 +428,8 @@ public class VisitorAppointmentTool {
JSONArray result = new JSONArray();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject tmp = jsonArray.getJSONObject(i);
if(tmp.getString("field_name").compareToIgnoreCase("接访员工手机号") == 0
|| tmp.getString("field_name").compareToIgnoreCase("接访员工姓名") == 0){
if (tmp.getString("field_name").compareToIgnoreCase("接访员工手机号") == 0
|| tmp.getString("field_name").compareToIgnoreCase("接访员工姓名") == 0) {
continue;
}
result.add(tmp);
......
......@@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import jakarta.annotation.PreDestroy;
import java.util.concurrent.*;
/**
......@@ -14,36 +15,35 @@ import java.util.concurrent.*;
@Slf4j
@Component // Spring默认单例模式
public class PlaywrightManagerImpl implements PlaywrightManager {
// 共享的Playwright实例
private volatile Playwright playwright;
// 共享的浏览器实例
private volatile Browser browser;
// 用户浏览器上下文映射表(用户ID -> BrowserContext)
private final ConcurrentMap<String, BrowserContext> userContexts = new ConcurrentHashMap<>();
// 用户上下文创建时间映射表(用于超时清理)
private final ConcurrentMap<String, Long> contextCreationTimes = new ConcurrentHashMap<>();
// 用户上下文超时时间(毫秒),默认30分钟
private static final long CONTEXT_TIMEOUT = 30 * 60 * 1000;
// 清理任务调度器
private final ScheduledExecutorService cleanupScheduler =
Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "PlaywrightCleanupScheduler");
t.setDaemon(true); // 设置为守护线程
return t;
});
private final ScheduledExecutorService cleanupScheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "PlaywrightCleanupScheduler");
t.setDaemon(true); // 设置为守护线程
return t;
});
// 标记是否已经初始化
private volatile boolean initialized = false;
// 用于同步初始化过程
private final Object initLock = new Object();
/**
* 延迟初始化Playwright和浏览器实例
*/
......@@ -53,23 +53,38 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
if (!initialized) {
try {
log.info("正在初始化Playwright管理器...");
// 创建Playwright实例
this.playwright = Playwright.create();
// 启动Chrome浏览器,无头模式
this.browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(true)
.setArgs(java.util.Arrays.asList(
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--remote-allow-origins=*")));
if (playwright == null) {
this.playwright = Playwright.create();
}
if (browser == null) {
// 启动Chrome浏览器,无头模式
this.browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(true)
.setArgs(java.util.Arrays.asList(
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--remote-allow-origins=*")));
this.browser.onDisconnected((browser) -> {
log.info("浏览器实例已断开连接");
this.browser.close();
userContexts.clear();
this.browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(true)
.setArgs(java.util.Arrays.asList(
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--remote-allow-origins=*")));
});
}
// 每5分钟检查一次超时的用户上下文
cleanupScheduler.scheduleAtFixedRate(this::cleanupExpiredContexts,
5, 5, TimeUnit.MINUTES);
cleanupScheduler.scheduleAtFixedRate(this::cleanupExpiredContexts,
5, 3600, TimeUnit.MINUTES);
this.initialized = true;
log.info("Playwright管理器初始化成功");
} catch (Exception e) {
......@@ -80,15 +95,15 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
}
}
}
// 移除@PostConstruct注解,避免在Spring初始化时自动调用
/*
@PostConstruct
public void initialize() {
lazyInitialize();
}
*/
* @PostConstruct
* public void initialize() {
* lazyInitialize();
* }
*/
@Override
public Playwright getPlaywright() {
lazyInitialize();
......@@ -97,7 +112,7 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
}
return playwright;
}
@Override
public Browser getBrowser() {
lazyInitialize();
......@@ -106,30 +121,33 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
}
return browser;
}
@Override
public BrowserContext getUserContext(String userId) {
lazyInitialize();
Browser.NewContextOptions options = new Browser.NewContextOptions()
.setViewportSize(1920, 1080) // 设置视口大小为全高清分辨率,适用于Windows 11桌面环境
.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"); // 设置用户代理为Windows 11 Chrome浏览器
.setViewportSize(1920, 1080) // 设置视口大小为全高清分辨率,适用于Windows 11桌面环境
.setUserAgent(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"); // 设置用户代理为Windows
// 11
// Chrome浏览器
return getUserContext(userId, options);
}
@Override
public BrowserContext getUserContext(String userId, Browser.NewContextOptions options) {
lazyInitialize();
if (userId == null || userId.isEmpty()) {
throw new IllegalArgumentException("User ID cannot be null or empty");
}
if (options == null) {
options = new Browser.NewContextOptions();
}
// 尝试从缓存中获取已存在的上下文
BrowserContext context = userContexts.get(userId);
// 如果上下文不存在或已关闭,则创建新的
if (context == null || isContextClosed(context)) {
try {
......@@ -142,19 +160,19 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
throw new RuntimeException("Failed to create browser context for user: " + userId, e);
}
}
return context;
}
@Override
public void releaseUserContext(String userId) {
if (userId == null || userId.isEmpty()) {
return;
}
BrowserContext context = userContexts.remove(userId);
contextCreationTimes.remove(userId);
if (context != null) {
try {
context.close();
......@@ -164,10 +182,10 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
}
}
}
/**
* 检查BrowserContext是否已关闭
*
*
* @param context 要检查的BrowserContext
* @return 如果上下文已关闭则返回true,否则返回false
*/
......@@ -182,14 +200,14 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
return true;
}
}
/**
* 清理过期的用户上下文
*/
private void cleanupExpiredContexts() {
long currentTime = System.currentTimeMillis();
long expiredThreshold = currentTime - CONTEXT_TIMEOUT;
for (String userId : contextCreationTimes.keySet()) {
Long creationTime = contextCreationTimes.get(userId);
if (creationTime != null && creationTime < expiredThreshold) {
......@@ -198,7 +216,7 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
}
}
}
/**
* 销毁所有资源
*/
......@@ -206,7 +224,7 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
@Override
public void destroy() {
log.info("开始销毁Playwright管理器资源...");
try {
// 关闭清理任务调度器
cleanupScheduler.shutdown();
......@@ -216,12 +234,12 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
} catch (Exception e) {
log.warn("关闭清理任务调度器时发生异常", e);
}
// 关闭所有用户上下文
for (String userId : userContexts.keySet()) {
releaseUserContext(userId);
}
// 关闭浏览器
try {
if (browser != null && browser.isConnected()) {
......@@ -231,7 +249,7 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
} catch (Exception e) {
log.warn("关闭浏览器实例时发生异常", e);
}
// 关闭Playwright
try {
if (playwright != null) {
......@@ -241,7 +259,7 @@ public class PlaywrightManagerImpl implements PlaywrightManager {
} catch (Exception e) {
log.warn("关闭Playwright实例时发生异常", e);
}
log.info("Playwright管理器资源已全部销毁");
}
}
\ No newline at end of file
package pangea.hiagent.web.repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import pangea.hiagent.model.AgentDialogue;
/**
......@@ -9,4 +11,6 @@ import pangea.hiagent.model.AgentDialogue;
*/
@Mapper
public interface AgentDialogueRepository extends BaseMapper<AgentDialogue> {
@Delete("DELETE FROM agent_dialogue WHERE user_id = #{userId} AND agent_id=#{agentId} ")
public void deleteDialogue(String userId,String agentId);
}
package pangea.hiagent.web.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pangea.hiagent.web.repository.AgentDialogueRepository;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
......@@ -10,6 +12,9 @@ import java.util.concurrent.ConcurrentMap;
@Service
public class ChatService {
@Autowired
private AgentDialogueRepository agentDialogueRepository;
private final ConcurrentMap<String,String> chatList = new ConcurrentHashMap<>(1024);
public boolean chatExists(String userId,String agentId) {
......@@ -26,6 +31,7 @@ public class ChatService {
String chatId = buildChatId(userId,agentId);
log.info("remove chatId:{}",chatId);
chatList.remove(chatId);
agentDialogueRepository.deleteDialogue(userId,agentId);
}
private String buildChatId(String userId,String agentId) {
......
......@@ -52,15 +52,15 @@ public class InfoCollectorService {
for(int i = 0; i < jsonArray.size(); i++){
JSONObject object = jsonArray.getJSONObject(i);
if(object.getString("field_name").compareToIgnoreCase("接访员工手机号") == 0){
String code = object.getString("code");
String code = object.getString("field_name");
saveValue(code, "15841169015");
}
if(object.getString("field_name").compareToIgnoreCase("接访员工姓名") == 0){
String code = object.getString("code");
String code = object.getString("field_name");
saveValue(code, "杜艺");
}
if(object.getString("field_name").compareToIgnoreCase("证件类型") == 0){
String code = object.getString("code");
String code = object.getString("field_name");
saveValue(code, "居民身份证");
}
}
......@@ -73,7 +73,7 @@ public class InfoCollectorService {
public Map<String,String> findLackInfo(String pageId) {
Set<String> valueKeys = values.keySet();
log.info("value keys {}", valueKeys);
Set<String> allKeys = infos.get(pageId).stream().map(t -> ((JSONObject) t).getString("code")).collect(Collectors.toSet());
Set<String> allKeys = infos.get(pageId).stream().map(t -> ((JSONObject) t).getString("field_name")).collect(Collectors.toSet());
log.info("all keys {}", allKeys);
allKeys.removeAll(valueKeys);
log.info("lack keys {}", allKeys);
......@@ -86,7 +86,7 @@ public class InfoCollectorService {
infos.get(pageId).stream().forEach(t ->
{
JSONObject info = (JSONObject) t;
String code = info.getString("code");
String code = info.getString("field_name");
if (allKeys.contains(code)) {
lackInfos.put(code,info.getString("field_name"));
}
......
......@@ -2,10 +2,10 @@
spring:
# 开发环境数据源配置
datasource:
url: jdbc:h2:file:./data/hiagent_dev_db;DB_CLOSE_ON_EXIT=FALSE
driver-class-name: org.h2.Driver
username: sa
password: sa
url: jdbc:mysql://${DB_HOST:127.0.0.1}:3306/hiagent?allowMultiQueries=true&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
driver-class-name: ${DB_DRIVER:com.mysql.cj.jdbc.Driver}
username: ${DB_NAME:root}
password: ${DB_PASSWORD:password}
# 开发环境JPA配置
jpa:
......@@ -21,7 +21,7 @@ spring:
init:
schema-locations: classpath:schema.sql
data-locations: classpath:data.sql
mode: always # 总是执行创建表和数据脚本,实现重新初始化
mode: never # 总是执行创建表和数据脚本,实现重新初始化
# 开启H2控制台
h2:
......
/*
* @Date: 2025-12-29 14:42:27
* @LastEditors: wangduo3 wangduo3@hisense.com
* @LastEditTime: 2025-12-29 16:56:52
* @FilePath: /pangea-agent/frontend/vite.config.ts
*/
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment