shinka-backup / docs /evaluation_agent_design.md
JustinTX's picture
Add files using upload-large-folder tool
1556404 verified

Evaluation Agent 讟计方案

📋 可行性分析

结论完党可行 将evaluation脚本改造成agent䞍仅技术䞊可行而䞔可以星著增区系统的适应性和智胜化皋床。


🏗 圓前架构分析

圓前Evaluation工䜜流

┌─────────────────────────────────────────────────────┐
│  EvolutionRunner (控制噚)                           │
│  ├─ 生成新代码 (gen_N/main.py)                     │
│  ├─ 提亀job到JobScheduler                          │
│  └─ 等埅结果                                        │
└────────────────┬────────────────────────────────────┘
                 │
                 ▌
┌─────────────────────────────────────────────────────┐
│  JobScheduler 执行呜什:                              │
│  python evaluate_with_auxiliary.py \                │
│    --program_path gen_N/main.py \                   │
│    --results_dir gen_N/results                      │
└────────────────┬────────────────────────────────────┘
                 │
                 ▌
┌─────────────────────────────────────────────────────┐
│  Evaluation Script (独立进皋)                       │
│  ├─ 加蜜皋序                                        │
│  ├─ 运行实验 (run_packing)                         │
│  ├─ 验证结果 (validate_packing)                    │
│  ├─ 计算metrics (固定的7䞪auxiliary metrics)       │
│  ├─ 生成文本反銈                                    │
│  └─ 保存结果到文件:                                 │
│      • metrics.json                                 │
│      • correct.json                                 │
│      • extra.npz                                    │
│      • auxiliary_analysis.json                      │
└────────────────┬────────────────────────────────────┘
                 │
                 ▌
┌─────────────────────────────────────────────────────┐
│  EvolutionRunner 读取结果                           │
│  ├─ 解析 metrics.json                              │
│  ├─ 提取 combined_score, public_metrics            │
│  ├─ 写入数据库 (ProgramDatabase)                   │
│  └─ 甚于选择䞋䞀代父皋序                            │
└─────────────────────────────────────────────────────┘

关键接口契纊

蟓入接口 (呜什行参数):

--program_path: str      # 芁评䌰的皋序路埄
--results_dir: str       # 结果保存目圕
--aux_config: str        # (可选) 蟅助评䌰配眮

蟓出接口 (文件系统):

# metrics.json
{
  "combined_score": 2.635,        # 䞻评分 (必须)
  "public": {                      # 公匀指标 (LLM可见)
    "centers_str": "...",
    "num_circles": 26,
    "aux_packing_efficiency": 0.842,
    "aux_gap_analysis": 0.756,
    ...
  },
  "private": {                     # 私有指标 (仅记圕)
    "reported_sum_of_radii": 2.635
  },
  "text_feedback": "..."          # (可选) 文本反銈
}

# correct.json
{
  "correct": true,
  "error": null
}

数据库Schema (Program衚):

@dataclass
class Program:
    # 身仜标识
    id: str
    code: str
    generation: int
    parent_id: Optional[str]
    
    # 评䌰结果 (由evaluation写入)
    combined_score: float
    public_metrics: Dict[str, Any]
    private_metrics: Dict[str, Any]
    text_feedback: str
    correct: bool
    
    # 蟅助数据
    embedding: List[float]
    metadata: Dict[str, Any]
    
    # 进化关系
    archive_inspiration_ids: List[str]
    top_k_inspiration_ids: List[str]
    children_count: int

🀖 Agent化改造方案

栞心讟计理念

Agent ≠ 脚本的区别:

  1. 自䞻决策: Agent胜根据context决定分析策略
  2. 劚态工具䜿甚: Agent胜调甚䞍同工具、生成新代码
  3. 历史感知: Agent胜访问数据库了解进化历史
  4. 元孊习: Agent胜改进自己的评䌰策略

Agent架构讟计

┌─────────────────────────────────────────────────────────────┐
│              EvaluationAgent (䞻控制噚)                     │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  Core Components:                                     │  │
│  │  • LLM (decision maker)                              │  │
│  │  • Tool Registry (可调甚的工具集)                    │  │
│  │  • Database Access (读写历史数据)                    │  │
│  │  • Code Executor (安党执行生成的代码)                │  │
│  └───────────────────────────────────────────────────────┘  │
│                                                             │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  Workflow:                                            │  │
│  │  1. 接收评䌰请求 (program_path, results_dir)         │  │
│  │  2. 查询数据库获取context                            │  │
│  │  3. LLM规划评䌰策略                                  │  │
│  │  4. 执行评䌰步骀 (调甚工具/生成代码)                 │  │
│  │  5. 聚合结果并生成反銈                               │  │
│  │  6. (可选) 曎新数据库元信息                          │  │
│  │  7. 保存标准蟓出文件                                 │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘

            Agent可甚的工具 (Tools):
            
┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐
│  Ground Truth    │  │  Auxiliary       │  │  Dynamic Metric  │
│  Evaluation      │  │  Metrics         │  │  Generator       │
│  • 运行皋序      │  │  • 预定义指标    │  │  • LLM生成代码   │
│  • 验证纊束      │  │  • 泚册系统      │  │  • 猖译并执行    │
│  • 计算䞻分数    │  │                  │  │  • 安党沙箱      │
└──────────────────┘  └──────────────────┘  └──────────────────┘

┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐
│  Database Query  │  │  Visualization   │  │  Meta Analysis   │
│  • 查询历史      │  │  • 生成囟衚      │  │  • 趋势分析      │
│  • 统计分析      │  │  • 保存可视化    │  │  • 策略掚荐      │
│  • 对比皋序      │  │                  │  │                  │
└──────────────────┘  └──────────────────┘  └──────────────────┘

            数据库访问权限:
            
┌──────────────────────────────────────────────────────────┐
│  Database Interface (ProgramDatabase)                    │
│  ┌────────────────────────────────────────────────────┐  │
│  │  READ Operations (Agent可甚):                      │  │
│  │  • get_all_programs()                              │  │
│  │  • get_programs_by_generation(gen)                 │  │
│  │  • get_top_programs(n, metric)                     │  │
│  │  • get_best_program(metric)                        │  │
│  │  • get_program(id)                                 │  │
│  │  • 自定义SQL查询 (受限)                            │  │
│  └────────────────────────────────────────────────────┘  │
│  ┌────────────────────────────────────────────────────┐  │
│  │  WRITE Operations (谚慎䜿甚):                      │  │
│  │  • 只胜写入metadata字段                            │  │
│  │  • 䞍胜修改 combined_score, correct 等栞心字段     │  │
│  │  • 可以添加额倖的分析结果到metadata                │  │
│  └────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘

🔌 Agent对倖接口讟计

1. 呜什行接口 (保持兌容)

# 基本接口 (䞎圓前完党兌容)
python evaluation_agent.py \
    --program_path gen_42/main.py \
    --results_dir gen_42/results

# 扩展接口 (新增功胜)
python evaluation_agent.py \
    --program_path gen_42/main.py \
    --results_dir gen_42/results \
    --db_path path/to/evolution.sqlite \      # Agent可访问数据库
    --agent_mode adaptive \                    # 评䌰暡匏: static|adaptive|exploratory
    --enable_dynamic_metrics \                 # 允讞生成新metrics
    --feedback_style detailed                  # 反銈风栌: minimal|normal|detailed

2. Python API接口

from shinka.evaluation import EvaluationAgent, AgentConfig

# 配眮Agent
agent_config = AgentConfig(
    # LLM配眮
    llm_model="native-gemini-2.5-pro",
    llm_temperature=0.7,
    
    # 评䌰暡匏
    mode="adaptive",  # static | adaptive | exploratory
    
    # 工具访问权限
    enable_ground_truth=True,         # 必须
    enable_auxiliary_metrics=True,    # 预定义蟅助指标
    enable_dynamic_metrics=True,      # LLM生成新指标
    enable_database_read=True,        # 读取历史数据
    enable_database_write_metadata=False,  # 写入元数据
    
    # 安党配眮
    code_execution_timeout=30,        # 生成代码执行超时
    max_tool_calls=20,                # 最倧工具调甚次数
    sandboxed_execution=True,         # 沙箱执行
    
    # 蟓出配眮
    generate_text_feedback=True,
    save_detailed_analysis=True,
    visualization=True,
)

# 创建Agent
agent = EvaluationAgent(
    config=agent_config,
    db_path="path/to/evolution.sqlite"  # 可选
)

# 执行评䌰
metrics, correct, error = agent.evaluate(
    program_path="gen_42/main.py",
    results_dir="gen_42/results"
)

# Agent䌚自劚保存标准蟓出文件
# - metrics.json
# - correct.json
# - auxiliary_analysis.json
# - (可选) agent_reasoning.json  # Agent的决策过皋

3. EvolutionRunner集成接口

from shinka.core import EvolutionRunner, EvolutionConfig
from shinka.database import DatabaseConfig
from shinka.launch import LocalJobConfig
from shinka.evaluation import EvaluationAgentConfig  # 新增

# 配眮job䜿甚Agent评䌰噚
job_config = LocalJobConfig(
    eval_program_path="shinka/evaluation/agent_main.py",  # Agent入口
    extra_cmd_args={
        "agent_mode": "adaptive",
        "enable_dynamic_metrics": True,
        "db_path": "auto",  # 自劚䌠递数据库路埄
    }
)

# 数据库配眮
db_config = DatabaseConfig(
    db_path="evolution_db.sqlite",
    # ... 其他配眮
)

# 进化配眮
evo_config = EvolutionConfig(
    # ... 其他配眮
    use_text_feedback=True,  # 接收Agent生成的反銈
)

# 运行时Agent䌚自劚获埗:
# 1. 圓前generation的皋序路埄
# 2. 数据库访问权限 (通过--db_path参数)
# 3. 历史皋序信息
runner = EvolutionRunner(
    job_config=job_config,
    db_config=db_config,
    evo_config=evo_config,
)
runner.run()

🛠 Agent工具系统讟计

工具接口规范

from typing import Any, Dict, Optional
from dataclasses import dataclass

@dataclass
class ToolResult:
    """工具执行结果"""
    success: bool
    data: Any
    error: Optional[str] = None
    cost: float = 0.0  # API成本

class Tool:
    """工具基类"""
    name: str
    description: str
    parameters: Dict[str, Any]  # JSON Schema
    
    def execute(self, **kwargs) -> ToolResult:
        """执行工具逻蟑"""
        raise NotImplementedError

栞心工具枅单

# ============================================================================
# 1. GROUND TRUTH EVALUATION (必需工具)
# ============================================================================

class RunProgramTool(Tool):
    """运行被评䌰皋序并获取原始结果"""
    name = "run_program"
    description = "Execute the program and get raw results (centers, radii, score)"
    
    def execute(self, program_path: str, num_runs: int = 1) -> ToolResult:
        # 调甚 run_shinka_eval 的底层逻蟑
        # 返回: centers, radii, reported_score
        pass

class ValidateResultsTool(Tool):
    """验证皋序蟓出是吊满足纊束"""
    name = "validate_results"
    description = "Validate if results satisfy all constraints"
    
    def execute(self, centers, radii) -> ToolResult:
        # 调甚 adapted_validate_packing
        # 返回: is_valid, error_message
        pass

# ============================================================================
# 2. AUXILIARY METRICS (预定义分析工具)
# ============================================================================

class ComputeMetricTool(Tool):
    """计算预定义的蟅助指标"""
    name = "compute_metric"
    description = "Compute a predefined auxiliary metric"
    parameters = {
        "metric_name": {
            "type": "string",
            "enum": ["packing_efficiency", "gap_analysis", "edge_utilization", ...]
        }
    }
    
    def execute(self, metric_name: str, centers, radii) -> ToolResult:
        # 调甚 METRIC_REGISTRY.get(metric_name)
        pass

class ListMetricsTool(Tool):
    """列出所有可甚的预定义指标"""
    name = "list_metrics"
    
    def execute(self) -> ToolResult:
        return ToolResult(
            success=True,
            data=METRIC_REGISTRY.list_metrics()
        )

# ============================================================================
# 3. DATABASE ACCESS (历史数据工具)
# ============================================================================

class QueryDatabaseTool(Tool):
    """查询数据库获取历史皋序信息"""
    name = "query_database"
    description = "Query historical programs from database"
    parameters = {
        "query_type": {
            "type": "string",
            "enum": ["top_programs", "by_generation", "best_program", "all"]
        },
        "filters": {
            "type": "object",
            "properties": {
                "metric": {"type": "string"},
                "n": {"type": "integer"},
                "generation": {"type": "integer"}
            }
        }
    }
    
    def execute(self, query_type: str, filters: Dict) -> ToolResult:
        if query_type == "top_programs":
            programs = self.db.get_top_programs(
                n=filters.get("n", 10),
                metric=filters.get("metric", "combined_score")
            )
        elif query_type == "by_generation":
            programs = self.db.get_programs_by_generation(filters["generation"])
        # ...
        
        return ToolResult(
            success=True,
            data=[p.to_dict() for p in programs]
        )

class CompareWithHistoryTool(Tool):
    """对比圓前皋序䞎历史皋序"""
    name = "compare_with_history"
    
    def execute(self, current_metrics: Dict, comparison_type: str) -> ToolResult:
        # comparison_type: "best" | "parent" | "generation_average"
        # 返回对比分析结果
        pass

# ============================================================================
# 4. DYNAMIC METRIC GENERATION (LLM生成新指标)
# ============================================================================

class GenerateMetricCodeTool(Tool):
    """让LLM生成新的评䌰指标代码"""
    name = "generate_metric_code"
    description = "Generate Python code for a new evaluation metric"
    parameters = {
        "metric_purpose": {"type": "string"},
        "inspiration_from": {"type": "string"}  # 参考已有指标
    }
    
    def execute(self, metric_purpose: str, inspiration_from: str = None) -> ToolResult:
        # 调甚LLM生成新metric代码
        # 䜿甚 LLMGeneratedMetric 框架
        prompt = f"""
        Generate a Python function to compute a new auxiliary metric for circle packing.
        
        Purpose: {metric_purpose}
        
        Requirements:
        1. Function signature: def metric_name(centers: np.ndarray, radii: np.ndarray) -> MetricResult
        2. Return MetricResult with name, value, interpretation, description, details
        3. Use numpy for computations
        4. Handle edge cases gracefully
        
        Example structure:
        ```python
        def my_metric(centers, radii):
            # Your analysis logic here
            score = ...
            
            return MetricResult(
                name="my_metric",
                value=float(score),
                interpretation="higher_better",
                description="What this metric measures",
                details={{"key": "value"}}
            )
        ```
        """
        
        llm_response = self.llm.query(prompt)
        code = extract_code_from_response(llm_response)
        
        return ToolResult(
            success=True,
            data={"code": code, "cost": llm_response.cost}
        )

class CompileAndTestMetricTool(Tool):
    """猖译并测试LLM生成的指标代码"""
    name = "compile_and_test_metric"
    
    def execute(self, code: str, test_data: Dict) -> ToolResult:
        metric = LLMGeneratedMetric(
            name="llm_metric",
            code=code,
            description="LLM generated metric",
            interpretation="higher_better"
        )
        
        if not metric.compile():
            return ToolResult(success=False, error="Compilation failed")
        
        # 测试执行
        try:
            result = metric.evaluate(
                centers=test_data["centers"],
                radii=test_data["radii"]
            )
            return ToolResult(success=True, data=result)
        except Exception as e:
            return ToolResult(success=False, error=str(e))

# ============================================================================
# 5. VISUALIZATION & ANALYSIS (分析工具)
# ============================================================================

class VisualizeTool(Tool):
    """生成可视化"""
    name = "visualize"
    
    def execute(self, vis_type: str, data: Dict, output_path: str) -> ToolResult:
        # vis_type: "packing" | "metrics_trend" | "comparison"
        pass

class StatisticalAnalysisTool(Tool):
    """统计分析工具"""
    name = "statistical_analysis"
    
    def execute(self, data: List[float], analysis_type: str) -> ToolResult:
        # analysis_type: "trend" | "distribution" | "correlation"
        pass

# ============================================================================
# 6. META OPERATIONS (元操䜜)
# ============================================================================

class UpdateMetadataTool(Tool):
    """曎新皋序的metadata字段"""
    name = "update_metadata"
    description = "Add analysis results to program metadata (write to DB)"
    
    def execute(self, program_id: str, metadata: Dict) -> ToolResult:
        # 仅允讞写入metadata字段䞍胜修改栞心评䌰字段
        program = self.db.get_program(program_id)
        if program:
            program.metadata.update(metadata)
            # 写回数据库
            # 泚意需芁扩展ProgramDatabase添加update_metadata方法
        pass

🧠 Agent决策流皋

Mode 1: Static Mode (兌容暡匏)

def static_evaluation(agent, program_path, results_dir):
    """
    完党兌容现有evaluation脚本的行䞺
    """
    # 1. 运行皋序
    result = agent.tools["run_program"].execute(program_path)
    centers, radii, score = result.data
    
    # 2. 验证结果
    validation = agent.tools["validate_results"].execute(centers, radii)
    correct = validation.data["is_valid"]
    
    # 3. 计算预定义auxiliary metrics
    auxiliary_results = {}
    for metric_name in agent.config.enabled_metrics:
        metric_result = agent.tools["compute_metric"].execute(
            metric_name, centers, radii
        )
        auxiliary_results[metric_name] = metric_result.data.value
    
    # 4. 生成标准反銈
    feedback = generate_standard_feedback(auxiliary_results, score)
    
    # 5. 保存结果
    metrics = {
        "combined_score": score,
        "public": {
            "centers_str": format_centers_string(centers),
            "num_circles": len(centers),
            **{f"aux_{k}": v for k, v in auxiliary_results.items()}
        },
        "private": {"reported_sum_of_radii": score},
        "text_feedback": feedback
    }
    
    save_metrics(results_dir, metrics, correct)
    return metrics, correct

Mode 2: Adaptive Mode (智胜暡匏)

def adaptive_evaluation(agent, program_path, results_dir, db_path):
    """
    Agent根据context智胜决策评䌰策略
    """
    # 1. 获取context
    context = agent.gather_context(program_path, db_path)
    
    # 2. LLM规划评䌰策略
    plan = agent.llm.plan_evaluation(context)
    
    # 瀺䟋plan:
    # {
    #   "steps": [
    #     {"action": "run_program", "params": {...}},
    #     {"action": "query_database", "params": {"query_type": "best_program"}},
    #     {"action": "compute_metric", "params": {"metric_name": "packing_efficiency"}},
    #     {"action": "compare_with_history", "params": {"comparison_type": "best"}},
    #     {"action": "generate_feedback", "params": {...}}
    #   ]
    # }
    
    # 3. 执行plan
    execution_log = []
    for step in plan["steps"]:
        tool = agent.tools[step["action"]]
        result = tool.execute(**step["params"])
        execution_log.append(result)
        
        # 劂果某步倱莥LLM可以调敎策略
        if not result.success:
            plan = agent.llm.replan(plan, execution_log, result.error)
    
    # 4. LLM聚合结果并生成反銈
    final_metrics, feedback = agent.llm.aggregate_results(execution_log, context)
    
    # 5. 保存结果 (保证接口兌容性)
    save_metrics(results_dir, final_metrics, correct)
    
    # 6. (可选) 保存Agent掚理过皋
    save_agent_reasoning(results_dir, plan, execution_log)
    
    return final_metrics, correct

Mode 3: Exploratory Mode (探玢暡匏)

def exploratory_evaluation(agent, program_path, results_dir, db_path):
    """
    Agent䞻劚探玢新的评䌰方法
    """
    # 1. 标准评䌰
    base_metrics, correct = adaptive_evaluation(agent, program_path, results_dir, db_path)
    
    # 2. 分析历史趋势
    trend_analysis = agent.tools["statistical_analysis"].execute(
        data=get_historical_scores(agent.db),
        analysis_type="trend"
    )
    
    # 3. 劂果发现评䌰盲点生成新metric
    if agent.detect_evaluation_gap(trend_analysis):
        # LLM生成新metric代码
        new_metric_code = agent.tools["generate_metric_code"].execute(
            metric_purpose="Identify patterns missed by existing metrics"
        )
        
        # 猖译并测试
        test_result = agent.tools["compile_and_test_metric"].execute(
            code=new_metric_code.data["code"],
            test_data={"centers": centers, "radii": radii}
        )
        
        if test_result.success:
            # 泚册新metric到党局registry
            register_new_metric(new_metric_code.data["code"])
            
            # 重新评䌰包含新metric
            extended_metrics = compute_with_new_metric(centers, radii)
            base_metrics["public"].update(extended_metrics)
    
    # 4. 保存扩展结果
    save_metrics(results_dir, base_metrics, correct)
    
    return base_metrics, correct

🔒 安党性讟计

代码执行沙箱

class SafeCodeExecutor:
    """安党的代码执行环境"""
    
    def __init__(self, timeout=30):
        self.timeout = timeout
        self.allowed_imports = {
            'numpy', 'scipy', 'math', 'statistics'
        }
        self.forbidden_operations = {
            '__import__', 'eval', 'exec', 'compile',
            'open', 'file', 'input', 'raw_input'
        }
    
    def execute(self, code: str, inputs: Dict) -> Any:
        """圚受限环境䞭执行代码"""
        # 1. 静态分析检查
        if self.has_forbidden_operations(code):
            raise SecurityError("Forbidden operations detected")
        
        # 2. 创建受限namespace
        namespace = {
            'np': numpy,
            'MetricResult': MetricResult,
            # ... 只提䟛必芁的暡块
        }
        namespace.update(inputs)
        
        # 3. 超时执行
        with timeout(self.timeout):
            exec(code, namespace)
        
        return namespace

数据库访问权限控制

class RestrictedDatabaseAccess:
    """受限的数据库访问接口"""
    
    def __init__(self, db: ProgramDatabase):
        self.db = db
        self.read_only_methods = [
            'get_all_programs', 'get_programs_by_generation',
            'get_top_programs', 'get_best_program', 'get_program'
        ]
        self.write_allowed_fields = ['metadata']  # 只胜写metadata
    
    def __getattr__(self, name):
        if name in self.read_only_methods:
            return getattr(self.db, name)
        else:
            raise PermissionError(f"Method {name} not allowed for agent")
    
    def update_metadata(self, program_id: str, metadata: Dict):
        """唯䞀允讞的写入操䜜"""
        program = self.db.get_program(program_id)
        if program:
            program.metadata.update(metadata)
            # 需芁圚ProgramDatabase䞭添加歀方法
            self.db.update_program_metadata(program_id, program.metadata)

📊 Agent䞎倖界的数据流

┌─────────────────────────────────────────────────────────────┐
│  EvolutionRunner (䞻系统)                                   │
│                                                             │
│  [每䞀代进化]                                                │
│  ├─ 生成新代码: gen_N/main.py                              │
│  ├─ 调甚Agent评䌰 ──────────────────────────┐              │
│  │                                           â–Œ              │
│  │                            ┌──────────────────────────┐  │
│  │                            │  EvaluationAgent         │  │
│  │                            │  (独立进皋)              │  │
│  │                            │                          │  │
│  │                            │  蟓入:                   │  │
│  │                            │  • program_path          │  │
│  │                            │  • results_dir           │  │
│  │                            │  • db_path (可选)        │  │
│  │                            │                          │  │
│  │                            │  Agent内郚流皋:          │  │
│  │                            │  1. 加蜜皋序             │  │
│  │                            │  2. 运行评䌰             │  │
│  │    读取数据库 ◄───────────┌  3. 查询DB历史 ──┐       │  │
│  │                            │  4. LLM规划      │       │  │
│  │                            │  5. 工具调甚     │       │  │
│  │                            │  6. 聚合结果     │       │  │
│  │    (可选)写metadata ◄─────┌  7. 保存蟓出     │       │  │
│  │                            │                  │       │  │
│  │                            │  蟓出文件:       │       │  │
│  │                            │  • metrics.json  │       │  │
│  │                            │  • correct.json  │       │  │
│  │                            │  • agent_log.json│       │  │
│  │                            └──────────────────┌───────┘  │
│  │                                               │          │
│  ├─ 读取评䌰结果 ◄────────────────────────────────┘          │
│  │   • combined_score                                       │
│  │   • public_metrics (含aux metrics)                      │
│  │   • text_feedback                                        │
│  │                                                          │
│  ├─ 写入数据库 (ProgramDatabase)                            │
│  │   • 创建新Program记圕                                    │
│  │   • 保存所有metrics                                      │
│  │   • 曎新archive                                          │
│  │                                                          │
│  └─ 选择父代 → 䞋䞀代 ────────────────────────►              │
└─────────────────────────────────────────────────────────────┘

           数据库 Schema (共享状态):
           
┌──────────────────────────────────────────────────────────┐
│  SQLite: evolution_db.sqlite                             │
│  ┌────────────────────────────────────────────────────┐  │
│  │  programs 衚                                       │  │
│  │  ├─ id (gen_N)                                    │  │
│  │  ├─ code                                          │  │
│  │  ├─ generation (N)                                │  │
│  │  ├─ combined_score  ◄── EvolutionRunner写入      │  │
│  │  ├─ public_metrics  ◄── EvolutionRunner写入      │  │
│  │  ├─ text_feedback   ◄── EvolutionRunner写入      │  │
│  │  ├─ correct         ◄── EvolutionRunner写入      │  │
│  │  │                                                │  │
│  │  └─ metadata        ◄── Agent可写入 (可选)       │  │
│  │     {                                             │  │
│  │       "agent_analysis": {...},                    │  │
│  │       "custom_metrics": {...},                    │  │
│  │       "evaluation_reasoning": "..."               │  │
│  │     }                                              │  │
│  └────────────────────────────────────────────────────┘  │
│                                                          │
│  Agent可读取党郚历史数据䜆只胜写入metadata字段         │
└──────────────────────────────────────────────────────────┘

🎯 Agent对倖接口总结

必需接口 (保持兌容)

# 1. 呜什行参数接口
--program_path: str      # 必需
--results_dir: str       # 必需

# 2. 蟓出文件接口 (标准契纊)
metrics.json: {
    "combined_score": float,      # 必需
    "public": dict,                # 必需
    "private": dict,               # 可选
    "text_feedback": str           # 可选 (use_text_feedback=True时)
}
correct.json: {
    "correct": bool,               # 必需
    "error": str | null            # 必需
}

扩展接口 (Agent特性)

# 1. 数据库访问接口
--db_path: str           # 可选提䟛后Agent可访问历史数据

# 2. Agent暡匏配眮
--agent_mode: str        # static | adaptive | exploratory
--enable_dynamic_metrics: bool
--max_tool_calls: int

# 3. 额倖蟓出文件
agent_reasoning.json: {  # Agent的决策过皋 (甚于调试和分析)
    "plan": [...],
    "execution_log": [...],
    "tool_costs": {...},
    "total_cost": float
}

auxiliary_analysis.json  # 诊细的蟅助分析 (已有)

visualizations/          # 可视化文件 (可选)
├─ packing_viz.png
├─ metrics_trend.png
└─ comparison.png

Python API接口

# 1. Agent类接口
class EvaluationAgent:
    def __init__(
        self, 
        config: AgentConfig, 
        db_path: Optional[str] = None
    ):
        pass
    
    def evaluate(
        self, 
        program_path: str, 
        results_dir: str
    ) -> Tuple[Dict, bool, Optional[str]]:
        """
        返回: (metrics, correct, error)
        侎 run_shinka_eval 完党兌容
        """
        pass

# 2. 工具接口 (䟛Agent内郚䜿甚)
class Tool:
    def execute(self, **kwargs) -> ToolResult:
        pass

# 3. 数据库接口扩展
class ProgramDatabase:
    # 新增方法䟛Agent䜿甚
    def update_program_metadata(
        self, 
        program_id: str, 
        metadata: Dict
    ) -> bool:
        pass

🚀 实现路线囟

Phase 1: 基础Agent框架 (2-3倩)

✓ 1. 创建 EvaluationAgent 类骚架
✓ 2. 实现 Tool 基类和工具泚册系统
✓ 3. 重构现有evaluation代码䞺工具
    - RunProgramTool
    - ValidateResultsTool
    - ComputeMetricTool
✓ 4. 实现 static_mode (完党兌容现有行䞺)
✓ 5. 单元测试

Phase 2: 数据库集成 (1-2倩)

✓ 1. 创建 RestrictedDatabaseAccess 接口
✓ 2. 实现数据库查询工具
    - QueryDatabaseTool
    - CompareWithHistoryTool
✓ 3. 扩展 ProgramDatabase.update_program_metadata()
✓ 4. 集成测试

Phase 3: Adaptive Mode (3-4倩)

✓ 1. 实现 LLM planning 逻蟑
✓ 2. Context gathering (历史数据分析)
✓ 3. 劚态工具调甚
✓ 4. 结果聚合和反銈生成
✓ 5. 端到端测试

Phase 4: Dynamic Metrics (2-3倩)

✓ 1. 实现 GenerateMetricCodeTool
✓ 2. SafeCodeExecutor 沙箱
✓ 3. 劚态metric泚册和验证
✓ 4. Exploratory mode 实现
✓ 5. 安党性测试

Phase 5: 可视化和分析 (1-2倩)

✓ 1. VisualizeTool
✓ 2. StatisticalAnalysisTool
✓ 3. Agent掚理过皋可视化

Phase 6: 生产就绪 (2-3倩)

✓ 1. 性胜䌘化
✓ 2. 错误倄理和恢倍
✓ 3. 日志和监控
✓ 4. 文档完善
✓ 5. 集成到EvolutionRunner

总计: 11-17倩匀发时闎


📝 䜿甚瀺䟋

瀺䟋1: 静态暡匏 (完党兌容)

from shinka.evaluation import EvaluationAgent, AgentConfig

config = AgentConfig(mode="static")
agent = EvaluationAgent(config)

metrics, correct, error = agent.evaluate(
    program_path="gen_42/main.py",
    results_dir="gen_42/results"
)

# 蟓出䞎现有evaluate_with_auxiliary.py完党盞同

瀺䟋2: 自适应暡匏 (智胜评䌰)

config = AgentConfig(
    mode="adaptive",
    enable_database_read=True,
    llm_model="native-gemini-2.5-pro"
)

agent = EvaluationAgent(
    config=config,
    db_path="evolution_db.sqlite"
)

metrics, correct, error = agent.evaluate(
    program_path="gen_100/main.py",
    results_dir="gen_100/results"
)

# Agent䌚:
# 1. 查询前99代的最䜳皋序
# 2. 分析圓前皋序盞对历史的改进
# 3. 智胜选择最盞关的auxiliary metrics
# 4. 生成䞪性化的反銈

瀺䟋3: 探玢暡匏 (自劚发现新指标)

config = AgentConfig(
    mode="exploratory",
    enable_dynamic_metrics=True,
    enable_database_read=True
)

agent = EvaluationAgent(config, db_path="evolution_db.sqlite")

metrics, correct, error = agent.evaluate(
    program_path="gen_150/main.py",
    results_dir="gen_150/results"
)

# Agent可胜䌚:
# 1. 发现现有metrics郜圚plateau
# 2. 生成新的metric来检测"corner circle size pattern"
# 3. 验证新metric䞎䞻分数的盞关性
# 4. 劂果有效泚册到党局registry䟛后续䜿甚

💡 䌘势和圱响

对进化系统的改进

  1. 曎智胜的评䌰: Agent可以根据进化阶段调敎评䌰策略
  2. 自适应反銈: 针对圓前代的具䜓问题提䟛针对性建议
  3. 自劚发现: 探玢新的评䌰绎床突砎人工讟计的局限
  4. 可解释性: Agent的掚理过皋可远溯方䟿调试

保持兌容性

  1. 接口兌容: 完党遵守现有的蟓入蟓出契纊
  2. 析进匏采甚: 可以从static暡匏匀始逐步启甚高级功胜
  3. 性胜可控: 可以配眮Agent的计算预算
  4. 无砎坏性: 䞍圱响现有实验的可倍现性

🎓 总结

Agent的栞心对倖接口

蟓入接口:
├─ 必需: program_path, results_dir
└─ 可选: db_path, agent_config

蟓出接口:
├─ 必需: metrics.json, correct.json
└─ 可选: agent_reasoning.json, visualizations/

数据库接口:
├─ READ: 可读取所有历史皋序数据
└─ WRITE: 仅可写入program.metadata字段

工具接口:
├─ Ground Truth: 运行和验证皋序
├─ Auxiliary Metrics: 预定义分析指标
├─ Database: 查询历史数据
├─ Dynamic: 生成新指标
└─ Visualization: 分析和可视化

关键讟计原则

  1. 接口兌容䌘先: Agent必须胜完党替代现有evaluation脚本
  2. 安党性: 代码执行沙箱、数据库权限控制
  3. 可扩展性: 工具系统支持持续添加新胜力
  4. 可观测性: Agent的决策过皋可远溯和调试
  5. 性胜可控: 通过配眮平衡智胜皋床和计算成本

实现可行性

✅ 技术可行: 所有组件郜有成熟的实现方案 ✅ 架构友奜: 䞎现有系统无猝集成 ✅ 析进匏: 可以分阶段实现和郚眲 ✅ 向后兌容: 䞍砎坏现有实验


这䞪Agent将evaluation从固定流皋提升䞺智胜决策过皋同时保持䞎现有系统的完矎兌容 🚀