Commit 7d82d6ea authored by youxiaoji's avatar youxiaoji

* [针对Bean类型的工具,增加token配置的逻辑]

parent ef0d62e2
...@@ -169,11 +169,10 @@ public class DefaultReactExecutor implements ReactExecutor { ...@@ -169,11 +169,10 @@ public class DefaultReactExecutor implements ReactExecutor {
Prompt prompt = buildPromptWithHistory(defaultSystemPrompt, userInput, agent, userId); Prompt prompt = buildPromptWithHistory(defaultSystemPrompt, userInput, agent, userId);
SseTokenEmitter sseTokenEmitter = (SseTokenEmitter)tokenConsumer; SseTokenEmitter sseTokenEmitter = (SseTokenEmitter)tokenConsumer;
UserToken userToken = userTokenService.getUserToken(sseTokenEmitter.getUserId(),"pangea");
String emitterId = sseTokenEmitter.getEmitterId(); String emitterId = sseTokenEmitter.getEmitterId();
chatClient.prompt(prompt) chatClient.prompt(prompt)
.tools(agentTools.toArray()) .tools(agentTools.toArray())
.toolContext(Map.of("emitterId",emitterId)) .toolContext(Map.of("emitterId", emitterId, "userId", sseTokenEmitter.getUserId()))
.stream() .stream()
.chatResponse() .chatResponse()
.subscribe( .subscribe(
......
package pangea.hiagent.tool.impl; package pangea.hiagent.tool.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import com.microsoft.playwright.*; import com.microsoft.playwright.*;
...@@ -11,11 +10,11 @@ import com.microsoft.playwright.options.WaitUntilState; ...@@ -11,11 +10,11 @@ import com.microsoft.playwright.options.WaitUntilState;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ToolContext; import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool; import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam; import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import pangea.hiagent.agent.service.UserSseService; import pangea.hiagent.agent.service.UserSseService;
import pangea.hiagent.common.utils.Contants; import pangea.hiagent.common.utils.Contants;
...@@ -25,6 +24,7 @@ import pangea.hiagent.model.Agent; ...@@ -25,6 +24,7 @@ import pangea.hiagent.model.Agent;
import pangea.hiagent.model.UserToken; import pangea.hiagent.model.UserToken;
import pangea.hiagent.web.service.AgentService; import pangea.hiagent.web.service.AgentService;
import pangea.hiagent.web.service.InfoCollectorService; import pangea.hiagent.web.service.InfoCollectorService;
import pangea.hiagent.web.service.UserTokenService;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
...@@ -39,6 +39,7 @@ import java.util.Set; ...@@ -39,6 +39,7 @@ import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@Slf4j @Slf4j
@Component
public class VisitorAppointmentTool { public class VisitorAppointmentTool {
public static final String pageId = "visitorAppointment"; public static final String pageId = "visitorAppointment";
...@@ -50,8 +51,6 @@ public class VisitorAppointmentTool { ...@@ -50,8 +51,6 @@ public class VisitorAppointmentTool {
// SSO密码(从配置文件读取) // SSO密码(从配置文件读取)
private String ldapToken; private String ldapToken;
private String iparkToken;
// Playwright实例 // Playwright实例
private Playwright playwright; private Playwright playwright;
...@@ -67,18 +66,19 @@ public class VisitorAppointmentTool { ...@@ -67,18 +66,19 @@ public class VisitorAppointmentTool {
private AgentService agentService; private AgentService agentService;
private InfoCollectorService infoCollectorService; private InfoCollectorService infoCollectorService;
private UserSseService userSseService; private UserSseService userSseService;
private UserTokenService userTokenService;
// 登录状态有效期(毫秒),设置为30分钟 // 登录状态有效期(毫秒),设置为30分钟
private static final long LOGIN_VALIDITY_PERIOD = 30 * 60 * 1000; private static final long LOGIN_VALIDITY_PERIOD = 30 * 60 * 1000;
public VisitorAppointmentTool(UserToken userToken, AgentService agentService, InfoCollectorService infoCollectorService, UserSseService userSseService) { public VisitorAppointmentTool(UserTokenService userTokenService,AgentService agentService, InfoCollectorService infoCollectorService, UserSseService userSseService) {
this.agentService = agentService; this.agentService = agentService;
this.infoCollectorService = infoCollectorService; this.infoCollectorService = infoCollectorService;
this.ssoToken = "33f667865c395f164d29487c15fe74bf76b463f2941ef6af55d14a35a11d60b1"; this.ssoToken = "33f667865c395f164d29487c15fe74bf76b463f2941ef6af55d14a35a11d60b1";
this.ldapToken = "AAECAzY5NDRBNTQ1Njk0NTRFMDV5b3V4aWFvamlaLv+jUGNEEORN24GLIC3OlqcCdw=="; this.ldapToken = "AAECAzY5NDRBNTQ1Njk0NTRFMDV5b3V4aWFvamlaLv+jUGNEEORN24GLIC3OlqcCdw==";
this.iparkToken = userToken.getTokenValue();
this.userSseService = userSseService; this.userSseService = userSseService;
this.userTokenService = userTokenService;
} }
@PostConstruct @PostConstruct
...@@ -98,9 +98,7 @@ public class VisitorAppointmentTool { ...@@ -98,9 +98,7 @@ public class VisitorAppointmentTool {
Cookie ldapTokenCookie = new Cookie("LtpaToken", ldapToken); Cookie ldapTokenCookie = new Cookie("LtpaToken", ldapToken);
ldapTokenCookie.setDomain(".hisense.com"); ldapTokenCookie.setDomain(".hisense.com");
ldapTokenCookie.setPath("/"); ldapTokenCookie.setPath("/");
Cookie tripCookie = new Cookie("jwtToken", iparkToken);
tripCookie.setDomain("vrms-proxy.hisense.com");
tripCookie.setPath("/");
// String userName= SecurityContextHolder.getContext().getAuthentication().getName(); // String userName= SecurityContextHolder.getContext().getAuthentication().getName();
...@@ -108,7 +106,6 @@ public class VisitorAppointmentTool { ...@@ -108,7 +106,6 @@ public class VisitorAppointmentTool {
List<Cookie> cookies = new ArrayList<>(); List<Cookie> cookies = new ArrayList<>();
cookies.add(ssoTokenCookie); cookies.add(ssoTokenCookie);
cookies.add(ldapTokenCookie); cookies.add(ldapTokenCookie);
cookies.add(tripCookie);
sharedContext.addCookies(cookies); sharedContext.addCookies(cookies);
...@@ -140,6 +137,21 @@ public class VisitorAppointmentTool { ...@@ -140,6 +137,21 @@ public class VisitorAppointmentTool {
log.error("海信SSO认证工具的Playwright资源释放失败: ", e); 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");
Cookie tripCookie = new Cookie("jwtToken", userToken.getTokenValue());
tripCookie.setDomain("vrms-proxy.hisense.com");
tripCookie.setPath("/");
List<Cookie> cookies = new ArrayList<>();
cookies.add(tripCookie);
sharedContext.addCookies(cookies);
log.info("end set access token for {}", userId);
return userToken.getTokenValue();
}
@Tool(description = "提交访客预约申请") @Tool(description = "提交访客预约申请")
public String submitAppointmentApply(ToolContext toolContext) { public String submitAppointmentApply(ToolContext toolContext) {
...@@ -147,7 +159,12 @@ public class VisitorAppointmentTool { ...@@ -147,7 +159,12 @@ public class VisitorAppointmentTool {
// .setScreenshots(true) // .setScreenshots(true)
// .setSnapshots(true) // .setSnapshots(true)
// .setSources(true)); // .setSources(true));
log.info("submit apply info "); log.info("submit apply info ");
String accessToken = setAccessToken(toolContext);
JSONArray jsonArray = infoCollectorService.getInfo(pageId); JSONArray jsonArray = infoCollectorService.getInfo(pageId);
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
...@@ -162,7 +179,7 @@ public class VisitorAppointmentTool { ...@@ -162,7 +179,7 @@ public class VisitorAppointmentTool {
log.info("正在访问业务系统页面: {}", destUrl); log.info("正在访问业务系统页面: {}", destUrl);
String faviconUrl = "https://vrms-proxy.hisense.com/favicon.ico"; String faviconUrl = "https://vrms-proxy.hisense.com/favicon.ico";
page.navigate(faviconUrl); page.navigate(faviconUrl);
page.evaluate("() => sessionStorage.setItem('Access-Token', '" + iparkToken + "')"); page.evaluate("() => sessionStorage.setItem('Access-Token', '" + accessToken + "')");
page.navigate(destUrl, new Page.NavigateOptions().setWaitUntil(WaitUntilState.NETWORKIDLE)); page.navigate(destUrl, new Page.NavigateOptions().setWaitUntil(WaitUntilState.NETWORKIDLE));
// 检查是否重定向到了SSO登录页面 // 检查是否重定向到了SSO登录页面
String currentUrl = page.url(); String currentUrl = page.url();
...@@ -351,6 +368,8 @@ public class VisitorAppointmentTool { ...@@ -351,6 +368,8 @@ public class VisitorAppointmentTool {
return stringBuilder.toString(); return stringBuilder.toString();
} }
String accessToken = setAccessToken(toolContext);
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
Page page = null; Page page = null;
...@@ -364,7 +383,7 @@ public class VisitorAppointmentTool { ...@@ -364,7 +383,7 @@ public class VisitorAppointmentTool {
log.info("正在访问业务系统页面: {}", destUrl); log.info("正在访问业务系统页面: {}", destUrl);
String faviconUrl = "https://vrms-proxy.hisense.com/favicon.ico"; String faviconUrl = "https://vrms-proxy.hisense.com/favicon.ico";
page.navigate(faviconUrl); page.navigate(faviconUrl);
page.evaluate("() => sessionStorage.setItem('Access-Token', '" + iparkToken + "')"); page.evaluate("() => sessionStorage.setItem('Access-Token', '" + accessToken + "')");
page.navigate(destUrl, new Page.NavigateOptions().setWaitUntil(WaitUntilState.NETWORKIDLE)); page.navigate(destUrl, new Page.NavigateOptions().setWaitUntil(WaitUntilState.NETWORKIDLE));
// 检查是否重定向到了SSO登录页面 // 检查是否重定向到了SSO登录页面
String currentUrl = page.url(); String currentUrl = page.url();
......
spring:
application:
name: hiagent
# 数据源配置
datasource:
url: jdbc:mysql://${DB_HOST:127.0.0.1}:3306/hiagent2?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:123456Aa?}
hikari:
maximum-pool-size: 10
minimum-idle: 2
connection-timeout: 30000
# 禁用Milvus自动配置
autoconfigure:
exclude:
- org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusVectorStoreAutoConfiguration
# SQL初始化配置
sql:
init:
schema-locations: classpath:schema.sql
mode: never
# mode: always
# JPA/Hibernate配置
jpa:
database-platform: org.hibernate.dialect.MySQL8Dialect
# hibernate:
# ddl-auto: create-drop
show-sql: true
properties:
hibernate:
format_sql: true
# H2 Console配置(仅开发环境)
# h2:
# console:
# enabled: true
# path: /h2-console
# Redis配置
data:
redis:
host: localhost
port: 6379
password:
timeout: 2000
database: 0
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: -1
# RabbitMQ配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /
connection-timeout: 15000
# Jackson配置
jackson:
serialization:
write-dates-as-timestamps: false
deserialization:
fail-on-unknown-properties: false
default-property-inclusion: non_null
# Web配置
web:
resources:
add-mappings: true
# servlet配置
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
# 默认性异步请求配置
mvc:
async:
request-timeout: 300000 # 5分钟,与SSE保持一致
# Spring AI配置
ai:
openai:
enabled: false
ollama:
enabled: false
# MyBatis Plus配置
mybatis-plus:
type-aliases-package: pangea.hiagent.model
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
cache-enabled: true
use-generated-keys: true
global-config:
db-config:
id-type: assign_uuid
table-underline: true
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
# Logging配置
logging:
level:
root: INFO
pangea.hiagent: DEBUG
org.springframework: INFO
org.springframework.security: DEBUG
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
file:
name: logs/hiagent.log
max-size: 10MB
max-history: 30
charset:
console: UTF-8
file: UTF-8
# Server配置
server:
port: 8080
servlet:
context-path: /
compression:
enabled: true
min-response-size: 1024
# SSE和异步请求超时配置
request-timeout: 300000 # 5分钟(毫秒)
# Undertow配置
undertow:
# IO线程数,默认为处理器数量
io-threads: 4
# 工作线程数
worker-threads: 50
# 缓冲区配置
buffer-size: 65536
# 是否直接分配缓冲区
direct-buffers: true
# HTTP/2支持
enable-http2: true
# 最大HTTP头大小
max-http-header-size: 8192
# 最大参数数量
max-parameters: 1000
# 最大请求头数量
max-headers: 200
# 最大cookies数量
max-cookies: 100
# URL编码字符集
url-charset: UTF-8
# 访问日志配置
accesslog:
enabled: false
pattern: common
dir: logs
prefix: access_log.
# SSL配置
ssl:
# SSL引擎
engine:
# 密码套件
enabled-protocols: TLSv1.2,TLSv1.3
# WebSocket配置
websocket:
# WebSocket消息缓冲区大小
buffer-size: 1048576
# 最大WebSocket帧大小
max-frame-size: 10485760
# 应用自定义配置
hiagent:
# JWT配置
jwt:
secret: ${JWT_SECRET:hiagent-secret-key-for-production-change-this}
expiration: 7200000 # 2小时
refresh-expiration: 604800000 # 7天
# Agent配置
agent:
default-model: deepseek-chat
default-temperature: 0.7
default-max-tokens: 4096
history-length: 10
# LLM配置
llm:
providers:
deepseek:
default-api-key: ${DEEPSEEK_API_KEY:sk-e8ef4359d20b413696512db21c09db87}
default-model: deepseek-chat
base-url: https://api.deepseek.com
openai:
default-api-key: ${OPENAI_API_KEY:}
default-model: gpt-3.5-turbo
base-url: https://api.openai.com/v1
ollama:
default-model: llama2
base-url: http://localhost:11434
# RAG配置
rag:
chunk-size: 512
chunk-overlap: 50
top-k: 5
score-threshold: 0.8
# Milvus Lite配置
milvus:
data-dir: ./milvus_data
db-name: hiagent
collection-name: document_embeddings
# ChatMemory配置
app:
chat-memory:
# 实现类型: caffeine, redis, hybrid
implementation: caffeine
caffeine:
# 是否启用Caffeine缓存
enabled: true
redis:
# 是否启用Redis缓存
enabled: false
\ No newline at end of file
...@@ -4,24 +4,12 @@ spring: ...@@ -4,24 +4,12 @@ spring:
# 配置文件激活 # 配置文件激活
profiles: profiles:
active: dev active: test
# 启用懒加载初始化 # 启用懒加载初始化
main: main:
lazy-initialization: true lazy-initialization: true
# 数据源配置
datasource:
url: jdbc:h2:mem:hiagent;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
driver-class-name: org.h2.Driver
username: sa
password: sa
hikari:
maximum-pool-size: 10
minimum-idle: 1
connection-timeout: 20000
initialization-fail-timeout: 0
# 禁用Milvus自动配置 # 禁用Milvus自动配置
autoconfigure: autoconfigure:
exclude: exclude:
...@@ -32,22 +20,6 @@ spring: ...@@ -32,22 +20,6 @@ spring:
init: init:
mode: never # 生产环境禁用SQL脚本自动初始化 mode: never # 生产环境禁用SQL脚本自动初始化
# JPA/Hibernate配置
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create # 生产环境仅验证表结构,不修改数据库
show-sql: false
properties:
hibernate:
format_sql: true
# H2 Console配置(仅开发环境)
h2:
console:
enabled: true
path: /h2-console
# Redis配置 # Redis配置
data: data:
redis: redis:
......
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