Преглед изворни кода

【新增】添加命令行客户端并优化配置管理

- 新增 BaseClient 类,实现命令行交互模式
- 重构 Config 类,支持默认配置和运行时配置的深度合并
- 更新 yaa.py 主入口,支持 --run 和 --serve 参数
- 调整 BaseServer 类,直接使用合并后的配置
- 优化 BaseAgent 类,使用 Config.merge_config 补全会话配置
PJ568 пре 1 година
родитељ
комит
07d6609aae
9 измењених фајлова са 181 додато и 51 уклоњено
  1. 1 1
      VERSION
  2. 5 1
      yaa/Agent/BaseAgent.py
  3. 48 0
      yaa/Client/BaseClient.py
  4. 7 0
      yaa/Client/__init__.py
  5. 72 19
      yaa/Config/Config.py
  6. 29 4
      yaa/Config/ServerConfig.py
  7. 1 1
      yaa/LLM_API/OpenAI.py
  8. 2 6
      yaa/Server/BaseServer.py
  9. 16 19
      yaa/yaa.py

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.1.0
+0.2.0

+ 5 - 1
yaa/Agent/BaseAgent.py

@@ -1,3 +1,4 @@
+from ..Config.Config import Config
 # from ..LLM_API.BaseAPI import BaseAPI
 from ..LLM_API.OpenAI import OpenAI_API
 
@@ -13,9 +14,12 @@ class BaseAgent:
             response_data (dict): 加入智能体信息的会话数据
         """
         try:
+            # 补全会话配置
+            merged_data = Config.merge_config(session_data)
+
             # 调用大模型API
             # response_data = BaseAPI.request(session_data)
-            response_data = OpenAI_API.request(session_data)
+            response_data = OpenAI_API.request(merged_data)
             
             return response_data
             

+ 48 - 0
yaa/Client/BaseClient.py

@@ -0,0 +1,48 @@
+import uuid
+from datetime import datetime
+from ..Agent.BaseAgent import BaseAgent
+from ..Config.Config import Config
+
+class BaseClient:
+    def run(message=None):
+        help_command = ['', '/?', '/help', '/h']
+
+        while True:
+            if not message or message == '':
+                message = input('> ')
+
+            if message in help_command:
+                print('可用命令:')
+                print(' /exit:退出程序')
+                message = None
+                continue
+            elif message == '/exit':
+                message = None
+                break
+
+            # 创建会话数据
+            session_data = {
+                'id': str(uuid.uuid4()),
+                'title': '会话',
+                'start_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
+                "type": "对话",
+                'messages': [
+                    {
+                        'role': 'user',
+                        'content': message
+                    }
+                ],
+                'config': {
+                    'yaa': Config.YAA_CONFIG,
+                    'llm_api': Config.LLM_API_CONFIG,
+                    'prompt': Config.PROMPT_CONFIG,
+                    'tool': Config.TOOL_CONFIG
+                }
+            }
+
+            message = None
+            
+            # 交给智能体处理
+            response_data = BaseAgent.Agent(session_data)
+
+            print(response_data['messages'])

+ 7 - 0
yaa/Client/__init__.py

@@ -0,0 +1,7 @@
+"""yaa 命令行客户端"""
+from ..Client.BaseClient import BaseClient
+
+
+__all__ = [
+    "BaseClient"
+]

+ 72 - 19
yaa/Config/Config.py

@@ -2,7 +2,7 @@
 
 职责:
 1. 提供系统默认配置项
-2. 管理配置加载优先级(默认配置 < 用户配置 < 运行时配置)
+2. 管理配置加载优先级(默认配置 < 运行时配置 < 用户配置)
 """
 
 class Config:
@@ -57,29 +57,82 @@ class Config:
     }
 
     @classmethod
-    def merge_config(cls, user_config=None):
+    def get_default_config(cls):
+        """获取默认配置"""
+        return {
+            'yaa': cls.YAA_CONFIG,
+            'llm_api': cls.LLM_API_CONFIG,
+            'prompt': cls.PROMPT_CONFIG,
+            'tool': cls.TOOL_CONFIG
+        }
+
+    @classmethod
+    def merge_config(cls, session_data=None):
         """合并用户配置和默认配置
         
         参数:
-            user_config (dict): 用户提供的配置字典
+            session_data (dict): 用户提供的会话数据,其中 session_data['config'] 为配置字典
             
         返回:
-            dict: 合并后的配置字典,保留所有原始字段并合并特定配置项
+            session_data (dict): 补充完缺少的配置项的会话数据字典
         """
-        if user_config is None:
-            user_config = {}
-            
-        # 保留所有原始字段
-        merged_config = user_config.copy()
+        if session_data is None:
+            raise ValueError('未提供会话数据')
+
+        # 从 session_data 中取出用户配置
+        user_config = session_data.get('config', {})
         
-        # 合并特定配置项
-        if 'yaa' in user_config:
-            merged_config['yaa'] = {**cls.YAA_CONFIG, **user_config['yaa']}
-        if 'llm_api' in user_config:
-            merged_config['llm_api'] = {**cls.LLM_API_CONFIG, **user_config['llm_api']}
-        if 'prompt' in user_config:
-            merged_config['prompt'] = {**cls.PROMPT_CONFIG, **user_config['prompt']}
-        if 'tool' in user_config:
-            merged_config['tool'] = {**cls.TOOL_CONFIG, **user_config['tool']}
+        session_data['config'] = cls._deep_merge(cls.get_default_config(), user_config)
+
+        return session_data
+    
+    @classmethod
+    def update_config(cls, runtime_config_path=None):
+        """更新默认配置(运行时配置优先)
+        
+        参数:
+            runtime_config_path (src): 运行时提供的会话数据 json 的路径
+        """
+        if runtime_config_path is None:
+            raise ValueError('未提供运行时配置路径')
+
+        import json
+
+        runtime_config = json.load(open(runtime_config_path, 'r'))
+
+        if runtime_config['config'] is None:
+            raise ValueError('未提供运行时配置')
+        
+        merged_config = cls._deep_merge(cls.get_default_config(), runtime_config['config'])
+
+        # 更新 YAA 配置
+        cls.YAA_CONFIG = {**cls.YAA_CONFIG, **merged_config['yaa']}
+        
+        # 更新 LLM API 配置
+        cls.LLM_API_CONFIG = {**cls.LLM_API_CONFIG, **merged_config['llm_api']}
+        
+        # 更新提示词配置
+        cls.PROMPT_CONFIG = {**cls.PROMPT_CONFIG, **merged_config['prompt']}
+        
+        # 更新工具调用配置
+        cls.TOOL_CONFIG = {**cls.TOOL_CONFIG, **merged_config['tool']}
+
+    @classmethod
+    def _deep_merge(cls, default_dict, target_dict):
+            """深度合并两个字典,用户字典优先
             
-        return merged_config
+            参数:
+                default_dict (dict): 默认配置字典
+                target_dict (dict): 目标配置字典
+                
+            返回:
+                dict: 合并后的字典
+            """
+            merged = default_dict.copy()
+            for key, value in target_dict.items():
+                if (key in merged and isinstance(merged[key], dict)
+                    and isinstance(value, dict)):
+                    merged[key] = cls._deep_merge(merged[key], value)
+                else:
+                    merged[key] = value
+            return merged

+ 29 - 4
yaa/Config/ServerConfig.py

@@ -29,6 +29,34 @@ class ServerConfig:
         'max_request_size': '10MB'
     }
 
+    @classmethod
+    def get_default_config(cls):
+        """获取默认配置"""
+        return {
+            'yaa_server': cls.YAA_SERVER_CONFIG,
+            'security': cls.SECURITY_CONFIG
+        }
+    
+    @classmethod
+    def _deep_merge(cls, default_dict, target_dict):
+            """深度合并两个字典,用户字典优先
+            
+            参数:
+                default_dict (dict): 默认配置字典
+                target_dict (dict): 目标配置字典
+                
+            返回:
+                dict: 合并后的字典
+            """
+            merged = default_dict.copy()
+            for key, value in target_dict.items():
+                if (key in merged and isinstance(merged[key], dict)
+                    and isinstance(value, dict)):
+                    merged[key] = cls._deep_merge(merged[key], value)
+                else:
+                    merged[key] = value
+            return merged
+
     @classmethod
     def merge_config(cls, args_config=None):
         """合并用户配置和默认配置
@@ -42,9 +70,6 @@ class ServerConfig:
         if args_config is None:
             args_config = {}
             
-        merged_config = {
-            'yaa_server': {**cls.YAA_SERVER_CONFIG, **args_config.get('yaa_server', {})},
-            'security': {**cls.SECURITY_CONFIG, **args_config.get('security', {})}
-        }
+        merged_config = cls._deep_merge(cls.get_default_config(), args_config)
         
         return merged_config

+ 1 - 1
yaa/LLM_API/OpenAI.py

@@ -9,7 +9,7 @@ class OpenAI_API:
         api_url = provider_config['api_url']
         api_key = provider_config['api_key']
         model_name = provider_config['model_name']
-        
+
         # 解析API URL
         parsed_url = urlparse(api_url)
         host = parsed_url.netloc

+ 2 - 6
yaa/Server/BaseServer.py

@@ -8,7 +8,6 @@
 
 import socket
 import json
-from ..Config.Config import Config
 from ..Agent.BaseAgent import BaseAgent
 
 class BaseServer:
@@ -53,12 +52,9 @@ class BaseServer:
                 
                 # 解析会话数据
                 session_data = json.loads(body)
-                
-                # 补全会话配置
-                merged_data = Config.merge_config(session_data)
-                
+
                 # 交给智能体处理
-                response_data = BaseAgent.Agent(merged_data)
+                response_data = BaseAgent.Agent(session_data)
                 
                 # 返回响应
                 conn.sendall(b'HTTP/1.1 200 OK\n')

+ 16 - 19
yaa/yaa.py

@@ -8,6 +8,8 @@
 
 import sys
 import argparse
+from .Client.BaseClient import BaseClient
+from .Config.Config import Config
 from .Config.ServerConfig import ServerConfig
 from .Server.BaseServer import BaseServer
 
@@ -16,32 +18,25 @@ def main():
     parser = argparse.ArgumentParser(description='yaa 智能体命令行工具')
 
     # 定义互斥参数组,--run 和 --serve 不能同时使用
-    group = parser.add_mutually_exclusive_group(required=True)
-    group.add_argument('--run', type=str, help='运行智能体')
+    group = parser.add_mutually_exclusive_group()
+    group.add_argument('--run', nargs='?', const='', help='运行智能体(可选值)')
     group.add_argument('--serve', action='store_true', help='启动服务模式')
+    parser.add_argument('--config', type=str, help='配置文件路径')
 
     # serve 模式的可选参数
     parser.add_argument('--port', type=int, default=12345, help='服务端口号,默认 12345')
-    parser.add_argument('--config', type=str, help='配置文件路径')
 
     args = parser.parse_args()
-
-    if args.run:
-        # TODO 命令行交互式应用模式运行此提示词
-        # print(f"输入的提示词: {args.run}")
-        pass
-    elif args.serve:
+    
+    # 如果指定了配置文件,则加载配置文件
+    if args.config:
+        Config.update_config(args.config)
+    if args.serve:
         try:
             # 构建运行时配置
             runtime_config = {
-                'yaa_server': {'port': args.port},
-                'security': {}
+                'yaa_server': {'port': args.port}
             }
-            # 如果指定了配置文件,则加载配置文件
-            if args.config:
-                # print(f"使用配置文件: {args.config}")
-                # TODO: 从配置文件加载配置
-                pass
             
             # 合并默认配置和运行时配置
             config = ServerConfig.merge_config(runtime_config)
@@ -52,10 +47,12 @@ def main():
             print("\n服务已停止")
         except Exception as e:
             print(f"服务启动失败: {str(e)}")
+    elif args.run:
+        # 命令行交互模式
+        BaseClient.run(args.run)
     else:
-        # TODO 命令行交互式应用模式
-        # print("命令行应用模式")
-        pass
+        # 命令行交互模式
+        BaseClient.run()
 
 if __name__ == "__main__":
     main()