Forráskód Böngészése

【更改】完成 yaa 的基本实现

- 新增 BaseFlowAnalyze.md 文件,详细描述了客户端与服务器的交互流程
- 完成 yaa 的各种基本类的实现
PJ568 1 éve
szülő
commit
e6ae92274c

+ 23 - 2
README.en.md

@@ -10,6 +10,27 @@
 
 `yaa` means Yet Another Agent, which can analyze and understand natural language instructions and automatically create, plan, execute, and check tasks.
 
----
+## Quick Start
 
-[yaa documentation](docs/README.md)
+Deploy locally:
+
+```bash
+git clone https://github.com/Byte-tea/yaa.git
+cd yaa
+```
+
+Run `yaa` service:
+
+```bash
+python -m yaa/yaa --serve
+```
+
+Command line interactive mode:
+
+```bash
+python -m yaa/yaa
+```
+
+## Project Implementation
+
+See [yaa documentation](docs/README.md) for details.

+ 23 - 2
README.md

@@ -10,6 +10,27 @@
 
 `yaa` 的意思是 Yet Another Agent。是一个能分析理解自然语言指示,自动创建、规划、执行、验证任务的智能体。
 
----
+## 快速上手
 
-[yaa 文档](docs/README.md)
+部署到本地:
+
+```bash
+git clone https://github.com/Byte-tea/yaa.git
+cd yaa
+```
+
+运行 `yaa` 服务:
+
+```bash
+python -m yaa/yaa --serve
+```
+
+命令行交互模式:
+
+```bash
+python -m yaa/yaa
+```
+
+## 项目实现
+
+详见 [yaa 文档](docs/README.md)。

+ 1 - 0
VERSION

@@ -0,0 +1 @@
+0.0.0

+ 51 - 0
docs/FlowAnalyze/BaseFlowAnalyze.md

@@ -0,0 +1,51 @@
+# 最基本流程分析
+
+## 客户端服务器交互
+
+1. 用户运行 `python -m yaa/yaa --serve` 启动服务端。
+2. 客户端发送请求到 `localhost:12345/`:
+
+   ```plaintext
+   Content-type: application/json
+   Accept: application/json
+   Authorization: YAA-API-KEY yaa
+   ```
+
+   ```json
+   {
+       "id": "3ff6bcb1-1dbe-4e04-969c-aa610da0d85f",
+       "title": "用于测试的会话",
+       "start_time": "2025-03-29 13:35:04",
+       "type": "对话",
+       "messages": [
+           {
+               "role": "user",
+               "content": "yaa 智能体,你好吗?"
+           }
+       ],
+       "config": {
+           "yaa" : {"stream": false},
+           "llm_api": {
+               "provider": {
+                   "api_url": "https://llm.pj568.sbs/v1/chat/completions",
+                   "api_key": "PJ568",
+                   "model_name": "@cf/qwen/qwen1.5-0.5b-chat",
+                   "model_type": {
+                       "is_function_call": false,
+                       "is_reasoning": false
+                   },
+                   "cost_per_ktoken": 0.0,
+                   "cost_unit": "CNY",
+               },
+               "stream": false,
+           }
+       }
+   }
+   ```
+
+3. yaa/Server/BaseServer.py 模块的 listen() 函数解析会话数据,将会话数据传给 yaa/Config/Config.py 模块的 merge_config(),取得补全的会话数据。然后将补全的会话数据传给 yaa/Agent/BaseAgent.py 模块的 Agent() 函数,创建智能体实例。
+4. yaa/Agent/BaseAgent.py 模块的 Agent() 函数将补全的会话数据传给 yaa/LLM_API/BaseAPI.py 模块的 request() 函数,请求大模型。
+5. yaa/Agent/BaseAgent.py 模块的 Agent() 函数返回 yaa/LLM_API/BaseAPI.py 模块的 request() 函数返回的会话数据。
+6. yaa/Server/BaseServer.py 模块的 listen() 函数返回 yaa/Agent/BaseAgent.py 模块的 Agent() 函数返回的会话数据。
+
+## 命令行交互

+ 5 - 1
docs/README.md

@@ -92,7 +92,7 @@ flowchart TD
 会话数据主要包含三个部分:
 
 - 属性:
-  - 编号:用于唯一标识会话数据。
+  - 编号:用于唯一标识会话数据,在客户端使用 uuid 生成。
   - 标题(可选,缺省值由大模型根据消息内容配合提示词生成):用于向用户展示会话数据的主题。
   - 开始时间(可选,缺省值取当前格林尼治时间):记录会话数据的开始时间。
   - 会话数据类型:如`聊天`、`代码`、`文档`等。
@@ -188,3 +188,7 @@ flowchart TD
     }
 }
 ```
+
+## 流程分析
+
+- [最基本流程分析](FlowAnalyze/BaseFlowAnalyze.md)

+ 32 - 27
yaa/Agent/BaseAgent.py

@@ -1,27 +1,32 @@
-# 智能体基类实现
-#
-# 职责:
-# 1. 处理用户任务请求
-# 2. 管理智能体工作流程(任务分析、提示词生成、API调用、工具执行)
-# 3. 状态管理和异常处理
-#
-# 主要工作流程:
-# 1. 接收来自 Session 的请求(包含会话历史和用户指示)
-# 2. 调用 PromptGenerator 生成提示词
-# 3. 通过 APIService 调用大语言模型 API
-# 4. 检测是否需要工具调用:
-#    - 是:检查用户授权 -> 执行工具 -> 将结果返回给提示词生成器
-#    - 否:检测任务是否完成 -> 返回结果或继续处理
-# 5. 流式传输状态更新给 Session
-#
-# 关键方法:
-# - run_task(): 主执行方法
-# - handle_tool_call(): 处理工具调用
-# - check_completion(): 检查任务是否完成
-# - stream_update(): 流式更新状态
-#
-# 与其他模块关系:
-# - 依赖 Modules/LLM_API.py 进行API调用
-# - 使用 Tools/BaseTool.py 执行工具
-# - 通过 Prompt/DefaultPrompt.py 获取提示词模板
-# - 与 Session/Session.py 交互更新状态
+from ..LLM_API.BaseAPI import BaseAPI
+
+class BaseAgent:
+    """智能体基类"""
+    def Agent(session_data):
+        """智能体主处理函数
+        
+        参数:
+            session_data (dict): 补全后的会话数据
+            
+        返回:
+            dict: 格式化后的响应数据,包含:
+                - id: 会话ID
+                - title: 会话标题
+                - start_time: 开始时间
+                - finish_reason: 结束原因
+                - messages: 消息列表
+                - usage: API使用情况
+        """
+        try:
+            # 调用大模型API
+            response_data = BaseAPI.request(session_data)
+            
+            return response_data
+            
+        except Exception as e:
+            # 错误处理
+            session_data['messages'].append({
+                "role": "system",
+                "content": f'处理请求时出错: {str(e)}'
+            })
+            return session_data

+ 0 - 0
yaa/Client/BaseClient.py


+ 16 - 11
yaa/Config/Config.py

@@ -20,14 +20,14 @@ class Config:
             'api_key': '',
             'model_name': 'gpt-4',
             'model_type': {
-                'is_function_call': True,
-                'is_reasoning': True
+                'is_function_call': False,
+                'is_reasoning': False
             },
             'cost_per_ktoken': 0.03,
             'cost_unit': 'USD',
             'max_tokens': 2000,
             'model_settings': {
-                'use_custom_temp': True,
+                'use_custom_temp': False,
                 'temperature': 0.7
             }
         },
@@ -64,17 +64,22 @@ class Config:
             user_config (dict): 用户提供的配置字典
             
         返回:
-            dict: 合并后的配置字典,用户配置优先于默认配置
+            dict: 合并后的配置字典,保留所有原始字段并合并特定配置项
         """
         if user_config is None:
             user_config = {}
             
-        merged_config = {
-            'yaa': {**cls.YAA_CONFIG, **user_config.get('yaa', {})},
-            'llm_api': {**cls.LLM_API_CONFIG, **user_config.get('llm_api', {})},
-            'prompt': {**cls.PROMPT_CONFIG, **user_config.get('prompt', {})},
-            'tool': {**cls.TOOL_CONFIG, **user_config.get('tool', {})},
-            # TODO 'security': {**cls.SECURITY_CONFIG, **user_config.get('security', {})}
-        }
+        # 保留所有原始字段
+        merged_config = user_config.copy()
         
+        # 合并特定配置项
+        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']}
+            
         return merged_config

+ 6 - 1
yaa/Config/ServerConfig.py

@@ -19,7 +19,12 @@ class ServerConfig:
     # 安全验证配置
     SECURITY_CONFIG = {
         'auth_required': True,
-        'api_key_header': 'X-API-KEY',
+        'api_key_header': 'YAA-API-KEY',
+        'api_key': [
+            {
+                'key': '636ebda2dccc312b88aed7c54786f8678d33d4f878da41c5302b3dcde563055b61e8ca047d333c45e9be1adc342ceb2850f23f294a8b1b1c2d2dd016713fef58', # 测试用密钥(BLAKE2):yaa
+            }
+        ],
         'rate_limit': '100/1m',
         'max_request_size': '10MB'
     }

+ 28 - 0
yaa/LLM_API/BaseAPI.py

@@ -0,0 +1,28 @@
+class BaseAPI:
+    def request(session_data):
+        # 添加系统回复消息
+        session_data['messages'].append({
+            "role": "system",
+            "content": "您好,此为 yaa 的系统回复。"
+        })
+
+        # 构建响应数据
+        # response_data = {
+        #     'id': session_data['id'],
+        #     'title': session_data.get('title', ''),
+        #     'start_time': session_data.get('start_time', ''),
+        #     'finish_reason': llm_response.get('finish_reason', 'completed'),
+        #     'messages': [
+        #         {
+        #             'role': 'assistant',
+        #             'content': llm_response.get('content', '')
+        #         }
+        #     ],
+        #     'usage': llm_response.get('usage', {
+        #         'prompt_tokens': 0,
+        #         'completion_tokens': 0,
+        #         'total_tokens': 0
+        #     })
+        # }
+
+        return session_data

+ 2 - 0
yaa/LLM_API/OpenAI.py

@@ -0,0 +1,2 @@
+class OpenAI_API():
+    pass

+ 7 - 0
yaa/LLM_API/__init__.py

@@ -0,0 +1,7 @@
+"""大语言模型 API 接口模块"""
+from ..LLM_API.BaseAPI import BaseAPI
+
+
+__all__ = [
+    "BaseAPI"
+]

+ 0 - 29
yaa/Modules/Auth.py

@@ -1,29 +0,0 @@
-# 身份验证与安全模块
-#
-# 职责:
-# 1. 验证 API 密钥有效性
-# 2. 设置和管理资源限制(CPU/内存/请求频率)
-# 3. 安全审计和日志记录
-#
-# 主要工作流程:
-# 1. 接收来自 Session 的验证请求(携带 API Key)
-# 2. 验证 Key 有效性(本地校验或远程认证)
-# 3. 初始化资源限制器(设置CPU/内存阈值)
-# 4. 返回验证结果和资源配额
-#
-# 安全机制:
-# - 密钥分级管理(不同权限级别)
-# - 请求频率限制
-# - 资源使用监控
-# - 异常行为检测
-#
-# 关键方法:
-# - verify_key(): 密钥验证
-# - setup_limits(): 设置资源限制
-# - check_quota(): 检查资源配额
-# - audit_log(): 安全审计日志
-#
-# 与其他模块关系:
-# - 被 Session.py 调用来验证请求
-# - 使用 DefaultConfig.py 的安全配置
-# - 与中断监控器交互处理资源超限

+ 0 - 125
yaa/Modules/LLM_API.py

@@ -1,125 +0,0 @@
-"""LLM API 模块
-
-职责:
-1. 管理与大语言模型的API交互
-2. 处理流式响应
-3. 实现自动重试机制
-4. 处理工具调用检测
-"""
-
-import json
-import time
-import requests
-from typing import Dict, Optional, Generator
-from ..Config.Config import Config
-
-class LLMAPI:
-    """大语言模型API封装类"""
-    
-    def __init__(self, config: Optional[Dict] = None):
-        """初始化LLM API
-        
-        参数:
-            config: 用户提供的配置字典,会与默认配置合并
-        """
-        self.config = Config.merge_config(config)['llm_api']
-        self.session = requests.Session()
-        
-    def _make_request_headers(self) -> Dict[str, str]:
-        """生成请求头"""
-        return {
-            "Content-Type": "application/json",
-            "Authorization": f"Bearer {self.config['provider']['api_key']}"
-        }
-    
-    def _build_request_data(self, messages: list, tools: Optional[list] = None) -> Dict:
-        """构建请求数据"""
-        data = {
-            "model": self.config['provider']['model_name'],
-            "messages": messages,
-            "temperature": self.config['provider']['model_settings']['temperature'],
-            "max_tokens": self.config['provider']['max_tokens'],
-            "stream": self.config['stream']
-        }
-        
-        if tools and self.config['provider']['model_type']['is_function_call']:
-            data["tools"] = tools
-            data["tool_choice"] = "auto"
-            
-        return data
-    
-    def _handle_stream_response(self, response) -> Generator[str, None, None]:
-        """处理流式响应"""
-        for chunk in response.iter_lines():
-            if chunk:
-                decoded = chunk.decode('utf-8')
-                if decoded.startswith("data: "):
-                    data = decoded[6:]
-                    if data != "[DONE]":
-                        try:
-                            json_data = json.loads(data)
-                            yield json_data
-                        except json.JSONDecodeError:
-                            continue
-    
-    def call(
-        self,
-        messages: list,
-        tools: Optional[list] = None,
-        retry_count: int = 0
-    ) -> Generator[Dict, None, None]:
-        """调用LLM API
-        
-        参数:
-            messages: 消息列表
-            tools: 可选工具列表
-            retry_count: 当前重试次数
-            
-        返回:
-            生成器,产生流式响应或完整响应
-        """
-        url = self.config['provider']['api_url']
-        headers = self._make_request_headers()
-        data = self._build_request_data(messages, tools)
-        
-        try:
-            response = self.session.post(
-                url,
-                headers=headers,
-                json=data,
-                stream=self.config['stream'],
-                timeout=self.config['request_timeout']
-            )
-            response.raise_for_status()
-            
-            if self.config['stream']:
-                return self._handle_stream_response(response)
-            else:
-                return [response.json()]
-                
-        except requests.exceptions.RequestException as e:
-            if retry_count < self.config['retry']['times']:
-                time.sleep(self.config['retry']['delay'])
-                return self.call(messages, tools, retry_count + 1)
-            raise Exception(f"API调用失败: {str(e)}")
-    
-    def detect_tool_call(self, response: Dict) -> Optional[Dict]:
-        """检测工具调用
-        
-        参数:
-            response: API响应字典
-            
-        返回:
-            如果检测到工具调用则返回工具信息,否则返回 None
-        """
-        if not self.config['provider']['model_type']['is_function_call']:
-            return None
-            
-        if "choices" in response and len(response["choices"]) > 0:
-            choice = response["choices"][0]
-            if "tool_calls" in choice["delta"]:
-                return choice["delta"]["tool_calls"]
-            if "tool_calls" in choice["message"]:
-                return choice["message"]["tool_calls"]
-                
-        return None

+ 0 - 80
yaa/Modules/Server.py

@@ -1,80 +0,0 @@
-"""服务器模块
-
-职责:
-1. 实现简单的TCP服务器监听
-2. 处理会话数据结构
-3. 返回响应消息
-"""
-
-import socket
-import json
-
-class Server:
-    def __init__(self, config):
-        """初始化服务器
-        
-        参数:
-            config (dict): 服务器配置字典,包含yaa_server和security配置
-        """
-        self.config = config
-        server_config = config['yaa_server']
-        self.port = server_config['port']
-        self.max_connections = server_config['max_connections']
-        self.timeout = server_config['timeout']
-        
-        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-        self.socket.settimeout(self.timeout)
-
-    def listen(self):
-        """服务器监听函数
-        
-        监听端口,智能体处理客户端发出的请求,返回请求结果
-        """
-        self.socket.bind(('0.0.0.0', self.port))
-        self.socket.listen(self.max_connections)
-        print(f"服务器已启动,监听端口 {self.port},最大连接数 {self.max_connections},超时时间 {self.timeout}秒")
-        
-        while True:
-            conn, addr = self.socket.accept()
-            try:
-                data = conn.recv(4096)
-                if data:
-                    session = json.loads(data.decode('utf-8'))
-                    response = self.process_session(session)
-                    conn.sendall(json.dumps(response).encode('utf-8'))
-            finally:
-                conn.close()
-
-    def process_session(self, session):
-        """ 处理会话数据
-        
-        根据 docs/README.md 中的会话数据结构定义进行处理
-        """
-        # 基本验证
-        if not isinstance(session, dict):
-            return self.return_message("无效的会话格式")
-            
-        if 'id' not in session:
-            # TODO 生成会话 ID
-            return self.return_message("会话 ID 缺失")
-
-        # TODO 智能体根据会话数据执行并生成结果
-        # ...
-
-        # 返回处理结果
-        return {
-            "status": "received",
-            "session_id": session['id'],
-            "message": "会话已接收"
-        }
-
-    def return_message(self, message):
-        """返回信息函数
-        
-        默认返回格式:
-        {
-            "message": message
-        }
-        """
-        return {"message": message}

+ 0 - 10
yaa/Modules/__init__.py

@@ -1,10 +0,0 @@
-from ..Modules.Auth import AuthService
-from ..Modules.LLM_API import APIService
-from ..Modules.Server import Server
-
-
-__all__ = [
-    "AuthService",
-    "APIService",
-    "Server"
-]

+ 91 - 0
yaa/Server/BaseServer.py

@@ -0,0 +1,91 @@
+"""基础服务器模块
+
+职责:
+1. 实现简单的 TCP 服务器监听
+2. 处理会话数据结构
+3. 返回响应消息
+"""
+
+import socket
+import json
+from ..Config.Config import Config
+from ..Agent.BaseAgent import BaseAgent
+
+class BaseServer:
+    def __init__(self, config=None):
+        """初始化服务器
+        
+        参数:
+            config (dict): 服务器配置,包含:
+                - yaa_server: 服务器配置(ip, port等)
+                - security: 安全配置
+        """
+        if config is None:
+            config = {}
+            
+        server_config = config.get('yaa_server', {})
+        self.host = server_config.get('ip', 'localhost')
+        self.port = server_config.get('port', 12345)
+        self.max_connections = server_config.get('max_connections', 1)
+        
+        self.security_config = config.get('security', {})
+        self.api_keys = [key['key'] for key in self.security_config.get('api_key', [])]
+        
+        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+        
+    def listen(self):
+        """监听并处理请求"""
+        self.socket.bind((self.host, self.port))
+        self.socket.listen(self.max_connections)
+        print(f"Server listening on {self.host}:{self.port}")
+        
+        while True:
+            conn, addr = self.socket.accept()
+            try:
+                # 接收请求数据
+                data = conn.recv(4096).decode('utf-8')
+                if not data:
+                    continue
+                    
+                # 解析请求头和JSON数据
+                headers, body = self._parse_request(data)
+                
+                # 解析会话数据
+                session_data = json.loads(body)
+                
+                # 补全会话配置
+                merged_data = Config.merge_config(session_data)
+                
+                # 交给智能体处理
+                response_data = BaseAgent.Agent(merged_data)
+                
+                # 返回响应
+                conn.sendall(b'HTTP/1.1 200 OK\n')
+                conn.sendall(b'Content-Type: application/json\n\n')
+                conn.sendall(json.dumps(response_data).encode('utf-8'))
+                
+            except Exception as e:
+                conn.sendall(b'HTTP/1.1 500 Internal Server Error\n\n')
+                print(f"Error processing request: {e}")
+            finally:
+                conn.close()
+    
+    def _parse_request(self, data):
+        """解析HTTP请求"""
+        parts = data.split('\r\n\r\n')
+        headers_part = parts[0]
+        body = parts[1] if len(parts) > 1 else ''
+        
+        headers = {}
+        for line in headers_part.split('\r\n')[1:]:  # 跳过第一行请求行
+            if ': ' in line:
+                key, value = line.split(': ', 1)
+                headers[key] = value
+                
+        return headers, body
+    
+    def _validate_auth(self, auth_header):
+        """验证授权头"""
+        # TODO
+        pass

+ 7 - 0
yaa/Server/__init__.py

@@ -0,0 +1,7 @@
+"""yaa 服务端接口"""
+from ..Server.BaseServer import BaseServer
+
+
+__all__ = [
+    "BaseServer"
+]

+ 0 - 35
yaa/Session/Session.py

@@ -1,35 +0,0 @@
-# 会话管理模块
-#
-# 职责:
-# 1. 管理用户会话生命周期(创建/维护/销毁)
-# 2. 存储和维护会话历史记录
-# 3. 同步智能体状态到前端
-#
-# 主要功能:
-# - 创建新会话并初始化上下文
-# - 维护会话历史(用户输入/模型响应/工具调用)
-# - 处理会话超时和清理
-# - 流式传输状态更新
-#
-# 数据结构:
-# {
-#   "session_id": "唯一标识",
-#   "created_at": "创建时间",
-#   "last_active": "最后活跃时间",
-#   "history": [
-#     {"role": "user", "content": "输入"},
-#     {"role": "agent", "content": "响应"}
-#   ],
-#   "status": "queuing/running/completed/failed"
-# }
-#
-# 关键方法:
-# - create_session(): 创建新会话
-# - update_history(): 更新会话历史
-# - stream_update(): 流式推送状态
-# - close_session(): 关闭会话
-#
-# 与其他模块关系:
-# - 被 yaa.py 主程序调用来管理会话
-# - 与 BaseAgent 交互传递会话上下文
-# - 使用 DefaultConfig 的会话配置

+ 0 - 6
yaa/Session/__init__.py

@@ -1,6 +0,0 @@
-from ..Session.Session import Session
-
-
-__all__ = [
-    "Session"
-]

+ 4 - 1
yaa/Tools/BaseTool.py

@@ -31,4 +31,7 @@
 # 与其他模块关系:
 # - 被 BaseAgent 调用来执行具体工具
 # - 受 Auth 模块的资源限制约束
-# - 执行结果返回给 Prompt 模块生成后续提示
+# - 执行结果返回给 Prompt 模块生成后续提示
+
+class BaseTool:
+    pass

+ 8 - 4
yaa/yaa.py

@@ -6,10 +6,12 @@
 3. 处理全局异常和中断
 """
 
+import sys
 import argparse
-from yaa.Config.ServerConfig import ServerConfig
-from yaa.Modules.Server import Server
+from .Config.ServerConfig import ServerConfig
+from .Server.BaseServer import BaseServer
 
+sys.path.append('..')
 def main():
     parser = argparse.ArgumentParser(description='yaa 智能体命令行工具')
 
@@ -35,13 +37,15 @@ def main():
                 'yaa_server': {'port': args.port},
                 'security': {}
             }
+            # 如果指定了配置文件,则加载配置文件
             if args.config:
-                print(f"使用配置文件: {args.config}")
+                # print(f"使用配置文件: {args.config}")
                 # TODO: 从配置文件加载配置
+                pass
             
             # 合并默认配置和运行时配置
             config = ServerConfig.merge_config(runtime_config)
-            server = Server(config=config)
+            server = BaseServer(config=config)
             print(f"启动服务, 端口号: {config['yaa_server']['port']}")
             server.listen()
         except KeyboardInterrupt: