Browse Source

修复 react_agent的config中redis配置的问题。

wangxq 1 month ago
parent
commit
1317e42918
6 changed files with 228 additions and 13 deletions
  1. 1 1
      app_config.py
  2. 18 4
      react_agent/api.py
  3. 15 3
      react_agent/config.py
  4. 13 1
      react_agent/enhanced_redis_api.py
  5. 154 0
      test_redis_modules.py
  6. 27 4
      unified_api.py

+ 1 - 1
app_config.py

@@ -164,7 +164,7 @@ DEFAULT_ANONYMOUS_USER = "guest"        # 匿名用户统一ID
 # Redis配置
 REDIS_HOST = "localhost"
 REDIS_PORT = 6379
-REDIS_DB = 0
+REDIS_DB = 1
 REDIS_PASSWORD = None
 
 # 缓存开关配置

+ 18 - 4
react_agent/api.py

@@ -21,10 +21,12 @@ import redis.asyncio as redis
 try:
     # 尝试相对导入(当作为模块导入时)
     from .agent import CustomReactAgent
+    from . import config
     from core.logging import get_react_agent_logger
 except ImportError:
     # 如果相对导入失败,尝试绝对导入(直接运行时)
     from agent import CustomReactAgent
+    import config
     from core.logging import get_react_agent_logger
 
 # 使用独立日志系统
@@ -95,10 +97,10 @@ async def initialize_agent():
         logger.info("🚀 正在异步初始化 Custom React Agent...")
         try:
             # 设置环境变量(checkpointer内部需要)
-            os.environ['REDIS_URL'] = 'redis://localhost:6379'
+            os.environ['REDIS_URL'] = config.REDIS_URL
             
             # 初始化共享的Redis客户端
-            _redis_client = redis.from_url('redis://localhost:6379', decode_responses=True)
+            _redis_client = redis.from_url(config.REDIS_URL, decode_responses=True)
             await _redis_client.ping()
             logger.info("✅ Redis客户端连接成功")
             
@@ -415,7 +417,13 @@ def get_user_conversations_simple_sync(user_id: str, limit: int = 10):
     
     try:
         # 创建Redis连接
-        redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
+        redis_client = redis.Redis(
+            host=config.REDIS_HOST,
+            port=config.REDIS_PORT,
+            db=config.REDIS_DB,
+            password=config.REDIS_PASSWORD,
+            decode_responses=True
+        )
         redis_client.ping()
         
         # 扫描用户的checkpoint keys
@@ -595,7 +603,13 @@ def test_redis_connection():
         import redis
         
         # 创建Redis连接
-        r = redis.Redis(host='localhost', port=6379, decode_responses=True)
+        r = redis.Redis(
+            host=config.REDIS_HOST,
+            port=config.REDIS_PORT,
+            db=config.REDIS_DB,
+            password=config.REDIS_PASSWORD,
+            decode_responses=True
+        )
         r.ping()
         
         # 扫描checkpoint keys

+ 15 - 3
react_agent/config.py

@@ -20,9 +20,21 @@ QWEN_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
 QWEN_MODEL = "qwen3-235b-a22b"
 
 # --- Redis 配置 ---
-# 如果存储到 DB3: REDIS_URL = "redis://localhost:6379/3"
-REDIS_URL = "redis://localhost:6379"
-REDIS_ENABLED = True
+REDIS_HOST = "localhost"
+REDIS_PORT = 6379
+REDIS_DB = 0
+REDIS_PASSWORD = None
+REDIS_ENABLED = True  # 是否启用Redis状态持久化(LangGraph的AsyncRedisSaver),用于保存对话历史和状态
+
+# 兼容性:保留REDIS_URL用于AsyncRedisSaver
+def _build_redis_url():
+    """构建Redis连接URL"""
+    if REDIS_PASSWORD:
+        return f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"
+    else:
+        return f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"
+
+REDIS_URL = _build_redis_url()
 
 # --- 日志配置 ---
 LOG_LEVEL = logging.INFO

+ 13 - 1
react_agent/enhanced_redis_api.py

@@ -8,6 +8,12 @@ from typing import List, Dict, Any, Optional
 from datetime import datetime
 import logging
 
+# 导入配置
+try:
+    from . import config
+except ImportError:
+    import config
+
 logger = logging.getLogger(__name__)
 
 def get_conversation_detail_from_redis(thread_id: str, include_tools: bool = False) -> Dict[str, Any]:
@@ -25,7 +31,13 @@ def get_conversation_detail_from_redis(thread_id: str, include_tools: bool = Fal
     """
     try:
         # 创建Redis连接
-        redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
+        redis_client = redis.Redis(
+            host=config.REDIS_HOST,
+            port=config.REDIS_PORT,
+            db=config.REDIS_DB,
+            password=config.REDIS_PASSWORD,
+            decode_responses=True
+        )
         redis_client.ping()
         
         # 扫描该thread的所有checkpoint keys

+ 154 - 0
test_redis_modules.py

@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Redis模块测试脚本
+用于检测Redis服务器是否安装了RediSearch和ReJSON模块
+"""
+
+import redis
+import sys
+from typing import Dict, Any
+
+
+def test_redis_modules(host: str = 'localhost', port: int = 6379, password: str = None, db: int = 0) -> Dict[str, Any]:
+    """
+    测试Redis服务器是否安装了RediSearch和ReJSON模块
+    
+    Args:
+        host: Redis服务器地址
+        port: Redis服务器端口
+        password: Redis密码(可选)
+        db: 数据库编号
+    
+    Returns:
+        包含测试结果的字典
+    """
+    results = {
+        'redis_connection': False,
+        'redijson_available': False,
+        'redisearch_available': False,
+        'errors': []
+    }
+    
+    try:
+        # 连接Redis
+        r = redis.Redis(host=host, port=port, password=password, db=db, decode_responses=True)
+        
+        # 测试连接
+        r.ping()
+        results['redis_connection'] = True
+        print(f"✅ Redis连接成功 - {host}:{port}")
+        
+    except Exception as e:
+        error_msg = f"❌ Redis连接失败: {str(e)}"
+        results['errors'].append(error_msg)
+        print(error_msg)
+        return results
+    
+    # 测试RedisJSON
+    try:
+        # 尝试设置JSON文档
+        r.execute_command('JSON.SET', 'test_doc', '$', '{"test":"value"}')
+        # 尝试获取JSON文档
+        result = r.execute_command('JSON.GET', 'test_doc')
+        # 清理测试数据
+        r.execute_command('JSON.DEL', 'test_doc')
+        
+        results['redijson_available'] = True
+        print("✅ RedisJSON 模块可用")
+        
+    except redis.exceptions.ResponseError as e:
+        error_msg = f"❌ RedisJSON 模块不可用: {str(e)}"
+        results['errors'].append(error_msg)
+        print(error_msg)
+    except Exception as e:
+        error_msg = f"❌ RedisJSON 测试失败: {str(e)}"
+        results['errors'].append(error_msg)
+        print(error_msg)
+    
+    # 测试RediSearch
+    try:
+        # 尝试创建索引
+        r.execute_command('FT.CREATE', 'test_idx', 'ON', 'HASH', 'PREFIX', '1', 'test:', 'SCHEMA', 'title', 'TEXT')
+        # 清理测试索引
+        r.execute_command('FT.DROPINDEX', 'test_idx')
+        
+        results['redisearch_available'] = True
+        print("✅ RediSearch 模块可用")
+        
+    except redis.exceptions.ResponseError as e:
+        error_msg = f"❌ RediSearch 模块不可用: {str(e)}"
+        results['errors'].append(error_msg)
+        print(error_msg)
+    except Exception as e:
+        error_msg = f"❌ RediSearch 测试失败: {str(e)}"
+        results['errors'].append(error_msg)
+        print(error_msg)
+    
+    return results
+
+
+def main():
+    """主函数"""
+    print("=" * 60)
+    print("Redis模块测试工具")
+    print("=" * 60)
+    
+    # 获取用户输入的Redis连接信息
+    print("\n请输入Redis服务器连接信息:")
+    host = 'localhost'
+    port_input = '6379'
+    password =  None
+    db_input = '0'
+    
+    try:
+        port = int(port_input)
+        db = int(db_input)
+    except ValueError:
+        print("❌ 端口和数据库编号必须是数字")
+        sys.exit(1)
+    
+    print(f"\n正在测试Redis服务器: {host}:{port}")
+    print("-" * 40)
+    
+    # 执行测试
+    results = test_redis_modules(host=host, port=port, password=password, db=db)
+    
+    # 输出测试总结
+    print("\n" + "=" * 60)
+    print("测试结果总结:")
+    print("=" * 60)
+    
+    if results['redis_connection']:
+        print("✅ Redis连接: 成功")
+    else:
+        print("❌ Redis连接: 失败")
+    
+    if results['redijson_available']:
+        print("✅ RedisJSON: 已安装")
+    else:
+        print("❌ RedisJSON: 未安装")
+    
+    if results['redisearch_available']:
+        print("✅ RediSearch: 已安装")
+    else:
+        print("❌ RediSearch: 未安装")
+    
+    if results['errors']:
+        print(f"\n错误信息:")
+        for error in results['errors']:
+            print(f"  - {error}")
+    
+    print("\n" + "=" * 60)
+    
+    # 返回适当的退出码
+    if results['redis_connection'] and results['redijson_available'] and results['redisearch_available']:
+        print("🎉 所有模块都可用!")
+        sys.exit(0)
+    else:
+        print("⚠️  部分模块不可用,请检查Redis配置")
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    main() 

+ 27 - 4
unified_api.py

@@ -70,14 +70,17 @@ logger = get_app_logger("UnifiedApp")
 try:
     from react_agent.agent import CustomReactAgent
     from react_agent.enhanced_redis_api import get_conversation_detail_from_redis
+    from react_agent import config as react_agent_config
 except ImportError:
     try:
         from test.custom_react_agent.agent import CustomReactAgent
         from test.custom_react_agent.enhanced_redis_api import get_conversation_detail_from_redis
+        from test.custom_react_agent import config as react_agent_config
     except ImportError:
         logger.warning("无法导入 CustomReactAgent,React Agent功能将不可用")
         CustomReactAgent = None
         get_conversation_detail_from_redis = None
+        react_agent_config = None
 
 # 初始化核心组件
 vn = create_vanna_instance()
@@ -281,11 +284,13 @@ async def get_react_agent() -> Any:
             
         logger.info("🚀 正在异步初始化 Custom React Agent...")
         try:
+            # 使用React Agent配置中的Redis URL
+            redis_url = react_agent_config.REDIS_URL if react_agent_config else 'redis://localhost:6379'
             # 设置环境变量
-            os.environ['REDIS_URL'] = 'redis://localhost:6379'
+            os.environ['REDIS_URL'] = redis_url
             
             # 初始化共享的Redis客户端
-            _redis_client = redis.from_url('redis://localhost:6379', decode_responses=True)
+            _redis_client = redis.from_url(redis_url, decode_responses=True)
             await _redis_client.ping()
             logger.info("✅ Redis客户端连接成功")
             
@@ -321,7 +326,16 @@ def get_user_conversations_simple_sync(user_id: str, limit: int = 10):
     
     try:
         # 创建Redis连接
-        redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
+        if react_agent_config:
+            redis_client = redis.Redis(
+                host=react_agent_config.REDIS_HOST,
+                port=react_agent_config.REDIS_PORT,
+                db=react_agent_config.REDIS_DB,
+                password=react_agent_config.REDIS_PASSWORD,
+                decode_responses=True
+            )
+        else:
+            redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
         redis_client.ping()
         
         # 扫描用户的checkpoint keys
@@ -2443,7 +2457,16 @@ def test_redis_connection():
         import redis
         
         # 创建Redis连接
-        r = redis.Redis(host='localhost', port=6379, decode_responses=True)
+        if react_agent_config:
+            r = redis.Redis(
+                host=react_agent_config.REDIS_HOST,
+                port=react_agent_config.REDIS_PORT,
+                db=react_agent_config.REDIS_DB,
+                password=react_agent_config.REDIS_PASSWORD,
+                decode_responses=True
+            )
+        else:
+            r = redis.Redis(host='localhost', port=6379, decode_responses=True)
         r.ping()
         
         # 扫描checkpoint keys