mem0 working

This commit is contained in:
rahulpscraftech360 2025-08-25 16:05:52 +05:30
parent cde33484d4
commit abb7a43921
33 changed files with 2491 additions and 118 deletions

View file

@ -0,0 +1,452 @@
# Firmware Update System Documentation
## Table of Contents
1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Components](#components)
4. [Firmware Upload Process](#firmware-upload-process)
5. [OTA Update Flow](#ota-update-flow)
6. [API Endpoints](#api-endpoints)
7. [Database Schema](#database-schema)
8. [Configuration](#configuration)
9. [Security Features](#security-features)
10. [Device-Server Communication](#device-server-communication)
---
## Overview
The Xiaozhi ESP32 Server implements a comprehensive Over-The-Air (OTA) firmware update system that allows remote firmware updates for ESP32 devices. The system supports automatic version checking, secure firmware distribution, and device-specific update policies.
### Key Features
- Automatic version comparison and update detection
- Secure firmware storage with MD5 hash verification
- Per-device update control (auto-update enable/disable)
- Download attempt limiting (3 attempts per UUID)
- Support for multiple firmware types (.bin and .apk)
- RESTful API for firmware management
---
## Architecture
```
┌─────────────────┐ ┌──────────────────┐ ┌────────────────┐
│ ESP32 Device │────▶│ Manager API │────▶│ Firmware Store │
│ │◀────│ (Java Spring) │◀────│ (uploadfile/) │
└─────────────────┘ └──────────────────┘ └────────────────┘
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ Database │ │
│ │ (ai_ota) │ │
│ └──────────────────┘ │
│ │
▼ │
┌─────────────────┐ │
│ Xiaozhi Server │ │
│ (Python) │◀──────────────────────────────────────┘
└─────────────────┘
```
---
## Components
### 1. Manager API (Java Spring Boot)
- **Location**: `main/manager-api/`
- **Main Controllers**:
- `OTAController.java`: Handles device OTA check requests
- `OTAMagController.java`: Manages firmware upload/download
- **Services**:
- `OtaServiceImpl.java`: Business logic for OTA operations
- `DeviceServiceImpl.java`: Device management and update checks
### 2. Xiaozhi Server (Python)
- **Location**: `main/xiaozhi-server/`
- **OTA Handler**: `core/api/ota_handler.py`
- Provides fallback OTA endpoint for direct device connections
### 3. Firmware Storage
- **Location**: `main/manager-api/uploadfile/`
- Files stored with MD5 hash as filename
- Supported formats: `.bin`, `.apk`
---
## Firmware Upload Process
### Step 1: Admin Upload
```http
POST /otaMag/upload
Content-Type: multipart/form-data
```
**Process Flow**:
1. Admin uploads firmware file through web interface
2. System validates file extension (.bin or .apk only)
3. MD5 hash calculated for the file
4. File saved as: `uploadfile/{md5_hash}.{extension}`
5. If file already exists (same MD5), returns existing path
6. Path returned to admin for database entry
**Code Location**: `OTAMagController.java:231-279`
### Step 2: Database Registration
Admin creates OTA entry with:
- **Firmware Name**: Descriptive name
- **Type**: Device type (e.g., "esp32-generic", "doit-ai-01-kit")
- **Version**: Semantic version (e.g., "1.7.6")
- **File Path**: Path from upload step
- **Size**: File size in bytes
- **Remark**: Optional description
---
## OTA Update Flow
### 1. Device Check Request
```http
POST /ota/
Headers:
Device-Id: {MAC_ADDRESS}
Client-Id: {CLIENT_ID}
Body:
{
"application": {
"version": "1.7.6"
},
"board": {
"type": "esp32-generic"
}
}
```
### 2. Server Processing
**Location**: `DeviceServiceImpl.java - checkDeviceActive()`
1. **Device Validation**:
- Verify MAC address format
- Check if device is registered in database
2. **Update Decision Logic**:
```java
if (device == null) {
// Device not registered - no update
return current_firmware_info;
}
if (device.autoUpdate != 0) {
// Check for newer version
OtaEntity latest = getLatestOta(device.type);
if (compareVersions(latest.version, current.version) > 0) {
// Generate download URL
return firmware_with_download_url;
}
}
```
3. **Download URL Generation**:
- Create temporary UUID
- Store OTA ID in Redis: `ota:id:{uuid}`
- Generate URL: `/otaMag/download/{uuid}`
- URL valid for 3 download attempts
### 3. Server Response
```json
{
"server_time": {
"timestamp": 1703123456789,
"timezone_offset": 480
},
"firmware": {
"version": "1.7.7",
"url": "http://server:8002/otaMag/download/abc-123-def"
},
"websocket": {
"url": "ws://server:8000/xiaozhi/v1/"
},
"mqtt": {
"endpoint": "broker:1883",
"client_id": "GID_test@@@mac@@@uuid",
"username": "base64_encoded_data",
"password": "hmac_signature"
}
}
```
### 4. Firmware Download
**Endpoint**: `GET /otaMag/download/{uuid}`
**Process**:
1. Validate UUID exists in Redis
2. Check download count (max 3 attempts)
3. Retrieve firmware file from storage
4. Return file as binary stream
5. Increment download counter
6. Clean up after 3 downloads
**Security Features**:
- UUID expires after use
- Download attempt limiting
- File path validation
- Safe filename generation
---
## API Endpoints
### OTA Check Endpoints
#### POST /ota/
- **Purpose**: Device firmware update check
- **Headers**: Device-Id, Client-Id
- **Response**: Update information if available
#### POST /ota/activate
- **Purpose**: Quick device activation check
- **Headers**: Device-Id, Client-Id
- **Response**: 200 if registered, 202 if not
### Management Endpoints
#### GET /otaMag
- **Purpose**: List all firmware entries
- **Permission**: superAdmin
- **Parameters**: page, limit
#### POST /otaMag
- **Purpose**: Create firmware entry
- **Permission**: superAdmin
- **Body**: OtaEntity
#### PUT /otaMag/{id}
- **Purpose**: Update firmware entry
- **Permission**: superAdmin
#### DELETE /otaMag/{id}
- **Purpose**: Delete firmware entry
- **Permission**: superAdmin
#### POST /otaMag/upload
- **Purpose**: Upload firmware file
- **Permission**: superAdmin
- **Returns**: File path for database
#### GET /otaMag/download/{uuid}
- **Purpose**: Download firmware file
- **Public**: Yes (with valid UUID)
- **Limit**: 3 attempts per UUID
---
## Database Schema
### Table: `ai_ota`
```sql
CREATE TABLE ai_ota (
id VARCHAR(36) PRIMARY KEY,
firmware_name VARCHAR(255),
type VARCHAR(100), -- Device type
version VARCHAR(50), -- Semantic version
size BIGINT, -- File size in bytes
remark TEXT, -- Description
firmware_path VARCHAR(500), -- File storage path
sort INT, -- Display order
updater BIGINT,
update_date DATETIME,
creator BIGINT,
create_date DATETIME
);
```
### Table: `ai_device`
```sql
CREATE TABLE ai_device (
id VARCHAR(36) PRIMARY KEY,
mac_address VARCHAR(50),
app_version VARCHAR(50), -- Current firmware version
auto_update TINYINT, -- 0=disabled, 1=enabled
-- other fields...
);
```
---
## Configuration
### System Parameters
Configure in `sys_params` table or through Parameter Management UI:
1. **server.websocket**
- WebSocket server URL for device connections
- Example: `ws://server:8000/xiaozhi/v1/`
2. **server.ota**
- OTA server base URL
- Example: `http://server:8002/xiaozhi/`
### Device Types
Configure in Dictionary Management (FIRMWARE_TYPE):
- `doit-ai-01-kit`: DOIT AI-01 Kit
- `esp32-generic`: ESP32 Generic
- `esp32s3-devkit`: ESP32-S3 DevKit
- `xiao-esp32s3`: XIAO ESP32S3
- `m5stack-core`: M5Stack Core
---
## Security Features
### 1. File Upload Security
- Extension validation (.bin, .apk only)
- MD5 hash verification
- Duplicate detection
- Admin permission required
### 2. Download Security
- Temporary UUID generation
- Redis-based token management
- Download attempt limiting (3 max)
- Automatic cleanup after use
### 3. Version Control
- Semantic versioning comparison
- Per-device update control
- Type-specific firmware matching
### 4. MQTT Authentication
- HMAC-SHA256 signature generation
- Base64 encoded credentials
- Session-specific UUIDs
---
## Device-Server Communication
### 1. Initial Connection
Device connects to OTA endpoint with:
- MAC address as Device-Id
- Current firmware version
- Board type information
### 2. Update Check Flow
```
Device Manager API Database
│ │ │
├──POST /ota/──────────────▶│ │
│ (version, type) │ │
│ ├──Check Device────────▶│
│ │◀─────────────────────┤
│ │ │
│ ├──Get Latest OTA──────▶│
│ │◀─────────────────────┤
│ │ │
│◀──Response────────────────┤ │
│ (download URL if update) │ │
│ │ │
├──GET /download/{uuid}────▶│ │
│ │ │
│◀──Firmware Binary─────────┤ │
```
### 3. Fallback Support
If Manager API unavailable, devices can connect to:
- Xiaozhi Server OTA endpoint: `http://server:8003/ota/`
- Provides basic connectivity information
- No firmware updates (returns current version)
---
## Version Comparison Logic
The system uses semantic versioning (MAJOR.MINOR.PATCH):
```java
private int compareVersions(String v1, String v2) {
String[] parts1 = v1.split("\\.");
String[] parts2 = v2.split("\\.");
for (int i = 0; i < Math.max(parts1.length, parts2.length); i++) {
int num1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0;
int num2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0;
if (num1 != num2) {
return Integer.compare(num1, num2);
}
}
return 0;
}
```
**Examples**:
- 1.7.7 > 1.7.6 ✓ (Update available)
- 2.0.0 > 1.9.9 ✓ (Major update)
- 1.7.6 = 1.7.6 ✗ (No update)
---
## Troubleshooting
### Common Issues
1. **"OTA接口不正常,缺少websocket地址"**
- Solution: Configure `server.websocket` parameter
2. **"OTA接口不正常,缺少ota地址"**
- Solution: Configure `server.ota` parameter
3. **Firmware file not found**
- Check file exists in `uploadfile/` directory
- Verify path in database matches actual file
4. **Device not receiving updates**
- Check `auto_update` flag is enabled (not 0)
- Verify device type matches firmware type
- Ensure version number is higher
5. **Download limit exceeded**
- UUID expired after 3 attempts
- Generate new download link
---
## Best Practices
1. **Version Management**
- Use semantic versioning consistently
- Test firmware thoroughly before deployment
- Keep previous versions for rollback
2. **Security**
- Regular security audits of firmware
- Monitor download patterns for abuse
- Use HTTPS in production
3. **Device Management**
- Group devices by type for targeted updates
- Implement staged rollouts for critical updates
- Monitor update success rates
4. **Storage Management**
- Regular cleanup of old firmware files
- Backup firmware files externally
- Monitor disk space usage
---
## Future Enhancements
Potential improvements to consider:
- Delta updates for bandwidth optimization
- Rollback mechanism for failed updates
- Update scheduling and staging
- Device group management
- Update progress tracking
- Firmware signing and verification
- Automated testing before deployment
---
*Last Updated: 2025-08-25*
*Document Version: 1.0.0*

View file

@ -0,0 +1,221 @@
# Manager API Documentation Guide
## Swagger/OpenAPI Documentation
The Manager API includes built-in Swagger/OpenAPI documentation using SpringDoc OpenAPI v2.8.8.
### Accessing Swagger UI
Once the Manager API is running, you can access the interactive API documentation at:
```
http://localhost:8080/swagger-ui/index.html
```
Replace `localhost:8080` with your actual server address and port.
### API Groups
The API is organized into the following groups:
1. **Device APIs** (`/device/**`)
- Device registration
- Device management
- Device binding/unbinding
- Device status reporting
2. **Agent APIs** (`/agent/**`)
- Agent management
- Agent configuration
- Agent templates
- Chat history
- Memory management
- Voice print management
- MCP access points
3. **Model APIs** (`/models/**`)
- Model configuration
- Model providers
- Voice models
- LLM models
- TTS/ASR/VAD models
4. **OTA APIs** (`/ota/**`)
- Over-the-air updates
- Firmware management
- Update status
5. **Timbre APIs** (`/ttsVoice/**`)
- TTS voice management
- Voice configuration
6. **Admin APIs** (`/admin/**`)
- User management
- System administration
- Server management
7. **User APIs** (`/user/**`)
- User authentication
- User profile
- Password management
8. **Config APIs** (`/config/**`)
- System configuration
- Agent model configuration
### OpenAPI JSON Specification
You can access the raw OpenAPI specification at:
```
http://localhost:8080/v3/api-docs
```
For specific API groups:
```
http://localhost:8080/v3/api-docs/device
http://localhost:8080/v3/api-docs/agent
http://localhost:8080/v3/api-docs/models
http://localhost:8080/v3/api-docs/ota
http://localhost:8080/v3/api-docs/timbre
http://localhost:8080/v3/api-docs/admin
http://localhost:8080/v3/api-docs/user
http://localhost:8080/v3/api-docs/config
```
## Key API Endpoints
### Authentication
- `POST /login` - User login
- `POST /logout` - User logout
- `POST /user/register` - User registration
### Agent Management
- `GET /agent/list` - Get user's agents
- `GET /agent/{id}` - Get agent details
- `POST /agent` - Create new agent
- `PUT /agent/{id}` - Update agent
- `DELETE /agent/{id}` - Delete agent
- `PUT /agent/saveMemory/{macAddress}` - Update agent memory
### Device Management
- `POST /device/register` - Register device
- `POST /device/bind` - Bind device to user
- `POST /device/unbind` - Unbind device
- `GET /device/list` - Get user's devices
- `POST /device/report` - Device status report
### Model Configuration
- `GET /models/provider` - Get model providers
- `POST /models/provider` - Add model provider
- `PUT /models/provider/{id}` - Update model provider
- `DELETE /models/provider/{id}` - Delete model provider
- `GET /models/config` - Get model configurations
- `GET /models/voice/{modelId}` - Get voice options for TTS model
### Configuration
- `GET /config/agentModels` - Get agent model configuration
- `POST /config/agentModels` - Update agent model configuration
## API Authentication
Most API endpoints require authentication. The API uses Shiro for security:
1. **Login** to get a session token:
```bash
POST /login
Content-Type: application/json
{
"username": "your-username",
"password": "your-password"
}
```
2. **Use the token** in subsequent requests (stored in cookies/session)
3. **Permissions** are role-based:
- `sys:role:normal` - Normal user permissions
- `sys:role:superAdmin` - Administrator permissions
## Example API Calls
### Create Memory Provider
```bash
POST /models/provider
Content-Type: application/json
{
"modelType": "Memory",
"providerCode": "mem0ai",
"name": "Mem0 Memory Provider",
"fields": [
{
"key": "api_key",
"label": "API Key",
"type": "password",
"value": "your-mem0-api-key"
}
],
"sort": 1
}
```
### Update Agent Memory
```bash
PUT /agent/saveMemory/{macAddress}
Content-Type: application/json
{
"summaryMemory": "Memory configuration instructions"
}
```
### Get Agent Configuration
```bash
GET /agent/{agentId}
```
## Data Models
The API uses DTOs (Data Transfer Objects) for request/response:
- **AgentDTO** - Agent information
- **AgentMemoryDTO** - Agent memory update
- **DeviceDTO** - Device information
- **ModelConfigDTO** - Model configuration
- **ModelProviderDTO** - Model provider configuration
All DTOs include Swagger annotations for documentation.
## Error Handling
The API returns standardized error responses:
```json
{
"code": 0, // 0 for success, non-zero for errors
"msg": "Success or error message",
"data": {} // Response data
}
```
Common error codes:
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not found
- `500` - Internal server error
## Development Tips
1. **Use Swagger UI** for testing APIs directly in the browser
2. **Check annotations** in controller classes for detailed API documentation
3. **Review DTOs** for request/response structures
4. **Monitor logs** for debugging API issues
## Additional Resources
- Controller classes in: `src/main/java/xiaozhi/modules/*/controller/`
- DTO classes in: `src/main/java/xiaozhi/modules/*/dto/`
- Entity classes in: `src/main/java/xiaozhi/modules/*/entity/`
- Service implementations in: `src/main/java/xiaozhi/modules/*/service/`

330
MEM0_INTEGRATION_GUIDE.md Normal file
View file

@ -0,0 +1,330 @@
# Mem0 Integration Guide for Xiaozhi ESP32 Server
## Overview
Mem0 is a memory management system integrated into the Xiaozhi ESP32 server that provides persistent memory capabilities for AI agents. This guide explains how to configure and use mem0 with both the manager API and web dashboard.
## Architecture
### Components
1. **Memory Provider** (`main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py`)
- Handles memory storage and retrieval
- Integrates with Mem0 cloud service
- Provides search and query capabilities
2. **Manager API** (`main/manager-api`)
- REST endpoints for memory configuration
- Agent memory management
- Database persistence
3. **Web Dashboard** (`main/manager-web`)
- UI for configuring memory providers
- Agent memory settings
- Visual management interface
## Configuration
### 1. Setting Up Mem0 API Key
#### Via Web Dashboard:
1. Navigate to **Provider Management** page
2. Click **Add** button
3. Select **Memory Module** as Category
4. Choose **mem0ai** as Provider Code
5. Enter configuration:
```json
{
"api_key": "your-mem0-api-key",
"api_version": "v1.1"
}
```
6. Save the provider configuration
#### Via Manager API:
```bash
POST /api/model/provider
Content-Type: application/json
{
"modelType": "Memory",
"providerCode": "mem0ai",
"name": "Mem0 Memory Provider",
"fields": [
{
"key": "api_key",
"label": "API Key",
"type": "password",
"value": "your-mem0-api-key"
},
{
"key": "api_version",
"label": "API Version",
"type": "text",
"value": "v1.1"
}
],
"sort": 1
}
```
### 2. Configuring Agent Memory
#### Via Web Dashboard:
1. Go to **Agent Management**
2. Create or edit an agent
3. In the agent configuration, enable memory:
- Toggle **Enable Memory** option
- Select **mem0ai** as memory provider
- Configure summary memory prompt
#### Via Manager API:
```bash
POST /api/agent
Content-Type: application/json
{
"name": "My AI Assistant",
"summaryMemory": "Build a dynamic memory network that retains key information while intelligently maintaining information evolution trajectories within limited space. Summarize important user information from conversations to provide more personalized service in future interactions.",
"memoryProvider": "mem0ai",
"enableMemory": true
}
```
### 3. Updating Agent Memory
The system supports dynamic memory updates through the API:
```bash
PUT /api/agent/saveMemory/{macAddress}
Content-Type: application/json
{
"summaryMemory": "Updated memory instructions for the agent"
}
```
## Memory Flow
### 1. Memory Save Process
```python
# When a conversation occurs:
1. Messages are collected from the dialogue
2. System filters out system messages
3. Formatted messages are sent to Mem0 API
4. Memory is associated with the agent's role_id
5. Result is logged for debugging
```
### 2. Memory Query Process
```python
# When agent needs to recall information:
1. Query string is sent to search method
2. Mem0 searches memories for the user_id (role_id)
3. Results are formatted with timestamps
4. Memories are sorted by recency (newest first)
5. Formatted memory string is returned to agent
```
## Integration Points
### WebSocket Server Integration
The memory provider is initialized in `websocket_server.py`:
- Checks if "Memory" is in selected_modules
- Creates memory provider instance
- Passes to ConnectionHandler for use during conversations
### Connection Handler
In `connection.py`, the memory provider:
- Saves conversation memories after each interaction
- Queries memories when needed for context
- Integrates with the dialogue flow
## API Endpoints
### Provider Management
- `GET /api/model/provider` - List all providers including memory
- `POST /api/model/provider` - Add new memory provider
- `PUT /api/model/provider/{id}` - Update memory provider configuration
- `DELETE /api/model/provider/{id}` - Remove memory provider
### Agent Memory Management
- `GET /api/agent/{id}` - Get agent details including memory settings
- `PUT /api/agent/{id}` - Update agent including memory configuration
- `PUT /api/agent/saveMemory/{macAddress}` - Update memory by device MAC
## Database Schema
### Model Provider Table
```sql
CREATE TABLE model_provider (
id BIGINT PRIMARY KEY,
model_type VARCHAR(50), -- 'Memory' for memory providers
provider_code VARCHAR(100), -- 'mem0ai'
name VARCHAR(255),
fields TEXT, -- JSON configuration
sort INT
);
```
### Agent Table
```sql
CREATE TABLE agent (
id VARCHAR(36) PRIMARY KEY,
summary_memory TEXT, -- Memory configuration prompt
-- other fields...
);
```
## Best Practices
### 1. Memory Prompt Design
Create effective summary memory prompts:
```text
"Build a dynamic memory network that retains key information while intelligently maintaining information evolution trajectories. Focus on:
- User preferences and habits
- Important personal information
- Conversation context and history
- Task-specific knowledge
Summarize in a way that enables personalized and contextual responses."
```
### 2. API Key Security
- Store API keys securely in the database
- Never expose keys in logs or responses
- Use environment variables for production deployments
### 3. Memory Management
- Regularly review and update memory prompts
- Monitor memory usage through Mem0 dashboard
- Clean up outdated memories periodically
### 4. Error Handling
The system includes robust error handling:
- Gracefully handles missing API keys
- Falls back to no-memory mode if service unavailable
- Logs errors for debugging without exposing sensitive data
## Troubleshooting
### Common Issues
1. **Memory not saving**
- Check API key configuration
- Verify mem0ai service is accessible
- Check logs in `tmp/server.log`
2. **No memories returned**
- Ensure agent has role_id configured
- Verify memories exist for the user
- Check query format and parameters
3. **Configuration not appearing**
- Restart the xiaozhi-server after configuration changes
- Verify database changes are committed
- Check provider is enabled in selected_modules
### Debug Mode
Enable debug logging to see memory operations:
```yaml
# In config.yaml
log:
log_level: DEBUG
```
## Example Integration
### Complete Setup Flow
1. **Install dependencies**:
```bash
pip install mem0ai==0.1.62
```
2. **Configure provider in dashboard**:
- Navigate to Provider Management
- Add mem0ai provider with API key
3. **Create agent with memory**:
- Go to Agent Management
- Create new agent
- Enable memory and select mem0ai
- Configure summary memory prompt
4. **Test memory functionality**:
- Connect device to agent
- Have conversations
- Check Mem0 dashboard for saved memories
- Test memory recall in subsequent conversations
## Advanced Features
### Custom Memory Formatting
The system formats memories with timestamps:
```python
[2024-03-15 14:30:45] User prefers morning meetings
[2024-03-14 10:15:23] User's favorite color is blue
[2024-03-13 09:45:12] User works in software engineering
```
### Memory Search
Query specific memories:
```python
results = memory_provider.query_memory("user preferences")
```
### Batch Operations
Process multiple agents' memories:
```python
for agent in agents:
memory_provider.role_id = agent.id
await memory_provider.save_memory(messages)
```
## Security Considerations
1. **API Key Protection**
- Use environment variables
- Encrypt keys in database
- Rotate keys regularly
2. **Data Privacy**
- Mem0 stores data securely
- Implement data retention policies
- Provide user data export/deletion options
3. **Access Control**
- Limit memory access by role
- Audit memory operations
- Implement rate limiting
## Performance Optimization
1. **Caching**
- Cache frequently accessed memories
- Use Redis for temporary storage
- Implement TTL for cache entries
2. **Batch Processing**
- Group memory operations
- Use async operations where possible
- Implement queue for high-volume scenarios
3. **Monitoring**
- Track memory API response times
- Monitor error rates
- Set up alerts for failures
## Future Enhancements
Potential improvements for mem0 integration:
- Local memory fallback option
- Memory compression algorithms
- Multi-agent memory sharing
- Memory analytics dashboard
- Automated memory pruning
- Memory export/import tools
## Support
For issues or questions:
- Check logs in `tmp/server.log`
- Review Mem0 documentation at https://docs.mem0.ai
- Contact support with error details and configuration

205
add_mem0_system_param.py Normal file
View file

@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""
Script to add mem0.api_key system parameter
This will bypass the API key masking issue
"""
import pymysql
import json
import sys
from datetime import datetime
# Database configuration - from application-dev.yml
DB_CONFIG = {
'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host
'port': 25037, # Railway MySQL port
'user': 'root', # Database username
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password
'database': 'railway', # Database name
'charset': 'utf8mb4',
'connect_timeout': 30, # Connection timeout in seconds
'read_timeout': 30,
'write_timeout': 30,
'autocommit': False,
'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config
}
# The actual mem0 API key
MEM0_API_KEY = "m0-WNBvGhsBGZU1NDKDF42ecLNAgMk0GRaToaKLT0wN"
# Colors for output
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def print_header(text):
"""Print a formatted header"""
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
def print_success(text):
"""Print success message"""
print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}")
def print_error(text):
"""Print error message"""
print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}")
def print_info(text):
"""Print info message"""
print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}")
def connect_to_database():
"""Connect to the MySQL database"""
try:
print_info("Connecting to database...")
connection = pymysql.connect(**DB_CONFIG)
# Test the connection
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
cursor.fetchone()
print_success("Successfully connected to database")
return connection
except Exception as e:
print_error(f"Failed to connect to database: {str(e)}")
return None
def add_system_parameter(connection):
"""Add mem0.api_key system parameter"""
try:
with connection.cursor() as cursor:
# Check if parameter already exists
cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',))
existing = cursor.fetchone()
if existing:
print_warning("Parameter mem0.api_key already exists:")
print(f" Current value: {existing[2][:10]}...{existing[2][-10:] if len(existing[2]) > 20 else existing[2]}")
response = input(f"{Colors.WARNING}Do you want to update it? (yes/no): {Colors.ENDC}").lower()
if response not in ['yes', 'y']:
print_info("Skipping update")
return True
# Update existing parameter
update_query = """
UPDATE sys_params
SET param_value = %s,
update_date = NOW(),
updater = 1
WHERE param_code = %s
"""
cursor.execute(update_query, (MEM0_API_KEY, 'mem0.api_key'))
connection.commit()
print_success("Updated existing mem0.api_key parameter")
else:
# Get the next ID
cursor.execute("SELECT MAX(id) FROM sys_params")
max_id = cursor.fetchone()[0]
next_id = (max_id or 0) + 1
# Insert new parameter
insert_query = """
INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark, create_date, creator)
VALUES (%s, %s, %s, %s, %s, %s, NOW(), %s)
"""
cursor.execute(insert_query, (
next_id,
'mem0.api_key',
MEM0_API_KEY,
'string',
1, # param_type: 1 for system parameters
'Mem0 AI API key for memory management',
1 # creator: admin user
))
connection.commit()
print_success("Added new mem0.api_key system parameter")
return True
except Exception as e:
connection.rollback()
print_error(f"Failed to add system parameter: {str(e)}")
return False
def verify_parameter(connection):
"""Verify the parameter was added correctly"""
try:
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',))
result = cursor.fetchone()
if result:
print_success("Parameter verification successful:")
print(f" ID: {result[0]}")
print(f" Code: {result[1]}")
print(f" Value: {result[2][:10]}...{result[2][-10:]}")
print(f" Type: {result[3]}")
print(f" Remark: {result[5]}")
return True
else:
print_error("Parameter not found after insertion")
return False
except Exception as e:
print_error(f"Failed to verify parameter: {str(e)}")
return False
def main():
"""Main function"""
print_header("Add Mem0 API Key System Parameter")
print_info(f"Target API Key: {MEM0_API_KEY[:10]}...{MEM0_API_KEY[-10:]}")
print_info(f"Timestamp: {datetime.now().isoformat()}")
# Connect to database
connection = connect_to_database()
if not connection:
print_error("Cannot proceed without database connection")
return 1
try:
# Add system parameter
if add_system_parameter(connection):
# Verify the parameter
if verify_parameter(connection):
print_success("\n✅ System parameter added successfully!")
print_info("\nNext steps:")
print_info("1. Restart the manager-api service to load the new parameter")
print_info("2. Test device connection again")
print_info("3. Check that mem0 authentication now works")
return 0
else:
return 1
else:
return 1
finally:
connection.close()
print_info("Database connection closed")
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\nScript interrupted by user")
sys.exit(0)
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
sys.exit(1)

178
check_system_params.py Normal file
View file

@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""
Script to check system parameters table for mem0.api_key
"""
import pymysql
import json
import sys
from datetime import datetime
# Database configuration - from application-dev.yml
DB_CONFIG = {
'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host
'port': 25037, # Railway MySQL port
'user': 'root', # Database username
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password
'database': 'railway', # Database name
'charset': 'utf8mb4',
'connect_timeout': 30, # Connection timeout in seconds
'read_timeout': 30,
'write_timeout': 30,
'autocommit': False,
'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config
}
# Colors for output
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def print_header(text):
"""Print a formatted header"""
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
def print_success(text):
"""Print success message"""
print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}")
def print_error(text):
"""Print error message"""
print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}")
def print_info(text):
"""Print info message"""
print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}")
def connect_to_database():
"""Connect to the MySQL database"""
try:
print_info("Connecting to database...")
connection = pymysql.connect(**DB_CONFIG)
# Test the connection
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
cursor.fetchone()
print_success("Successfully connected to database")
return connection
except Exception as e:
print_error(f"Failed to connect to database: {str(e)}")
return None
def check_system_params(connection):
"""Check system parameters table for mem0.api_key"""
try:
with connection.cursor() as cursor:
# First, let's see what tables exist
print_info("Checking available tables...")
cursor.execute("SHOW TABLES LIKE '%param%'")
param_tables = cursor.fetchall()
if param_tables:
print_success(f"Found parameter-related tables:")
for table in param_tables:
print(f" - {table[0]}")
# Try different possible table names
possible_tables = [
'sys_params',
'system_params',
'sys_parameters',
'system_parameters',
'config_params',
'application_params'
]
found_table = None
for table_name in possible_tables:
try:
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
found_table = table_name
print_success(f"Found system parameters table: {table_name}")
break
except pymysql.err.ProgrammingError:
continue
if found_table:
# First, check the table structure
cursor.execute(f"DESCRIBE {found_table}")
columns = cursor.fetchall()
print_info(f"Table structure for {found_table}:")
for col in columns:
print(f" {col[0]} ({col[1]})")
# Show all parameters for context
cursor.execute(f"SELECT * FROM {found_table} LIMIT 10")
all_params = cursor.fetchall()
print_info(f"\nFirst 10 parameters in {found_table}:")
for row in all_params:
print(f" Row: {row}")
# Try to find mem0 parameter based on actual column structure
if columns:
# Assume first column is key, second is value
key_col = columns[0][0]
query = f"SELECT * FROM {found_table} WHERE {key_col} = %s OR {key_col} LIKE %s"
cursor.execute(query, ('mem0.api_key', '%mem0%'))
results = cursor.fetchall()
if results:
print_success("Found mem0-related parameters:")
for row in results:
print(f" Row: {row}")
else:
print_warning("No mem0.api_key parameter found in system parameters")
else:
print_warning("No system parameters table found")
print_info("Available tables:")
cursor.execute("SHOW TABLES")
all_tables = cursor.fetchall()
for table in all_tables:
print(f" - {table[0]}")
except Exception as e:
print_error(f"Failed to check system parameters: {str(e)}")
def main():
"""Main function"""
print_header("System Parameters Check Script")
print_info(f"Timestamp: {datetime.now().isoformat()}")
# Connect to database
connection = connect_to_database()
if not connection:
print_error("Cannot proceed without database connection")
return 1
try:
check_system_params(connection)
finally:
connection.close()
print_info("Database connection closed")
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\nScript interrupted by user")
sys.exit(0)
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
sys.exit(1)

View file

@ -1,4 +1,4 @@
This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#deployment-documentation)
# Project Introduction

View file

@ -8,8 +8,8 @@ import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
/**
* Swagger配置
* Copyright (c) 人人开源 All rights reserved.
* Swagger Configuration
* Copyright (c) RenRen Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Configuration
@ -82,8 +82,8 @@ public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI().info(new Info()
.title("xiaozhi-esp32-manager-api")
.description("xiaozhi-esp32-manager-api文档")
.title("Xiaozhi ESP32 Manager API")
.description("Xiaozhi ESP32 Manager API Documentation")
.version("3.0")
.termsOfService("https://127.0.0.1"));
}

View file

@ -13,7 +13,7 @@ import xiaozhi.common.utils.Result;
import xiaozhi.modules.agent.dto.AgentChatHistoryReportDTO;
import xiaozhi.modules.agent.service.biz.AgentChatHistoryBizService;
@Tag(name = "智能体聊天历史管理")
@Tag(name = "Agent Chat History Management")
@RequiredArgsConstructor
@RestController
@RequestMapping("/agent/chat-history")
@ -27,7 +27,7 @@ public class AgentChatHistoryController {
*
* @param request 包含上传文件及相关信息的请求对象
*/
@Operation(summary = "小智服务聊天上报请求")
@Operation(summary = "Xiaozhi service chat report request")
@PostMapping("/report")
public Result<Boolean> uploadFile(@Valid @RequestBody AgentChatHistoryReportDTO request) {
Boolean result = agentChatHistoryBizService.report(request);

View file

@ -53,7 +53,7 @@ import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体管理")
@Tag(name = "Agent Management")
@AllArgsConstructor
@RestController
@RequestMapping("/agent")
@ -67,7 +67,7 @@ public class AgentController {
private final RedisUtils redisUtils;
@GetMapping("/list")
@Operation(summary = "获取用户智能体列表")
@Operation(summary = "Get user agents list")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentDTO>> getUserAgents() {
UserDetail user = SecurityUser.getUser();
@ -76,7 +76,7 @@ public class AgentController {
}
@GetMapping("/all")
@Operation(summary = "智能体列表(管理员)")
@Operation(summary = "Agent list (admin)")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@ -89,7 +89,7 @@ public class AgentController {
}
@GetMapping("/{id}")
@Operation(summary = "获取智能体详情")
@Operation(summary = "Get agent details")
@RequiresPermissions("sys:role:normal")
public Result<AgentInfoVO> getAgentById(@PathVariable("id") String id) {
AgentInfoVO agent = agentService.getAgentById(id);
@ -97,7 +97,7 @@ public class AgentController {
}
@PostMapping
@Operation(summary = "创建智能体")
@Operation(summary = "Create agent")
@RequiresPermissions("sys:role:normal")
public Result<String> save(@RequestBody @Valid AgentCreateDTO dto) {
String agentId = agentService.createAgent(dto);
@ -105,7 +105,7 @@ public class AgentController {
}
@PutMapping("/saveMemory/{macAddress}")
@Operation(summary = "根据设备id更新智能体")
@Operation(summary = "Update agent by device ID")
public Result<Void> updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) {
DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
if (device == null) {
@ -118,7 +118,7 @@ public class AgentController {
}
@PutMapping("/{id}")
@Operation(summary = "更新智能体")
@Operation(summary = "Update agent")
@RequiresPermissions("sys:role:normal")
public Result<Void> update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) {
agentService.updateAgentById(id, dto);
@ -126,7 +126,7 @@ public class AgentController {
}
@DeleteMapping("/{id}")
@Operation(summary = "删除智能体")
@Operation(summary = "Delete agent")
@RequiresPermissions("sys:role:normal")
public Result<Void> delete(@PathVariable String id) {
// 先删除关联的设备
@ -141,7 +141,7 @@ public class AgentController {
}
@GetMapping("/template")
@Operation(summary = "智能体模板模板列表")
@Operation(summary = "Agent template list")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> templateList() {
List<AgentTemplateEntity> list = agentTemplateService
@ -150,7 +150,7 @@ public class AgentController {
}
@GetMapping("/{id}/sessions")
@Operation(summary = "获取智能体会话列表")
@Operation(summary = "Get agent sessions list")
@RequiresPermissions("sys:role:normal")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@ -165,7 +165,7 @@ public class AgentController {
}
@GetMapping("/{id}/chat-history/{sessionId}")
@Operation(summary = "获取智能体聊天记录")
@Operation(summary = "Get agent chat history")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentChatHistoryDTO>> getAgentChatHistory(
@PathVariable("id") String id,
@ -183,7 +183,7 @@ public class AgentController {
return new Result<List<AgentChatHistoryDTO>>().ok(result);
}
@GetMapping("/{id}/chat-history/user")
@Operation(summary = "获取智能体聊天记录(用户)")
@Operation(summary = "Get agent chat history (user)")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentChatHistoryUserVO>> getRecentlyFiftyByAgentId(
@PathVariable("id") String id) {
@ -201,7 +201,7 @@ public class AgentController {
}
@GetMapping("/{id}/chat-history/audio")
@Operation(summary = "获取音频内容")
@Operation(summary = "Get audio content")
@RequiresPermissions("sys:role:normal")
public Result<String> getContentByAudioId(
@PathVariable("id") String id) {
@ -211,7 +211,7 @@ public class AgentController {
}
@PostMapping("/audio/{audioId}")
@Operation(summary = "获取音频下载ID")
@Operation(summary = "Get audio download ID")
@RequiresPermissions("sys:role:normal")
public Result<String> getAudioId(@PathVariable("audioId") String audioId) {
byte[] audioData = agentChatAudioService.getAudio(audioId);
@ -224,7 +224,7 @@ public class AgentController {
}
@GetMapping("/play/{uuid}")
@Operation(summary = "播放音频")
@Operation(summary = "Play audio")
public ResponseEntity<byte[]> playAudio(@PathVariable("uuid") String uuid) {
String audioId = (String) redisUtils.get(RedisKeys.getAgentAudioIdKey(uuid));

View file

@ -17,7 +17,7 @@ import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
import xiaozhi.modules.agent.service.AgentService;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体Mcp接入点管理")
@Tag(name = "Agent MCP Access Point Management")
@RequiredArgsConstructor
@RestController
@RequestMapping("/agent/mcp")
@ -31,7 +31,7 @@ public class AgentMcpAccessPointController {
* @param audioId 智能体id
* @return 返回错误提醒或者Mcp接入点地址
*/
@Operation(summary = "获取智能体的Mcp接入点地址")
@Operation(summary = "Get agent MCP access point address")
@GetMapping("/address/{agentId}")
@RequiresPermissions("sys:role:normal")
public Result<String> getAgentMcpAccessAddress(@PathVariable("agentId") String agentId) {
@ -49,7 +49,7 @@ public class AgentMcpAccessPointController {
return new Result<String>().ok(agentMcpAccessAddress);
}
@Operation(summary = "获取智能体的Mcp工具列表")
@Operation(summary = "Get agent MCP tools list")
@GetMapping("/tools/{agentId}")
@RequiresPermissions("sys:role:normal")
public Result<List<String>> getAgentMcpToolsList(@PathVariable("agentId") String agentId) {

View file

@ -21,7 +21,7 @@ import xiaozhi.modules.config.service.ConfigService;
*/
@RestController
@RequestMapping("config")
@Tag(name = "参数管理")
@Tag(name = "Parameter Management")
@AllArgsConstructor
public class ConfigController {
private final ConfigService configService;

View file

@ -398,6 +398,22 @@ public class ConfigServiceImpl implements ConfigService {
}
if ("Memory".equals(modelTypes[i])) {
Map<String, Object> map = (Map<String, Object>) model.getConfigJson();
// Fix for Memory configuration API key
if ("mem0ai".equals(map.get("type"))) {
// Always use the actual API key from system parameters for mem0
String mem0ApiKey = sysParamsService.getValue("mem0.api_key", false);
if (StringUtils.isNotBlank(mem0ApiKey)) {
map.put("api_key", mem0ApiKey);
System.out.println("[DEBUG] Using mem0 API key from system parameters");
} else {
// Fallback to the original logic
String apiKey = (String) map.get("api_key");
System.out.println("[DEBUG] No system parameter for mem0.api_key, using config value: " +
(apiKey != null ? "(length: " + apiKey.length() + ")" : "null"));
}
}
if ("mem_local_short".equals(map.get("type"))) {
memLocalShortLLMModelId = (String) map.get("llm");
if (StringUtils.isNotBlank(memLocalShortLLMModelId)

View file

@ -30,7 +30,7 @@ import xiaozhi.modules.timbre.service.TimbreService;
@AllArgsConstructor
@RestController
@RequestMapping("/models")
@Tag(name = "模型配置")
@Tag(name = "Model Configuration")
public class ModelController {
private final ModelProviderService modelProviderService;
@ -40,7 +40,7 @@ public class ModelController {
private final AgentTemplateService agentTemplateService;
@GetMapping("/names")
@Operation(summary = "获取所有模型名称")
@Operation(summary = "Get all model names")
@RequiresPermissions("sys:role:normal")
public Result<List<ModelBasicInfoDTO>> getModelNames(@RequestParam String modelType,
@RequestParam(required = false) String modelName) {
@ -49,7 +49,7 @@ public class ModelController {
}
@GetMapping("/llm/names")
@Operation(summary = "获取LLM模型信息")
@Operation(summary = "Get LLM model information")
@RequiresPermissions("sys:role:normal")
public Result<List<LlmModelBasicInfoDTO>> getLlmModelCodeList(@RequestParam(required = false) String modelName) {
List<LlmModelBasicInfoDTO> llmModelCodeList = modelConfigService.getLlmModelCodeList(modelName);
@ -57,7 +57,7 @@ public class ModelController {
}
@GetMapping("/{modelType}/provideTypes")
@Operation(summary = "获取模型供应器列表")
@Operation(summary = "Get model provider list")
@RequiresPermissions("sys:role:superAdmin")
public Result<List<ModelProviderDTO>> getModelProviderList(@PathVariable String modelType) {
List<ModelProviderDTO> modelProviderDTOS = modelProviderService.getListByModelType(modelType);
@ -65,7 +65,7 @@ public class ModelController {
}
@GetMapping("/list")
@Operation(summary = "获取模型配置列表")
@Operation(summary = "Get model configuration list")
@RequiresPermissions("sys:role:superAdmin")
public Result<PageData<ModelConfigDTO>> getModelConfigList(
@RequestParam(required = true) String modelType,
@ -77,7 +77,7 @@ public class ModelController {
}
@PostMapping("/{modelType}/{provideCode}")
@Operation(summary = "新增模型配置")
@Operation(summary = "Add model configuration")
@RequiresPermissions("sys:role:superAdmin")
public Result<ModelConfigDTO> addModelConfig(@PathVariable String modelType,
@PathVariable String provideCode,
@ -88,7 +88,7 @@ public class ModelController {
}
@PutMapping("/{modelType}/{provideCode}/{id}")
@Operation(summary = "编辑模型配置")
@Operation(summary = "Edit model configuration")
@RequiresPermissions("sys:role:superAdmin")
public Result<ModelConfigDTO> editModelConfig(@PathVariable String modelType,
@PathVariable String provideCode,
@ -100,7 +100,7 @@ public class ModelController {
}
@DeleteMapping("/{id}")
@Operation(summary = "删除模型配置")
@Operation(summary = "Delete model configuration")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> deleteModelConfig(@PathVariable String id) {
modelConfigService.delete(id);
@ -108,7 +108,7 @@ public class ModelController {
}
@GetMapping("/{id}")
@Operation(summary = "获取模型配置")
@Operation(summary = "Get model configuration")
@RequiresPermissions("sys:role:superAdmin")
public Result<ModelConfigDTO> getModelConfig(@PathVariable String id) {
ModelConfigEntity item = modelConfigService.selectById(id);
@ -117,7 +117,7 @@ public class ModelController {
}
@PutMapping("/enable/{id}/{status}")
@Operation(summary = "启用/关闭模型配置")
@Operation(summary = "Enable/disable model configuration")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> enableModelConfig(@PathVariable String id, @PathVariable Integer status) {
ModelConfigEntity entity = modelConfigService.selectById(id);
@ -130,7 +130,7 @@ public class ModelController {
}
@PutMapping("/default/{id}")
@Operation(summary = "设置默认模型")
@Operation(summary = "Set default model")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> setDefaultModel(@PathVariable String id) {
ModelConfigEntity entity = modelConfigService.selectById(id);
@ -151,7 +151,7 @@ public class ModelController {
}
@GetMapping("/{modelId}/voices")
@Operation(summary = "获取模型音色")
@Operation(summary = "Get model voices")
@RequiresPermissions("sys:role:normal")
public Result<List<VoiceDTO>> getVoiceList(@PathVariable String modelId,
@RequestParam(required = false) String voiceName) {

View file

@ -26,13 +26,13 @@ import xiaozhi.modules.model.service.ModelProviderService;
@AllArgsConstructor
@RestController
@RequestMapping("/models/provider")
@Tag(name = "模型供应器")
@Tag(name = "Model Provider")
public class ModelProviderController {
private final ModelProviderService modelProviderService;
@GetMapping
@Operation(summary = "获取模型供应器列表")
@Operation(summary = "Get model provider list")
@RequiresPermissions("sys:role:superAdmin")
public Result<PageData<ModelProviderDTO>> getListPage(ModelProviderDTO modelProviderDTO,
@RequestParam(required = true, defaultValue = "0") String page,
@ -42,7 +42,7 @@ public class ModelProviderController {
}
@PostMapping
@Operation(summary = "新增模型供应器")
@Operation(summary = "Add model provider")
@RequiresPermissions("sys:role:superAdmin")
public Result<ModelProviderDTO> add(@RequestBody @Validated ModelProviderDTO modelProviderDTO) {
ModelProviderDTO resp = modelProviderService.add(modelProviderDTO);
@ -50,7 +50,7 @@ public class ModelProviderController {
}
@PutMapping
@Operation(summary = "修改模型供应器")
@Operation(summary = "Edit model provider")
@RequiresPermissions("sys:role:superAdmin")
public Result<ModelProviderDTO> edit(@RequestBody @Validated(UpdateGroup.class) ModelProviderDTO modelProviderDTO) {
ModelProviderDTO resp = modelProviderService.edit(modelProviderDTO);
@ -58,7 +58,7 @@ public class ModelProviderController {
}
@PostMapping("/delete")
@Operation(summary = "删除模型供应器")
@Operation(summary = "Delete model provider")
@RequiresPermissions("sys:role:superAdmin")
@Parameter(name = "ids", description = "ID数组", required = true)
public Result<Void> delete(@RequestBody List<String> ids) {
@ -67,7 +67,7 @@ public class ModelProviderController {
}
@GetMapping("/plugin/names")
@Tag(name = "获取插件名称列表")
@Tag(name = "Get Plugin Name List")
public Result<List<ModelProviderDTO>> getPluginNameList() {
return ResultUtils.success(modelProviderService.getPluginList());
}

View file

@ -45,7 +45,7 @@ import xiaozhi.modules.sys.vo.SysDictDataItem;
@AllArgsConstructor
@RestController
@RequestMapping("/user")
@Tag(name = "登录管理")
@Tag(name = "Login Management")
public class LoginController {
private final SysUserService sysUserService;
private final SysUserTokenService sysUserTokenService;
@ -54,7 +54,7 @@ public class LoginController {
private final SysDictDataService sysDictDataService;
@GetMapping("/captcha")
@Operation(summary = "验证码")
@Operation(summary = "Captcha")
public void captcha(HttpServletResponse response, String uuid) throws IOException {
// uuid不能为空
AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);
@ -63,7 +63,7 @@ public class LoginController {
}
@PostMapping("/smsVerification")
@Operation(summary = "短信验证码")
@Operation(summary = "SMS verification code")
public Result<Void> smsVerification(@RequestBody SmsVerificationDTO dto) {
// 验证图形验证码
boolean validate = captchaService.validate(dto.getCaptchaId(), dto.getCaptcha(), true);
@ -81,7 +81,7 @@ public class LoginController {
}
@PostMapping("/login")
@Operation(summary = "登录")
@Operation(summary = "Login")
public Result<TokenDTO> login(@RequestBody LoginDTO login) {
// 验证是否正确输入验证码
boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha(), true);
@ -102,7 +102,7 @@ public class LoginController {
}
@PostMapping("/register")
@Operation(summary = "注册")
@Operation(summary = "Register")
public Result<Void> register(@RequestBody LoginDTO login) {
if (!sysUserService.getAllowUserRegister()) {
throw new RenException("当前不允许普通用户注册");
@ -143,7 +143,7 @@ public class LoginController {
}
@GetMapping("/info")
@Operation(summary = "用户信息获取")
@Operation(summary = "Get user information")
public Result<UserDetail> info() {
UserDetail user = SecurityUser.getUser();
Result<UserDetail> result = new Result<>();
@ -152,7 +152,7 @@ public class LoginController {
}
@PutMapping("/change-password")
@Operation(summary = "修改用户密码")
@Operation(summary = "Change user password")
public Result<?> changePassword(@RequestBody PasswordDTO passwordDTO) {
// 判断非空
ValidatorUtils.validateEntity(passwordDTO);
@ -162,7 +162,7 @@ public class LoginController {
}
@PutMapping("/retrieve-password")
@Operation(summary = "找回密码")
@Operation(summary = "Retrieve password")
public Result<?> retrievePassword(@RequestBody RetrievePasswordDTO dto) {
// 是否开启手机注册
Boolean isMobileRegister = sysParamsService
@ -195,7 +195,7 @@ public class LoginController {
}
@GetMapping("/pub-config")
@Operation(summary = "公共配置")
@Operation(summary = "Public configuration")
public Result<Map<String, Object>> pubConfig() {
Map<String, Object> config = new HashMap<>();
config.put("enableMobileRegister", sysParamsService

View file

@ -37,14 +37,14 @@ import xiaozhi.modules.sys.vo.AdminPageUserVO;
@AllArgsConstructor
@RestController
@RequestMapping("/admin")
@Tag(name = "管理员管理")
@Tag(name = "Administrator Management")
public class AdminController {
private final SysUserService sysUserService;
private final DeviceService deviceService;
@GetMapping("/users")
@Operation(summary = "分页查找用户")
@Operation(summary = "Paginated user search")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = "mobile", description = "用户手机号码", required = false),
@ -63,7 +63,7 @@ public class AdminController {
}
@PutMapping("/users/{id}")
@Operation(summary = "重置密码")
@Operation(summary = "Reset password")
@RequiresPermissions("sys:role:superAdmin")
public Result<String> update(
@PathVariable Long id) {
@ -72,7 +72,7 @@ public class AdminController {
}
@DeleteMapping("/users/{id}")
@Operation(summary = "用户删除")
@Operation(summary = "Delete user")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> delete(@PathVariable Long id) {
sysUserService.deleteById(id);
@ -80,7 +80,7 @@ public class AdminController {
}
@PutMapping("/users/changeStatus/{status}")
@Operation(summary = "批量修改用户状态")
@Operation(summary = "Batch modify user status")
@RequiresPermissions("sys:role:superAdmin")
@Parameter(name = "status", description = "用户状态", required = true)
public Result<Void> changeStatus(@PathVariable Integer status, @RequestBody String[] userIds) {
@ -89,7 +89,7 @@ public class AdminController {
}
@GetMapping("/device/all")
@Operation(summary = "分页查找设备")
@Operation(summary = "Paginated device search")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = "keywords", description = "设备关键词", required = false),

View file

@ -36,7 +36,7 @@ import xiaozhi.modules.sys.utils.WebSocketClientManager;
*/
@RestController
@RequestMapping("/admin/server")
@Tag(name = "服务端管理")
@Tag(name = "Server Management")
@AllArgsConstructor
public class ServerSideManageController {
private final SysParamsService sysParamsService;
@ -47,7 +47,7 @@ public class ServerSideManageController {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Operation(summary = "获取Ws服务端列表")
@Operation(summary = "Get WebSocket server list")
@GetMapping("/server-list")
@RequiresPermissions("sys:role:superAdmin")
public Result<List<String>> getWsServerList() {
@ -58,7 +58,7 @@ public class ServerSideManageController {
return new Result<List<String>>().ok(Arrays.asList(wsText.split(";")));
}
@Operation(summary = "通知python服务端更新配置")
@Operation(summary = "Notify Python server to update configuration")
@PostMapping("/emit-action")
@LogOperation("通知python服务端更新配置")
@RequiresPermissions("sys:role:superAdmin")

View file

@ -37,12 +37,12 @@ import xiaozhi.modules.sys.vo.SysDictDataVO;
@AllArgsConstructor
@RestController
@RequestMapping("/admin/dict/data")
@Tag(name = "字典数据管理")
@Tag(name = "Dictionary Data Management")
public class SysDictDataController {
private final SysDictDataService sysDictDataService;
@GetMapping("/page")
@Operation(summary = "分页查询字典数据")
@Operation(summary = "Paginated dictionary data query")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({ @Parameter(name = "dictTypeId", description = "字典类型ID", required = true),
@Parameter(name = "dictLabel", description = "数据标签"), @Parameter(name = "dictValue", description = "数据值"),
@ -60,7 +60,7 @@ public class SysDictDataController {
}
@GetMapping("/{id}")
@Operation(summary = "获取字典数据详情")
@Operation(summary = "Get dictionary data details")
@RequiresPermissions("sys:role:superAdmin")
public Result<SysDictDataVO> get(@PathVariable("id") Long id) {
SysDictDataVO vo = sysDictDataService.get(id);
@ -68,7 +68,7 @@ public class SysDictDataController {
}
@PostMapping("/save")
@Operation(summary = "新增字典数据")
@Operation(summary = "Add dictionary data")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> save(@RequestBody SysDictDataDTO dto) {
ValidatorUtils.validateEntity(dto);
@ -77,7 +77,7 @@ public class SysDictDataController {
}
@PutMapping("/update")
@Operation(summary = "修改字典数据")
@Operation(summary = "Modify dictionary data")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> update(@RequestBody SysDictDataDTO dto) {
ValidatorUtils.validateEntity(dto);
@ -86,7 +86,7 @@ public class SysDictDataController {
}
@PostMapping("/delete")
@Operation(summary = "删除字典数据")
@Operation(summary = "Delete dictionary data")
@RequiresPermissions("sys:role:superAdmin")
@Parameter(name = "ids", description = "ID数组", required = true)
public Result<Void> delete(@RequestBody Long[] ids) {
@ -95,7 +95,7 @@ public class SysDictDataController {
}
@GetMapping("/type/{dictType}")
@Operation(summary = "获取字典数据列表")
@Operation(summary = "Get dictionary data list")
@RequiresPermissions("sys:role:normal")
public Result<List<SysDictDataItem>> getDictDataByType(@PathVariable("dictType") String dictType) {
List<SysDictDataItem> list = sysDictDataService.getDictDataByType(dictType);

View file

@ -34,12 +34,12 @@ import xiaozhi.modules.sys.vo.SysDictTypeVO;
@AllArgsConstructor
@RestController
@RequestMapping("/admin/dict/type")
@Tag(name = "字典类型管理")
@Tag(name = "Dictionary Type Management")
public class SysDictTypeController {
private final SysDictTypeService sysDictTypeService;
@GetMapping("/page")
@Operation(summary = "分页查询字典类型")
@Operation(summary = "Paginated dictionary type query")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({ @Parameter(name = "dictType", description = "字典类型编码"),
@Parameter(name = "dictName", description = "字典类型名称"),
@ -52,7 +52,7 @@ public class SysDictTypeController {
}
@GetMapping("/{id}")
@Operation(summary = "获取字典类型详情")
@Operation(summary = "Get dictionary type details")
@RequiresPermissions("sys:role:superAdmin")
public Result<SysDictTypeVO> get(@PathVariable("id") Long id) {
SysDictTypeVO vo = sysDictTypeService.get(id);
@ -60,7 +60,7 @@ public class SysDictTypeController {
}
@PostMapping("/save")
@Operation(summary = "保存字典类型")
@Operation(summary = "Save dictionary type")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> save(@RequestBody SysDictTypeDTO dto) {
// 参数校验
@ -71,7 +71,7 @@ public class SysDictTypeController {
}
@PutMapping("/update")
@Operation(summary = "修改字典类型")
@Operation(summary = "Modify dictionary type")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> update(@RequestBody SysDictTypeDTO dto) {
// 参数校验
@ -82,7 +82,7 @@ public class SysDictTypeController {
}
@PostMapping("/delete")
@Operation(summary = "删除字典类型")
@Operation(summary = "Delete dictionary type")
@RequiresPermissions("sys:role:superAdmin")
@Parameter(name = "ids", description = "ID数组", required = true)
public Result<Void> delete(@RequestBody Long[] ids) {

View file

@ -45,7 +45,7 @@ import xiaozhi.modules.sys.utils.WebSocketValidator;
*/
@RestController
@RequestMapping("admin/params")
@Tag(name = "参数管理")
@Tag(name = "Parameter Management")
@AllArgsConstructor
public class SysParamsController {
private final SysParamsService sysParamsService;
@ -53,7 +53,7 @@ public class SysParamsController {
private final RestTemplate restTemplate;
@GetMapping("page")
@Operation(summary = "分页")
@Operation(summary = "Pagination")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
@ -69,7 +69,7 @@ public class SysParamsController {
}
@GetMapping("{id}")
@Operation(summary = "信息")
@Operation(summary = "Information")
@RequiresPermissions("sys:role:superAdmin")
public Result<SysParamsDTO> get(@PathVariable("id") Long id) {
SysParamsDTO data = sysParamsService.get(id);
@ -78,7 +78,7 @@ public class SysParamsController {
}
@PostMapping
@Operation(summary = "保存")
@Operation(summary = "Save")
@LogOperation("保存")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> save(@RequestBody SysParamsDTO dto) {
@ -91,7 +91,7 @@ public class SysParamsController {
}
@PutMapping
@Operation(summary = "修改")
@Operation(summary = "Modify")
@LogOperation("修改")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> update(@RequestBody SysParamsDTO dto) {
@ -150,7 +150,7 @@ public class SysParamsController {
}
@PostMapping("/delete")
@Operation(summary = "删除")
@Operation(summary = "Delete")
@LogOperation("删除")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> delete(@RequestBody String[] ids) {

View file

@ -35,12 +35,12 @@ import xiaozhi.modules.timbre.vo.TimbreDetailsVO;
@AllArgsConstructor
@RestController
@RequestMapping("/ttsVoice")
@Tag(name = "音色管理")
@Tag(name = "Timbre Management")
public class TimbreController {
private final TimbreService timbreService;
@GetMapping
@Operation(summary = "分页查找")
@Operation(summary = "Paginated search")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = "ttsModelId", description = "对应 TTS 模型主键", required = true),
@ -62,7 +62,7 @@ public class TimbreController {
}
@PostMapping
@Operation(summary = "音色保存")
@Operation(summary = "Save timbre")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> save(@RequestBody TimbreDataDTO dto) {
ValidatorUtils.validateEntity(dto);
@ -71,7 +71,7 @@ public class TimbreController {
}
@PutMapping("/{id}")
@Operation(summary = "音色修改")
@Operation(summary = "Modify timbre")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> update(
@PathVariable String id,
@ -82,7 +82,7 @@ public class TimbreController {
}
@PostMapping("/delete")
@Operation(summary = "音色删除")
@Operation(summary = "Delete timbre")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> delete(@RequestBody String[] ids) {
timbreService.delete(ids);

View file

@ -1,4 +1,5 @@
VUE_APP_API_BASE_URL=/xiaozhi
VUE_APP_PUBLIC_PATH=/
# 是否开启CDN
VUE_APP_USE_CDN=false
VUE_APP_USE_CDN=false
VUE_APP_TITLE=cheeko

View file

@ -1,5 +1,5 @@
<template>
<el-dialog :title="'与' + agentName + '的聊天记录' + (currentMacAddress ? '[' + currentMacAddress + ']' : '')"
<el-dialog :title="'Chat History with ' + agentName + (currentMacAddress ? ' [' + currentMacAddress + ']' : '')"
:visible.sync="dialogVisible" width="80%" :before-close="handleClose" custom-class="chat-history-dialog">
<div class="chat-container">
<div class="session-list" @scroll="handleScroll">
@ -11,8 +11,8 @@
<div class="message-count">{{ session.chatCount > 99 ? '99' : session.chatCount }}</div>
</div>
</div>
<div v-if="loading" class="loading">加载中...</div>
<div v-if="!hasMore" class="no-more">没有更多记录了</div>
<div v-if="loading" class="loading">Loading...</div>
<div v-if="!hasMore" class="no-more">No more records</div>
</div>
<div class="chat-content">
<div v-if="currentSessionId" class="messages">
@ -32,7 +32,7 @@
</div>
</div>
<div v-else class="no-session-selected">
请选择会话查看聊天记录
Please select a session to view chat history
</div>
</div>
</div>
@ -230,9 +230,9 @@ export default {
const minutes = date.getMinutes().toString().padStart(2, '0');
if (date >= today) {
return `今天 ${hours}:${minutes}`;
return `Today ${hours}:${minutes}`;
} else if (date >= yesterday) {
return `昨天 ${hours}:${minutes}`;
return `Yesterday ${hours}:${minutes}`;
} else {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');

View file

@ -5,11 +5,11 @@
{{ device.agentName }}
</div>
<div>
<img src="@/assets/home/delete.png" alt="" style="width: 18px;height: 18px;margin-right: 10px;"
<img src="@/assets/home/delete.png" alt="" class="action-icon delete-icon"
@click.stop="handleDelete" />
<el-tooltip class="item" effect="dark" :content="device.systemPrompt" placement="top"
popper-class="custom-tooltip">
<img src="@/assets/home/info.png" alt="" style="width: 18px;height: 18px;" />
<img src="@/assets/home/info.png" alt="" class="action-icon info-icon" />
</el-tooltip>
</div>
</div>
@ -141,6 +141,35 @@ export default {
color: #999;
cursor: not-allowed;
}
.action-icon {
width: 24px;
height: 24px;
cursor: pointer;
transition: all 0.3s ease;
margin-right: 10px;
border-radius: 4px;
padding: 2px;
}
.action-icon:hover {
transform: scale(1.2);
background-color: rgba(87, 120, 255, 0.1);
}
.delete-icon:hover {
background-color: rgba(245, 108, 108, 0.1);
filter: brightness(1.2);
}
.info-icon {
margin-right: 0;
}
.info-icon:hover {
background-color: rgba(64, 158, 255, 0.1);
filter: brightness(1.2);
}
</style>
<style>

View file

@ -150,23 +150,23 @@ export default {
this.isLoading = false;
});
},
// 删除智能体
// Delete agent
handleDeleteAgent(agentId) {
this.$confirm('确定要删除该智能体吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
this.$confirm('Are you sure you want to delete this agent?', 'Confirm', {
confirmButtonText: 'Confirm',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
Api.agent.deleteAgent(agentId, (res) => {
if (res.data.code === 0) {
this.$message.success({
message: '删除成功',
message: 'Deleted successfully',
showClose: true
});
this.fetchAgentList(); // 刷新列表
this.fetchAgentList(); // Refresh list
} else {
this.$message.error({
message: res.data.msg || '删除失败',
message: res.data.msg || 'Failed to delete',
showClose: true
});
}

View file

@ -84,7 +84,7 @@
</div>
</el-form-item>
</div>
<el-form-item v-for="(model, index) in models.slice(2)" :key="`model-${index}`" :label="model.label"
<el-form-item v-for="(model, index) in models.slice(2).filter(m => m.type !== 'VLLM')" :key="`model-${index}`" :label="model.label"
class="model-item">
<div class="model-select-wrapper">
<el-select v-model="form.model[model.key]" filterable placeholder="Please select" class="form-select"
@ -281,15 +281,15 @@ export default {
try {
this.applyTemplateData(template);
this.$message.success({
message: `「${template.agentName}」模板已应用`,
message: `"${template.agentName}" template applied`,
showClose: true
});
} catch (error) {
this.$message.error({
message: '应用模板失败',
message: 'Failed to apply template',
showClose: true
});
console.error('应用模板失败:', error);
console.error('Failed to apply template:', error);
} finally {
this.loadingTemplate = false;
}
@ -692,16 +692,18 @@ export default {
.template-item {
height: 4vh;
width: 76px;
width: auto;
border-radius: 8px;
background: #e6ebff;
background: hsl(228, 100%, 95%);
line-height: 4vh;
font-weight: 400;
font-size: 11px;
font-size: 14px;
text-align: center;
color: #5778ff;
cursor: pointer;
transition: background-color 0.3s ease;
padding-left: 10px;
padding-right: 10px;
}
.template-item:hover {

View file

@ -255,6 +255,17 @@ class ConnectionHandler:
"""Save memory and close the connection"""
try:
if self.memory:
# Log where memory is being saved based on memory type
memory_type = getattr(self, 'memory_type', 'unknown')
if memory_type == "nomem":
self.logger.bind(tag=TAG).info("Memory saving DISABLED (using nomem)")
elif memory_type == "mem0ai":
self.logger.bind(tag=TAG).info("Saving memory to MEM0 CLOUD")
elif memory_type == "mem_local_short":
self.logger.bind(tag=TAG).info("Saving memory to LOCAL STORAGE (mem_local_short)")
else:
self.logger.bind(tag=TAG).info(f"Saving memory using: {memory_type}")
# Use a thread pool to save memory asynchronously
def save_memory_task():
try:
@ -264,6 +275,7 @@ class ConnectionHandler:
loop.run_until_complete(
self.memory.save_memory(self.dialogue.dialogue)
)
self.logger.bind(tag=TAG).info(f"Memory saved successfully using {memory_type}")
except Exception as e:
self.logger.bind(tag=TAG).error(
f"Failed to save memory: {e}")
@ -474,6 +486,24 @@ class ConnectionHandler:
)
private_config["delete_audio"] = bool(
self.config.get("delete_audio", True))
# Log the actual API key status for debugging (without exposing the full key)
if "Memory" in private_config and "Memory_mem0ai" in private_config.get("Memory", {}):
mem0_config = private_config["Memory"]["Memory_mem0ai"]
api_key = mem0_config.get("api_key", "")
# DEBUG: Print the full API key to verify what's being received
self.logger.bind(tag=TAG).info(f"[DEBUG] Raw mem0 API key received: '{api_key}'")
if api_key == "***":
self.logger.bind(tag=TAG).warning(
"Mem0 API key is MASKED (***) from manager API - please configure the actual API key in the Manager Web Dashboard under Provider Management"
)
elif api_key:
masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****"
self.logger.bind(tag=TAG).debug(f"Mem0 API key received: {masked_key} (length: {len(api_key)})")
else:
self.logger.bind(tag=TAG).warning("Mem0 API key is empty in differential configuration")
self.logger.bind(tag=TAG).info(
f"{time.time() - begin_time} seconds, successfully obtained differential configuration: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
)
@ -606,11 +636,16 @@ class ConnectionHandler:
memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
"type"
]
# Store memory type for logging
self.memory_type = memory_type
# If using nomem, return directly
if memory_type == "nomem":
self.logger.bind(tag=TAG).info("Memory module initialized: DISABLED (nomem)")
return
# Use mem_local_short mode
elif memory_type == "mem_local_short":
self.logger.bind(tag=TAG).info("Memory module initialized: LOCAL STORAGE (mem_local_short)")
memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
"llm"
]
@ -632,7 +667,11 @@ class ConnectionHandler:
# Otherwise use main LLM
self.memory.set_llm(self.llm)
self.logger.bind(tag=TAG).info(
"Using main LLM as intent recognition model")
"Using main LLM as memory model")
elif memory_type == "mem0ai":
self.logger.bind(tag=TAG).info("Memory module initialized: MEM0 CLOUD (mem0ai)")
else:
self.logger.bind(tag=TAG).info(f"Memory module initialized: {memory_type}")
def _initialize_intent(self):
if self.intent is None:

View file

@ -95,8 +95,10 @@ def opus_to_wav(conn, opus_data):
def enqueue_tts_report(conn, text, opus_data):
if not conn.read_config_from_api or conn.need_bind or not conn.report_tts_enable:
conn.logger.bind(tag=TAG).info("Chat history NOT SAVED - API config or binding not enabled")
return
if conn.chat_history_conf == 0:
conn.logger.bind(tag=TAG).info("Chat history NOT SAVED - Disabled in configuration (chatHistoryConf = 0)")
return
"""Add TTS data to reporting queue
@ -109,13 +111,13 @@ def enqueue_tts_report(conn, text, opus_data):
# Use connection object's queue, pass text and binary data instead of file path
if conn.chat_history_conf == 2:
conn.report_queue.put((2, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"TTS data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
conn.logger.bind(tag=TAG).info(
f"Chat history saving to MYSQL DATABASE with TEXT + AUDIO (device: {conn.device_id}, audio size: {len(opus_data)} bytes)"
)
else:
conn.report_queue.put((2, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"TTS data added to reporting queue: {conn.device_id}, no audio reporting"
conn.logger.bind(tag=TAG).info(
f"Chat history saving to MYSQL DATABASE with TEXT ONLY (device: {conn.device_id})"
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Failed to add TTS to reporting queue: {text}, {e}")
@ -123,8 +125,10 @@ def enqueue_tts_report(conn, text, opus_data):
def enqueue_asr_report(conn, text, opus_data):
if not conn.read_config_from_api or conn.need_bind or not conn.report_asr_enable:
conn.logger.bind(tag=TAG).info("User audio NOT SAVED - API config or binding not enabled")
return
if conn.chat_history_conf == 0:
conn.logger.bind(tag=TAG).info("User audio NOT SAVED - Disabled in configuration (chatHistoryConf = 0)")
return
"""Add ASR data to reporting queue
@ -137,13 +141,13 @@ def enqueue_asr_report(conn, text, opus_data):
# Use connection object's queue, pass text and binary data instead of file path
if conn.chat_history_conf == 2:
conn.report_queue.put((1, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"ASR data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
conn.logger.bind(tag=TAG).info(
f"User audio saving to MYSQL DATABASE with TEXT + AUDIO (device: {conn.device_id}, audio size: {len(opus_data)} bytes)"
)
else:
conn.report_queue.put((1, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"ASR data added to reporting queue: {conn.device_id}, no audio reporting"
conn.logger.bind(tag=TAG).info(
f"User audio saving to MYSQL DATABASE with TEXT ONLY (device: {conn.device_id})"
)
except Exception as e:
conn.logger.bind(tag=TAG).debug(f"Failed to add ASR to reporting queue: {text}, {e}")

View file

@ -11,15 +11,26 @@ class MemoryProvider(MemoryProviderBase):
super().__init__(config)
self.api_key = config.get("api_key", "")
self.api_version = config.get("api_version", "v1.1")
# Debug logging for API key (show first/last 4 chars only for security)
if self.api_key:
masked_key = f"{self.api_key[:4]}...{self.api_key[-4:]}" if len(self.api_key) > 8 else "****"
logger.bind(tag=TAG).debug(f"Mem0 API key configured: {masked_key} (length: {len(self.api_key)})")
else:
logger.bind(tag=TAG).warning("Mem0 API key is empty or not configured")
model_key_msg = check_model_key("Mem0ai", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
logger.bind(tag=TAG).error(f"API key validation failed. Please check your Mem0 API key configuration.")
self.use_mem0 = False
return
else:
self.use_mem0 = True
logger.bind(tag=TAG).debug("Mem0 API key passed initial validation")
try:
logger.bind(tag=TAG).debug(f"Attempting to connect to Mem0ai service with API version: {self.api_version}")
self.client = MemoryClient(api_key=self.api_key)
logger.bind(tag=TAG).info(
"Successfully connected to Mem0ai service")
@ -28,6 +39,8 @@ class MemoryProvider(MemoryProviderBase):
f"Error occurred while connecting to Mem0ai service: {str(e)}")
logger.bind(tag=TAG).error(
f"Detailed error: {traceback.format_exc()}")
logger.bind(tag=TAG).error(
"Please verify your API key at https://app.mem0.ai/dashboard/api-keys")
self.use_mem0 = False
async def save_memory(self, msgs):

View file

@ -73,6 +73,20 @@ def initialize_modules(
if "type" not in config["Memory"][select_memory_module]
else config["Memory"][select_memory_module]["type"]
)
# Debug logging for memory configuration
memory_config = config["Memory"][select_memory_module]
logger.bind(tag=TAG).debug(f"Memory module selected: {select_memory_module}")
logger.bind(tag=TAG).debug(f"Memory type: {memory_type}")
logger.bind(tag=TAG).debug(f"Memory config keys: {list(memory_config.keys()) if isinstance(memory_config, dict) else 'Not a dict'}")
if memory_type == "mem0ai" and isinstance(memory_config, dict):
api_key = memory_config.get("api_key", "")
if api_key:
masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****"
logger.bind(tag=TAG).debug(f"Mem0 API key from config: {masked_key} (length: {len(api_key)})")
else:
logger.bind(tag=TAG).warning("Mem0 API key not found in configuration")
modules["memory"] = memory.create_instance(
memory_type,

307
test_manager_api.py Normal file
View file

@ -0,0 +1,307 @@
#!/usr/bin/env python3
"""
Test script for Manager API configuration endpoints
This script tests the getAgentModels endpoint that xiaozhi-server uses to get device configuration
"""
import requests
import json
import sys
from datetime import datetime
# Configuration
MANAGER_API_BASE_URL = "http://192.168.1.105:8002/xiaozhi"
SECRET = "66122e75-3b2a-45d7-a082-0f0894529348"
# Test device information
TEST_DEVICE_MAC = "68:25:dd:bb:4d:44" # Your actual device MAC
TEST_CLIENT_ID = "test-client-001"
# Colors for output
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def print_header(text):
"""Print a formatted header"""
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
def print_success(text):
"""Print success message"""
print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}")
def print_error(text):
"""Print error message"""
print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}")
def print_info(text):
"""Print info message"""
print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}")
def print_json(data, indent=2):
"""Pretty print JSON data"""
print(json.dumps(data, indent=indent, ensure_ascii=False))
def test_server_config():
"""Test getting server configuration"""
print_header("Testing Server Configuration Endpoint")
url = f"{MANAGER_API_BASE_URL}/config/server-base"
# Use Bearer token authentication like the actual client
headers = {
"Authorization": f"Bearer {SECRET}",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "PythonClient/2.0 Test"
}
try:
print_info(f"POST {url}")
response = requests.post(url, headers=headers, json={})
if response.status_code == 200:
data = response.json()
if data.get("code") == 0:
print_success("Server configuration retrieved successfully")
print_info("Server Configuration:")
print_json(data.get("data", {}))
return data.get("data")
else:
print_error(f"API returned error: {data.get('msg')}")
else:
print_error(f"HTTP {response.status_code}: {response.text}")
except Exception as e:
print_error(f"Request failed: {str(e)}")
return None
def test_agent_models(mac_address=TEST_DEVICE_MAC, client_id=TEST_CLIENT_ID):
"""Test getting agent models configuration for a device"""
print_header("Testing Agent Models Configuration Endpoint")
url = f"{MANAGER_API_BASE_URL}/config/agent-models"
# Build request body (no secret in body, it's in the header)
request_data = {
"macAddress": mac_address,
"clientId": client_id,
"selectedModule": {
"VAD": None,
"ASR": None,
"LLM": None,
"TTS": None,
"Memory": None,
"Intent": None,
"VLLM": None
}
}
# Use Bearer token authentication
headers = {
"Authorization": f"Bearer {SECRET}",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "PythonClient/2.0 Test"
}
try:
print_info(f"POST {url}")
print_info(f"Device MAC: {mac_address}")
print_info(f"Client ID: {client_id}")
print_info("Request Body:")
print_json(request_data)
response = requests.post(url, json=request_data, headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("code") == 0:
print_success("Agent models configuration retrieved successfully")
config = data.get("data", {})
# Analyze the configuration
analyze_configuration(config)
# Save to file for analysis
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"agent_config_{timestamp}.json"
with open(filename, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
print_success(f"Configuration saved to {filename}")
return config
else:
print_error(f"API returned error: {data.get('msg')}")
if "OTA_DEVICE_NEED_BIND" in str(data.get("code", "")):
print_info("Device needs binding. Bind code: " + data.get("msg", ""))
else:
print_error(f"HTTP {response.status_code}: {response.text}")
except Exception as e:
print_error(f"Request failed: {str(e)}")
return None
def analyze_configuration(config):
"""Analyze and display key configuration details"""
print_header("Configuration Analysis")
# Check selected modules
if "selected_module" in config:
print_info("Selected Modules:")
for module, value in config["selected_module"].items():
status = f"{Colors.OKGREEN}[OK]{Colors.ENDC}" if value else f"{Colors.WARNING}[X]{Colors.ENDC}"
print(f" {status} {module}: {value or 'Not configured'}")
# Check Memory configuration specifically
if "Memory" in config:
print_info("\nMemory Configuration:")
for mem_id, mem_config in config["Memory"].items():
print(f" Module: {mem_id}")
if isinstance(mem_config, dict):
for key, value in mem_config.items():
if key == "api_key":
# Check if API key is masked
if value == "***":
print_error(f" {key}: {value} (MASKED - This is the problem!)")
elif value and len(value) > 20:
print_success(f" {key}: {value[:10]}...{value[-10:]} (length: {len(value)})")
else:
print_warning(f" {key}: {value} (Suspicious - too short!)")
else:
print(f" {key}: {value}")
# Check LLM configuration
if "LLM" in config:
print_info("\nLLM Configuration:")
for llm_id, llm_config in config["LLM"].items():
print(f" Module: {llm_id}")
if isinstance(llm_config, dict):
for key, value in llm_config.items():
if key == "api_key":
if value == "***":
print_error(f" {key}: {value} (MASKED)")
else:
print(f" {key}: {value[:10]}...{value[-10:] if len(str(value)) > 20 else value}")
elif key in ["base_url", "model_name"]:
print(f" {key}: {value}")
# Check other important settings
print_info("\nOther Settings:")
print(f" Chat History Config: {config.get('chat_history_conf', 'Not set')}")
print(f" Device Max Output Size: {config.get('device_max_output_size', 'Not set')}")
print(f" Summary Memory: {config.get('summaryMemory', 'Not set')}")
# Check plugins
if "plugins" in config:
print_info("\nPlugins:")
for plugin_name in config["plugins"].keys():
print(f" + {plugin_name}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}")
def test_device_registration():
"""Test device registration status"""
print_header("Testing Device Registration")
url = f"{MANAGER_API_BASE_URL}/device/info/{TEST_DEVICE_MAC}"
# Use Bearer token authentication
headers = {
"Authorization": f"Bearer {SECRET}",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "PythonClient/2.0 Test"
}
try:
print_info(f"GET {url}")
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("code") == 0:
device_info = data.get("data")
if device_info:
print_success("Device is registered")
print_info(f"Device ID: {device_info.get('id')}")
print_info(f"Agent ID: {device_info.get('agentId')}")
print_info(f"User ID: {device_info.get('userId')}")
else:
print_warning("Device not found in database")
else:
print_error(f"API returned error: {data.get('msg')}")
else:
print_error(f"HTTP {response.status_code}: {response.text}")
except Exception as e:
print_error(f"Request failed: {str(e)}")
def main():
"""Main test function"""
print_header("Manager API Configuration Test Script")
print_info(f"Manager API URL: {MANAGER_API_BASE_URL}")
print_info(f"Test Device MAC: {TEST_DEVICE_MAC}")
print_info(f"Timestamp: {datetime.now().isoformat()}")
# Test server configuration
server_config = test_server_config()
# Test device registration
test_device_registration()
# Test agent models configuration
agent_config = test_agent_models()
# Summary
print_header("Test Summary")
if agent_config:
# Check for masked API keys
memory_config = agent_config.get("Memory", {})
masked_keys = []
for module_id, module_config in memory_config.items():
if isinstance(module_config, dict):
api_key = module_config.get("api_key")
if api_key == "***":
masked_keys.append(f"Memory/{module_id}")
llm_config = agent_config.get("LLM", {})
for module_id, module_config in llm_config.items():
if isinstance(module_config, dict):
api_key = module_config.get("api_key")
if api_key == "***":
masked_keys.append(f"LLM/{module_id}")
if masked_keys:
print_error("PROBLEM FOUND: The following API keys are masked:")
for key in masked_keys:
print(f" - {key}")
print_warning("\nSolution Options:")
print(" 1. Add system parameter 'mem0.api_key' with the actual API key")
print(" 2. Update the database directly with the actual API key")
print(" 3. Modify the backend to not mask API keys for device connections")
else:
print_success("All API keys appear to be properly configured")
else:
print_error("Failed to retrieve agent configuration")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nTest interrupted by user")
sys.exit(0)
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
sys.exit(1)

296
update_mem0_api_key.py Normal file
View file

@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""
Script to update mem0 API key directly in the database
This bypasses the masking issue by directly updating the database
"""
import pymysql
import json
import sys
from datetime import datetime
# Database configuration - from application-dev.yml
DB_CONFIG = {
'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host
'port': 25037, # Railway MySQL port
'user': 'root', # Database username
'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password
'database': 'railway', # Database name
'charset': 'utf8mb4',
'connect_timeout': 30, # Connection timeout in seconds
'read_timeout': 30,
'write_timeout': 30,
'autocommit': False,
'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config
}
# The actual mem0 API key
MEM0_API_KEY = "m0-WNBvGhsBGZU1NDKDF42ecLNAgMk0GRaToaKLT0wN"
# Colors for output
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def print_header(text):
"""Print a formatted header"""
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
def print_success(text):
"""Print success message"""
print(f"{Colors.OKGREEN}✓ {text}{Colors.ENDC}")
def print_error(text):
"""Print error message"""
print(f"{Colors.FAIL}✗ {text}{Colors.ENDC}")
def print_info(text):
"""Print info message"""
print(f"{Colors.OKCYAN}ℹ {text}{Colors.ENDC}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.WARNING}⚠ {text}{Colors.ENDC}")
def connect_to_database():
"""Connect to the MySQL database with retry logic"""
max_retries = 3
retry_delay = 5
for attempt in range(1, max_retries + 1):
try:
print_info(f"Connecting to database... (Attempt {attempt}/{max_retries})")
print_info(f"Host: {DB_CONFIG['host']}:{DB_CONFIG['port']}")
connection = pymysql.connect(**DB_CONFIG)
# Test the connection
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
cursor.fetchone()
print_success("Successfully connected to database")
return connection
except pymysql.err.OperationalError as e:
error_code = e.args[0] if e.args else None
error_msg = e.args[1] if len(e.args) > 1 else str(e)
if error_code == 2013:
print_warning(f"Connection lost during query. This might be a network issue.")
elif error_code == 1045:
print_error(f"Access denied. Check your username and password.")
return None
else:
print_warning(f"Connection error: {error_msg}")
if attempt < max_retries:
print_info(f"Retrying in {retry_delay} seconds...")
import time
time.sleep(retry_delay)
else:
print_error(f"Failed to connect after {max_retries} attempts")
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
if attempt < max_retries:
print_info(f"Retrying in {retry_delay} seconds...")
import time
time.sleep(retry_delay)
else:
return None
return None
def find_mem0_configs(connection):
"""Find all mem0ai configurations in the database"""
try:
with connection.cursor() as cursor:
# Query to find mem0ai configurations
query = """
SELECT id, model_name, config_json
FROM ai_model_config
WHERE model_type = 'Memory'
AND JSON_EXTRACT(config_json, '$.type') = 'mem0ai'
"""
cursor.execute(query)
results = cursor.fetchall()
if results:
print_success(f"Found {len(results)} mem0ai configuration(s)")
for row in results:
config_id, model_name, config_json_str = row
config_json = json.loads(config_json_str) if config_json_str else {}
current_api_key = config_json.get('api_key', '')
print_info(f"\nConfiguration ID: {config_id}")
print_info(f"Model Name: {model_name}")
if current_api_key == "***":
print_warning(f"Current API key: {current_api_key} (MASKED)")
elif current_api_key == MEM0_API_KEY:
print_success(f"Current API key: {current_api_key[:10]}...{current_api_key[-10:]} (Already correct)")
elif current_api_key:
print_warning(f"Current API key: {current_api_key[:10]}...{current_api_key[-10:] if len(current_api_key) > 20 else current_api_key}")
else:
print_warning("Current API key: (empty)")
return results
else:
print_warning("No mem0ai configurations found")
return []
except Exception as e:
print_error(f"Failed to query database: {str(e)}")
return []
def update_api_keys(connection, configs):
"""Update the API keys for mem0ai configurations"""
if not configs:
print_warning("No configurations to update")
return False
try:
with connection.cursor() as cursor:
updated_count = 0
for config_id, model_name, config_json_str in configs:
config_json = json.loads(config_json_str) if config_json_str else {}
current_api_key = config_json.get('api_key', '')
# Only update if the API key is different
if current_api_key != MEM0_API_KEY:
print_info(f"\nUpdating configuration: {config_id} ({model_name})")
# Update the API key in the JSON
config_json['api_key'] = MEM0_API_KEY
updated_json = json.dumps(config_json)
# Update query
update_query = """
UPDATE ai_model_config
SET config_json = %s,
update_date = NOW()
WHERE id = %s
"""
cursor.execute(update_query, (updated_json, config_id))
updated_count += 1
print_success(f"Updated API key for {model_name}")
else:
print_info(f"\nSkipping {model_name} - API key already correct")
if updated_count > 0:
connection.commit()
print_success(f"\n{updated_count} configuration(s) updated successfully")
return True
else:
print_info("\nNo configurations needed updating")
return True
except Exception as e:
connection.rollback()
print_error(f"Failed to update database: {str(e)}")
return False
def verify_update(connection):
"""Verify that the update was successful"""
try:
with connection.cursor() as cursor:
query = """
SELECT id, model_name, JSON_EXTRACT(config_json, '$.api_key') as api_key
FROM ai_model_config
WHERE model_type = 'Memory'
AND JSON_EXTRACT(config_json, '$.type') = 'mem0ai'
"""
cursor.execute(query)
results = cursor.fetchall()
print_header("Verification Results")
all_correct = True
for config_id, model_name, api_key in results:
# Remove quotes from JSON extracted value
api_key = api_key.strip('"') if api_key else ''
if api_key == MEM0_API_KEY:
print_success(f"{model_name}: API key is correct")
else:
print_error(f"{model_name}: API key is incorrect ({api_key})")
all_correct = False
return all_correct
except Exception as e:
print_error(f"Failed to verify update: {str(e)}")
return False
def main():
"""Main function"""
print_header("Mem0 API Key Update Script")
print_info(f"Target API Key: {MEM0_API_KEY[:10]}...{MEM0_API_KEY[-10:]}")
print_info(f"Timestamp: {datetime.now().isoformat()}")
# Connect to database
connection = connect_to_database()
if not connection:
print_error("Cannot proceed without database connection")
return 1
try:
# Find mem0 configurations
configs = find_mem0_configs(connection)
if configs:
# Ask for confirmation
print_warning("\nThis will update the API key in the database.")
response = input(f"{Colors.WARNING}Do you want to proceed? (yes/no): {Colors.ENDC}").lower()
if response in ['yes', 'y']:
# Update API keys
if update_api_keys(connection, configs):
# Verify the update
if verify_update(connection):
print_success("\n✅ All API keys updated successfully!")
print_info("\nNext steps:")
print_info("1. Clear Redis cache if you're using it")
print_info("2. Restart the manager-api service")
print_info("3. Restart the xiaozhi-server")
return 0
else:
print_error("\n❌ Verification failed - some keys may not be updated correctly")
return 1
else:
print_error("\n❌ Update failed")
return 1
else:
print_info("Update cancelled by user")
return 0
else:
print_warning("\nNo mem0ai configurations found to update")
print_info("Make sure you have configured mem0ai in the Model Configuration")
return 0
finally:
connection.close()
print_info("\nDatabase connection closed")
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\nScript interrupted by user")
sys.exit(0)
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
sys.exit(1)

266
update_mem0_via_api.py Normal file
View file

@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""
Script to update mem0 API key via the Manager API
This updates the model configuration through the API instead of direct database access
"""
import requests
import json
import sys
from datetime import datetime
# API Configuration
MANAGER_API_BASE_URL = "http://192.168.1.105:8002/xiaozhi"
SECRET = "66122e75-3b2a-45d7-a082-0f0894529348"
# The actual mem0 API key
MEM0_API_KEY = "m0-WNBvGhsBGZU1NDKDF42ecLNAgMk0GRaToaKLT0wN"
# You might need to login first to get a session
# Update these with your admin credentials
ADMIN_USERNAME = "admin" # Update this
ADMIN_PASSWORD = "admin" # Update this
# Colors for output
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def print_header(text):
"""Print a formatted header"""
print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}")
print(f"{Colors.HEADER}{text}{Colors.ENDC}")
print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}")
def print_success(text):
"""Print success message"""
print(f"{Colors.OKGREEN}✓ {text}{Colors.ENDC}")
def print_error(text):
"""Print error message"""
print(f"{Colors.FAIL}✗ {text}{Colors.ENDC}")
def print_info(text):
"""Print info message"""
print(f"{Colors.OKCYAN}ℹ {text}{Colors.ENDC}")
def print_warning(text):
"""Print warning message"""
print(f"{Colors.WARNING}⚠ {text}{Colors.ENDC}")
def login():
"""Login to get session cookie"""
print_header("Logging in to Manager API")
url = f"{MANAGER_API_BASE_URL}/login"
data = {
"username": ADMIN_USERNAME,
"password": ADMIN_PASSWORD
}
try:
session = requests.Session()
response = session.post(url, json=data)
if response.status_code == 200:
result = response.json()
if result.get("code") == 0:
print_success("Login successful")
return session
else:
print_error(f"Login failed: {result.get('msg')}")
return None
else:
print_error(f"HTTP {response.status_code}: {response.text}")
return None
except Exception as e:
print_error(f"Login request failed: {str(e)}")
return None
def get_memory_configs(session):
"""Get all memory model configurations"""
print_header("Fetching Memory Configurations")
url = f"{MANAGER_API_BASE_URL}/models/list"
params = {
"modelType": "memory",
"page": "0",
"limit": "100"
}
headers = {
"Authorization": f"Bearer {SECRET}",
"Content-Type": "application/json"
}
try:
response = session.get(url, params=params, headers=headers)
if response.status_code == 200:
result = response.json()
if result.get("code") == 0:
data = result.get("data", {})
configs = data.get("list", [])
mem0_configs = []
for config in configs:
config_json = config.get("configJson", {})
if config_json.get("type") == "mem0ai":
mem0_configs.append(config)
print_info(f"Found mem0ai config: {config.get('modelName')} (ID: {config.get('id')})")
current_key = config_json.get("api_key", "")
if current_key == "***":
print_warning(f" Current API key: {current_key} (MASKED)")
elif current_key == MEM0_API_KEY:
print_success(f" Current API key: {current_key[:10]}...{current_key[-10:]} (Already correct)")
else:
print_warning(f" Current API key: {current_key[:10] if len(current_key) > 10 else current_key}...")
return mem0_configs
else:
print_error(f"API error: {result.get('msg')}")
return []
else:
print_error(f"HTTP {response.status_code}: {response.text}")
return []
except Exception as e:
print_error(f"Request failed: {str(e)}")
return []
def update_config(session, config):
"""Update a single configuration"""
config_id = config.get("id")
model_name = config.get("modelName")
print_info(f"\nUpdating {model_name} (ID: {config_id})")
# Get the current configuration
url = f"{MANAGER_API_BASE_URL}/models/{config_id}"
headers = {
"Authorization": f"Bearer {SECRET}",
"Content-Type": "application/json"
}
try:
response = session.get(url, headers=headers)
if response.status_code != 200 or response.json().get("code") != 0:
print_error("Failed to get current configuration")
return False
current_config = response.json().get("data", {})
# Update the configuration with the new API key
config_json = current_config.get("configJson", {})
config_json["api_key"] = MEM0_API_KEY
# Prepare update payload
update_data = {
"modelName": current_config.get("modelName"),
"isDefault": current_config.get("isDefault", 0),
"isEnabled": current_config.get("isEnabled", 1),
"configJson": config_json,
"docLink": current_config.get("docLink", ""),
"remark": current_config.get("remark", ""),
"sort": current_config.get("sort", 0)
}
# Send update request
update_url = f"{MANAGER_API_BASE_URL}/models/memory/mem0ai/{config_id}"
response = session.put(update_url, json=update_data, headers=headers)
if response.status_code == 200:
result = response.json()
if result.get("code") == 0:
print_success(f"Successfully updated {model_name}")
return True
else:
print_error(f"Update failed: {result.get('msg')}")
return False
else:
print_error(f"HTTP {response.status_code}: {response.text}")
return False
except Exception as e:
print_error(f"Update request failed: {str(e)}")
return False
def main():
"""Main function"""
print_header("Mem0 API Key Update via Manager API")
print_info(f"Target API Key: {MEM0_API_KEY[:10]}...{MEM0_API_KEY[-10:]}")
print_info(f"API URL: {MANAGER_API_BASE_URL}")
print_info(f"Timestamp: {datetime.now().isoformat()}")
# Login to get session
session = login()
if not session:
print_error("Cannot proceed without authentication")
print_info("\nPlease update ADMIN_USERNAME and ADMIN_PASSWORD in this script")
return 1
# Get memory configurations
configs = get_memory_configs(session)
if not configs:
print_warning("No mem0ai configurations found")
return 0
# Check if any need updating
configs_to_update = []
for config in configs:
config_json = config.get("configJson", {})
current_key = config_json.get("api_key", "")
if current_key != MEM0_API_KEY:
configs_to_update.append(config)
if not configs_to_update:
print_success("\nAll mem0ai configurations already have the correct API key")
return 0
# Ask for confirmation
print_warning(f"\nFound {len(configs_to_update)} configuration(s) that need updating")
response = input(f"{Colors.WARNING}Do you want to proceed? (yes/no): {Colors.ENDC}").lower()
if response not in ['yes', 'y']:
print_info("Update cancelled by user")
return 0
# Update configurations
print_header("Updating Configurations")
success_count = 0
for config in configs_to_update:
if update_config(session, config):
success_count += 1
# Summary
print_header("Update Summary")
if success_count == len(configs_to_update):
print_success(f"✅ Successfully updated {success_count} configuration(s)")
print_info("\nNext steps:")
print_info("1. Clear Redis cache if enabled")
print_info("2. Restart the xiaozhi-server")
return 0
else:
print_warning(f"Updated {success_count} out of {len(configs_to_update)} configurations")
return 1
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\n\nScript interrupted by user")
sys.exit(0)
except Exception as e:
print_error(f"Unexpected error: {str(e)}")
sys.exit(1)