AgentEvalTool/backend/agenteval/web/deps.py
sinohqb 12481cd1b8 v0.3-s1: 规则层异步化 + 工具函数去重 + HTTP 通道
## 核心变更

### 规则层全面异步化(DEBT-1)
- EvalRule.evaluate() 签名改为 async def,全量同步改造(无兼容层)
- LlmScoreRule._call_llm: requests.post → httpx.AsyncClient,彻底消除事件循环阻塞
- engine._save_rule_results: rule.evaluate() → await rule.evaluate()

### 工具函数去重(DEBT-2)
- 新建 agenteval/utils/llm.py,统一三个函数:
  - extract_reply_text (原 5 处重复)
  - extract_content_from_llm_response (原 2 处重复)
  - parse_json_from_llm_text (统一 LLM 输出 JSON 解析)
- engine.py / llm_score.py / runs.py / report.py 全部切换到 utils.llm

### HTTP 通用通道(S1-3)
- 新建 channels/http.py (HttpChannel)
  - 配置化 send_url / reply_url 模板 ({message}, {msg_id} 占位)
  - dot-path 提取 msg_id 和 reply_text
  - 可选 reply_ready_path 就绪标志
  - 长连接 AsyncClient 复用
- ChannelFactory 注册 ChannelType.HTTP → HttpChannel

### 测试
- 新增 tests/unit/test_http_channel_and_rules.py (19 个测试)
- _get_path / health_check / send / poll_reply / 超时 / 就绪标志 / async 规则评估
- 测试总数:24 → 43,全部通过

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-17 10:52:32 +08:00

42 lines
1.2 KiB
Python

"""Shared FastAPI dependencies for routers.
Centralizes DB session management and API-key authentication so routers no
longer re-declare these helpers themselves.
"""
from typing import Optional
from fastapi import Depends, Header, HTTPException, status
from agenteval.config import get_settings
from agenteval.storage.db import get_session
def get_db():
"""Yield a SQLModel Session and guarantee close() on request completion."""
session = get_session()
try:
yield session
finally:
session.close()
def require_api_key(x_api_key: Optional[str] = Header(default=None)) -> None:
"""Enforce X-API-Key header when AGENTEVAL_API_KEY is configured.
When the setting is empty (default), the check is a no-op so local dev keeps
working without extra configuration.
"""
configured = get_settings().api_key
if not configured:
return
if not x_api_key or x_api_key != configured:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or missing X-API-Key",
)
# Convenience alias used by routers via ``dependencies=[Depends(auth_required)]``.
auth_required = Depends(require_api_key)