新增功能: - execution_log 模块:自动记录引擎调用耗时、成功/失败、错误详情 - 所有搜索引擎自动跟踪每次调用的性能指标 - CLI 搜索后自动显示执行摘要 - health 命令使用 ParallelSearch 检测所有引擎连通性 - 新增 log 命令查看历史执行日志
65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
"""Base engine class and shared data models."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from abc import ABC, abstractmethod
|
|
from dataclasses import dataclass, field
|
|
from typing import Any
|
|
|
|
from scripts.core.execution_log import execution_log
|
|
|
|
|
|
@dataclass
|
|
class EngineResult:
|
|
"""Unified result from any engine."""
|
|
title: str
|
|
url: str
|
|
snippet: str = ""
|
|
source: str = ""
|
|
category: str = "" # "general" | "news" | "academic" | "github"
|
|
published: str = ""
|
|
extra: dict[str, Any] = field(default_factory=dict)
|
|
|
|
|
|
class BaseEngine(ABC):
|
|
"""Base class for all search engines.
|
|
|
|
Automatically tracks execution timing and errors via execution_log.
|
|
"""
|
|
|
|
name: str = "unknown"
|
|
timeout: float = 10.0
|
|
|
|
def __init__(self, timeout: float = 10.0):
|
|
self.timeout = timeout
|
|
|
|
async def search_with_log(
|
|
self, query: str, max_results: int = 10, **kwargs
|
|
) -> list[EngineResult]:
|
|
"""Search with automatic execution logging.
|
|
|
|
Subclasses override `search()`, not this method.
|
|
"""
|
|
with execution_log.track(self.name, "search", query=query) as ctx:
|
|
results = await self.search(query, max_results=max_results, **kwargs)
|
|
ctx.result_count = len(results)
|
|
return results
|
|
|
|
@abstractmethod
|
|
async def search(self, query: str, max_results: int = 10,
|
|
**kwargs) -> list[EngineResult]:
|
|
...
|
|
|
|
async def health(self) -> dict:
|
|
"""Quick connectivity check."""
|
|
with execution_log.track(self.name, "health") as ctx:
|
|
try:
|
|
results = await self.search("test", max_results=1)
|
|
ctx.result_count = len(results)
|
|
return {"name": self.name, "status": "ok", "count": len(results)}
|
|
except Exception as e:
|
|
ctx.success = False
|
|
ctx.error = str(e)
|
|
ctx.error_type = type(e).__name__
|
|
return {"name": self.name, "status": "fail", "error": str(e)}
|