Просмотр исходного кода

治理(Trace接口): 收窄异常并清理冗余格式化

清理 Trace HTTP、Goal、运行状态和上传接口中的未使用导入、无效 f-string 与静默异常,保留现有路由、响应结构和事件语义。
SamLee 17 часов назад
Родитель
Сommit
6018ee5946

+ 9 - 2
agent/agent/trace/api.py

@@ -6,6 +6,7 @@ Trace RESTful API
 
 import os
 import json
+import logging
 import httpx
 from datetime import datetime, timezone
 from typing import List, Optional, Dict, Any
@@ -14,6 +15,8 @@ from pydantic import BaseModel
 
 from .protocols import TraceStore
 
+logger = logging.getLogger(__name__)
+
 
 router = APIRouter(prefix="/api/traces", tags=["traces"])
 
@@ -275,7 +278,11 @@ async def submit_knowledge_feedback(trace_id: str, req: KnowledgeFeedbackRequest
                 updated_count += 1
             except Exception as e:
                 # 记录警告但不中断整体提交
-                print(f"[KnowledgeFeedback] KnowHub 更新失败 {item.knowledge_id}: {e}")
+                logger.warning(
+                    "KnowHub knowledge update failed: knowledge_id=%s error=%s",
+                    item.knowledge_id,
+                    e,
+                )
 
     return {"status": "ok", "updated": updated_count}
 
@@ -318,7 +325,7 @@ async def extract_comment_proxy(req: Dict[str, Any]):
                     if "task" in parsed and "content" in parsed:
                         raw = part
                         break
-                except Exception:
+                except (json.JSONDecodeError, TypeError):
                     continue
         extracted = json.loads(raw)
         task = extracted.get("task", "").strip()

+ 0 - 1
agent/agent/trace/examples_api.py

@@ -2,7 +2,6 @@
 Examples API - 提供 examples 项目列表和 prompt 读取接口
 """
 
-import os
 from typing import List, Optional
 from pathlib import Path
 from fastapi import APIRouter, HTTPException

+ 4 - 4
agent/agent/trace/goal_tool.py

@@ -5,7 +5,7 @@ Goal 工具 - 计划管理
 """
 
 import logging
-from typing import Optional, List, TYPE_CHECKING
+from typing import Optional, TYPE_CHECKING
 
 from agent.tools import tool
 
@@ -42,7 +42,7 @@ async def inject_knowledge_for_goal(
     """
     # 检查是否启用知识注入
     if knowledge_config and not getattr(knowledge_config, 'enable_injection', True):
-        logger.debug(f"[Knowledge Inject] 知识注入已禁用,跳过")
+        logger.debug("[Knowledge Inject] 知识注入已禁用,跳过")
         return None
 
     try:
@@ -92,12 +92,12 @@ async def inject_knowledge_for_goal(
                             "sources": [],
                         }
                     )
-                    logger.info(f"[Knowledge Inject] 已记录 query 事件到 cognition_log")
+                    logger.info("[Knowledge Inject] 已记录 query 事件到 cognition_log")
 
             return f"📚 已注入 {knowledge_count} 条相关知识"
         else:
             goal.knowledge = []
-            logger.info(f"[Knowledge Inject] 未找到相关知识")
+            logger.info("[Knowledge Inject] 未找到相关知识")
             return None
 
     except Exception as e:

+ 2 - 2
agent/agent/trace/run_api.py

@@ -708,8 +708,8 @@ async def list_running():
                             trace_info["is_active"] = time_since_activity < 30
                             trace_info["seconds_since_activity"] = int(time_since_activity)
                         trace_info["status"] = trace.status
-                except Exception:
-                    pass
+                except Exception as exc:
+                    logger.debug("Failed to inspect running trace %s: %s", tid, exc)
 
             running.append(trace_info)
 

+ 2 - 2
agent/agent/trace/upload_api.py

@@ -8,7 +8,7 @@ import os
 import shutil
 import tempfile
 import zipfile
-from typing import List, Dict, Any
+from typing import List, Dict
 from fastapi import APIRouter, UploadFile, File, HTTPException
 from pydantic import BaseModel
 
@@ -180,7 +180,7 @@ async def upload_traces(file: UploadFile = File(...)):
         elif imported and failed:
             message = f"Imported {len(imported)} trace(s), {len(failed)} failed"
         elif not imported and failed:
-            message = f"Failed to import all traces"
+            message = "Failed to import all traces"
         else:
             message = "No valid traces found in the zip file"