Merge branch 'dev' into timezone_in_chathistory

This commit is contained in:
rahulpscraftech360 2025-09-13 12:22:03 +05:30 committed by GitHub
commit adbd8d419f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 388 additions and 33 deletions

27
ecosystem.config.js Normal file
View file

@ -0,0 +1,27 @@
module.exports = {
apps: [
{
name: "manager-api",
script: "mvn",
args: "spring-boot:run",
cwd: "/root/xiaozhi-esp32-server/main/manager-api",
interpreter: "none" // important, tells PM2 not to use node/python
},
{
name: "manager-web",
script: "npm",
args: "run serve",
cwd: "/root/xiaozhi-esp32-server/main/manager-web",
interpreter: "none"
},
{
name: "mqtt-gateway",
script: "app.js",
cwd: "/root/xiaozhi-esp32-server/main/mqtt-gateway",
interpreter: "node",
watch: true
}
]
};

View file

@ -0,0 +1,31 @@
# Spring Profile Configuration
# Set to 'dev' for development or 'prod' for production
SPRING_PROFILES_ACTIVE=dev
# Server Configuration
SERVER_PORT=8002
# Database Configuration (Override if needed)
# DB_HOST=localhost
# DB_PORT=3306
# DB_NAME=xiaozhi
# DB_USERNAME=root
# DB_PASSWORD=your_password_here
# Redis Configuration (Override if needed)
# REDIS_HOST=localhost
# REDIS_PORT=6379
# REDIS_PASSWORD=your_redis_password
# External Services
XIAOZHI_PYTHON_SERVER_URL=http://localhost:8003
# Vector Database (Qdrant)
QDRANT_URL=your_qdrant_url_here
QDRANT_API_KEY=your_qdrant_api_key_here
# Voyage AI API Key
VOYAGE_API_KEY=your_voyage_api_key_here
# Textbook Upload Directory
TEXTBOOK_UPLOAD_DIR=/path/to/uploadfile/textbooks

7
main/manager-api/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
# Environment files
.env
.env.local
.env.*.local
# But keep the example
!.env.example

View file

@ -2,12 +2,36 @@ package xiaozhi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
System.out.println("http://localhost:8002/xiaozhi/doc.html");
// Log profile before Spring Boot starts
String activeProfile = System.getenv("SPRING_PROFILES_ACTIVE");
if (activeProfile != null && !activeProfile.isEmpty()) {
System.out.println("\n========================================");
System.out.println("Starting with profile: " + activeProfile.toUpperCase());
System.out.println("========================================\n");
}
ConfigurableApplicationContext context = SpringApplication.run(AdminApplication.class, args);
Environment env = context.getEnvironment();
String[] profiles = env.getActiveProfiles();
if (profiles.length > 0) {
System.out.println("\n========================================");
System.out.println("Active Profile: " + profiles[0].toUpperCase());
System.out.println("Configuration: application-" + profiles[0] + ".yml");
System.out.println("========================================");
} else {
System.out.println("\n========================================");
System.out.println("No active profile set - using default configuration");
System.out.println("========================================");
}
System.out.println("Server started: http://localhost:8002/xiaozhi/doc.html\n");
}
}

View file

@ -38,6 +38,7 @@ public class RenExceptionHandler {
@ExceptionHandler(DuplicateKeyException.class)
public Result<Void> handleDuplicateKeyException(DuplicateKeyException ex) {
log.error("Duplicate key error: {}", ex.getMessage(), ex);
Result<Void> result = new Result<>();
result.error(ErrorCode.DB_RECORD_EXISTS);

View file

@ -67,11 +67,21 @@ public class AgentController {
private final RedisUtils redisUtils;
@GetMapping("/list")
@Operation(summary = "Get user agents list")
@Operation(summary = "Get agents list (admin gets all agents, user gets own agents)")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentDTO>> getUserAgents() {
public Result<List<AgentDTO>> getAgentsList() {
UserDetail user = SecurityUser.getUser();
List<AgentDTO> agents = agentService.getUserAgents(user.getId());
List<AgentDTO> agents;
// Check if user is super admin
if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) {
// Admin sees all agents from all users with owner information
agents = agentService.getAllAgentsForAdmin();
} else {
// Regular user sees only their own agents
agents = agentService.getUserAgents(user.getId());
}
return new Result<List<AgentDTO>>().ok(agents);
}

View file

@ -1,8 +1,10 @@
package xiaozhi.modules.agent.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import xiaozhi.common.dao.BaseDao;
import xiaozhi.modules.agent.entity.AgentEntity;
@ -30,6 +32,24 @@ public interface AgentDao extends BaseDao<AgentEntity> {
" ORDER BY d.id DESC LIMIT 1")
AgentEntity getDefaultAgentByMacAddress(@Param("macAddress") String macAddress);
/**
* 获取所有智能体及其所有者信息(管理员专用)
*
* @return 所有智能体列表及用户信息
*/
@Select("SELECT " +
"a.id, a.agent_name, a.system_prompt, a.tts_model_id, " +
"a.llm_model_id, a.vllm_model_id, a.mem_model_id, a.tts_voice_id, " +
"a.created_at, a.updated_at, a.user_id, " +
"u.username as owner_username, " +
"GROUP_CONCAT(d.mac_address SEPARATOR ',') as device_mac_addresses " +
"FROM ai_agent a " +
"LEFT JOIN sys_user u ON a.user_id = u.id " +
"LEFT JOIN ai_device d ON a.id = d.agent_id " +
"GROUP BY a.id " +
"ORDER BY a.created_at DESC")
List<Map<String, Object>> getAllAgentsWithOwnerInfo();
/**
* 根据id查询agent信息,包括插件信息
*

View file

@ -45,4 +45,14 @@ public class AgentDTO {
@Schema(description = "设备数量", example = "10")
private Integer deviceCount;
@Schema(description = "设备MAC地址列表", example = "AA:BB:CC:DD:EE:FF,11:22:33:44:55:66")
private String deviceMacAddresses;
// 管理员专用字段 - 智能体所有者信息
@Schema(description = "所有者用户名", example = "john_doe")
private String ownerUsername;
@Schema(description = "创建时间", example = "2024-03-20 10:00:00")
private Date createDate;
}

View file

@ -43,6 +43,21 @@ public interface AgentService extends BaseService<AgentEntity> {
*/
boolean insert(AgentEntity entity);
/**
* 获取用户的智能体列表
*
* @param userId 用户ID
* @return 智能体列表
*/
List<AgentDTO> getUserAgents(Long userId);
/**
* 获取所有智能体列表(管理员专用,包含用户信息)
*
* @return 所有智能体列表
*/
List<AgentDTO> getAllAgentsForAdmin();
/**
* 根据用户ID删除智能体
*

View file

@ -5,6 +5,7 @@ import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -96,7 +97,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
// 如果智能体编码为空,自动生成一个带前缀的编码
if (entity.getAgentCode() == null || entity.getAgentCode().trim().isEmpty()) {
entity.setAgentCode("AGT_" + System.currentTimeMillis());
entity.setAgentCode("AGT_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
}
// 如果排序字段为空,设置默认值0
@ -149,6 +150,59 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
}).collect(Collectors.toList());
}
@Override
public List<AgentDTO> getAllAgentsForAdmin() {
List<Map<String, Object>> agentMaps = agentDao.getAllAgentsWithOwnerInfo();
return agentMaps.stream().map(agentMap -> {
AgentDTO dto = new AgentDTO();
// 基础智能体信息
String agentId = (String) agentMap.get("id");
dto.setId(agentId);
dto.setAgentName((String) agentMap.get("agent_name"));
dto.setSystemPrompt((String) agentMap.get("system_prompt"));
// Handle LocalDateTime to Date conversion for createDate
Object createdAt = agentMap.get("created_at");
if (createdAt instanceof java.time.LocalDateTime) {
dto.setCreateDate(java.sql.Timestamp.valueOf((java.time.LocalDateTime) createdAt));
}
// 获取模型名称 - 同用户方法
String ttsModelId = (String) agentMap.get("tts_model_id");
String llmModelId = (String) agentMap.get("llm_model_id");
String vllmModelId = (String) agentMap.get("vllm_model_id");
String memModelId = (String) agentMap.get("mem_model_id");
String ttsVoiceId = (String) agentMap.get("tts_voice_id");
dto.setTtsModelName(modelConfigService.getModelNameById(ttsModelId));
dto.setLlmModelName(modelConfigService.getModelNameById(llmModelId));
dto.setVllmModelName(modelConfigService.getModelNameById(vllmModelId));
dto.setMemModelId(memModelId);
dto.setTtsVoiceName(timbreModelService.getTimbreNameById(ttsVoiceId));
// 获取智能体最近的最后连接时长 - 同用户方法
dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agentId));
// 获取设备MAC地址列表 - 管理员专用
String macAddresses = (String) agentMap.get("device_mac_addresses");
dto.setDeviceMacAddresses(macAddresses);
// 计算设备数量(从MAC地址列表或使用原方法)
if (macAddresses != null && !macAddresses.isEmpty()) {
dto.setDeviceCount(macAddresses.split(",").length);
} else {
// 使用原来的方法获取设备数量
dto.setDeviceCount(getDeviceCountByAgentId(agentId));
}
// 管理员专用字段 - 用户信息
dto.setOwnerUsername((String) agentMap.get("owner_username"));
return dto;
}).collect(Collectors.toList());
}
@Override
public Integer getDeviceCountByAgentId(String agentId) {
if (StringUtils.isBlank(agentId)) {
@ -377,6 +431,17 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
entity.setChatHistoryConf(template.getChatHistoryConf());
entity.setLangCode(template.getLangCode());
entity.setLanguage(template.getLanguage());
// Override with custom defaults for memory and voice
entity.setMemModelId("Memory_mem0ai"); // Always use memoAI for memory
entity.setTtsModelId("TTS_EdgeTTS"); // Always use EdgeTTS model
entity.setTtsVoiceId("TTS_EdgeTTS_Ana"); // Always use EdgeTTS Ana voice (en-US-AnaNeural)
// Log the overridden values for debugging
System.out.println("Creating agent with overridden defaults:");
System.out.println(" Memory: " + entity.getMemModelId());
System.out.println(" TTS Model: " + entity.getTtsModelId());
System.out.println(" TTS Voice: " + entity.getTtsVoiceId());
}
// 设置用户ID和创建者信息
@ -388,12 +453,28 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
// 保存智能体
insert(entity);
// 先检查是否已存在插件映射
List<AgentPluginMapping> existingMappings = agentPluginMappingService.list(
new QueryWrapper<AgentPluginMapping>()
.eq("agent_id", entity.getId()));
// 收集已存在的插件ID
Set<String> existingPluginIds = existingMappings.stream()
.map(AgentPluginMapping::getPluginId)
.collect(Collectors.toSet());
// 设置默认插件
List<AgentPluginMapping> toInsert = new ArrayList<>();
// 播放音乐、播放故事、查天气、查新闻
String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_STORY",
"SYSTEM_PLUGIN_WEATHER", "SYSTEM_PLUGIN_NEWS_NEWSNOW" };
for (String pluginId : pluginIds) {
// 跳过已存在的插件映射
if (existingPluginIds.contains(pluginId)) {
continue;
}
ModelProviderDTO provider = modelProviderService.getById(pluginId);
if (provider == null) {
continue;
@ -412,8 +493,11 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
mapping.setAgentId(entity.getId());
toInsert.add(mapping);
}
// 保存默认插件
// 只有当有新插件需要插入时才保存
if (!toInsert.isEmpty()) {
agentPluginMappingService.saveBatch(toInsert);
}
return entity.getId();
}
}

View file

@ -71,7 +71,17 @@ public class DeviceController {
@RequiresPermissions("sys:role:normal")
public Result<List<DeviceEntity>> getUserDevices(@PathVariable String agentId) {
UserDetail user = SecurityUser.getUser();
List<DeviceEntity> devices = deviceService.getUserDevices(user.getId(), agentId);
List<DeviceEntity> devices;
// Check if user is super admin
if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) {
// Admin can see all devices for any agent
devices = deviceService.getDevicesByAgentId(agentId);
} else {
// Regular user can only see their own devices
devices = deviceService.getUserDevices(user.getId(), agentId);
}
return new Result<List<DeviceEntity>>().ok(devices);
}

View file

@ -25,6 +25,11 @@ public interface DeviceService extends BaseService<DeviceEntity> {
*/
List<DeviceEntity> getUserDevices(Long userId, String agentId);
/**
* 获取指定智能体的所有设备列表(管理员专用)
*/
List<DeviceEntity> getDevicesByAgentId(String agentId);
/**
* 解绑设备
*/

View file

@ -211,6 +211,13 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
return baseDao.selectList(wrapper);
}
@Override
public List<DeviceEntity> getDevicesByAgentId(String agentId) {
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
wrapper.eq("agent_id", agentId);
return baseDao.selectList(wrapper);
}
@Override
public void unbindDevice(Long userId, String deviceId) {
UpdateWrapper<DeviceEntity> wrapper = new UpdateWrapper<>();

View file

@ -0,0 +1,62 @@
knife4j:
production: false
enable: true
basic:
enable: false
username: renren
password: 2ZABCDEUgF
setting:
enableFooter: false
spring:
datasource:
druid:
#MySQL
# driver-class-name: com.mysql.cj.jdbc.Driver
# # Railway MySQL Configuration - Updated for Railway database
# url: jdbc:mysql://yamanote.proxy.rlwy.net:16958/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
# username: root
# password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK
driver-class-name: com.mysql.cj.jdbc.Driver
# Railway MySQL Configuration - Updated for Railway database
url: jdbc:mysql://nozomi.proxy.rlwy.net:25037/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
username: root
password: OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 6000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
test-while-idle: true
test-on-borrow: false
test-on-return: false
stat-view-servlet:
enabled: false
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
wall:
config:
multi-statement-allow: true
data:
redis:
# Railway Redis Configuration
host: maglev.proxy.rlwy.net # Railway Redis服务器地址
port: 16780 # Railway Redis服务器连接端口
password: beVfOKcZjMUCBiZIQnvSMivhpSeijpKP # Railway Redis服务器连接密码
username: default # Railway Redis用户名
database: 0 # Redis数据库索引(默认为0)
timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间
ssl:
enabled: false # 尝试禁用SSL,Railway可能不需要
lettuce:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
shutdown-timeout: 100ms # 客户端优雅关闭的等待时间

View file

@ -14,8 +14,10 @@ server:
spring:
# 环境 dev|test|prod
# Profile will be set by SPRING_PROFILES_ACTIVE environment variable
# Default to 'dev' if not specified
profiles:
active: dev # Using dev profile with Railway database configuration
default: dev
messages:
encoding: UTF-8
basename: i18n/messages

View file

@ -0,0 +1,3 @@
-- Add EdgeTTS Ana voice (en-US-AnaNeural) for default agent configuration
delete from `ai_tts_voice` where id = 'TTS_EdgeTTS_Ana';
INSERT INTO `ai_tts_voice` VALUES ('TTS_EdgeTTS_Ana', 'TTS_EdgeTTS', 'EdgeTTS Ana', 'en-US-AnaNeural', 'English', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL);

View file

@ -410,4 +410,11 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202509030001_clear_tts_config_checksum.sql
- changeSet:
id: 202509061300
author: claude
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202509061300_add_ana_voice.sql

View file

@ -1,9 +1,15 @@
<template>
<div class="device-item">
<div style="display: flex;justify-content: space-between;">
<div>
<div style="font-weight: 700;font-size: 18px;text-align: left;color: #3d4566;">
{{ device.agentName }}
</div>
<!-- Admin-only: Show owner username -->
<div v-if="isAdmin && device.ownerUsername" class="owner-info">
Owner: {{ device.ownerUsername }}
</div>
</div>
<div>
<img src="@/assets/home/delete.png" alt="" class="action-icon delete-icon"
@click.stop="handleDelete" />
@ -53,6 +59,9 @@ export default {
return { switchValue: false }
},
computed: {
isAdmin() {
return this.$store.getters.getIsSuperAdmin;
},
formattedLastConnectedTime() {
if (!this.device.lastConnectedAt) return 'No conversations yet';
@ -112,6 +121,14 @@ export default {
text-align: left;
}
.owner-info {
font-weight: 400;
font-size: 12px;
color: #5778ff;
text-align: left;
margin-top: 5px;
}
.settings-btn {
font-weight: 500;
font-size: 11px;

View file

@ -1,12 +1,17 @@
{
"production": {
"chat_servers": [
"ws://192.168.1.166:8000/toy/v1/"
"ws://139.59.7.72:8000/toy/v1/"
]
},
"development": {
"chat_servers": [
"ws://192.168.1.166:8000/toy/v1/"
"ws://139.59.7.72:8000/toy/v1/"
],
"mac_addresss": [
]

View file

@ -904,22 +904,20 @@ TTS:
voice: "OUeAo1mhq6IBExi"
output_dir: tmp/
# #####################################################################################
# ##############################Semantic Search Configuration###########################
# Semantic search for improved music matching using vector embeddings
semantic_search:
# Enable semantic search for music (requires Qdrant and sentence-transformers)
enabled: false # Set to true to enable
# Qdrant vector database URL (can be local or cloud instance)
qdrant_url: "https://your-qdrant-instance.com" # Change to your Qdrant URL
# Qdrant API key (required for cloud instances, optional for local)
qdrant_api_key: "your-qdrant-api-key" # Change to your API key
enabled: true # Set to false to disable
# Qdrant vector database URL - using same instance as memory system
qdrant_url: "https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io"
# Qdrant API key - using your reference code's API key
qdrant_api_key: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk"
# Vector collection name for music embeddings
collection_name: "xiaozhi_music"
# Sentence transformer model for embeddings (smaller models are faster)
# Options: "all-MiniLM-L6-v2" (fast), "all-mpnet-base-v2" (better quality)
# Sentence transformer model for embeddings (fast and efficient)
embedding_model: "all-MiniLM-L6-v2"
# Number of search results to return
search_limit: 5
# Minimum similarity score threshold (0.0 to 1.0, higher = more strict)
# Minimum similarity score threshold (0.5 = 50% similarity required)
min_score_threshold: 0.5

View file

@ -127,7 +127,9 @@ def _extract_song_name(text):
"I want to hear",
"listen to",
"play some music",
"music"
"music",
"tell",
"can you tell"
]
text_lower = text.lower()
@ -447,7 +449,9 @@ def initialize_multilingual_music_system(conn):
if SEMANTIC_SEARCH is None:
try:
semantic_config = conn.config.get('semantic_search', {})
if semantic_config.get('enabled', False):
SEMANTIC_SEARCH = SemanticMusicSearch(semantic_config)
if SEMANTIC_SEARCH.initialize():
conn.logger.bind(tag=TAG).info("Semantic music search initialized successfully")

View file

@ -53,8 +53,10 @@ class SemanticMusicSearch:
self.is_available = True
# Qdrant configuration
self.qdrant_url = self.config.get("qdrant_url", "https://localhost:6333")
self.qdrant_api_key = self.config.get("qdrant_api_key", None)
self.qdrant_url = self.config.get("qdrant_url", "https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io")
self.qdrant_api_key = self.config.get("qdrant_api_key", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk")
self.collection_name = self.config.get("collection_name", "xiaozhi_music")
# Embedding model configuration

View file

@ -43,6 +43,10 @@ amazon_transcribe
# Semantic search dependencies
qdrant-client>=1.7.0
sentence-transformers>=2.2.0
pyspellchecker>=0.7.0
# Google Cloud Speech v2 dependencies
google-cloud-speech>=2.26.0
pyspellchecker>=0.7.0